##// END OF EJS Templates
users: ported controllers from pylons into pyramid views.
marcink -
r2114:6e357177 default
parent child Browse files
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,505 +1,570 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 import operator
23 import operator
24
24
25 from pyramid.httpexceptions import HTTPFound
25 from pyramid.httpexceptions import HTTPFound
26
26
27 from rhodecode.lib import helpers as h
27 from rhodecode.lib import helpers as h
28 from rhodecode.lib.utils2 import StrictAttributeDict, safe_int, datetime_to_time
28 from rhodecode.lib.utils2 import StrictAttributeDict, safe_int, datetime_to_time
29 from rhodecode.lib.vcs.exceptions import RepositoryRequirementError
29 from rhodecode.lib.vcs.exceptions import RepositoryRequirementError
30 from rhodecode.model import repo
30 from rhodecode.model import repo
31 from rhodecode.model import repo_group
31 from rhodecode.model import repo_group
32 from rhodecode.model import user_group
32 from rhodecode.model import user_group
33 from rhodecode.model import user
33 from rhodecode.model.db import User
34 from rhodecode.model.db import User
34 from rhodecode.model.scm import ScmModel
35 from rhodecode.model.scm import ScmModel
35
36
36 log = logging.getLogger(__name__)
37 log = logging.getLogger(__name__)
37
38
38
39
39 ADMIN_PREFIX = '/_admin'
40 ADMIN_PREFIX = '/_admin'
40 STATIC_FILE_PREFIX = '/_static'
41 STATIC_FILE_PREFIX = '/_static'
41
42
42 URL_NAME_REQUIREMENTS = {
43 URL_NAME_REQUIREMENTS = {
43 # group name can have a slash in them, but they must not end with a slash
44 # group name can have a slash in them, but they must not end with a slash
44 'group_name': r'.*?[^/]',
45 'group_name': r'.*?[^/]',
45 'repo_group_name': r'.*?[^/]',
46 'repo_group_name': r'.*?[^/]',
46 # repo names can have a slash in them, but they must not end with a slash
47 # repo names can have a slash in them, but they must not end with a slash
47 'repo_name': r'.*?[^/]',
48 'repo_name': r'.*?[^/]',
48 # file path eats up everything at the end
49 # file path eats up everything at the end
49 'f_path': r'.*',
50 'f_path': r'.*',
50 # reference types
51 # reference types
51 'source_ref_type': '(branch|book|tag|rev|\%\(source_ref_type\)s)',
52 'source_ref_type': '(branch|book|tag|rev|\%\(source_ref_type\)s)',
52 'target_ref_type': '(branch|book|tag|rev|\%\(target_ref_type\)s)',
53 'target_ref_type': '(branch|book|tag|rev|\%\(target_ref_type\)s)',
53 }
54 }
54
55
55
56
56 def add_route_with_slash(config,name, pattern, **kw):
57 def add_route_with_slash(config,name, pattern, **kw):
57 config.add_route(name, pattern, **kw)
58 config.add_route(name, pattern, **kw)
58 if not pattern.endswith('/'):
59 if not pattern.endswith('/'):
59 config.add_route(name + '_slash', pattern + '/', **kw)
60 config.add_route(name + '_slash', pattern + '/', **kw)
60
61
61
62
62 def add_route_requirements(route_path, requirements=URL_NAME_REQUIREMENTS):
63 def add_route_requirements(route_path, requirements=URL_NAME_REQUIREMENTS):
63 """
64 """
64 Adds regex requirements to pyramid routes using a mapping dict
65 Adds regex requirements to pyramid routes using a mapping dict
65 e.g::
66 e.g::
66 add_route_requirements('{repo_name}/settings')
67 add_route_requirements('{repo_name}/settings')
67 """
68 """
68 for key, regex in requirements.items():
69 for key, regex in requirements.items():
69 route_path = route_path.replace('{%s}' % key, '{%s:%s}' % (key, regex))
70 route_path = route_path.replace('{%s}' % key, '{%s:%s}' % (key, regex))
70 return route_path
71 return route_path
71
72
72
73
73 def get_format_ref_id(repo):
74 def get_format_ref_id(repo):
74 """Returns a `repo` specific reference formatter function"""
75 """Returns a `repo` specific reference formatter function"""
75 if h.is_svn(repo):
76 if h.is_svn(repo):
76 return _format_ref_id_svn
77 return _format_ref_id_svn
77 else:
78 else:
78 return _format_ref_id
79 return _format_ref_id
79
80
80
81
81 def _format_ref_id(name, raw_id):
82 def _format_ref_id(name, raw_id):
82 """Default formatting of a given reference `name`"""
83 """Default formatting of a given reference `name`"""
83 return name
84 return name
84
85
85
86
86 def _format_ref_id_svn(name, raw_id):
87 def _format_ref_id_svn(name, raw_id):
87 """Special way of formatting a reference for Subversion including path"""
88 """Special way of formatting a reference for Subversion including path"""
88 return '%s@%s' % (name, raw_id)
89 return '%s@%s' % (name, raw_id)
89
90
90
91
91 class TemplateArgs(StrictAttributeDict):
92 class TemplateArgs(StrictAttributeDict):
92 pass
93 pass
93
94
94
95
95 class BaseAppView(object):
96 class BaseAppView(object):
96
97
97 def __init__(self, context, request):
98 def __init__(self, context, request):
98 self.request = request
99 self.request = request
99 self.context = context
100 self.context = context
100 self.session = request.session
101 self.session = request.session
101 self._rhodecode_user = request.user # auth user
102 self._rhodecode_user = request.user # auth user
102 self._rhodecode_db_user = self._rhodecode_user.get_instance()
103 self._rhodecode_db_user = self._rhodecode_user.get_instance()
103 self._maybe_needs_password_change(
104 self._maybe_needs_password_change(
104 request.matched_route.name, self._rhodecode_db_user)
105 request.matched_route.name, self._rhodecode_db_user)
105
106
106 def _maybe_needs_password_change(self, view_name, user_obj):
107 def _maybe_needs_password_change(self, view_name, user_obj):
107 log.debug('Checking if user %s needs password change on view %s',
108 log.debug('Checking if user %s needs password change on view %s',
108 user_obj, view_name)
109 user_obj, view_name)
109 skip_user_views = [
110 skip_user_views = [
110 'logout', 'login',
111 'logout', 'login',
111 'my_account_password', 'my_account_password_update'
112 'my_account_password', 'my_account_password_update'
112 ]
113 ]
113
114
114 if not user_obj:
115 if not user_obj:
115 return
116 return
116
117
117 if user_obj.username == User.DEFAULT_USER:
118 if user_obj.username == User.DEFAULT_USER:
118 return
119 return
119
120
120 now = time.time()
121 now = time.time()
121 should_change = user_obj.user_data.get('force_password_change')
122 should_change = user_obj.user_data.get('force_password_change')
122 change_after = safe_int(should_change) or 0
123 change_after = safe_int(should_change) or 0
123 if should_change and now > change_after:
124 if should_change and now > change_after:
124 log.debug('User %s requires password change', user_obj)
125 log.debug('User %s requires password change', user_obj)
125 h.flash('You are required to change your password', 'warning',
126 h.flash('You are required to change your password', 'warning',
126 ignore_duplicate=True)
127 ignore_duplicate=True)
127
128
128 if view_name not in skip_user_views:
129 if view_name not in skip_user_views:
129 raise HTTPFound(
130 raise HTTPFound(
130 self.request.route_path('my_account_password'))
131 self.request.route_path('my_account_password'))
131
132
132 def _log_creation_exception(self, e, repo_name):
133 def _log_creation_exception(self, e, repo_name):
133 _ = self.request.translate
134 _ = self.request.translate
134 reason = None
135 reason = None
135 if len(e.args) == 2:
136 if len(e.args) == 2:
136 reason = e.args[1]
137 reason = e.args[1]
137
138
138 if reason == 'INVALID_CERTIFICATE':
139 if reason == 'INVALID_CERTIFICATE':
139 log.exception(
140 log.exception(
140 'Exception creating a repository: invalid certificate')
141 'Exception creating a repository: invalid certificate')
141 msg = (_('Error creating repository %s: invalid certificate')
142 msg = (_('Error creating repository %s: invalid certificate')
142 % repo_name)
143 % repo_name)
143 else:
144 else:
144 log.exception("Exception creating a repository")
145 log.exception("Exception creating a repository")
145 msg = (_('Error creating repository %s')
146 msg = (_('Error creating repository %s')
146 % repo_name)
147 % repo_name)
147 return msg
148 return msg
148
149
149 def _get_local_tmpl_context(self, include_app_defaults=False):
150 def _get_local_tmpl_context(self, include_app_defaults=False):
150 c = TemplateArgs()
151 c = TemplateArgs()
151 c.auth_user = self.request.user
152 c.auth_user = self.request.user
152 # TODO(marcink): migrate the usage of c.rhodecode_user to c.auth_user
153 # TODO(marcink): migrate the usage of c.rhodecode_user to c.auth_user
153 c.rhodecode_user = self.request.user
154 c.rhodecode_user = self.request.user
154
155
155 if include_app_defaults:
156 if include_app_defaults:
156 # NOTE(marcink): after full pyramid migration include_app_defaults
157 # NOTE(marcink): after full pyramid migration include_app_defaults
157 # should be turned on by default
158 # should be turned on by default
158 from rhodecode.lib.base import attach_context_attributes
159 from rhodecode.lib.base import attach_context_attributes
159 attach_context_attributes(c, self.request, self.request.user.user_id)
160 attach_context_attributes(c, self.request, self.request.user.user_id)
160
161
161 return c
162 return c
162
163
163 def _register_global_c(self, tmpl_args):
164 def _register_global_c(self, tmpl_args):
164 """
165 """
165 Registers attributes to pylons global `c`
166 Registers attributes to pylons global `c`
166 """
167 """
167
168
168 # TODO(marcink): remove once pyramid migration is finished
169 # TODO(marcink): remove once pyramid migration is finished
169 from pylons import tmpl_context as c
170 from pylons import tmpl_context as c
170 try:
171 try:
171 for k, v in tmpl_args.items():
172 for k, v in tmpl_args.items():
172 setattr(c, k, v)
173 setattr(c, k, v)
173 except TypeError:
174 except TypeError:
174 log.exception('Failed to register pylons C')
175 log.exception('Failed to register pylons C')
175 pass
176 pass
176
177
177 def _get_template_context(self, tmpl_args):
178 def _get_template_context(self, tmpl_args):
178 self._register_global_c(tmpl_args)
179 self._register_global_c(tmpl_args)
179
180
180 local_tmpl_args = {
181 local_tmpl_args = {
181 'defaults': {},
182 'defaults': {},
182 'errors': {},
183 'errors': {},
183 # register a fake 'c' to be used in templates instead of global
184 # register a fake 'c' to be used in templates instead of global
184 # pylons c, after migration to pyramid we should rename it to 'c'
185 # pylons c, after migration to pyramid we should rename it to 'c'
185 # make sure we replace usage of _c in templates too
186 # make sure we replace usage of _c in templates too
186 '_c': tmpl_args
187 '_c': tmpl_args
187 }
188 }
188 local_tmpl_args.update(tmpl_args)
189 local_tmpl_args.update(tmpl_args)
189 return local_tmpl_args
190 return local_tmpl_args
190
191
191 def load_default_context(self):
192 def load_default_context(self):
192 """
193 """
193 example:
194 example:
194
195
195 def load_default_context(self):
196 def load_default_context(self):
196 c = self._get_local_tmpl_context()
197 c = self._get_local_tmpl_context()
197 c.custom_var = 'foobar'
198 c.custom_var = 'foobar'
198 self._register_global_c(c)
199 self._register_global_c(c)
199 return c
200 return c
200 """
201 """
201 raise NotImplementedError('Needs implementation in view class')
202 raise NotImplementedError('Needs implementation in view class')
202
203
203
204
204 class RepoAppView(BaseAppView):
205 class RepoAppView(BaseAppView):
205
206
206 def __init__(self, context, request):
207 def __init__(self, context, request):
207 super(RepoAppView, self).__init__(context, request)
208 super(RepoAppView, self).__init__(context, request)
208 self.db_repo = request.db_repo
209 self.db_repo = request.db_repo
209 self.db_repo_name = self.db_repo.repo_name
210 self.db_repo_name = self.db_repo.repo_name
210 self.db_repo_pull_requests = ScmModel().get_pull_requests(self.db_repo)
211 self.db_repo_pull_requests = ScmModel().get_pull_requests(self.db_repo)
211
212
212 def _handle_missing_requirements(self, error):
213 def _handle_missing_requirements(self, error):
213 log.error(
214 log.error(
214 'Requirements are missing for repository %s: %s',
215 'Requirements are missing for repository %s: %s',
215 self.db_repo_name, error.message)
216 self.db_repo_name, error.message)
216
217
217 def _get_local_tmpl_context(self, include_app_defaults=False):
218 def _get_local_tmpl_context(self, include_app_defaults=False):
218 _ = self.request.translate
219 _ = self.request.translate
219 c = super(RepoAppView, self)._get_local_tmpl_context(
220 c = super(RepoAppView, self)._get_local_tmpl_context(
220 include_app_defaults=include_app_defaults)
221 include_app_defaults=include_app_defaults)
221
222
222 # register common vars for this type of view
223 # register common vars for this type of view
223 c.rhodecode_db_repo = self.db_repo
224 c.rhodecode_db_repo = self.db_repo
224 c.repo_name = self.db_repo_name
225 c.repo_name = self.db_repo_name
225 c.repository_pull_requests = self.db_repo_pull_requests
226 c.repository_pull_requests = self.db_repo_pull_requests
226
227
227 c.repository_requirements_missing = False
228 c.repository_requirements_missing = False
228 try:
229 try:
229 self.rhodecode_vcs_repo = self.db_repo.scm_instance()
230 self.rhodecode_vcs_repo = self.db_repo.scm_instance()
230 except RepositoryRequirementError as e:
231 except RepositoryRequirementError as e:
231 c.repository_requirements_missing = True
232 c.repository_requirements_missing = True
232 self._handle_missing_requirements(e)
233 self._handle_missing_requirements(e)
233 self.rhodecode_vcs_repo = None
234 self.rhodecode_vcs_repo = None
234
235
235 if (not c.repository_requirements_missing
236 if (not c.repository_requirements_missing
236 and self.rhodecode_vcs_repo is None):
237 and self.rhodecode_vcs_repo is None):
237 # unable to fetch this repo as vcs instance, report back to user
238 # unable to fetch this repo as vcs instance, report back to user
238 h.flash(_(
239 h.flash(_(
239 "The repository `%(repo_name)s` cannot be loaded in filesystem. "
240 "The repository `%(repo_name)s` cannot be loaded in filesystem. "
240 "Please check if it exist, or is not damaged.") %
241 "Please check if it exist, or is not damaged.") %
241 {'repo_name': c.repo_name},
242 {'repo_name': c.repo_name},
242 category='error', ignore_duplicate=True)
243 category='error', ignore_duplicate=True)
243 raise HTTPFound(h.route_path('home'))
244 raise HTTPFound(h.route_path('home'))
244
245
245 return c
246 return c
246
247
247 def _get_f_path(self, matchdict, default=None):
248 def _get_f_path(self, matchdict, default=None):
248 f_path = matchdict.get('f_path')
249 f_path = matchdict.get('f_path')
249 if f_path:
250 if f_path:
250 # fix for multiple initial slashes that causes errors for GIT
251 # fix for multiple initial slashes that causes errors for GIT
251 return f_path.lstrip('/')
252 return f_path.lstrip('/')
252
253
253 return default
254 return default
254
255
255
256
256 class RepoGroupAppView(BaseAppView):
257 class RepoGroupAppView(BaseAppView):
257 def __init__(self, context, request):
258 def __init__(self, context, request):
258 super(RepoGroupAppView, self).__init__(context, request)
259 super(RepoGroupAppView, self).__init__(context, request)
259 self.db_repo_group = request.db_repo_group
260 self.db_repo_group = request.db_repo_group
260 self.db_repo_group_name = self.db_repo_group.group_name
261 self.db_repo_group_name = self.db_repo_group.group_name
261
262
262
263
263 class UserGroupAppView(BaseAppView):
264 class UserGroupAppView(BaseAppView):
264 def __init__(self, context, request):
265 def __init__(self, context, request):
265 super(UserGroupAppView, self).__init__(context, request)
266 super(UserGroupAppView, self).__init__(context, request)
266 self.db_user_group = request.db_user_group
267 self.db_user_group = request.db_user_group
267 self.db_user_group_name = self.db_user_group.users_group_name
268 self.db_user_group_name = self.db_user_group.users_group_name
268
269
269
270
271 class UserAppView(BaseAppView):
272 def __init__(self, context, request):
273 super(UserAppView, self).__init__(context, request)
274 self.db_user = request.db_user
275 self.db_user_id = self.db_user.user_id
276
277 _ = self.request.translate
278 if not request.db_user_supports_default:
279 if self.db_user.username == User.DEFAULT_USER:
280 h.flash(_("Editing user `{}` is disabled.".format(
281 User.DEFAULT_USER)), category='warning')
282 raise HTTPFound(h.route_path('users'))
283
284
270 class DataGridAppView(object):
285 class DataGridAppView(object):
271 """
286 """
272 Common class to have re-usable grid rendering components
287 Common class to have re-usable grid rendering components
273 """
288 """
274
289
275 def _extract_ordering(self, request, column_map=None):
290 def _extract_ordering(self, request, column_map=None):
276 column_map = column_map or {}
291 column_map = column_map or {}
277 column_index = safe_int(request.GET.get('order[0][column]'))
292 column_index = safe_int(request.GET.get('order[0][column]'))
278 order_dir = request.GET.get(
293 order_dir = request.GET.get(
279 'order[0][dir]', 'desc')
294 'order[0][dir]', 'desc')
280 order_by = request.GET.get(
295 order_by = request.GET.get(
281 'columns[%s][data][sort]' % column_index, 'name_raw')
296 'columns[%s][data][sort]' % column_index, 'name_raw')
282
297
283 # translate datatable to DB columns
298 # translate datatable to DB columns
284 order_by = column_map.get(order_by) or order_by
299 order_by = column_map.get(order_by) or order_by
285
300
286 search_q = request.GET.get('search[value]')
301 search_q = request.GET.get('search[value]')
287 return search_q, order_by, order_dir
302 return search_q, order_by, order_dir
288
303
289 def _extract_chunk(self, request):
304 def _extract_chunk(self, request):
290 start = safe_int(request.GET.get('start'), 0)
305 start = safe_int(request.GET.get('start'), 0)
291 length = safe_int(request.GET.get('length'), 25)
306 length = safe_int(request.GET.get('length'), 25)
292 draw = safe_int(request.GET.get('draw'))
307 draw = safe_int(request.GET.get('draw'))
293 return draw, start, length
308 return draw, start, length
294
309
295 def _get_order_col(self, order_by, model):
310 def _get_order_col(self, order_by, model):
296 if isinstance(order_by, basestring):
311 if isinstance(order_by, basestring):
297 try:
312 try:
298 return operator.attrgetter(order_by)(model)
313 return operator.attrgetter(order_by)(model)
299 except AttributeError:
314 except AttributeError:
300 return None
315 return None
301 else:
316 else:
302 return order_by
317 return order_by
303
318
304
319
305 class BaseReferencesView(RepoAppView):
320 class BaseReferencesView(RepoAppView):
306 """
321 """
307 Base for reference view for branches, tags and bookmarks.
322 Base for reference view for branches, tags and bookmarks.
308 """
323 """
309 def load_default_context(self):
324 def load_default_context(self):
310 c = self._get_local_tmpl_context()
325 c = self._get_local_tmpl_context()
311
326
312 self._register_global_c(c)
327 self._register_global_c(c)
313 return c
328 return c
314
329
315 def load_refs_context(self, ref_items, partials_template):
330 def load_refs_context(self, ref_items, partials_template):
316 _render = self.request.get_partial_renderer(partials_template)
331 _render = self.request.get_partial_renderer(partials_template)
317 pre_load = ["author", "date", "message"]
332 pre_load = ["author", "date", "message"]
318
333
319 is_svn = h.is_svn(self.rhodecode_vcs_repo)
334 is_svn = h.is_svn(self.rhodecode_vcs_repo)
320 is_hg = h.is_hg(self.rhodecode_vcs_repo)
335 is_hg = h.is_hg(self.rhodecode_vcs_repo)
321
336
322 format_ref_id = get_format_ref_id(self.rhodecode_vcs_repo)
337 format_ref_id = get_format_ref_id(self.rhodecode_vcs_repo)
323
338
324 closed_refs = {}
339 closed_refs = {}
325 if is_hg:
340 if is_hg:
326 closed_refs = self.rhodecode_vcs_repo.branches_closed
341 closed_refs = self.rhodecode_vcs_repo.branches_closed
327
342
328 data = []
343 data = []
329 for ref_name, commit_id in ref_items:
344 for ref_name, commit_id in ref_items:
330 commit = self.rhodecode_vcs_repo.get_commit(
345 commit = self.rhodecode_vcs_repo.get_commit(
331 commit_id=commit_id, pre_load=pre_load)
346 commit_id=commit_id, pre_load=pre_load)
332 closed = ref_name in closed_refs
347 closed = ref_name in closed_refs
333
348
334 # TODO: johbo: Unify generation of reference links
349 # TODO: johbo: Unify generation of reference links
335 use_commit_id = '/' in ref_name or is_svn
350 use_commit_id = '/' in ref_name or is_svn
336
351
337 if use_commit_id:
352 if use_commit_id:
338 files_url = h.route_path(
353 files_url = h.route_path(
339 'repo_files',
354 'repo_files',
340 repo_name=self.db_repo_name,
355 repo_name=self.db_repo_name,
341 f_path=ref_name if is_svn else '',
356 f_path=ref_name if is_svn else '',
342 commit_id=commit_id)
357 commit_id=commit_id)
343
358
344 else:
359 else:
345 files_url = h.route_path(
360 files_url = h.route_path(
346 'repo_files',
361 'repo_files',
347 repo_name=self.db_repo_name,
362 repo_name=self.db_repo_name,
348 f_path=ref_name if is_svn else '',
363 f_path=ref_name if is_svn else '',
349 commit_id=ref_name,
364 commit_id=ref_name,
350 _query=dict(at=ref_name))
365 _query=dict(at=ref_name))
351
366
352 data.append({
367 data.append({
353 "name": _render('name', ref_name, files_url, closed),
368 "name": _render('name', ref_name, files_url, closed),
354 "name_raw": ref_name,
369 "name_raw": ref_name,
355 "date": _render('date', commit.date),
370 "date": _render('date', commit.date),
356 "date_raw": datetime_to_time(commit.date),
371 "date_raw": datetime_to_time(commit.date),
357 "author": _render('author', commit.author),
372 "author": _render('author', commit.author),
358 "commit": _render(
373 "commit": _render(
359 'commit', commit.message, commit.raw_id, commit.idx),
374 'commit', commit.message, commit.raw_id, commit.idx),
360 "commit_raw": commit.idx,
375 "commit_raw": commit.idx,
361 "compare": _render(
376 "compare": _render(
362 'compare', format_ref_id(ref_name, commit.raw_id)),
377 'compare', format_ref_id(ref_name, commit.raw_id)),
363 })
378 })
364
379
365 return data
380 return data
366
381
367
382
368 class RepoRoutePredicate(object):
383 class RepoRoutePredicate(object):
369 def __init__(self, val, config):
384 def __init__(self, val, config):
370 self.val = val
385 self.val = val
371
386
372 def text(self):
387 def text(self):
373 return 'repo_route = %s' % self.val
388 return 'repo_route = %s' % self.val
374
389
375 phash = text
390 phash = text
376
391
377 def __call__(self, info, request):
392 def __call__(self, info, request):
378
393
379 if hasattr(request, 'vcs_call'):
394 if hasattr(request, 'vcs_call'):
380 # skip vcs calls
395 # skip vcs calls
381 return
396 return
382
397
383 repo_name = info['match']['repo_name']
398 repo_name = info['match']['repo_name']
384 repo_model = repo.RepoModel()
399 repo_model = repo.RepoModel()
385 by_name_match = repo_model.get_by_repo_name(repo_name, cache=True)
400 by_name_match = repo_model.get_by_repo_name(repo_name, cache=True)
386
401
387 def redirect_if_creating(db_repo):
402 def redirect_if_creating(db_repo):
388 if db_repo.repo_state in [repo.Repository.STATE_PENDING]:
403 if db_repo.repo_state in [repo.Repository.STATE_PENDING]:
389 raise HTTPFound(
404 raise HTTPFound(
390 request.route_path('repo_creating',
405 request.route_path('repo_creating',
391 repo_name=db_repo.repo_name))
406 repo_name=db_repo.repo_name))
392
407
393 if by_name_match:
408 if by_name_match:
394 # register this as request object we can re-use later
409 # register this as request object we can re-use later
395 request.db_repo = by_name_match
410 request.db_repo = by_name_match
396 redirect_if_creating(by_name_match)
411 redirect_if_creating(by_name_match)
397 return True
412 return True
398
413
399 by_id_match = repo_model.get_repo_by_id(repo_name)
414 by_id_match = repo_model.get_repo_by_id(repo_name)
400 if by_id_match:
415 if by_id_match:
401 request.db_repo = by_id_match
416 request.db_repo = by_id_match
402 redirect_if_creating(by_id_match)
417 redirect_if_creating(by_id_match)
403 return True
418 return True
404
419
405 return False
420 return False
406
421
407
422
408 class RepoTypeRoutePredicate(object):
423 class RepoTypeRoutePredicate(object):
409 def __init__(self, val, config):
424 def __init__(self, val, config):
410 self.val = val or ['hg', 'git', 'svn']
425 self.val = val or ['hg', 'git', 'svn']
411
426
412 def text(self):
427 def text(self):
413 return 'repo_accepted_type = %s' % self.val
428 return 'repo_accepted_type = %s' % self.val
414
429
415 phash = text
430 phash = text
416
431
417 def __call__(self, info, request):
432 def __call__(self, info, request):
418 if hasattr(request, 'vcs_call'):
433 if hasattr(request, 'vcs_call'):
419 # skip vcs calls
434 # skip vcs calls
420 return
435 return
421
436
422 rhodecode_db_repo = request.db_repo
437 rhodecode_db_repo = request.db_repo
423
438
424 log.debug(
439 log.debug(
425 '%s checking repo type for %s in %s',
440 '%s checking repo type for %s in %s',
426 self.__class__.__name__, rhodecode_db_repo.repo_type, self.val)
441 self.__class__.__name__, rhodecode_db_repo.repo_type, self.val)
427
442
428 if rhodecode_db_repo.repo_type in self.val:
443 if rhodecode_db_repo.repo_type in self.val:
429 return True
444 return True
430 else:
445 else:
431 log.warning('Current view is not supported for repo type:%s',
446 log.warning('Current view is not supported for repo type:%s',
432 rhodecode_db_repo.repo_type)
447 rhodecode_db_repo.repo_type)
433 #
448 #
434 # h.flash(h.literal(
449 # h.flash(h.literal(
435 # _('Action not supported for %s.' % rhodecode_repo.alias)),
450 # _('Action not supported for %s.' % rhodecode_repo.alias)),
436 # category='warning')
451 # category='warning')
437 # return redirect(
452 # return redirect(
438 # route_path('repo_summary', repo_name=cls.rhodecode_db_repo.repo_name))
453 # route_path('repo_summary', repo_name=cls.rhodecode_db_repo.repo_name))
439
454
440 return False
455 return False
441
456
442
457
443 class RepoGroupRoutePredicate(object):
458 class RepoGroupRoutePredicate(object):
444 def __init__(self, val, config):
459 def __init__(self, val, config):
445 self.val = val
460 self.val = val
446
461
447 def text(self):
462 def text(self):
448 return 'repo_group_route = %s' % self.val
463 return 'repo_group_route = %s' % self.val
449
464
450 phash = text
465 phash = text
451
466
452 def __call__(self, info, request):
467 def __call__(self, info, request):
453 if hasattr(request, 'vcs_call'):
468 if hasattr(request, 'vcs_call'):
454 # skip vcs calls
469 # skip vcs calls
455 return
470 return
456
471
457 repo_group_name = info['match']['repo_group_name']
472 repo_group_name = info['match']['repo_group_name']
458 repo_group_model = repo_group.RepoGroupModel()
473 repo_group_model = repo_group.RepoGroupModel()
459 by_name_match = repo_group_model.get_by_group_name(
474 by_name_match = repo_group_model.get_by_group_name(
460 repo_group_name, cache=True)
475 repo_group_name, cache=True)
461
476
462 if by_name_match:
477 if by_name_match:
463 # register this as request object we can re-use later
478 # register this as request object we can re-use later
464 request.db_repo_group = by_name_match
479 request.db_repo_group = by_name_match
465 return True
480 return True
466
481
467 return False
482 return False
468
483
469
484
470 class UserGroupRoutePredicate(object):
485 class UserGroupRoutePredicate(object):
471 def __init__(self, val, config):
486 def __init__(self, val, config):
472 self.val = val
487 self.val = val
473
488
474 def text(self):
489 def text(self):
475 return 'user_group_route = %s' % self.val
490 return 'user_group_route = %s' % self.val
476
491
477 phash = text
492 phash = text
478
493
479 def __call__(self, info, request):
494 def __call__(self, info, request):
480 if hasattr(request, 'vcs_call'):
495 if hasattr(request, 'vcs_call'):
481 # skip vcs calls
496 # skip vcs calls
482 return
497 return
483
498
484 user_group_id = info['match']['user_group_id']
499 user_group_id = info['match']['user_group_id']
485 user_group_model = user_group.UserGroup()
500 user_group_model = user_group.UserGroup()
486 by_name_match = user_group_model.get(
501 by_id_match = user_group_model.get(
487 user_group_id, cache=True)
502 user_group_id, cache=True)
488
503
489 if by_name_match:
504 if by_id_match:
490 # register this as request object we can re-use later
505 # register this as request object we can re-use later
491 request.db_user_group = by_name_match
506 request.db_user_group = by_id_match
492 return True
507 return True
493
508
494 return False
509 return False
495
510
496
511
512 class UserRoutePredicateBase(object):
513 supports_default = None
514
515 def __init__(self, val, config):
516 self.val = val
517
518 def text(self):
519 raise NotImplementedError()
520
521 def __call__(self, info, request):
522 if hasattr(request, 'vcs_call'):
523 # skip vcs calls
524 return
525
526 user_id = info['match']['user_id']
527 user_model = user.User()
528 by_id_match = user_model.get(
529 user_id, cache=True)
530
531 if by_id_match:
532 # register this as request object we can re-use later
533 request.db_user = by_id_match
534 request.db_user_supports_default = self.supports_default
535 return True
536
537 return False
538
539
540 class UserRoutePredicate(UserRoutePredicateBase):
541 supports_default = False
542
543 def text(self):
544 return 'user_route = %s' % self.val
545
546 phash = text
547
548
549 class UserRouteWithDefaultPredicate(UserRoutePredicateBase):
550 supports_default = True
551
552 def text(self):
553 return 'user_with_default_route = %s' % self.val
554
555 phash = text
556
557
497 def includeme(config):
558 def includeme(config):
498 config.add_route_predicate(
559 config.add_route_predicate(
499 'repo_route', RepoRoutePredicate)
560 'repo_route', RepoRoutePredicate)
500 config.add_route_predicate(
561 config.add_route_predicate(
501 'repo_accepted_types', RepoTypeRoutePredicate)
562 'repo_accepted_types', RepoTypeRoutePredicate)
502 config.add_route_predicate(
563 config.add_route_predicate(
503 'repo_group_route', RepoGroupRoutePredicate)
564 'repo_group_route', RepoGroupRoutePredicate)
504 config.add_route_predicate(
565 config.add_route_predicate(
505 'user_group_route', UserGroupRoutePredicate)
566 'user_group_route', UserGroupRoutePredicate)
567 config.add_route_predicate(
568 'user_route_with_default', UserRouteWithDefaultPredicate)
569 config.add_route_predicate(
570 'user_route', UserRoutePredicate) No newline at end of file
@@ -1,253 +1,312 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
21
22 from rhodecode.apps.admin.navigation import NavigationRegistry
22 from rhodecode.apps.admin.navigation import NavigationRegistry
23 from rhodecode.config.routing import ADMIN_PREFIX
23 from rhodecode.config.routing import ADMIN_PREFIX
24 from rhodecode.lib.utils2 import str2bool
24 from rhodecode.lib.utils2 import str2bool
25
25
26
26
27 def admin_routes(config):
27 def admin_routes(config):
28 """
28 """
29 Admin prefixed routes
29 Admin prefixed routes
30 """
30 """
31
31
32 config.add_route(
32 config.add_route(
33 name='admin_audit_logs',
33 name='admin_audit_logs',
34 pattern='/audit_logs')
34 pattern='/audit_logs')
35
35
36 config.add_route(
36 config.add_route(
37 name='admin_audit_log_entry',
37 name='admin_audit_log_entry',
38 pattern='/audit_logs/{audit_log_id}')
38 pattern='/audit_logs/{audit_log_id}')
39
39
40 config.add_route(
40 config.add_route(
41 name='pull_requests_global_0', # backward compat
41 name='pull_requests_global_0', # backward compat
42 pattern='/pull_requests/{pull_request_id:\d+}')
42 pattern='/pull_requests/{pull_request_id:\d+}')
43 config.add_route(
43 config.add_route(
44 name='pull_requests_global_1', # backward compat
44 name='pull_requests_global_1', # backward compat
45 pattern='/pull-requests/{pull_request_id:\d+}')
45 pattern='/pull-requests/{pull_request_id:\d+}')
46 config.add_route(
46 config.add_route(
47 name='pull_requests_global',
47 name='pull_requests_global',
48 pattern='/pull-request/{pull_request_id:\d+}')
48 pattern='/pull-request/{pull_request_id:\d+}')
49
49
50 config.add_route(
50 config.add_route(
51 name='admin_settings_open_source',
51 name='admin_settings_open_source',
52 pattern='/settings/open_source')
52 pattern='/settings/open_source')
53 config.add_route(
53 config.add_route(
54 name='admin_settings_vcs_svn_generate_cfg',
54 name='admin_settings_vcs_svn_generate_cfg',
55 pattern='/settings/vcs/svn_generate_cfg')
55 pattern='/settings/vcs/svn_generate_cfg')
56
56
57 config.add_route(
57 config.add_route(
58 name='admin_settings_system',
58 name='admin_settings_system',
59 pattern='/settings/system')
59 pattern='/settings/system')
60 config.add_route(
60 config.add_route(
61 name='admin_settings_system_update',
61 name='admin_settings_system_update',
62 pattern='/settings/system/updates')
62 pattern='/settings/system/updates')
63
63
64 config.add_route(
64 config.add_route(
65 name='admin_settings_sessions',
65 name='admin_settings_sessions',
66 pattern='/settings/sessions')
66 pattern='/settings/sessions')
67 config.add_route(
67 config.add_route(
68 name='admin_settings_sessions_cleanup',
68 name='admin_settings_sessions_cleanup',
69 pattern='/settings/sessions/cleanup')
69 pattern='/settings/sessions/cleanup')
70
70
71 config.add_route(
71 config.add_route(
72 name='admin_settings_process_management',
72 name='admin_settings_process_management',
73 pattern='/settings/process_management')
73 pattern='/settings/process_management')
74 config.add_route(
74 config.add_route(
75 name='admin_settings_process_management_signal',
75 name='admin_settings_process_management_signal',
76 pattern='/settings/process_management/signal')
76 pattern='/settings/process_management/signal')
77
77
78 # default settings
78 # default settings
79 config.add_route(
79 config.add_route(
80 name='admin_defaults_repositories',
80 name='admin_defaults_repositories',
81 pattern='/defaults/repositories')
81 pattern='/defaults/repositories')
82 config.add_route(
82 config.add_route(
83 name='admin_defaults_repositories_update',
83 name='admin_defaults_repositories_update',
84 pattern='/defaults/repositories/update')
84 pattern='/defaults/repositories/update')
85
85
86 # global permissions
86 # global permissions
87
87
88 config.add_route(
88 config.add_route(
89 name='admin_permissions_application',
89 name='admin_permissions_application',
90 pattern='/permissions/application')
90 pattern='/permissions/application')
91 config.add_route(
91 config.add_route(
92 name='admin_permissions_application_update',
92 name='admin_permissions_application_update',
93 pattern='/permissions/application/update')
93 pattern='/permissions/application/update')
94
94
95 config.add_route(
95 config.add_route(
96 name='admin_permissions_global',
96 name='admin_permissions_global',
97 pattern='/permissions/global')
97 pattern='/permissions/global')
98 config.add_route(
98 config.add_route(
99 name='admin_permissions_global_update',
99 name='admin_permissions_global_update',
100 pattern='/permissions/global/update')
100 pattern='/permissions/global/update')
101
101
102 config.add_route(
102 config.add_route(
103 name='admin_permissions_object',
103 name='admin_permissions_object',
104 pattern='/permissions/object')
104 pattern='/permissions/object')
105 config.add_route(
105 config.add_route(
106 name='admin_permissions_object_update',
106 name='admin_permissions_object_update',
107 pattern='/permissions/object/update')
107 pattern='/permissions/object/update')
108
108
109 config.add_route(
109 config.add_route(
110 name='admin_permissions_ips',
110 name='admin_permissions_ips',
111 pattern='/permissions/ips')
111 pattern='/permissions/ips')
112
112
113 config.add_route(
113 config.add_route(
114 name='admin_permissions_overview',
114 name='admin_permissions_overview',
115 pattern='/permissions/overview')
115 pattern='/permissions/overview')
116
116
117 config.add_route(
117 config.add_route(
118 name='admin_permissions_auth_token_access',
118 name='admin_permissions_auth_token_access',
119 pattern='/permissions/auth_token_access')
119 pattern='/permissions/auth_token_access')
120
120
121 config.add_route(
121 config.add_route(
122 name='admin_permissions_ssh_keys',
122 name='admin_permissions_ssh_keys',
123 pattern='/permissions/ssh_keys')
123 pattern='/permissions/ssh_keys')
124 config.add_route(
124 config.add_route(
125 name='admin_permissions_ssh_keys_data',
125 name='admin_permissions_ssh_keys_data',
126 pattern='/permissions/ssh_keys/data')
126 pattern='/permissions/ssh_keys/data')
127 config.add_route(
127 config.add_route(
128 name='admin_permissions_ssh_keys_update',
128 name='admin_permissions_ssh_keys_update',
129 pattern='/permissions/ssh_keys/update')
129 pattern='/permissions/ssh_keys/update')
130
130
131 # users admin
131 # users admin
132 config.add_route(
132 config.add_route(
133 name='users',
133 name='users',
134 pattern='/users')
134 pattern='/users')
135
135
136 config.add_route(
136 config.add_route(
137 name='users_data',
137 name='users_data',
138 pattern='/users_data')
138 pattern='/users_data')
139
139
140 config.add_route(
141 name='users_create',
142 pattern='/users/create')
143
144 config.add_route(
145 name='users_new',
146 pattern='/users/new')
147
148 # user management
149 config.add_route(
150 name='user_edit',
151 pattern='/users/{user_id:\d+}/edit',
152 user_route=True)
153 config.add_route(
154 name='user_edit_advanced',
155 pattern='/users/{user_id:\d+}/edit/advanced',
156 user_route=True)
157 config.add_route(
158 name='user_edit_global_perms',
159 pattern='/users/{user_id:\d+}/edit/global_permissions',
160 user_route=True)
161 config.add_route(
162 name='user_edit_global_perms_update',
163 pattern='/users/{user_id:\d+}/edit/global_permissions/update',
164 user_route=True)
165 config.add_route(
166 name='user_update',
167 pattern='/users/{user_id:\d+}/update',
168 user_route=True)
169 config.add_route(
170 name='user_delete',
171 pattern='/users/{user_id:\d+}/delete',
172 user_route=True)
173 config.add_route(
174 name='user_force_password_reset',
175 pattern='/users/{user_id:\d+}/password_reset',
176 user_route=True)
177 config.add_route(
178 name='user_create_personal_repo_group',
179 pattern='/users/{user_id:\d+}/create_repo_group',
180 user_route=True)
181
140 # user auth tokens
182 # user auth tokens
141 config.add_route(
183 config.add_route(
142 name='edit_user_auth_tokens',
184 name='edit_user_auth_tokens',
143 pattern='/users/{user_id:\d+}/edit/auth_tokens')
185 pattern='/users/{user_id:\d+}/edit/auth_tokens',
186 user_route=True)
144 config.add_route(
187 config.add_route(
145 name='edit_user_auth_tokens_add',
188 name='edit_user_auth_tokens_add',
146 pattern='/users/{user_id:\d+}/edit/auth_tokens/new')
189 pattern='/users/{user_id:\d+}/edit/auth_tokens/new',
190 user_route=True)
147 config.add_route(
191 config.add_route(
148 name='edit_user_auth_tokens_delete',
192 name='edit_user_auth_tokens_delete',
149 pattern='/users/{user_id:\d+}/edit/auth_tokens/delete')
193 pattern='/users/{user_id:\d+}/edit/auth_tokens/delete',
194 user_route=True)
150
195
151 # user ssh keys
196 # user ssh keys
152 config.add_route(
197 config.add_route(
153 name='edit_user_ssh_keys',
198 name='edit_user_ssh_keys',
154 pattern='/users/{user_id:\d+}/edit/ssh_keys')
199 pattern='/users/{user_id:\d+}/edit/ssh_keys',
200 user_route=True)
155 config.add_route(
201 config.add_route(
156 name='edit_user_ssh_keys_generate_keypair',
202 name='edit_user_ssh_keys_generate_keypair',
157 pattern='/users/{user_id:\d+}/edit/ssh_keys/generate')
203 pattern='/users/{user_id:\d+}/edit/ssh_keys/generate',
204 user_route=True)
158 config.add_route(
205 config.add_route(
159 name='edit_user_ssh_keys_add',
206 name='edit_user_ssh_keys_add',
160 pattern='/users/{user_id:\d+}/edit/ssh_keys/new')
207 pattern='/users/{user_id:\d+}/edit/ssh_keys/new',
208 user_route=True)
161 config.add_route(
209 config.add_route(
162 name='edit_user_ssh_keys_delete',
210 name='edit_user_ssh_keys_delete',
163 pattern='/users/{user_id:\d+}/edit/ssh_keys/delete')
211 pattern='/users/{user_id:\d+}/edit/ssh_keys/delete',
212 user_route=True)
164
213
165 # user emails
214 # user emails
166 config.add_route(
215 config.add_route(
167 name='edit_user_emails',
216 name='edit_user_emails',
168 pattern='/users/{user_id:\d+}/edit/emails')
217 pattern='/users/{user_id:\d+}/edit/emails',
218 user_route=True)
169 config.add_route(
219 config.add_route(
170 name='edit_user_emails_add',
220 name='edit_user_emails_add',
171 pattern='/users/{user_id:\d+}/edit/emails/new')
221 pattern='/users/{user_id:\d+}/edit/emails/new',
222 user_route=True)
172 config.add_route(
223 config.add_route(
173 name='edit_user_emails_delete',
224 name='edit_user_emails_delete',
174 pattern='/users/{user_id:\d+}/edit/emails/delete')
225 pattern='/users/{user_id:\d+}/edit/emails/delete',
226 user_route=True)
175
227
176 # user IPs
228 # user IPs
177 config.add_route(
229 config.add_route(
178 name='edit_user_ips',
230 name='edit_user_ips',
179 pattern='/users/{user_id:\d+}/edit/ips')
231 pattern='/users/{user_id:\d+}/edit/ips',
232 user_route=True)
180 config.add_route(
233 config.add_route(
181 name='edit_user_ips_add',
234 name='edit_user_ips_add',
182 pattern='/users/{user_id:\d+}/edit/ips/new')
235 pattern='/users/{user_id:\d+}/edit/ips/new',
236 user_route_with_default=True) # enabled for default user too
183 config.add_route(
237 config.add_route(
184 name='edit_user_ips_delete',
238 name='edit_user_ips_delete',
185 pattern='/users/{user_id:\d+}/edit/ips/delete')
239 pattern='/users/{user_id:\d+}/edit/ips/delete',
240 user_route_with_default=True) # enabled for default user too
186
241
187 # user perms
242 # user perms
188 config.add_route(
243 config.add_route(
189 name='edit_user_perms_summary',
244 name='edit_user_perms_summary',
190 pattern='/users/{user_id:\d+}/edit/permissions_summary')
245 pattern='/users/{user_id:\d+}/edit/permissions_summary',
246 user_route=True)
191 config.add_route(
247 config.add_route(
192 name='edit_user_perms_summary_json',
248 name='edit_user_perms_summary_json',
193 pattern='/users/{user_id:\d+}/edit/permissions_summary/json')
249 pattern='/users/{user_id:\d+}/edit/permissions_summary/json',
250 user_route=True)
194
251
195 # user user groups management
252 # user user groups management
196 config.add_route(
253 config.add_route(
197 name='edit_user_groups_management',
254 name='edit_user_groups_management',
198 pattern='/users/{user_id:\d+}/edit/groups_management')
255 pattern='/users/{user_id:\d+}/edit/groups_management',
256 user_route=True)
199
257
200 config.add_route(
258 config.add_route(
201 name='edit_user_groups_management_updates',
259 name='edit_user_groups_management_updates',
202 pattern='/users/{user_id:\d+}/edit/edit_user_groups_management/updates')
260 pattern='/users/{user_id:\d+}/edit/edit_user_groups_management/updates',
261 user_route=True)
203
262
204 # user audit logs
263 # user audit logs
205 config.add_route(
264 config.add_route(
206 name='edit_user_audit_logs',
265 name='edit_user_audit_logs',
207 pattern='/users/{user_id:\d+}/edit/audit')
266 pattern='/users/{user_id:\d+}/edit/audit', user_route=True)
208
267
209 # user-groups admin
268 # user-groups admin
210 config.add_route(
269 config.add_route(
211 name='user_groups',
270 name='user_groups',
212 pattern='/user_groups')
271 pattern='/user_groups')
213
272
214 config.add_route(
273 config.add_route(
215 name='user_groups_data',
274 name='user_groups_data',
216 pattern='/user_groups_data')
275 pattern='/user_groups_data')
217
276
218 config.add_route(
277 config.add_route(
219 name='user_groups_new',
278 name='user_groups_new',
220 pattern='/user_groups/new')
279 pattern='/user_groups/new')
221
280
222 config.add_route(
281 config.add_route(
223 name='user_groups_create',
282 name='user_groups_create',
224 pattern='/user_groups/create')
283 pattern='/user_groups/create')
225
284
226 # repos admin
285 # repos admin
227 config.add_route(
286 config.add_route(
228 name='repos',
287 name='repos',
229 pattern='/repos')
288 pattern='/repos')
230
289
231 config.add_route(
290 config.add_route(
232 name='repo_new',
291 name='repo_new',
233 pattern='/repos/new')
292 pattern='/repos/new')
234
293
235 config.add_route(
294 config.add_route(
236 name='repo_create',
295 name='repo_create',
237 pattern='/repos/create')
296 pattern='/repos/create')
238
297
239
298
240 def includeme(config):
299 def includeme(config):
241 settings = config.get_settings()
300 settings = config.get_settings()
242
301
243 # Create admin navigation registry and add it to the pyramid registry.
302 # Create admin navigation registry and add it to the pyramid registry.
244 labs_active = str2bool(settings.get('labs_settings_active', False))
303 labs_active = str2bool(settings.get('labs_settings_active', False))
245 navigation_registry = NavigationRegistry(labs_active=labs_active)
304 navigation_registry = NavigationRegistry(labs_active=labs_active)
246 config.registry.registerUtility(navigation_registry)
305 config.registry.registerUtility(navigation_registry)
247
306
248 # main admin routes
307 # main admin routes
249 config.add_route(name='admin_home', pattern=ADMIN_PREFIX)
308 config.add_route(name='admin_home', pattern=ADMIN_PREFIX)
250 config.include(admin_routes, route_prefix=ADMIN_PREFIX)
309 config.include(admin_routes, route_prefix=ADMIN_PREFIX)
251
310
252 # Scan module for configuration decorators.
311 # Scan module for configuration decorators.
253 config.scan('.views', ignore='.tests')
312 config.scan('.views', ignore='.tests')
This diff has been collapsed as it changes many lines, (516 lines changed) Show them Hide them
@@ -1,281 +1,783 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 import pytest
21 import pytest
22 from sqlalchemy.orm.exc import NoResultFound
22
23
23 from rhodecode.model.db import User, UserApiKeys, UserEmailMap
24 from rhodecode.lib import auth
25 from rhodecode.lib import helpers as h
26 from rhodecode.model import validators
27 from rhodecode.model.db import User, UserApiKeys, UserEmailMap, Repository
24 from rhodecode.model.meta import Session
28 from rhodecode.model.meta import Session
25 from rhodecode.model.user import UserModel
29 from rhodecode.model.user import UserModel
26
30
27 from rhodecode.tests import (
31 from rhodecode.tests import (
28 TestController, TEST_USER_REGULAR_LOGIN, assert_session_flash)
32 TestController, TEST_USER_REGULAR_LOGIN, assert_session_flash)
29 from rhodecode.tests.fixture import Fixture
33 from rhodecode.tests.fixture import Fixture
30
34
31 fixture = Fixture()
35 fixture = Fixture()
32
36
33
37
34 def route_path(name, params=None, **kwargs):
38 def route_path(name, params=None, **kwargs):
35 import urllib
39 import urllib
36 from rhodecode.apps._base import ADMIN_PREFIX
40 from rhodecode.apps._base import ADMIN_PREFIX
37
41
38 base_url = {
42 base_url = {
39 'users':
43 'users':
40 ADMIN_PREFIX + '/users',
44 ADMIN_PREFIX + '/users',
41 'users_data':
45 'users_data':
42 ADMIN_PREFIX + '/users_data',
46 ADMIN_PREFIX + '/users_data',
47 'users_create':
48 ADMIN_PREFIX + '/users/create',
49 'users_new':
50 ADMIN_PREFIX + '/users/new',
51 'user_edit':
52 ADMIN_PREFIX + '/users/{user_id}/edit',
53 'user_edit_advanced':
54 ADMIN_PREFIX + '/users/{user_id}/edit/advanced',
55 'user_edit_global_perms':
56 ADMIN_PREFIX + '/users/{user_id}/edit/global_permissions',
57 'user_edit_global_perms_update':
58 ADMIN_PREFIX + '/users/{user_id}/edit/global_permissions/update',
59 'user_update':
60 ADMIN_PREFIX + '/users/{user_id}/update',
61 'user_delete':
62 ADMIN_PREFIX + '/users/{user_id}/delete',
63 'user_force_password_reset':
64 ADMIN_PREFIX + '/users/{user_id}/password_reset',
65 'user_create_personal_repo_group':
66 ADMIN_PREFIX + '/users/{user_id}/create_repo_group',
67
43 'edit_user_auth_tokens':
68 'edit_user_auth_tokens':
44 ADMIN_PREFIX + '/users/{user_id}/edit/auth_tokens',
69 ADMIN_PREFIX + '/users/{user_id}/edit/auth_tokens',
45 'edit_user_auth_tokens_add':
70 'edit_user_auth_tokens_add':
46 ADMIN_PREFIX + '/users/{user_id}/edit/auth_tokens/new',
71 ADMIN_PREFIX + '/users/{user_id}/edit/auth_tokens/new',
47 'edit_user_auth_tokens_delete':
72 'edit_user_auth_tokens_delete':
48 ADMIN_PREFIX + '/users/{user_id}/edit/auth_tokens/delete',
73 ADMIN_PREFIX + '/users/{user_id}/edit/auth_tokens/delete',
49
74
50 'edit_user_emails':
75 'edit_user_emails':
51 ADMIN_PREFIX + '/users/{user_id}/edit/emails',
76 ADMIN_PREFIX + '/users/{user_id}/edit/emails',
52 'edit_user_emails_add':
77 'edit_user_emails_add':
53 ADMIN_PREFIX + '/users/{user_id}/edit/emails/new',
78 ADMIN_PREFIX + '/users/{user_id}/edit/emails/new',
54 'edit_user_emails_delete':
79 'edit_user_emails_delete':
55 ADMIN_PREFIX + '/users/{user_id}/edit/emails/delete',
80 ADMIN_PREFIX + '/users/{user_id}/edit/emails/delete',
56
81
57 'edit_user_ips':
82 'edit_user_ips':
58 ADMIN_PREFIX + '/users/{user_id}/edit/ips',
83 ADMIN_PREFIX + '/users/{user_id}/edit/ips',
59 'edit_user_ips_add':
84 'edit_user_ips_add':
60 ADMIN_PREFIX + '/users/{user_id}/edit/ips/new',
85 ADMIN_PREFIX + '/users/{user_id}/edit/ips/new',
61 'edit_user_ips_delete':
86 'edit_user_ips_delete':
62 ADMIN_PREFIX + '/users/{user_id}/edit/ips/delete',
87 ADMIN_PREFIX + '/users/{user_id}/edit/ips/delete',
88
89 'edit_user_perms_summary':
90 ADMIN_PREFIX + '/users/{user_id}/edit/permissions_summary',
91 'edit_user_perms_summary_json':
92 ADMIN_PREFIX + '/users/{user_id}/edit/permissions_summary/json',
93
94 'edit_user_audit_logs':
95 ADMIN_PREFIX + '/users/{user_id}/edit/audit',
96
63 }[name].format(**kwargs)
97 }[name].format(**kwargs)
64
98
65 if params:
99 if params:
66 base_url = '{}?{}'.format(base_url, urllib.urlencode(params))
100 base_url = '{}?{}'.format(base_url, urllib.urlencode(params))
67 return base_url
101 return base_url
68
102
69
103
70 class TestAdminUsersView(TestController):
104 class TestAdminUsersView(TestController):
71
105
72 def test_show_users(self):
106 def test_show_users(self):
73 self.log_user()
107 self.log_user()
74 self.app.get(route_path('users'))
108 self.app.get(route_path('users'))
75
109
76 def test_show_users_data(self, xhr_header):
110 def test_show_users_data(self, xhr_header):
77 self.log_user()
111 self.log_user()
78 response = self.app.get(route_path(
112 response = self.app.get(route_path(
79 'users_data'), extra_environ=xhr_header)
113 'users_data'), extra_environ=xhr_header)
80
114
81 all_users = User.query().filter(
115 all_users = User.query().filter(
82 User.username != User.DEFAULT_USER).count()
116 User.username != User.DEFAULT_USER).count()
83 assert response.json['recordsTotal'] == all_users
117 assert response.json['recordsTotal'] == all_users
84
118
85 def test_show_users_data_filtered(self, xhr_header):
119 def test_show_users_data_filtered(self, xhr_header):
86 self.log_user()
120 self.log_user()
87 response = self.app.get(route_path(
121 response = self.app.get(route_path(
88 'users_data', params={'search[value]': 'empty_search'}),
122 'users_data', params={'search[value]': 'empty_search'}),
89 extra_environ=xhr_header)
123 extra_environ=xhr_header)
90
124
91 all_users = User.query().filter(
125 all_users = User.query().filter(
92 User.username != User.DEFAULT_USER).count()
126 User.username != User.DEFAULT_USER).count()
93 assert response.json['recordsTotal'] == all_users
127 assert response.json['recordsTotal'] == all_users
94 assert response.json['recordsFiltered'] == 0
128 assert response.json['recordsFiltered'] == 0
95
129
96 def test_auth_tokens_default_user(self):
130 def test_auth_tokens_default_user(self):
97 self.log_user()
131 self.log_user()
98 user = User.get_default_user()
132 user = User.get_default_user()
99 response = self.app.get(
133 response = self.app.get(
100 route_path('edit_user_auth_tokens', user_id=user.user_id),
134 route_path('edit_user_auth_tokens', user_id=user.user_id),
101 status=302)
135 status=302)
102
136
103 def test_auth_tokens(self):
137 def test_auth_tokens(self):
104 self.log_user()
138 self.log_user()
105
139
106 user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
140 user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
107 response = self.app.get(
141 response = self.app.get(
108 route_path('edit_user_auth_tokens', user_id=user.user_id))
142 route_path('edit_user_auth_tokens', user_id=user.user_id))
109 for token in user.auth_tokens:
143 for token in user.auth_tokens:
110 response.mustcontain(token)
144 response.mustcontain(token)
111 response.mustcontain('never')
145 response.mustcontain('never')
112
146
113 @pytest.mark.parametrize("desc, lifetime", [
147 @pytest.mark.parametrize("desc, lifetime", [
114 ('forever', -1),
148 ('forever', -1),
115 ('5mins', 60*5),
149 ('5mins', 60*5),
116 ('30days', 60*60*24*30),
150 ('30days', 60*60*24*30),
117 ])
151 ])
118 def test_add_auth_token(self, desc, lifetime, user_util):
152 def test_add_auth_token(self, desc, lifetime, user_util):
119 self.log_user()
153 self.log_user()
120 user = user_util.create_user()
154 user = user_util.create_user()
121 user_id = user.user_id
155 user_id = user.user_id
122
156
123 response = self.app.post(
157 response = self.app.post(
124 route_path('edit_user_auth_tokens_add', user_id=user_id),
158 route_path('edit_user_auth_tokens_add', user_id=user_id),
125 {'description': desc, 'lifetime': lifetime,
159 {'description': desc, 'lifetime': lifetime,
126 'csrf_token': self.csrf_token})
160 'csrf_token': self.csrf_token})
127 assert_session_flash(response, 'Auth token successfully created')
161 assert_session_flash(response, 'Auth token successfully created')
128
162
129 response = response.follow()
163 response = response.follow()
130 user = User.get(user_id)
164 user = User.get(user_id)
131 for auth_token in user.auth_tokens:
165 for auth_token in user.auth_tokens:
132 response.mustcontain(auth_token)
166 response.mustcontain(auth_token)
133
167
134 def test_delete_auth_token(self, user_util):
168 def test_delete_auth_token(self, user_util):
135 self.log_user()
169 self.log_user()
136 user = user_util.create_user()
170 user = user_util.create_user()
137 user_id = user.user_id
171 user_id = user.user_id
138 keys = user.auth_tokens
172 keys = user.auth_tokens
139 assert 2 == len(keys)
173 assert 2 == len(keys)
140
174
141 response = self.app.post(
175 response = self.app.post(
142 route_path('edit_user_auth_tokens_add', user_id=user_id),
176 route_path('edit_user_auth_tokens_add', user_id=user_id),
143 {'description': 'desc', 'lifetime': -1,
177 {'description': 'desc', 'lifetime': -1,
144 'csrf_token': self.csrf_token})
178 'csrf_token': self.csrf_token})
145 assert_session_flash(response, 'Auth token successfully created')
179 assert_session_flash(response, 'Auth token successfully created')
146 response.follow()
180 response.follow()
147
181
148 # now delete our key
182 # now delete our key
149 keys = UserApiKeys.query().filter(UserApiKeys.user_id == user_id).all()
183 keys = UserApiKeys.query().filter(UserApiKeys.user_id == user_id).all()
150 assert 3 == len(keys)
184 assert 3 == len(keys)
151
185
152 response = self.app.post(
186 response = self.app.post(
153 route_path('edit_user_auth_tokens_delete', user_id=user_id),
187 route_path('edit_user_auth_tokens_delete', user_id=user_id),
154 {'del_auth_token': keys[0].user_api_key_id,
188 {'del_auth_token': keys[0].user_api_key_id,
155 'csrf_token': self.csrf_token})
189 'csrf_token': self.csrf_token})
156
190
157 assert_session_flash(response, 'Auth token successfully deleted')
191 assert_session_flash(response, 'Auth token successfully deleted')
158 keys = UserApiKeys.query().filter(UserApiKeys.user_id == user_id).all()
192 keys = UserApiKeys.query().filter(UserApiKeys.user_id == user_id).all()
159 assert 2 == len(keys)
193 assert 2 == len(keys)
160
194
161 def test_ips(self):
195 def test_ips(self):
162 self.log_user()
196 self.log_user()
163 user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
197 user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
164 response = self.app.get(route_path('edit_user_ips', user_id=user.user_id))
198 response = self.app.get(route_path('edit_user_ips', user_id=user.user_id))
165 response.mustcontain('All IP addresses are allowed')
199 response.mustcontain('All IP addresses are allowed')
166
200
167 @pytest.mark.parametrize("test_name, ip, ip_range, failure", [
201 @pytest.mark.parametrize("test_name, ip, ip_range, failure", [
168 ('127/24', '127.0.0.1/24', '127.0.0.0 - 127.0.0.255', False),
202 ('127/24', '127.0.0.1/24', '127.0.0.0 - 127.0.0.255', False),
169 ('10/32', '10.0.0.10/32', '10.0.0.10 - 10.0.0.10', False),
203 ('10/32', '10.0.0.10/32', '10.0.0.10 - 10.0.0.10', False),
170 ('0/16', '0.0.0.0/16', '0.0.0.0 - 0.0.255.255', False),
204 ('0/16', '0.0.0.0/16', '0.0.0.0 - 0.0.255.255', False),
171 ('0/8', '0.0.0.0/8', '0.0.0.0 - 0.255.255.255', False),
205 ('0/8', '0.0.0.0/8', '0.0.0.0 - 0.255.255.255', False),
172 ('127_bad_mask', '127.0.0.1/99', '127.0.0.1 - 127.0.0.1', True),
206 ('127_bad_mask', '127.0.0.1/99', '127.0.0.1 - 127.0.0.1', True),
173 ('127_bad_ip', 'foobar', 'foobar', True),
207 ('127_bad_ip', 'foobar', 'foobar', True),
174 ])
208 ])
175 def test_ips_add(self, user_util, test_name, ip, ip_range, failure):
209 def test_ips_add(self, user_util, test_name, ip, ip_range, failure):
176 self.log_user()
210 self.log_user()
177 user = user_util.create_user(username=test_name)
211 user = user_util.create_user(username=test_name)
178 user_id = user.user_id
212 user_id = user.user_id
179
213
180 response = self.app.post(
214 response = self.app.post(
181 route_path('edit_user_ips_add', user_id=user_id),
215 route_path('edit_user_ips_add', user_id=user_id),
182 params={'new_ip': ip, 'csrf_token': self.csrf_token})
216 params={'new_ip': ip, 'csrf_token': self.csrf_token})
183
217
184 if failure:
218 if failure:
185 assert_session_flash(
219 assert_session_flash(
186 response, 'Please enter a valid IPv4 or IpV6 address')
220 response, 'Please enter a valid IPv4 or IpV6 address')
187 response = self.app.get(route_path('edit_user_ips', user_id=user_id))
221 response = self.app.get(route_path('edit_user_ips', user_id=user_id))
188
222
189 response.mustcontain(no=[ip])
223 response.mustcontain(no=[ip])
190 response.mustcontain(no=[ip_range])
224 response.mustcontain(no=[ip_range])
191
225
192 else:
226 else:
193 response = self.app.get(route_path('edit_user_ips', user_id=user_id))
227 response = self.app.get(route_path('edit_user_ips', user_id=user_id))
194 response.mustcontain(ip)
228 response.mustcontain(ip)
195 response.mustcontain(ip_range)
229 response.mustcontain(ip_range)
196
230
197 def test_ips_delete(self, user_util):
231 def test_ips_delete(self, user_util):
198 self.log_user()
232 self.log_user()
199 user = user_util.create_user()
233 user = user_util.create_user()
200 user_id = user.user_id
234 user_id = user.user_id
201 ip = '127.0.0.1/32'
235 ip = '127.0.0.1/32'
202 ip_range = '127.0.0.1 - 127.0.0.1'
236 ip_range = '127.0.0.1 - 127.0.0.1'
203 new_ip = UserModel().add_extra_ip(user_id, ip)
237 new_ip = UserModel().add_extra_ip(user_id, ip)
204 Session().commit()
238 Session().commit()
205 new_ip_id = new_ip.ip_id
239 new_ip_id = new_ip.ip_id
206
240
207 response = self.app.get(route_path('edit_user_ips', user_id=user_id))
241 response = self.app.get(route_path('edit_user_ips', user_id=user_id))
208 response.mustcontain(ip)
242 response.mustcontain(ip)
209 response.mustcontain(ip_range)
243 response.mustcontain(ip_range)
210
244
211 self.app.post(
245 self.app.post(
212 route_path('edit_user_ips_delete', user_id=user_id),
246 route_path('edit_user_ips_delete', user_id=user_id),
213 params={'del_ip_id': new_ip_id, 'csrf_token': self.csrf_token})
247 params={'del_ip_id': new_ip_id, 'csrf_token': self.csrf_token})
214
248
215 response = self.app.get(route_path('edit_user_ips', user_id=user_id))
249 response = self.app.get(route_path('edit_user_ips', user_id=user_id))
216 response.mustcontain('All IP addresses are allowed')
250 response.mustcontain('All IP addresses are allowed')
217 response.mustcontain(no=[ip])
251 response.mustcontain(no=[ip])
218 response.mustcontain(no=[ip_range])
252 response.mustcontain(no=[ip_range])
219
253
220 def test_emails(self):
254 def test_emails(self):
221 self.log_user()
255 self.log_user()
222 user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
256 user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
223 response = self.app.get(route_path('edit_user_emails', user_id=user.user_id))
257 response = self.app.get(
258 route_path('edit_user_emails', user_id=user.user_id))
224 response.mustcontain('No additional emails specified')
259 response.mustcontain('No additional emails specified')
225
260
226 def test_emails_add(self, user_util):
261 def test_emails_add(self, user_util):
227 self.log_user()
262 self.log_user()
228 user = user_util.create_user()
263 user = user_util.create_user()
229 user_id = user.user_id
264 user_id = user.user_id
230
265
231 self.app.post(
266 self.app.post(
232 route_path('edit_user_emails_add', user_id=user_id),
267 route_path('edit_user_emails_add', user_id=user_id),
233 params={'new_email': 'example@rhodecode.com',
268 params={'new_email': 'example@rhodecode.com',
234 'csrf_token': self.csrf_token})
269 'csrf_token': self.csrf_token})
235
270
236 response = self.app.get(route_path('edit_user_emails', user_id=user_id))
271 response = self.app.get(
272 route_path('edit_user_emails', user_id=user_id))
237 response.mustcontain('example@rhodecode.com')
273 response.mustcontain('example@rhodecode.com')
238
274
239 def test_emails_add_existing_email(self, user_util, user_regular):
275 def test_emails_add_existing_email(self, user_util, user_regular):
240 existing_email = user_regular.email
276 existing_email = user_regular.email
241
277
242 self.log_user()
278 self.log_user()
243 user = user_util.create_user()
279 user = user_util.create_user()
244 user_id = user.user_id
280 user_id = user.user_id
245
281
246 response = self.app.post(
282 response = self.app.post(
247 route_path('edit_user_emails_add', user_id=user_id),
283 route_path('edit_user_emails_add', user_id=user_id),
248 params={'new_email': existing_email,
284 params={'new_email': existing_email,
249 'csrf_token': self.csrf_token})
285 'csrf_token': self.csrf_token})
250 assert_session_flash(
286 assert_session_flash(
251 response, 'This e-mail address is already taken')
287 response, 'This e-mail address is already taken')
252
288
253 response = self.app.get(route_path('edit_user_emails', user_id=user_id))
289 response = self.app.get(
290 route_path('edit_user_emails', user_id=user_id))
254 response.mustcontain(no=[existing_email])
291 response.mustcontain(no=[existing_email])
255
292
256 def test_emails_delete(self, user_util):
293 def test_emails_delete(self, user_util):
257 self.log_user()
294 self.log_user()
258 user = user_util.create_user()
295 user = user_util.create_user()
259 user_id = user.user_id
296 user_id = user.user_id
260
297
261 self.app.post(
298 self.app.post(
262 route_path('edit_user_emails_add', user_id=user_id),
299 route_path('edit_user_emails_add', user_id=user_id),
263 params={'new_email': 'example@rhodecode.com',
300 params={'new_email': 'example@rhodecode.com',
264 'csrf_token': self.csrf_token})
301 'csrf_token': self.csrf_token})
265
302
266 response = self.app.get(route_path('edit_user_emails', user_id=user_id))
303 response = self.app.get(
304 route_path('edit_user_emails', user_id=user_id))
267 response.mustcontain('example@rhodecode.com')
305 response.mustcontain('example@rhodecode.com')
268
306
269 user_email = UserEmailMap.query()\
307 user_email = UserEmailMap.query()\
270 .filter(UserEmailMap.email == 'example@rhodecode.com') \
308 .filter(UserEmailMap.email == 'example@rhodecode.com') \
271 .filter(UserEmailMap.user_id == user_id)\
309 .filter(UserEmailMap.user_id == user_id)\
272 .one()
310 .one()
273
311
274 del_email_id = user_email.email_id
312 del_email_id = user_email.email_id
275 self.app.post(
313 self.app.post(
276 route_path('edit_user_emails_delete', user_id=user_id),
314 route_path('edit_user_emails_delete', user_id=user_id),
277 params={'del_email_id': del_email_id,
315 params={'del_email_id': del_email_id,
278 'csrf_token': self.csrf_token})
316 'csrf_token': self.csrf_token})
279
317
280 response = self.app.get(route_path('edit_user_emails', user_id=user_id))
318 response = self.app.get(
281 response.mustcontain(no=['example@rhodecode.com']) No newline at end of file
319 route_path('edit_user_emails', user_id=user_id))
320 response.mustcontain(no=['example@rhodecode.com'])
321
322
323 def test_create(self, request, xhr_header):
324 self.log_user()
325 username = 'newtestuser'
326 password = 'test12'
327 password_confirmation = password
328 name = 'name'
329 lastname = 'lastname'
330 email = 'mail@mail.com'
331
332 self.app.get(route_path('users_new'))
333
334 response = self.app.post(route_path('users_create'), params={
335 'username': username,
336 'password': password,
337 'password_confirmation': password_confirmation,
338 'firstname': name,
339 'active': True,
340 'lastname': lastname,
341 'extern_name': 'rhodecode',
342 'extern_type': 'rhodecode',
343 'email': email,
344 'csrf_token': self.csrf_token,
345 })
346 user_link = h.link_to(
347 username,
348 route_path(
349 'user_edit', user_id=User.get_by_username(username).user_id))
350 assert_session_flash(response, 'Created user %s' % (user_link,))
351
352 @request.addfinalizer
353 def cleanup():
354 fixture.destroy_user(username)
355 Session().commit()
356
357 new_user = User.query().filter(User.username == username).one()
358
359 assert new_user.username == username
360 assert auth.check_password(password, new_user.password)
361 assert new_user.name == name
362 assert new_user.lastname == lastname
363 assert new_user.email == email
364
365 response = self.app.get(route_path('users_data'),
366 extra_environ=xhr_header)
367 response.mustcontain(username)
368
369 def test_create_err(self):
370 self.log_user()
371 username = 'new_user'
372 password = ''
373 name = 'name'
374 lastname = 'lastname'
375 email = 'errmail.com'
376
377 self.app.get(route_path('users_new'))
378
379 response = self.app.post(route_path('users_create'), params={
380 'username': username,
381 'password': password,
382 'name': name,
383 'active': False,
384 'lastname': lastname,
385 'email': email,
386 'csrf_token': self.csrf_token,
387 })
388
389 msg = validators.ValidUsername(
390 False, {})._messages['system_invalid_username']
391 msg = h.html_escape(msg % {'username': 'new_user'})
392 response.mustcontain('<span class="error-message">%s</span>' % msg)
393 response.mustcontain(
394 '<span class="error-message">Please enter a value</span>')
395 response.mustcontain(
396 '<span class="error-message">An email address must contain a'
397 ' single @</span>')
398
399 def get_user():
400 Session().query(User).filter(User.username == username).one()
401
402 with pytest.raises(NoResultFound):
403 get_user()
404
405 def test_new(self):
406 self.log_user()
407 self.app.get(route_path('users_new'))
408
409 @pytest.mark.parametrize("name, attrs", [
410 ('firstname', {'firstname': 'new_username'}),
411 ('lastname', {'lastname': 'new_username'}),
412 ('admin', {'admin': True}),
413 ('admin', {'admin': False}),
414 ('extern_type', {'extern_type': 'ldap'}),
415 ('extern_type', {'extern_type': None}),
416 ('extern_name', {'extern_name': 'test'}),
417 ('extern_name', {'extern_name': None}),
418 ('active', {'active': False}),
419 ('active', {'active': True}),
420 ('email', {'email': 'some@email.com'}),
421 ('language', {'language': 'de'}),
422 ('language', {'language': 'en'}),
423 # ('new_password', {'new_password': 'foobar123',
424 # 'password_confirmation': 'foobar123'})
425 ])
426 def test_update(self, name, attrs, user_util):
427 self.log_user()
428 usr = user_util.create_user(
429 password='qweqwe',
430 email='testme@rhodecode.org',
431 extern_type='rhodecode',
432 extern_name='xxx',
433 )
434 user_id = usr.user_id
435 Session().commit()
436
437 params = usr.get_api_data()
438 cur_lang = params['language'] or 'en'
439 params.update({
440 'password_confirmation': '',
441 'new_password': '',
442 'language': cur_lang,
443 'csrf_token': self.csrf_token,
444 })
445 params.update({'new_password': ''})
446 params.update(attrs)
447 if name == 'email':
448 params['emails'] = [attrs['email']]
449 elif name == 'extern_type':
450 # cannot update this via form, expected value is original one
451 params['extern_type'] = "rhodecode"
452 elif name == 'extern_name':
453 # cannot update this via form, expected value is original one
454 params['extern_name'] = 'xxx'
455 # special case since this user is not
456 # logged in yet his data is not filled
457 # so we use creation data
458
459 response = self.app.post(
460 route_path('user_update', user_id=usr.user_id), params)
461 assert response.status_int == 302
462 assert_session_flash(response, 'User updated successfully')
463
464 updated_user = User.get(user_id)
465 updated_params = updated_user.get_api_data()
466 updated_params.update({'password_confirmation': ''})
467 updated_params.update({'new_password': ''})
468
469 del params['csrf_token']
470 assert params == updated_params
471
472 def test_update_and_migrate_password(
473 self, autologin_user, real_crypto_backend, user_util):
474
475 user = user_util.create_user()
476 temp_user = user.username
477 user.password = auth._RhodeCodeCryptoSha256().hash_create(
478 b'test123')
479 Session().add(user)
480 Session().commit()
481
482 params = user.get_api_data()
483
484 params.update({
485 'password_confirmation': 'qweqwe123',
486 'new_password': 'qweqwe123',
487 'language': 'en',
488 'csrf_token': autologin_user.csrf_token,
489 })
490
491 response = self.app.post(
492 route_path('user_update', user_id=user.user_id), params)
493 assert response.status_int == 302
494 assert_session_flash(response, 'User updated successfully')
495
496 # new password should be bcrypted, after log-in and transfer
497 user = User.get_by_username(temp_user)
498 assert user.password.startswith('$')
499
500 updated_user = User.get_by_username(temp_user)
501 updated_params = updated_user.get_api_data()
502 updated_params.update({'password_confirmation': 'qweqwe123'})
503 updated_params.update({'new_password': 'qweqwe123'})
504
505 del params['csrf_token']
506 assert params == updated_params
507
508 def test_delete(self):
509 self.log_user()
510 username = 'newtestuserdeleteme'
511
512 fixture.create_user(name=username)
513
514 new_user = Session().query(User)\
515 .filter(User.username == username).one()
516 response = self.app.post(
517 route_path('user_delete', user_id=new_user.user_id),
518 params={'csrf_token': self.csrf_token})
519
520 assert_session_flash(response, 'Successfully deleted user')
521
522 def test_delete_owner_of_repository(self, request, user_util):
523 self.log_user()
524 obj_name = 'test_repo'
525 usr = user_util.create_user()
526 username = usr.username
527 fixture.create_repo(obj_name, cur_user=usr.username)
528
529 new_user = Session().query(User)\
530 .filter(User.username == username).one()
531 response = self.app.post(
532 route_path('user_delete', user_id=new_user.user_id),
533 params={'csrf_token': self.csrf_token})
534
535 msg = 'user "%s" still owns 1 repositories and cannot be removed. ' \
536 'Switch owners or remove those repositories:%s' % (username,
537 obj_name)
538 assert_session_flash(response, msg)
539 fixture.destroy_repo(obj_name)
540
541 def test_delete_owner_of_repository_detaching(self, request, user_util):
542 self.log_user()
543 obj_name = 'test_repo'
544 usr = user_util.create_user(auto_cleanup=False)
545 username = usr.username
546 fixture.create_repo(obj_name, cur_user=usr.username)
547
548 new_user = Session().query(User)\
549 .filter(User.username == username).one()
550 response = self.app.post(
551 route_path('user_delete', user_id=new_user.user_id),
552 params={'user_repos': 'detach', 'csrf_token': self.csrf_token})
553
554 msg = 'Detached 1 repositories'
555 assert_session_flash(response, msg)
556 fixture.destroy_repo(obj_name)
557
558 def test_delete_owner_of_repository_deleting(self, request, user_util):
559 self.log_user()
560 obj_name = 'test_repo'
561 usr = user_util.create_user(auto_cleanup=False)
562 username = usr.username
563 fixture.create_repo(obj_name, cur_user=usr.username)
564
565 new_user = Session().query(User)\
566 .filter(User.username == username).one()
567 response = self.app.post(
568 route_path('user_delete', user_id=new_user.user_id),
569 params={'user_repos': 'delete', 'csrf_token': self.csrf_token})
570
571 msg = 'Deleted 1 repositories'
572 assert_session_flash(response, msg)
573
574 def test_delete_owner_of_repository_group(self, request, user_util):
575 self.log_user()
576 obj_name = 'test_group'
577 usr = user_util.create_user()
578 username = usr.username
579 fixture.create_repo_group(obj_name, cur_user=usr.username)
580
581 new_user = Session().query(User)\
582 .filter(User.username == username).one()
583 response = self.app.post(
584 route_path('user_delete', user_id=new_user.user_id),
585 params={'csrf_token': self.csrf_token})
586
587 msg = 'user "%s" still owns 1 repository groups and cannot be removed. ' \
588 'Switch owners or remove those repository groups:%s' % (username,
589 obj_name)
590 assert_session_flash(response, msg)
591 fixture.destroy_repo_group(obj_name)
592
593 def test_delete_owner_of_repository_group_detaching(self, request, user_util):
594 self.log_user()
595 obj_name = 'test_group'
596 usr = user_util.create_user(auto_cleanup=False)
597 username = usr.username
598 fixture.create_repo_group(obj_name, cur_user=usr.username)
599
600 new_user = Session().query(User)\
601 .filter(User.username == username).one()
602 response = self.app.post(
603 route_path('user_delete', user_id=new_user.user_id),
604 params={'user_repo_groups': 'delete', 'csrf_token': self.csrf_token})
605
606 msg = 'Deleted 1 repository groups'
607 assert_session_flash(response, msg)
608
609 def test_delete_owner_of_repository_group_deleting(self, request, user_util):
610 self.log_user()
611 obj_name = 'test_group'
612 usr = user_util.create_user(auto_cleanup=False)
613 username = usr.username
614 fixture.create_repo_group(obj_name, cur_user=usr.username)
615
616 new_user = Session().query(User)\
617 .filter(User.username == username).one()
618 response = self.app.post(
619 route_path('user_delete', user_id=new_user.user_id),
620 params={'user_repo_groups': 'detach', 'csrf_token': self.csrf_token})
621
622 msg = 'Detached 1 repository groups'
623 assert_session_flash(response, msg)
624 fixture.destroy_repo_group(obj_name)
625
626 def test_delete_owner_of_user_group(self, request, user_util):
627 self.log_user()
628 obj_name = 'test_user_group'
629 usr = user_util.create_user()
630 username = usr.username
631 fixture.create_user_group(obj_name, cur_user=usr.username)
632
633 new_user = Session().query(User)\
634 .filter(User.username == username).one()
635 response = self.app.post(
636 route_path('user_delete', user_id=new_user.user_id),
637 params={'csrf_token': self.csrf_token})
638
639 msg = 'user "%s" still owns 1 user groups and cannot be removed. ' \
640 'Switch owners or remove those user groups:%s' % (username,
641 obj_name)
642 assert_session_flash(response, msg)
643 fixture.destroy_user_group(obj_name)
644
645 def test_delete_owner_of_user_group_detaching(self, request, user_util):
646 self.log_user()
647 obj_name = 'test_user_group'
648 usr = user_util.create_user(auto_cleanup=False)
649 username = usr.username
650 fixture.create_user_group(obj_name, cur_user=usr.username)
651
652 new_user = Session().query(User)\
653 .filter(User.username == username).one()
654 try:
655 response = self.app.post(
656 route_path('user_delete', user_id=new_user.user_id),
657 params={'user_user_groups': 'detach',
658 'csrf_token': self.csrf_token})
659
660 msg = 'Detached 1 user groups'
661 assert_session_flash(response, msg)
662 finally:
663 fixture.destroy_user_group(obj_name)
664
665 def test_delete_owner_of_user_group_deleting(self, request, user_util):
666 self.log_user()
667 obj_name = 'test_user_group'
668 usr = user_util.create_user(auto_cleanup=False)
669 username = usr.username
670 fixture.create_user_group(obj_name, cur_user=usr.username)
671
672 new_user = Session().query(User)\
673 .filter(User.username == username).one()
674 response = self.app.post(
675 route_path('user_delete', user_id=new_user.user_id),
676 params={'user_user_groups': 'delete', 'csrf_token': self.csrf_token})
677
678 msg = 'Deleted 1 user groups'
679 assert_session_flash(response, msg)
680
681 def test_edit(self, user_util):
682 self.log_user()
683 user = user_util.create_user()
684 self.app.get(route_path('user_edit', user_id=user.user_id))
685
686 def test_edit_default_user_redirect(self):
687 self.log_user()
688 user = User.get_default_user()
689 self.app.get(route_path('user_edit', user_id=user.user_id), status=302)
690
691 @pytest.mark.parametrize(
692 'repo_create, repo_create_write, user_group_create, repo_group_create,'
693 'fork_create, inherit_default_permissions, expect_error,'
694 'expect_form_error', [
695 ('hg.create.none', 'hg.create.write_on_repogroup.false',
696 'hg.usergroup.create.false', 'hg.repogroup.create.false',
697 'hg.fork.none', 'hg.inherit_default_perms.false', False, False),
698 ('hg.create.repository', 'hg.create.write_on_repogroup.false',
699 'hg.usergroup.create.false', 'hg.repogroup.create.false',
700 'hg.fork.none', 'hg.inherit_default_perms.false', False, False),
701 ('hg.create.repository', 'hg.create.write_on_repogroup.true',
702 'hg.usergroup.create.true', 'hg.repogroup.create.true',
703 'hg.fork.repository', 'hg.inherit_default_perms.false', False,
704 False),
705 ('hg.create.XXX', 'hg.create.write_on_repogroup.true',
706 'hg.usergroup.create.true', 'hg.repogroup.create.true',
707 'hg.fork.repository', 'hg.inherit_default_perms.false', False,
708 True),
709 ('', '', '', '', '', '', True, False),
710 ])
711 def test_global_perms_on_user(
712 self, repo_create, repo_create_write, user_group_create,
713 repo_group_create, fork_create, expect_error, expect_form_error,
714 inherit_default_permissions, user_util):
715 self.log_user()
716 user = user_util.create_user()
717 uid = user.user_id
718
719 # ENABLE REPO CREATE ON A GROUP
720 perm_params = {
721 'inherit_default_permissions': False,
722 'default_repo_create': repo_create,
723 'default_repo_create_on_write': repo_create_write,
724 'default_user_group_create': user_group_create,
725 'default_repo_group_create': repo_group_create,
726 'default_fork_create': fork_create,
727 'default_inherit_default_permissions': inherit_default_permissions,
728 'csrf_token': self.csrf_token,
729 }
730 response = self.app.post(
731 route_path('user_edit_global_perms_update', user_id=uid),
732 params=perm_params)
733
734 if expect_form_error:
735 assert response.status_int == 200
736 response.mustcontain('Value must be one of')
737 else:
738 if expect_error:
739 msg = 'An error occurred during permissions saving'
740 else:
741 msg = 'User global permissions updated successfully'
742 ug = User.get(uid)
743 del perm_params['inherit_default_permissions']
744 del perm_params['csrf_token']
745 assert perm_params == ug.get_default_perms()
746 assert_session_flash(response, msg)
747
748 def test_global_permissions_initial_values(self, user_util):
749 self.log_user()
750 user = user_util.create_user()
751 uid = user.user_id
752 response = self.app.get(
753 route_path('user_edit_global_perms', user_id=uid))
754 default_user = User.get_default_user()
755 default_permissions = default_user.get_default_perms()
756 assert_response = response.assert_response()
757 expected_permissions = (
758 'default_repo_create', 'default_repo_create_on_write',
759 'default_fork_create', 'default_repo_group_create',
760 'default_user_group_create', 'default_inherit_default_permissions')
761 for permission in expected_permissions:
762 css_selector = '[name={}][checked=checked]'.format(permission)
763 element = assert_response.get_element(css_selector)
764 assert element.value == default_permissions[permission]
765
766 def test_perms_summary_page(self):
767 user = self.log_user()
768 response = self.app.get(
769 route_path('edit_user_perms_summary', user_id=user['user_id']))
770 for repo in Repository.query().all():
771 response.mustcontain(repo.repo_name)
772
773 def test_perms_summary_page_json(self):
774 user = self.log_user()
775 response = self.app.get(
776 route_path('edit_user_perms_summary_json', user_id=user['user_id']))
777 for repo in Repository.query().all():
778 response.mustcontain(repo.repo_name)
779
780 def test_audit_log_page(self):
781 user = self.log_user()
782 self.app.get(
783 route_path('edit_user_audit_logs', user_id=user['user_id']))
This diff has been collapsed as it changes many lines, (691 lines changed) Show them Hide them
@@ -1,668 +1,1177 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
22 import logging
21 import logging
23 import datetime
22 import datetime
24 import formencode
23 import formencode
25 import formencode.htmlfill
24 import formencode.htmlfill
26
25
27 from pyramid.httpexceptions import HTTPFound
26 from pyramid.httpexceptions import HTTPFound
28 from pyramid.view import view_config
27 from pyramid.view import view_config
29 from sqlalchemy.sql.functions import coalesce
28 from pyramid.renderers import render
30 from sqlalchemy.exc import IntegrityError
29 from pyramid.response import Response
31
30
32 from rhodecode.apps._base import BaseAppView, DataGridAppView
31 from rhodecode.apps._base import BaseAppView, DataGridAppView, UserAppView
33 from rhodecode.apps.ssh_support import SshKeyFileChangeEvent
32 from rhodecode.apps.ssh_support import SshKeyFileChangeEvent
33 from rhodecode.authentication.plugins import auth_rhodecode
34 from rhodecode.events import trigger
34 from rhodecode.events import trigger
35
35
36 from rhodecode.lib import audit_logger
36 from rhodecode.lib import audit_logger
37 from rhodecode.lib.exceptions import (
38 UserCreationError, UserOwnsReposException, UserOwnsRepoGroupsException,
39 UserOwnsUserGroupsException, DefaultUserException)
37 from rhodecode.lib.ext_json import json
40 from rhodecode.lib.ext_json import json
38 from rhodecode.lib.auth import (
41 from rhodecode.lib.auth import (
39 LoginRequired, HasPermissionAllDecorator, CSRFRequired)
42 LoginRequired, HasPermissionAllDecorator, CSRFRequired)
40 from rhodecode.lib import helpers as h
43 from rhodecode.lib import helpers as h
41 from rhodecode.lib.utils2 import safe_int, safe_unicode
44 from rhodecode.lib.utils2 import safe_int, safe_unicode, AttributeDict
42 from rhodecode.model.auth_token import AuthTokenModel
45 from rhodecode.model.auth_token import AuthTokenModel
46 from rhodecode.model.forms import (
47 UserForm, UserIndividualPermissionsForm, UserPermissionsForm)
48 from rhodecode.model.permission import PermissionModel
49 from rhodecode.model.repo_group import RepoGroupModel
43 from rhodecode.model.ssh_key import SshKeyModel
50 from rhodecode.model.ssh_key import SshKeyModel
44 from rhodecode.model.user import UserModel
51 from rhodecode.model.user import UserModel
45 from rhodecode.model.user_group import UserGroupModel
52 from rhodecode.model.user_group import UserGroupModel
46 from rhodecode.model.db import (
53 from rhodecode.model.db import (
47 or_, User, UserIpMap, UserEmailMap, UserApiKeys, UserSshKeys)
54 or_, coalesce,IntegrityError, User, UserGroup, UserIpMap, UserEmailMap,
55 UserApiKeys, UserSshKeys, RepoGroup)
48 from rhodecode.model.meta import Session
56 from rhodecode.model.meta import Session
49
57
50 log = logging.getLogger(__name__)
58 log = logging.getLogger(__name__)
51
59
52
60
53 class AdminUsersView(BaseAppView, DataGridAppView):
61 class AdminUsersView(BaseAppView, DataGridAppView):
54 ALLOW_SCOPED_TOKENS = False
55 """
56 This view has alternative version inside EE, if modified please take a look
57 in there as well.
58 """
59
62
60 def load_default_context(self):
63 def load_default_context(self):
61 c = self._get_local_tmpl_context()
64 c = self._get_local_tmpl_context()
62 c.allow_scoped_tokens = self.ALLOW_SCOPED_TOKENS
63 self._register_global_c(c)
65 self._register_global_c(c)
64 return c
66 return c
65
67
66 def _redirect_for_default_user(self, username):
67 _ = self.request.translate
68 if username == User.DEFAULT_USER:
69 h.flash(_("You can't edit this user"), category='warning')
70 # TODO(marcink): redirect to 'users' admin panel once this
71 # is a pyramid view
72 raise HTTPFound('/')
73
74 @LoginRequired()
68 @LoginRequired()
75 @HasPermissionAllDecorator('hg.admin')
69 @HasPermissionAllDecorator('hg.admin')
76 @view_config(
70 @view_config(
77 route_name='users', request_method='GET',
71 route_name='users', request_method='GET',
78 renderer='rhodecode:templates/admin/users/users.mako')
72 renderer='rhodecode:templates/admin/users/users.mako')
79 def users_list(self):
73 def users_list(self):
80 c = self.load_default_context()
74 c = self.load_default_context()
81 return self._get_template_context(c)
75 return self._get_template_context(c)
82
76
83 @LoginRequired()
77 @LoginRequired()
84 @HasPermissionAllDecorator('hg.admin')
78 @HasPermissionAllDecorator('hg.admin')
85 @view_config(
79 @view_config(
86 # renderer defined below
80 # renderer defined below
87 route_name='users_data', request_method='GET',
81 route_name='users_data', request_method='GET',
88 renderer='json_ext', xhr=True)
82 renderer='json_ext', xhr=True)
89 def users_list_data(self):
83 def users_list_data(self):
90 column_map = {
84 column_map = {
91 'first_name': 'name',
85 'first_name': 'name',
92 'last_name': 'lastname',
86 'last_name': 'lastname',
93 }
87 }
94 draw, start, limit = self._extract_chunk(self.request)
88 draw, start, limit = self._extract_chunk(self.request)
95 search_q, order_by, order_dir = self._extract_ordering(
89 search_q, order_by, order_dir = self._extract_ordering(
96 self.request, column_map=column_map)
90 self.request, column_map=column_map)
97
91
98 _render = self.request.get_partial_renderer(
92 _render = self.request.get_partial_renderer(
99 'data_table/_dt_elements.mako')
93 'data_table/_dt_elements.mako')
100
94
101 def user_actions(user_id, username):
95 def user_actions(user_id, username):
102 return _render("user_actions", user_id, username)
96 return _render("user_actions", user_id, username)
103
97
104 users_data_total_count = User.query()\
98 users_data_total_count = User.query()\
105 .filter(User.username != User.DEFAULT_USER) \
99 .filter(User.username != User.DEFAULT_USER) \
106 .count()
100 .count()
107
101
108 # json generate
102 # json generate
109 base_q = User.query().filter(User.username != User.DEFAULT_USER)
103 base_q = User.query().filter(User.username != User.DEFAULT_USER)
110
104
111 if search_q:
105 if search_q:
112 like_expression = u'%{}%'.format(safe_unicode(search_q))
106 like_expression = u'%{}%'.format(safe_unicode(search_q))
113 base_q = base_q.filter(or_(
107 base_q = base_q.filter(or_(
114 User.username.ilike(like_expression),
108 User.username.ilike(like_expression),
115 User._email.ilike(like_expression),
109 User._email.ilike(like_expression),
116 User.name.ilike(like_expression),
110 User.name.ilike(like_expression),
117 User.lastname.ilike(like_expression),
111 User.lastname.ilike(like_expression),
118 ))
112 ))
119
113
120 users_data_total_filtered_count = base_q.count()
114 users_data_total_filtered_count = base_q.count()
121
115
122 sort_col = getattr(User, order_by, None)
116 sort_col = getattr(User, order_by, None)
123 if sort_col:
117 if sort_col:
124 if order_dir == 'asc':
118 if order_dir == 'asc':
125 # handle null values properly to order by NULL last
119 # handle null values properly to order by NULL last
126 if order_by in ['last_activity']:
120 if order_by in ['last_activity']:
127 sort_col = coalesce(sort_col, datetime.date.max)
121 sort_col = coalesce(sort_col, datetime.date.max)
128 sort_col = sort_col.asc()
122 sort_col = sort_col.asc()
129 else:
123 else:
130 # handle null values properly to order by NULL last
124 # handle null values properly to order by NULL last
131 if order_by in ['last_activity']:
125 if order_by in ['last_activity']:
132 sort_col = coalesce(sort_col, datetime.date.min)
126 sort_col = coalesce(sort_col, datetime.date.min)
133 sort_col = sort_col.desc()
127 sort_col = sort_col.desc()
134
128
135 base_q = base_q.order_by(sort_col)
129 base_q = base_q.order_by(sort_col)
136 base_q = base_q.offset(start).limit(limit)
130 base_q = base_q.offset(start).limit(limit)
137
131
138 users_list = base_q.all()
132 users_list = base_q.all()
139
133
140 users_data = []
134 users_data = []
141 for user in users_list:
135 for user in users_list:
142 users_data.append({
136 users_data.append({
143 "username": h.gravatar_with_user(self.request, user.username),
137 "username": h.gravatar_with_user(self.request, user.username),
144 "email": user.email,
138 "email": user.email,
145 "first_name": user.first_name,
139 "first_name": user.first_name,
146 "last_name": user.last_name,
140 "last_name": user.last_name,
147 "last_login": h.format_date(user.last_login),
141 "last_login": h.format_date(user.last_login),
148 "last_activity": h.format_date(user.last_activity),
142 "last_activity": h.format_date(user.last_activity),
149 "active": h.bool2icon(user.active),
143 "active": h.bool2icon(user.active),
150 "active_raw": user.active,
144 "active_raw": user.active,
151 "admin": h.bool2icon(user.admin),
145 "admin": h.bool2icon(user.admin),
152 "extern_type": user.extern_type,
146 "extern_type": user.extern_type,
153 "extern_name": user.extern_name,
147 "extern_name": user.extern_name,
154 "action": user_actions(user.user_id, user.username),
148 "action": user_actions(user.user_id, user.username),
155 })
149 })
156
150
157 data = ({
151 data = ({
158 'draw': draw,
152 'draw': draw,
159 'data': users_data,
153 'data': users_data,
160 'recordsTotal': users_data_total_count,
154 'recordsTotal': users_data_total_count,
161 'recordsFiltered': users_data_total_filtered_count,
155 'recordsFiltered': users_data_total_filtered_count,
162 })
156 })
163
157
164 return data
158 return data
165
159
160 def _set_personal_repo_group_template_vars(self, c_obj):
161 DummyUser = AttributeDict({
162 'username': '${username}',
163 'user_id': '${user_id}',
164 })
165 c_obj.default_create_repo_group = RepoGroupModel() \
166 .get_default_create_personal_repo_group()
167 c_obj.personal_repo_group_name = RepoGroupModel() \
168 .get_personal_group_name(DummyUser)
169
170 @LoginRequired()
171 @HasPermissionAllDecorator('hg.admin')
172 @view_config(
173 route_name='users_new', request_method='GET',
174 renderer='rhodecode:templates/admin/users/user_add.mako')
175 def users_new(self):
176 _ = self.request.translate
177 c = self.load_default_context()
178 c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.name
179 self._set_personal_repo_group_template_vars(c)
180 return self._get_template_context(c)
181
182 @LoginRequired()
183 @HasPermissionAllDecorator('hg.admin')
184 @CSRFRequired()
185 @view_config(
186 route_name='users_create', request_method='POST',
187 renderer='rhodecode:templates/admin/users/user_add.mako')
188 def users_create(self):
189 _ = self.request.translate
190 c = self.load_default_context()
191 c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.name
192 user_model = UserModel()
193 user_form = UserForm()()
194 try:
195 form_result = user_form.to_python(dict(self.request.POST))
196 user = user_model.create(form_result)
197 Session().flush()
198 creation_data = user.get_api_data()
199 username = form_result['username']
200
201 audit_logger.store_web(
202 'user.create', action_data={'data': creation_data},
203 user=c.rhodecode_user)
204
205 user_link = h.link_to(
206 h.escape(username),
207 h.route_path('user_edit', user_id=user.user_id))
208 h.flash(h.literal(_('Created user %(user_link)s')
209 % {'user_link': user_link}), category='success')
210 Session().commit()
211 except formencode.Invalid as errors:
212 self._set_personal_repo_group_template_vars(c)
213 data = render(
214 'rhodecode:templates/admin/users/user_add.mako',
215 self._get_template_context(c), self.request)
216 html = formencode.htmlfill.render(
217 data,
218 defaults=errors.value,
219 errors=errors.error_dict or {},
220 prefix_error=False,
221 encoding="UTF-8",
222 force_defaults=False
223 )
224 return Response(html)
225 except UserCreationError as e:
226 h.flash(e, 'error')
227 except Exception:
228 log.exception("Exception creation of user")
229 h.flash(_('Error occurred during creation of user %s')
230 % self.request.POST.get('username'), category='error')
231 raise HTTPFound(h.route_path('users'))
232
233
234 class UsersView(UserAppView):
235 ALLOW_SCOPED_TOKENS = False
236 """
237 This view has alternative version inside EE, if modified please take a look
238 in there as well.
239 """
240
241 def load_default_context(self):
242 c = self._get_local_tmpl_context()
243 c.allow_scoped_tokens = self.ALLOW_SCOPED_TOKENS
244 c.allowed_languages = [
245 ('en', 'English (en)'),
246 ('de', 'German (de)'),
247 ('fr', 'French (fr)'),
248 ('it', 'Italian (it)'),
249 ('ja', 'Japanese (ja)'),
250 ('pl', 'Polish (pl)'),
251 ('pt', 'Portuguese (pt)'),
252 ('ru', 'Russian (ru)'),
253 ('zh', 'Chinese (zh)'),
254 ]
255 req = self.request
256
257 c.available_permissions = req.registry.settings['available_permissions']
258 PermissionModel().set_global_permission_choices(
259 c, gettext_translator=req.translate)
260
261 self._register_global_c(c)
262 return c
263
264 @LoginRequired()
265 @HasPermissionAllDecorator('hg.admin')
266 @CSRFRequired()
267 @view_config(
268 route_name='user_update', request_method='POST',
269 renderer='rhodecode:templates/admin/users/user_edit.mako')
270 def user_update(self):
271 _ = self.request.translate
272 c = self.load_default_context()
273
274 user_id = self.db_user_id
275 c.user = self.db_user
276
277 c.active = 'profile'
278 c.extern_type = c.user.extern_type
279 c.extern_name = c.user.extern_name
280 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
281 available_languages = [x[0] for x in c.allowed_languages]
282 _form = UserForm(edit=True, available_languages=available_languages,
283 old_data={'user_id': user_id,
284 'email': c.user.email})()
285 form_result = {}
286 old_values = c.user.get_api_data()
287 try:
288 form_result = _form.to_python(dict(self.request.POST))
289 skip_attrs = ['extern_type', 'extern_name']
290 # TODO: plugin should define if username can be updated
291 if c.extern_type != "rhodecode":
292 # forbid updating username for external accounts
293 skip_attrs.append('username')
294
295 UserModel().update_user(
296 user_id, skip_attrs=skip_attrs, **form_result)
297
298 audit_logger.store_web(
299 'user.edit', action_data={'old_data': old_values},
300 user=c.rhodecode_user)
301
302 Session().commit()
303 h.flash(_('User updated successfully'), category='success')
304 except formencode.Invalid as errors:
305 data = render(
306 'rhodecode:templates/admin/users/user_edit.mako',
307 self._get_template_context(c), self.request)
308 html = formencode.htmlfill.render(
309 data,
310 defaults=errors.value,
311 errors=errors.error_dict or {},
312 prefix_error=False,
313 encoding="UTF-8",
314 force_defaults=False
315 )
316 return Response(html)
317 except UserCreationError as e:
318 h.flash(e, 'error')
319 except Exception:
320 log.exception("Exception updating user")
321 h.flash(_('Error occurred during update of user %s')
322 % form_result.get('username'), category='error')
323 raise HTTPFound(h.route_path('user_edit', user_id=user_id))
324
325 @LoginRequired()
326 @HasPermissionAllDecorator('hg.admin')
327 @CSRFRequired()
328 @view_config(
329 route_name='user_delete', request_method='POST',
330 renderer='rhodecode:templates/admin/users/user_edit.mako')
331 def user_delete(self):
332 _ = self.request.translate
333 c = self.load_default_context()
334 c.user = self.db_user
335
336 _repos = c.user.repositories
337 _repo_groups = c.user.repository_groups
338 _user_groups = c.user.user_groups
339
340 handle_repos = None
341 handle_repo_groups = None
342 handle_user_groups = None
343 # dummy call for flash of handle
344 set_handle_flash_repos = lambda: None
345 set_handle_flash_repo_groups = lambda: None
346 set_handle_flash_user_groups = lambda: None
347
348 if _repos and self.request.POST.get('user_repos'):
349 do = self.request.POST['user_repos']
350 if do == 'detach':
351 handle_repos = 'detach'
352 set_handle_flash_repos = lambda: h.flash(
353 _('Detached %s repositories') % len(_repos),
354 category='success')
355 elif do == 'delete':
356 handle_repos = 'delete'
357 set_handle_flash_repos = lambda: h.flash(
358 _('Deleted %s repositories') % len(_repos),
359 category='success')
360
361 if _repo_groups and self.request.POST.get('user_repo_groups'):
362 do = self.request.POST['user_repo_groups']
363 if do == 'detach':
364 handle_repo_groups = 'detach'
365 set_handle_flash_repo_groups = lambda: h.flash(
366 _('Detached %s repository groups') % len(_repo_groups),
367 category='success')
368 elif do == 'delete':
369 handle_repo_groups = 'delete'
370 set_handle_flash_repo_groups = lambda: h.flash(
371 _('Deleted %s repository groups') % len(_repo_groups),
372 category='success')
373
374 if _user_groups and self.request.POST.get('user_user_groups'):
375 do = self.request.POST['user_user_groups']
376 if do == 'detach':
377 handle_user_groups = 'detach'
378 set_handle_flash_user_groups = lambda: h.flash(
379 _('Detached %s user groups') % len(_user_groups),
380 category='success')
381 elif do == 'delete':
382 handle_user_groups = 'delete'
383 set_handle_flash_user_groups = lambda: h.flash(
384 _('Deleted %s user groups') % len(_user_groups),
385 category='success')
386
387 old_values = c.user.get_api_data()
388 try:
389 UserModel().delete(c.user, handle_repos=handle_repos,
390 handle_repo_groups=handle_repo_groups,
391 handle_user_groups=handle_user_groups)
392
393 audit_logger.store_web(
394 'user.delete', action_data={'old_data': old_values},
395 user=c.rhodecode_user)
396
397 Session().commit()
398 set_handle_flash_repos()
399 set_handle_flash_repo_groups()
400 set_handle_flash_user_groups()
401 h.flash(_('Successfully deleted user'), category='success')
402 except (UserOwnsReposException, UserOwnsRepoGroupsException,
403 UserOwnsUserGroupsException, DefaultUserException) as e:
404 h.flash(e, category='warning')
405 except Exception:
406 log.exception("Exception during deletion of user")
407 h.flash(_('An error occurred during deletion of user'),
408 category='error')
409 raise HTTPFound(h.route_path('users'))
410
411 @LoginRequired()
412 @HasPermissionAllDecorator('hg.admin')
413 @view_config(
414 route_name='user_edit', request_method='GET',
415 renderer='rhodecode:templates/admin/users/user_edit.mako')
416 def user_edit(self):
417 _ = self.request.translate
418 c = self.load_default_context()
419 c.user = self.db_user
420
421 c.active = 'profile'
422 c.extern_type = c.user.extern_type
423 c.extern_name = c.user.extern_name
424 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
425
426 defaults = c.user.get_dict()
427 defaults.update({'language': c.user.user_data.get('language')})
428
429 data = render(
430 'rhodecode:templates/admin/users/user_edit.mako',
431 self._get_template_context(c), self.request)
432 html = formencode.htmlfill.render(
433 data,
434 defaults=defaults,
435 encoding="UTF-8",
436 force_defaults=False
437 )
438 return Response(html)
439
440 @LoginRequired()
441 @HasPermissionAllDecorator('hg.admin')
442 @view_config(
443 route_name='user_edit_advanced', request_method='GET',
444 renderer='rhodecode:templates/admin/users/user_edit.mako')
445 def user_edit_advanced(self):
446 _ = self.request.translate
447 c = self.load_default_context()
448
449 user_id = self.db_user_id
450 c.user = self.db_user
451
452 c.active = 'advanced'
453 c.personal_repo_group = RepoGroup.get_user_personal_repo_group(user_id)
454 c.personal_repo_group_name = RepoGroupModel()\
455 .get_personal_group_name(c.user)
456
457 c.user_to_review_rules = sorted(
458 (x.user for x in c.user.user_review_rules),
459 key=lambda u: u.username.lower())
460
461 c.first_admin = User.get_first_super_admin()
462 defaults = c.user.get_dict()
463
464 # Interim workaround if the user participated on any pull requests as a
465 # reviewer.
466 has_review = len(c.user.reviewer_pull_requests)
467 c.can_delete_user = not has_review
468 c.can_delete_user_message = ''
469 inactive_link = h.link_to(
470 'inactive', h.route_path('user_edit', user_id=user_id, _anchor='active'))
471 if has_review == 1:
472 c.can_delete_user_message = h.literal(_(
473 'The user participates as reviewer in {} pull request and '
474 'cannot be deleted. \nYou can set the user to '
475 '"{}" instead of deleting it.').format(
476 has_review, inactive_link))
477 elif has_review:
478 c.can_delete_user_message = h.literal(_(
479 'The user participates as reviewer in {} pull requests and '
480 'cannot be deleted. \nYou can set the user to '
481 '"{}" instead of deleting it.').format(
482 has_review, inactive_link))
483
484 data = render(
485 'rhodecode:templates/admin/users/user_edit.mako',
486 self._get_template_context(c), self.request)
487 html = formencode.htmlfill.render(
488 data,
489 defaults=defaults,
490 encoding="UTF-8",
491 force_defaults=False
492 )
493 return Response(html)
494
495 @LoginRequired()
496 @HasPermissionAllDecorator('hg.admin')
497 @view_config(
498 route_name='user_edit_global_perms', request_method='GET',
499 renderer='rhodecode:templates/admin/users/user_edit.mako')
500 def user_edit_global_perms(self):
501 _ = self.request.translate
502 c = self.load_default_context()
503 c.user = self.db_user
504
505 c.active = 'global_perms'
506
507 c.default_user = User.get_default_user()
508 defaults = c.user.get_dict()
509 defaults.update(c.default_user.get_default_perms(suffix='_inherited'))
510 defaults.update(c.default_user.get_default_perms())
511 defaults.update(c.user.get_default_perms())
512
513 data = render(
514 'rhodecode:templates/admin/users/user_edit.mako',
515 self._get_template_context(c), self.request)
516 html = formencode.htmlfill.render(
517 data,
518 defaults=defaults,
519 encoding="UTF-8",
520 force_defaults=False
521 )
522 return Response(html)
523
524 @LoginRequired()
525 @HasPermissionAllDecorator('hg.admin')
526 @CSRFRequired()
527 @view_config(
528 route_name='user_edit_global_perms_update', request_method='POST',
529 renderer='rhodecode:templates/admin/users/user_edit.mako')
530 def user_edit_global_perms_update(self):
531 _ = self.request.translate
532 c = self.load_default_context()
533
534 user_id = self.db_user_id
535 c.user = self.db_user
536
537 c.active = 'global_perms'
538 try:
539 # first stage that verifies the checkbox
540 _form = UserIndividualPermissionsForm()
541 form_result = _form.to_python(dict(self.request.POST))
542 inherit_perms = form_result['inherit_default_permissions']
543 c.user.inherit_default_permissions = inherit_perms
544 Session().add(c.user)
545
546 if not inherit_perms:
547 # only update the individual ones if we un check the flag
548 _form = UserPermissionsForm(
549 [x[0] for x in c.repo_create_choices],
550 [x[0] for x in c.repo_create_on_write_choices],
551 [x[0] for x in c.repo_group_create_choices],
552 [x[0] for x in c.user_group_create_choices],
553 [x[0] for x in c.fork_choices],
554 [x[0] for x in c.inherit_default_permission_choices])()
555
556 form_result = _form.to_python(dict(self.request.POST))
557 form_result.update({'perm_user_id': c.user.user_id})
558
559 PermissionModel().update_user_permissions(form_result)
560
561 # TODO(marcink): implement global permissions
562 # audit_log.store_web('user.edit.permissions')
563
564 Session().commit()
565 h.flash(_('User global permissions updated successfully'),
566 category='success')
567
568 except formencode.Invalid as errors:
569 data = render(
570 'rhodecode:templates/admin/users/user_edit.mako',
571 self._get_template_context(c), self.request)
572 html = formencode.htmlfill.render(
573 data,
574 defaults=errors.value,
575 errors=errors.error_dict or {},
576 prefix_error=False,
577 encoding="UTF-8",
578 force_defaults=False
579 )
580 return Response(html)
581 except Exception:
582 log.exception("Exception during permissions saving")
583 h.flash(_('An error occurred during permissions saving'),
584 category='error')
585 raise HTTPFound(h.route_path('user_edit_global_perms', user_id=user_id))
586
587 @LoginRequired()
588 @HasPermissionAllDecorator('hg.admin')
589 @CSRFRequired()
590 @view_config(
591 route_name='user_force_password_reset', request_method='POST',
592 renderer='rhodecode:templates/admin/users/user_edit.mako')
593 def user_force_password_reset(self):
594 """
595 toggle reset password flag for this user
596 """
597 _ = self.request.translate
598 c = self.load_default_context()
599
600 user_id = self.db_user_id
601 c.user = self.db_user
602
603 try:
604 old_value = c.user.user_data.get('force_password_change')
605 c.user.update_userdata(force_password_change=not old_value)
606
607 if old_value:
608 msg = _('Force password change disabled for user')
609 audit_logger.store_web(
610 'user.edit.password_reset.disabled',
611 user=c.rhodecode_user)
612 else:
613 msg = _('Force password change enabled for user')
614 audit_logger.store_web(
615 'user.edit.password_reset.enabled',
616 user=c.rhodecode_user)
617
618 Session().commit()
619 h.flash(msg, category='success')
620 except Exception:
621 log.exception("Exception during password reset for user")
622 h.flash(_('An error occurred during password reset for user'),
623 category='error')
624
625 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
626
627 @LoginRequired()
628 @HasPermissionAllDecorator('hg.admin')
629 @CSRFRequired()
630 @view_config(
631 route_name='user_create_personal_repo_group', request_method='POST',
632 renderer='rhodecode:templates/admin/users/user_edit.mako')
633 def user_create_personal_repo_group(self):
634 """
635 Create personal repository group for this user
636 """
637 from rhodecode.model.repo_group import RepoGroupModel
638
639 _ = self.request.translate
640 c = self.load_default_context()
641
642 user_id = self.db_user_id
643 c.user = self.db_user
644
645 personal_repo_group = RepoGroup.get_user_personal_repo_group(
646 c.user.user_id)
647 if personal_repo_group:
648 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
649
650 personal_repo_group_name = RepoGroupModel().get_personal_group_name(
651 c.user)
652 named_personal_group = RepoGroup.get_by_group_name(
653 personal_repo_group_name)
654 try:
655
656 if named_personal_group and named_personal_group.user_id == c.user.user_id:
657 # migrate the same named group, and mark it as personal
658 named_personal_group.personal = True
659 Session().add(named_personal_group)
660 Session().commit()
661 msg = _('Linked repository group `%s` as personal' % (
662 personal_repo_group_name,))
663 h.flash(msg, category='success')
664 elif not named_personal_group:
665 RepoGroupModel().create_personal_repo_group(c.user)
666
667 msg = _('Created repository group `%s`' % (
668 personal_repo_group_name,))
669 h.flash(msg, category='success')
670 else:
671 msg = _('Repository group `%s` is already taken' % (
672 personal_repo_group_name,))
673 h.flash(msg, category='warning')
674 except Exception:
675 log.exception("Exception during repository group creation")
676 msg = _(
677 'An error occurred during repository group creation for user')
678 h.flash(msg, category='error')
679 Session().rollback()
680
681 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
682
166 @LoginRequired()
683 @LoginRequired()
167 @HasPermissionAllDecorator('hg.admin')
684 @HasPermissionAllDecorator('hg.admin')
168 @view_config(
685 @view_config(
169 route_name='edit_user_auth_tokens', request_method='GET',
686 route_name='edit_user_auth_tokens', request_method='GET',
170 renderer='rhodecode:templates/admin/users/user_edit.mako')
687 renderer='rhodecode:templates/admin/users/user_edit.mako')
171 def auth_tokens(self):
688 def auth_tokens(self):
172 _ = self.request.translate
689 _ = self.request.translate
173 c = self.load_default_context()
690 c = self.load_default_context()
174
691 c.user = self.db_user
175 user_id = self.request.matchdict.get('user_id')
176 c.user = User.get_or_404(user_id)
177 self._redirect_for_default_user(c.user.username)
178
692
179 c.active = 'auth_tokens'
693 c.active = 'auth_tokens'
180
694
181 c.lifetime_values = AuthTokenModel.get_lifetime_values(translator=_)
695 c.lifetime_values = AuthTokenModel.get_lifetime_values(translator=_)
182 c.role_values = [
696 c.role_values = [
183 (x, AuthTokenModel.cls._get_role_name(x))
697 (x, AuthTokenModel.cls._get_role_name(x))
184 for x in AuthTokenModel.cls.ROLES]
698 for x in AuthTokenModel.cls.ROLES]
185 c.role_options = [(c.role_values, _("Role"))]
699 c.role_options = [(c.role_values, _("Role"))]
186 c.user_auth_tokens = AuthTokenModel().get_auth_tokens(
700 c.user_auth_tokens = AuthTokenModel().get_auth_tokens(
187 c.user.user_id, show_expired=True)
701 c.user.user_id, show_expired=True)
188 return self._get_template_context(c)
702 return self._get_template_context(c)
189
703
190 def maybe_attach_token_scope(self, token):
704 def maybe_attach_token_scope(self, token):
191 # implemented in EE edition
705 # implemented in EE edition
192 pass
706 pass
193
707
194 @LoginRequired()
708 @LoginRequired()
195 @HasPermissionAllDecorator('hg.admin')
709 @HasPermissionAllDecorator('hg.admin')
196 @CSRFRequired()
710 @CSRFRequired()
197 @view_config(
711 @view_config(
198 route_name='edit_user_auth_tokens_add', request_method='POST')
712 route_name='edit_user_auth_tokens_add', request_method='POST')
199 def auth_tokens_add(self):
713 def auth_tokens_add(self):
200 _ = self.request.translate
714 _ = self.request.translate
201 c = self.load_default_context()
715 c = self.load_default_context()
202
716
203 user_id = self.request.matchdict.get('user_id')
717 user_id = self.db_user_id
204 c.user = User.get_or_404(user_id)
718 c.user = self.db_user
205
206 self._redirect_for_default_user(c.user.username)
207
719
208 user_data = c.user.get_api_data()
720 user_data = c.user.get_api_data()
209 lifetime = safe_int(self.request.POST.get('lifetime'), -1)
721 lifetime = safe_int(self.request.POST.get('lifetime'), -1)
210 description = self.request.POST.get('description')
722 description = self.request.POST.get('description')
211 role = self.request.POST.get('role')
723 role = self.request.POST.get('role')
212
724
213 token = AuthTokenModel().create(
725 token = AuthTokenModel().create(
214 c.user.user_id, description, lifetime, role)
726 c.user.user_id, description, lifetime, role)
215 token_data = token.get_api_data()
727 token_data = token.get_api_data()
216
728
217 self.maybe_attach_token_scope(token)
729 self.maybe_attach_token_scope(token)
218 audit_logger.store_web(
730 audit_logger.store_web(
219 'user.edit.token.add', action_data={
731 'user.edit.token.add', action_data={
220 'data': {'token': token_data, 'user': user_data}},
732 'data': {'token': token_data, 'user': user_data}},
221 user=self._rhodecode_user, )
733 user=self._rhodecode_user, )
222 Session().commit()
734 Session().commit()
223
735
224 h.flash(_("Auth token successfully created"), category='success')
736 h.flash(_("Auth token successfully created"), category='success')
225 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
737 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
226
738
227 @LoginRequired()
739 @LoginRequired()
228 @HasPermissionAllDecorator('hg.admin')
740 @HasPermissionAllDecorator('hg.admin')
229 @CSRFRequired()
741 @CSRFRequired()
230 @view_config(
742 @view_config(
231 route_name='edit_user_auth_tokens_delete', request_method='POST')
743 route_name='edit_user_auth_tokens_delete', request_method='POST')
232 def auth_tokens_delete(self):
744 def auth_tokens_delete(self):
233 _ = self.request.translate
745 _ = self.request.translate
234 c = self.load_default_context()
746 c = self.load_default_context()
235
747
236 user_id = self.request.matchdict.get('user_id')
748 user_id = self.db_user_id
237 c.user = User.get_or_404(user_id)
749 c.user = self.db_user
238 self._redirect_for_default_user(c.user.username)
750
239 user_data = c.user.get_api_data()
751 user_data = c.user.get_api_data()
240
752
241 del_auth_token = self.request.POST.get('del_auth_token')
753 del_auth_token = self.request.POST.get('del_auth_token')
242
754
243 if del_auth_token:
755 if del_auth_token:
244 token = UserApiKeys.get_or_404(del_auth_token)
756 token = UserApiKeys.get_or_404(del_auth_token)
245 token_data = token.get_api_data()
757 token_data = token.get_api_data()
246
758
247 AuthTokenModel().delete(del_auth_token, c.user.user_id)
759 AuthTokenModel().delete(del_auth_token, c.user.user_id)
248 audit_logger.store_web(
760 audit_logger.store_web(
249 'user.edit.token.delete', action_data={
761 'user.edit.token.delete', action_data={
250 'data': {'token': token_data, 'user': user_data}},
762 'data': {'token': token_data, 'user': user_data}},
251 user=self._rhodecode_user,)
763 user=self._rhodecode_user,)
252 Session().commit()
764 Session().commit()
253 h.flash(_("Auth token successfully deleted"), category='success')
765 h.flash(_("Auth token successfully deleted"), category='success')
254
766
255 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
767 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
256
768
257 @LoginRequired()
769 @LoginRequired()
258 @HasPermissionAllDecorator('hg.admin')
770 @HasPermissionAllDecorator('hg.admin')
259 @view_config(
771 @view_config(
260 route_name='edit_user_ssh_keys', request_method='GET',
772 route_name='edit_user_ssh_keys', request_method='GET',
261 renderer='rhodecode:templates/admin/users/user_edit.mako')
773 renderer='rhodecode:templates/admin/users/user_edit.mako')
262 def ssh_keys(self):
774 def ssh_keys(self):
263 _ = self.request.translate
775 _ = self.request.translate
264 c = self.load_default_context()
776 c = self.load_default_context()
265
777 c.user = self.db_user
266 user_id = self.request.matchdict.get('user_id')
267 c.user = User.get_or_404(user_id)
268 self._redirect_for_default_user(c.user.username)
269
778
270 c.active = 'ssh_keys'
779 c.active = 'ssh_keys'
271 c.default_key = self.request.GET.get('default_key')
780 c.default_key = self.request.GET.get('default_key')
272 c.user_ssh_keys = SshKeyModel().get_ssh_keys(c.user.user_id)
781 c.user_ssh_keys = SshKeyModel().get_ssh_keys(c.user.user_id)
273 return self._get_template_context(c)
782 return self._get_template_context(c)
274
783
275 @LoginRequired()
784 @LoginRequired()
276 @HasPermissionAllDecorator('hg.admin')
785 @HasPermissionAllDecorator('hg.admin')
277 @view_config(
786 @view_config(
278 route_name='edit_user_ssh_keys_generate_keypair', request_method='GET',
787 route_name='edit_user_ssh_keys_generate_keypair', request_method='GET',
279 renderer='rhodecode:templates/admin/users/user_edit.mako')
788 renderer='rhodecode:templates/admin/users/user_edit.mako')
280 def ssh_keys_generate_keypair(self):
789 def ssh_keys_generate_keypair(self):
281 _ = self.request.translate
790 _ = self.request.translate
282 c = self.load_default_context()
791 c = self.load_default_context()
283
792
284 user_id = self.request.matchdict.get('user_id')
793 c.user = self.db_user
285 c.user = User.get_or_404(user_id)
286 self._redirect_for_default_user(c.user.username)
287
794
288 c.active = 'ssh_keys_generate'
795 c.active = 'ssh_keys_generate'
289 comment = 'RhodeCode-SSH {}'.format(c.user.email or '')
796 comment = 'RhodeCode-SSH {}'.format(c.user.email or '')
290 c.private, c.public = SshKeyModel().generate_keypair(comment=comment)
797 c.private, c.public = SshKeyModel().generate_keypair(comment=comment)
291
798
292 return self._get_template_context(c)
799 return self._get_template_context(c)
293
800
294 @LoginRequired()
801 @LoginRequired()
295 @HasPermissionAllDecorator('hg.admin')
802 @HasPermissionAllDecorator('hg.admin')
296 @CSRFRequired()
803 @CSRFRequired()
297 @view_config(
804 @view_config(
298 route_name='edit_user_ssh_keys_add', request_method='POST')
805 route_name='edit_user_ssh_keys_add', request_method='POST')
299 def ssh_keys_add(self):
806 def ssh_keys_add(self):
300 _ = self.request.translate
807 _ = self.request.translate
301 c = self.load_default_context()
808 c = self.load_default_context()
302
809
303 user_id = self.request.matchdict.get('user_id')
810 user_id = self.db_user_id
304 c.user = User.get_or_404(user_id)
811 c.user = self.db_user
305
306 self._redirect_for_default_user(c.user.username)
307
812
308 user_data = c.user.get_api_data()
813 user_data = c.user.get_api_data()
309 key_data = self.request.POST.get('key_data')
814 key_data = self.request.POST.get('key_data')
310 description = self.request.POST.get('description')
815 description = self.request.POST.get('description')
311
816
312 try:
817 try:
313 if not key_data:
818 if not key_data:
314 raise ValueError('Please add a valid public key')
819 raise ValueError('Please add a valid public key')
315
820
316 key = SshKeyModel().parse_key(key_data.strip())
821 key = SshKeyModel().parse_key(key_data.strip())
317 fingerprint = key.hash_md5()
822 fingerprint = key.hash_md5()
318
823
319 ssh_key = SshKeyModel().create(
824 ssh_key = SshKeyModel().create(
320 c.user.user_id, fingerprint, key_data, description)
825 c.user.user_id, fingerprint, key_data, description)
321 ssh_key_data = ssh_key.get_api_data()
826 ssh_key_data = ssh_key.get_api_data()
322
827
323 audit_logger.store_web(
828 audit_logger.store_web(
324 'user.edit.ssh_key.add', action_data={
829 'user.edit.ssh_key.add', action_data={
325 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
830 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
326 user=self._rhodecode_user, )
831 user=self._rhodecode_user, )
327 Session().commit()
832 Session().commit()
328
833
329 # Trigger an event on change of keys.
834 # Trigger an event on change of keys.
330 trigger(SshKeyFileChangeEvent(), self.request.registry)
835 trigger(SshKeyFileChangeEvent(), self.request.registry)
331
836
332 h.flash(_("Ssh Key successfully created"), category='success')
837 h.flash(_("Ssh Key successfully created"), category='success')
333
838
334 except IntegrityError:
839 except IntegrityError:
335 log.exception("Exception during ssh key saving")
840 log.exception("Exception during ssh key saving")
336 h.flash(_('An error occurred during ssh key saving: {}').format(
841 h.flash(_('An error occurred during ssh key saving: {}').format(
337 'Such key already exists, please use a different one'),
842 'Such key already exists, please use a different one'),
338 category='error')
843 category='error')
339 except Exception as e:
844 except Exception as e:
340 log.exception("Exception during ssh key saving")
845 log.exception("Exception during ssh key saving")
341 h.flash(_('An error occurred during ssh key saving: {}').format(e),
846 h.flash(_('An error occurred during ssh key saving: {}').format(e),
342 category='error')
847 category='error')
343
848
344 return HTTPFound(
849 return HTTPFound(
345 h.route_path('edit_user_ssh_keys', user_id=user_id))
850 h.route_path('edit_user_ssh_keys', user_id=user_id))
346
851
347 @LoginRequired()
852 @LoginRequired()
348 @HasPermissionAllDecorator('hg.admin')
853 @HasPermissionAllDecorator('hg.admin')
349 @CSRFRequired()
854 @CSRFRequired()
350 @view_config(
855 @view_config(
351 route_name='edit_user_ssh_keys_delete', request_method='POST')
856 route_name='edit_user_ssh_keys_delete', request_method='POST')
352 def ssh_keys_delete(self):
857 def ssh_keys_delete(self):
353 _ = self.request.translate
858 _ = self.request.translate
354 c = self.load_default_context()
859 c = self.load_default_context()
355
860
356 user_id = self.request.matchdict.get('user_id')
861 user_id = self.db_user_id
357 c.user = User.get_or_404(user_id)
862 c.user = self.db_user
358 self._redirect_for_default_user(c.user.username)
863
359 user_data = c.user.get_api_data()
864 user_data = c.user.get_api_data()
360
865
361 del_ssh_key = self.request.POST.get('del_ssh_key')
866 del_ssh_key = self.request.POST.get('del_ssh_key')
362
867
363 if del_ssh_key:
868 if del_ssh_key:
364 ssh_key = UserSshKeys.get_or_404(del_ssh_key)
869 ssh_key = UserSshKeys.get_or_404(del_ssh_key)
365 ssh_key_data = ssh_key.get_api_data()
870 ssh_key_data = ssh_key.get_api_data()
366
871
367 SshKeyModel().delete(del_ssh_key, c.user.user_id)
872 SshKeyModel().delete(del_ssh_key, c.user.user_id)
368 audit_logger.store_web(
873 audit_logger.store_web(
369 'user.edit.ssh_key.delete', action_data={
874 'user.edit.ssh_key.delete', action_data={
370 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
875 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
371 user=self._rhodecode_user,)
876 user=self._rhodecode_user,)
372 Session().commit()
877 Session().commit()
373 # Trigger an event on change of keys.
878 # Trigger an event on change of keys.
374 trigger(SshKeyFileChangeEvent(), self.request.registry)
879 trigger(SshKeyFileChangeEvent(), self.request.registry)
375 h.flash(_("Ssh key successfully deleted"), category='success')
880 h.flash(_("Ssh key successfully deleted"), category='success')
376
881
377 return HTTPFound(h.route_path('edit_user_ssh_keys', user_id=user_id))
882 return HTTPFound(h.route_path('edit_user_ssh_keys', user_id=user_id))
378
883
379 @LoginRequired()
884 @LoginRequired()
380 @HasPermissionAllDecorator('hg.admin')
885 @HasPermissionAllDecorator('hg.admin')
381 @view_config(
886 @view_config(
382 route_name='edit_user_emails', request_method='GET',
887 route_name='edit_user_emails', request_method='GET',
383 renderer='rhodecode:templates/admin/users/user_edit.mako')
888 renderer='rhodecode:templates/admin/users/user_edit.mako')
384 def emails(self):
889 def emails(self):
385 _ = self.request.translate
890 _ = self.request.translate
386 c = self.load_default_context()
891 c = self.load_default_context()
387
892 c.user = self.db_user
388 user_id = self.request.matchdict.get('user_id')
389 c.user = User.get_or_404(user_id)
390 self._redirect_for_default_user(c.user.username)
391
893
392 c.active = 'emails'
894 c.active = 'emails'
393 c.user_email_map = UserEmailMap.query() \
895 c.user_email_map = UserEmailMap.query() \
394 .filter(UserEmailMap.user == c.user).all()
896 .filter(UserEmailMap.user == c.user).all()
395
897
396 return self._get_template_context(c)
898 return self._get_template_context(c)
397
899
398 @LoginRequired()
900 @LoginRequired()
399 @HasPermissionAllDecorator('hg.admin')
901 @HasPermissionAllDecorator('hg.admin')
400 @CSRFRequired()
902 @CSRFRequired()
401 @view_config(
903 @view_config(
402 route_name='edit_user_emails_add', request_method='POST')
904 route_name='edit_user_emails_add', request_method='POST')
403 def emails_add(self):
905 def emails_add(self):
404 _ = self.request.translate
906 _ = self.request.translate
405 c = self.load_default_context()
907 c = self.load_default_context()
406
908
407 user_id = self.request.matchdict.get('user_id')
909 user_id = self.db_user_id
408 c.user = User.get_or_404(user_id)
910 c.user = self.db_user
409 self._redirect_for_default_user(c.user.username)
410
911
411 email = self.request.POST.get('new_email')
912 email = self.request.POST.get('new_email')
412 user_data = c.user.get_api_data()
913 user_data = c.user.get_api_data()
413 try:
914 try:
414 UserModel().add_extra_email(c.user.user_id, email)
915 UserModel().add_extra_email(c.user.user_id, email)
415 audit_logger.store_web(
916 audit_logger.store_web(
416 'user.edit.email.add', action_data={'email': email, 'user': user_data},
917 'user.edit.email.add',
918 action_data={'email': email, 'user': user_data},
417 user=self._rhodecode_user)
919 user=self._rhodecode_user)
418 Session().commit()
920 Session().commit()
419 h.flash(_("Added new email address `%s` for user account") % email,
921 h.flash(_("Added new email address `%s` for user account") % email,
420 category='success')
922 category='success')
421 except formencode.Invalid as error:
923 except formencode.Invalid as error:
422 h.flash(h.escape(error.error_dict['email']), category='error')
924 h.flash(h.escape(error.error_dict['email']), category='error')
925 except IntegrityError:
926 log.warning("Email %s already exists", email)
927 h.flash(_('Email `{}` is already registered for another user.').format(email),
928 category='error')
423 except Exception:
929 except Exception:
424 log.exception("Exception during email saving")
930 log.exception("Exception during email saving")
425 h.flash(_('An error occurred during email saving'),
931 h.flash(_('An error occurred during email saving'),
426 category='error')
932 category='error')
427 raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id))
933 raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id))
428
934
429 @LoginRequired()
935 @LoginRequired()
430 @HasPermissionAllDecorator('hg.admin')
936 @HasPermissionAllDecorator('hg.admin')
431 @CSRFRequired()
937 @CSRFRequired()
432 @view_config(
938 @view_config(
433 route_name='edit_user_emails_delete', request_method='POST')
939 route_name='edit_user_emails_delete', request_method='POST')
434 def emails_delete(self):
940 def emails_delete(self):
435 _ = self.request.translate
941 _ = self.request.translate
436 c = self.load_default_context()
942 c = self.load_default_context()
437
943
438 user_id = self.request.matchdict.get('user_id')
944 user_id = self.db_user_id
439 c.user = User.get_or_404(user_id)
945 c.user = self.db_user
440 self._redirect_for_default_user(c.user.username)
441
946
442 email_id = self.request.POST.get('del_email_id')
947 email_id = self.request.POST.get('del_email_id')
443 user_model = UserModel()
948 user_model = UserModel()
444
949
445 email = UserEmailMap.query().get(email_id).email
950 email = UserEmailMap.query().get(email_id).email
446 user_data = c.user.get_api_data()
951 user_data = c.user.get_api_data()
447 user_model.delete_extra_email(c.user.user_id, email_id)
952 user_model.delete_extra_email(c.user.user_id, email_id)
448 audit_logger.store_web(
953 audit_logger.store_web(
449 'user.edit.email.delete', action_data={'email': email, 'user': user_data},
954 'user.edit.email.delete',
955 action_data={'email': email, 'user': user_data},
450 user=self._rhodecode_user)
956 user=self._rhodecode_user)
451 Session().commit()
957 Session().commit()
452 h.flash(_("Removed email address from user account"),
958 h.flash(_("Removed email address from user account"),
453 category='success')
959 category='success')
454 raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id))
960 raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id))
455
961
456 @LoginRequired()
962 @LoginRequired()
457 @HasPermissionAllDecorator('hg.admin')
963 @HasPermissionAllDecorator('hg.admin')
458 @view_config(
964 @view_config(
459 route_name='edit_user_ips', request_method='GET',
965 route_name='edit_user_ips', request_method='GET',
460 renderer='rhodecode:templates/admin/users/user_edit.mako')
966 renderer='rhodecode:templates/admin/users/user_edit.mako')
461 def ips(self):
967 def ips(self):
462 _ = self.request.translate
968 _ = self.request.translate
463 c = self.load_default_context()
969 c = self.load_default_context()
464
970 c.user = self.db_user
465 user_id = self.request.matchdict.get('user_id')
466 c.user = User.get_or_404(user_id)
467 self._redirect_for_default_user(c.user.username)
468
971
469 c.active = 'ips'
972 c.active = 'ips'
470 c.user_ip_map = UserIpMap.query() \
973 c.user_ip_map = UserIpMap.query() \
471 .filter(UserIpMap.user == c.user).all()
974 .filter(UserIpMap.user == c.user).all()
472
975
473 c.inherit_default_ips = c.user.inherit_default_permissions
976 c.inherit_default_ips = c.user.inherit_default_permissions
474 c.default_user_ip_map = UserIpMap.query() \
977 c.default_user_ip_map = UserIpMap.query() \
475 .filter(UserIpMap.user == User.get_default_user()).all()
978 .filter(UserIpMap.user == User.get_default_user()).all()
476
979
477 return self._get_template_context(c)
980 return self._get_template_context(c)
478
981
479 @LoginRequired()
982 @LoginRequired()
480 @HasPermissionAllDecorator('hg.admin')
983 @HasPermissionAllDecorator('hg.admin')
481 @CSRFRequired()
984 @CSRFRequired()
482 @view_config(
985 @view_config(
483 route_name='edit_user_ips_add', request_method='POST')
986 route_name='edit_user_ips_add', request_method='POST')
987 # NOTE(marcink): this view is allowed for default users, as we can
988 # edit their IP white list
484 def ips_add(self):
989 def ips_add(self):
485 _ = self.request.translate
990 _ = self.request.translate
486 c = self.load_default_context()
991 c = self.load_default_context()
487
992
488 user_id = self.request.matchdict.get('user_id')
993 user_id = self.db_user_id
489 c.user = User.get_or_404(user_id)
994 c.user = self.db_user
490 # NOTE(marcink): this view is allowed for default users, as we can
491 # edit their IP white list
492
995
493 user_model = UserModel()
996 user_model = UserModel()
494 desc = self.request.POST.get('description')
997 desc = self.request.POST.get('description')
495 try:
998 try:
496 ip_list = user_model.parse_ip_range(
999 ip_list = user_model.parse_ip_range(
497 self.request.POST.get('new_ip'))
1000 self.request.POST.get('new_ip'))
498 except Exception as e:
1001 except Exception as e:
499 ip_list = []
1002 ip_list = []
500 log.exception("Exception during ip saving")
1003 log.exception("Exception during ip saving")
501 h.flash(_('An error occurred during ip saving:%s' % (e,)),
1004 h.flash(_('An error occurred during ip saving:%s' % (e,)),
502 category='error')
1005 category='error')
503 added = []
1006 added = []
504 user_data = c.user.get_api_data()
1007 user_data = c.user.get_api_data()
505 for ip in ip_list:
1008 for ip in ip_list:
506 try:
1009 try:
507 user_model.add_extra_ip(c.user.user_id, ip, desc)
1010 user_model.add_extra_ip(c.user.user_id, ip, desc)
508 audit_logger.store_web(
1011 audit_logger.store_web(
509 'user.edit.ip.add', action_data={'ip': ip, 'user': user_data},
1012 'user.edit.ip.add',
1013 action_data={'ip': ip, 'user': user_data},
510 user=self._rhodecode_user)
1014 user=self._rhodecode_user)
511 Session().commit()
1015 Session().commit()
512 added.append(ip)
1016 added.append(ip)
513 except formencode.Invalid as error:
1017 except formencode.Invalid as error:
514 msg = error.error_dict['ip']
1018 msg = error.error_dict['ip']
515 h.flash(msg, category='error')
1019 h.flash(msg, category='error')
516 except Exception:
1020 except Exception:
517 log.exception("Exception during ip saving")
1021 log.exception("Exception during ip saving")
518 h.flash(_('An error occurred during ip saving'),
1022 h.flash(_('An error occurred during ip saving'),
519 category='error')
1023 category='error')
520 if added:
1024 if added:
521 h.flash(
1025 h.flash(
522 _("Added ips %s to user whitelist") % (', '.join(ip_list), ),
1026 _("Added ips %s to user whitelist") % (', '.join(ip_list), ),
523 category='success')
1027 category='success')
524 if 'default_user' in self.request.POST:
1028 if 'default_user' in self.request.POST:
525 # case for editing global IP list we do it for 'DEFAULT' user
1029 # case for editing global IP list we do it for 'DEFAULT' user
526 raise HTTPFound(h.route_path('admin_permissions_ips'))
1030 raise HTTPFound(h.route_path('admin_permissions_ips'))
527 raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id))
1031 raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id))
528
1032
529 @LoginRequired()
1033 @LoginRequired()
530 @HasPermissionAllDecorator('hg.admin')
1034 @HasPermissionAllDecorator('hg.admin')
531 @CSRFRequired()
1035 @CSRFRequired()
532 @view_config(
1036 @view_config(
533 route_name='edit_user_ips_delete', request_method='POST')
1037 route_name='edit_user_ips_delete', request_method='POST')
1038 # NOTE(marcink): this view is allowed for default users, as we can
1039 # edit their IP white list
534 def ips_delete(self):
1040 def ips_delete(self):
535 _ = self.request.translate
1041 _ = self.request.translate
536 c = self.load_default_context()
1042 c = self.load_default_context()
537
1043
538 user_id = self.request.matchdict.get('user_id')
1044 user_id = self.db_user_id
539 c.user = User.get_or_404(user_id)
1045 c.user = self.db_user
540 # NOTE(marcink): this view is allowed for default users, as we can
541 # edit their IP white list
542
1046
543 ip_id = self.request.POST.get('del_ip_id')
1047 ip_id = self.request.POST.get('del_ip_id')
544 user_model = UserModel()
1048 user_model = UserModel()
545 user_data = c.user.get_api_data()
1049 user_data = c.user.get_api_data()
546 ip = UserIpMap.query().get(ip_id).ip_addr
1050 ip = UserIpMap.query().get(ip_id).ip_addr
547 user_model.delete_extra_ip(c.user.user_id, ip_id)
1051 user_model.delete_extra_ip(c.user.user_id, ip_id)
548 audit_logger.store_web(
1052 audit_logger.store_web(
549 'user.edit.ip.delete', action_data={'ip': ip, 'user': user_data},
1053 'user.edit.ip.delete', action_data={'ip': ip, 'user': user_data},
550 user=self._rhodecode_user)
1054 user=self._rhodecode_user)
551 Session().commit()
1055 Session().commit()
552 h.flash(_("Removed ip address from user whitelist"), category='success')
1056 h.flash(_("Removed ip address from user whitelist"), category='success')
553
1057
554 if 'default_user' in self.request.POST:
1058 if 'default_user' in self.request.POST:
555 # case for editing global IP list we do it for 'DEFAULT' user
1059 # case for editing global IP list we do it for 'DEFAULT' user
556 raise HTTPFound(h.route_path('admin_permissions_ips'))
1060 raise HTTPFound(h.route_path('admin_permissions_ips'))
557 raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id))
1061 raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id))
558
1062
559 @LoginRequired()
1063 @LoginRequired()
560 @HasPermissionAllDecorator('hg.admin')
1064 @HasPermissionAllDecorator('hg.admin')
561 @view_config(
1065 @view_config(
562 route_name='edit_user_groups_management', request_method='GET',
1066 route_name='edit_user_groups_management', request_method='GET',
563 renderer='rhodecode:templates/admin/users/user_edit.mako')
1067 renderer='rhodecode:templates/admin/users/user_edit.mako')
564 def groups_management(self):
1068 def groups_management(self):
565 c = self.load_default_context()
1069 c = self.load_default_context()
1070 c.user = self.db_user
1071 c.data = c.user.group_member
566
1072
567 user_id = self.request.matchdict.get('user_id')
568 c.user = User.get_or_404(user_id)
569 c.data = c.user.group_member
570 self._redirect_for_default_user(c.user.username)
571 groups = [UserGroupModel.get_user_groups_as_dict(group.users_group)
1073 groups = [UserGroupModel.get_user_groups_as_dict(group.users_group)
572 for group in c.user.group_member]
1074 for group in c.user.group_member]
573 c.groups = json.dumps(groups)
1075 c.groups = json.dumps(groups)
574 c.active = 'groups'
1076 c.active = 'groups'
575
1077
576 return self._get_template_context(c)
1078 return self._get_template_context(c)
577
1079
578 @LoginRequired()
1080 @LoginRequired()
579 @HasPermissionAllDecorator('hg.admin')
1081 @HasPermissionAllDecorator('hg.admin')
580 @CSRFRequired()
1082 @CSRFRequired()
581 @view_config(
1083 @view_config(
582 route_name='edit_user_groups_management_updates', request_method='POST')
1084 route_name='edit_user_groups_management_updates', request_method='POST')
583 def groups_management_updates(self):
1085 def groups_management_updates(self):
584 _ = self.request.translate
1086 _ = self.request.translate
585 c = self.load_default_context()
1087 c = self.load_default_context()
586
1088
587 user_id = self.request.matchdict.get('user_id')
1089 user_id = self.db_user_id
588 c.user = User.get_or_404(user_id)
1090 c.user = self.db_user
589 self._redirect_for_default_user(c.user.username)
590
1091
591 user_groups = set(self.request.POST.getall('users_group_id'))
1092 user_groups = set(self.request.POST.getall('users_group_id'))
592 user_groups_objects = []
1093 user_groups_objects = []
593
1094
594 for ugid in user_groups:
1095 for ugid in user_groups:
595 user_groups_objects.append(
1096 user_groups_objects.append(
596 UserGroupModel().get_group(safe_int(ugid)))
1097 UserGroupModel().get_group(safe_int(ugid)))
597 user_group_model = UserGroupModel()
1098 user_group_model = UserGroupModel()
598 user_group_model.change_groups(c.user, user_groups_objects)
1099 added_to_groups, removed_from_groups = \
1100 user_group_model.change_groups(c.user, user_groups_objects)
1101
1102 user_data = c.user.get_api_data()
1103 for user_group_id in added_to_groups:
1104 user_group = UserGroup.get(user_group_id)
1105 old_values = user_group.get_api_data()
1106 audit_logger.store_web(
1107 'user_group.edit.member.add',
1108 action_data={'user': user_data, 'old_data': old_values},
1109 user=self._rhodecode_user)
1110
1111 for user_group_id in removed_from_groups:
1112 user_group = UserGroup.get(user_group_id)
1113 old_values = user_group.get_api_data()
1114 audit_logger.store_web(
1115 'user_group.edit.member.delete',
1116 action_data={'user': user_data, 'old_data': old_values},
1117 user=self._rhodecode_user)
599
1118
600 Session().commit()
1119 Session().commit()
601 c.active = 'user_groups_management'
1120 c.active = 'user_groups_management'
602 h.flash(_("Groups successfully changed"), category='success')
1121 h.flash(_("Groups successfully changed"), category='success')
603
1122
604 return HTTPFound(h.route_path(
1123 return HTTPFound(h.route_path(
605 'edit_user_groups_management', user_id=user_id))
1124 'edit_user_groups_management', user_id=user_id))
606
1125
607 @LoginRequired()
1126 @LoginRequired()
608 @HasPermissionAllDecorator('hg.admin')
1127 @HasPermissionAllDecorator('hg.admin')
609 @view_config(
1128 @view_config(
610 route_name='edit_user_audit_logs', request_method='GET',
1129 route_name='edit_user_audit_logs', request_method='GET',
611 renderer='rhodecode:templates/admin/users/user_edit.mako')
1130 renderer='rhodecode:templates/admin/users/user_edit.mako')
612 def user_audit_logs(self):
1131 def user_audit_logs(self):
613 _ = self.request.translate
1132 _ = self.request.translate
614 c = self.load_default_context()
1133 c = self.load_default_context()
1134 c.user = self.db_user
615
1135
616 user_id = self.request.matchdict.get('user_id')
617 c.user = User.get_or_404(user_id)
618 self._redirect_for_default_user(c.user.username)
619 c.active = 'audit'
1136 c.active = 'audit'
620
1137
621 p = safe_int(self.request.GET.get('page', 1), 1)
1138 p = safe_int(self.request.GET.get('page', 1), 1)
622
1139
623 filter_term = self.request.GET.get('filter')
1140 filter_term = self.request.GET.get('filter')
624 user_log = UserModel().get_user_log(c.user, filter_term)
1141 user_log = UserModel().get_user_log(c.user, filter_term)
625
1142
626 def url_generator(**kw):
1143 def url_generator(**kw):
627 if filter_term:
1144 if filter_term:
628 kw['filter'] = filter_term
1145 kw['filter'] = filter_term
629 return self.request.current_route_path(_query=kw)
1146 return self.request.current_route_path(_query=kw)
630
1147
631 c.audit_logs = h.Page(
1148 c.audit_logs = h.Page(
632 user_log, page=p, items_per_page=10, url=url_generator)
1149 user_log, page=p, items_per_page=10, url=url_generator)
633 c.filter_term = filter_term
1150 c.filter_term = filter_term
634 return self._get_template_context(c)
1151 return self._get_template_context(c)
635
1152
636 @LoginRequired()
1153 @LoginRequired()
637 @HasPermissionAllDecorator('hg.admin')
1154 @HasPermissionAllDecorator('hg.admin')
638 @view_config(
1155 @view_config(
639 route_name='edit_user_perms_summary', request_method='GET',
1156 route_name='edit_user_perms_summary', request_method='GET',
640 renderer='rhodecode:templates/admin/users/user_edit.mako')
1157 renderer='rhodecode:templates/admin/users/user_edit.mako')
641 def user_perms_summary(self):
1158 def user_perms_summary(self):
642 _ = self.request.translate
1159 _ = self.request.translate
643 c = self.load_default_context()
1160 c = self.load_default_context()
644
1161 c.user = self.db_user
645 user_id = self.request.matchdict.get('user_id')
646 c.user = User.get_or_404(user_id)
647 self._redirect_for_default_user(c.user.username)
648
1162
649 c.active = 'perms_summary'
1163 c.active = 'perms_summary'
650 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
1164 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
651
1165
652 return self._get_template_context(c)
1166 return self._get_template_context(c)
653
1167
654 @LoginRequired()
1168 @LoginRequired()
655 @HasPermissionAllDecorator('hg.admin')
1169 @HasPermissionAllDecorator('hg.admin')
656 @view_config(
1170 @view_config(
657 route_name='edit_user_perms_summary_json', request_method='GET',
1171 route_name='edit_user_perms_summary_json', request_method='GET',
658 renderer='json_ext')
1172 renderer='json_ext')
659 def user_perms_summary_json(self):
1173 def user_perms_summary_json(self):
660 self.load_default_context()
1174 self.load_default_context()
661
1175 perm_user = self.db_user.AuthUser(ip_addr=self.request.remote_addr)
662 user_id = self.request.matchdict.get('user_id')
663 user = User.get_or_404(user_id)
664 self._redirect_for_default_user(user.username)
665
666 perm_user = user.AuthUser(ip_addr=self.request.remote_addr)
667
1176
668 return perm_user.permissions
1177 return perm_user.permissions
@@ -1,182 +1,182 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 environment configuration
22 Pylons environment configuration
23 """
23 """
24
24
25 import os
25 import os
26 import logging
26 import logging
27 import rhodecode
27 import rhodecode
28 import platform
28 import platform
29 import re
29 import re
30 import io
30 import io
31
31
32 from mako.lookup import TemplateLookup
32 from mako.lookup import TemplateLookup
33 from pylons.configuration import PylonsConfig
33 from pylons.configuration import PylonsConfig
34 from pylons.error import handle_mako_error
34 from pylons.error import handle_mako_error
35 from pyramid.settings import asbool
35 from pyramid.settings import asbool
36
36
37 # ------------------------------------------------------------------------------
37 # ------------------------------------------------------------------------------
38 # CELERY magic until refactor - issue #4163 - import order matters here:
38 # CELERY magic until refactor - issue #4163 - import order matters here:
39 from rhodecode.lib import celerypylons # this must be first, celerypylons
39 from rhodecode.lib import celerypylons # this must be first, celerypylons
40 # sets config settings upon import
40 # sets config settings upon import
41
41
42 import rhodecode.integrations # any modules using celery task
42 import rhodecode.integrations # any modules using celery task
43 # decorators should be added afterwards:
43 # decorators should be added afterwards:
44 # ------------------------------------------------------------------------------
44 # ------------------------------------------------------------------------------
45
45
46 from rhodecode.lib import app_globals
46 from rhodecode.lib import app_globals
47 from rhodecode.config import utils
47 from rhodecode.config import utils
48 from rhodecode.config.routing import make_map
48 from rhodecode.config.routing import make_map
49 from rhodecode.config.jsroutes import generate_jsroutes_content
49 from rhodecode.config.jsroutes import generate_jsroutes_content
50
50
51 from rhodecode.lib import helpers
51 from rhodecode.lib import helpers
52 from rhodecode.lib.auth import set_available_permissions
52 from rhodecode.lib.auth import set_available_permissions
53 from rhodecode.lib.utils import (
53 from rhodecode.lib.utils import (
54 repo2db_mapper, make_db_config, set_rhodecode_config,
54 repo2db_mapper, make_db_config, set_rhodecode_config,
55 load_rcextensions)
55 load_rcextensions)
56 from rhodecode.lib.utils2 import str2bool, aslist
56 from rhodecode.lib.utils2 import str2bool, aslist
57 from rhodecode.lib.vcs import connect_vcs, start_vcs_server
57 from rhodecode.lib.vcs import connect_vcs, start_vcs_server
58 from rhodecode.model.scm import ScmModel
58 from rhodecode.model.scm import ScmModel
59
59
60 log = logging.getLogger(__name__)
60 log = logging.getLogger(__name__)
61
61
62 def load_environment(global_conf, app_conf, initial=False,
62 def load_environment(global_conf, app_conf, initial=False,
63 test_env=None, test_index=None):
63 test_env=None, test_index=None):
64 """
64 """
65 Configure the Pylons environment via the ``pylons.config``
65 Configure the Pylons environment via the ``pylons.config``
66 object
66 object
67 """
67 """
68 config = PylonsConfig()
68 config = PylonsConfig()
69
69
70
70
71 # Pylons paths
71 # Pylons paths
72 root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
72 root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
73 paths = {
73 paths = {
74 'root': root,
74 'root': root,
75 'controllers': os.path.join(root, 'controllers'),
75 'controllers': os.path.join(root, 'controllers'),
76 'static_files': os.path.join(root, 'public'),
76 'static_files': os.path.join(root, 'public'),
77 'templates': [os.path.join(root, 'templates')],
77 'templates': [os.path.join(root, 'templates')],
78 }
78 }
79
79
80 # Initialize config with the basic options
80 # Initialize config with the basic options
81 config.init_app(global_conf, app_conf, package='rhodecode', paths=paths)
81 config.init_app(global_conf, app_conf, package='rhodecode', paths=paths)
82
82
83 # store some globals into rhodecode
83 # store some globals into rhodecode
84 rhodecode.CELERY_ENABLED = str2bool(config['app_conf'].get('use_celery'))
84 rhodecode.CELERY_ENABLED = str2bool(config['app_conf'].get('use_celery'))
85 rhodecode.CELERY_EAGER = str2bool(
85 rhodecode.CELERY_EAGER = str2bool(
86 config['app_conf'].get('celery.always.eager'))
86 config['app_conf'].get('celery.always.eager'))
87
87
88 config['routes.map'] = make_map(config)
88 config['routes.map'] = make_map(config)
89
89
90 config['pylons.app_globals'] = app_globals.Globals(config)
90 config['pylons.app_globals'] = app_globals.Globals(config)
91 config['pylons.h'] = helpers
91 config['pylons.h'] = helpers
92 rhodecode.CONFIG = config
92 rhodecode.CONFIG = config
93
93
94 load_rcextensions(root_path=config['here'])
94 load_rcextensions(root_path=config['here'])
95
95
96 # Setup cache object as early as possible
96 # Setup cache object as early as possible
97 import pylons
97 import pylons
98 pylons.cache._push_object(config['pylons.app_globals'].cache)
98 pylons.cache._push_object(config['pylons.app_globals'].cache)
99
99
100 # Create the Mako TemplateLookup, with the default auto-escaping
100 # Create the Mako TemplateLookup, with the default auto-escaping
101 config['pylons.app_globals'].mako_lookup = TemplateLookup(
101 config['pylons.app_globals'].mako_lookup = TemplateLookup(
102 directories=paths['templates'],
102 directories=paths['templates'],
103 error_handler=handle_mako_error,
103 error_handler=handle_mako_error,
104 module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
104 module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
105 input_encoding='utf-8', default_filters=['escape'],
105 input_encoding='utf-8', default_filters=['escape'],
106 imports=['from webhelpers.html import escape'])
106 imports=['from webhelpers.html import escape'])
107
107
108 # sets the c attribute access when don't existing attribute are accessed
108 # sets the c attribute access when don't existing attribute are accessed
109 config['pylons.strict_tmpl_context'] = True
109 config['pylons.strict_tmpl_context'] = True
110
110
111 # configure channelstream
111 # configure channelstream
112 config['channelstream_config'] = {
112 config['channelstream_config'] = {
113 'enabled': asbool(config.get('channelstream.enabled', False)),
113 'enabled': asbool(config.get('channelstream.enabled', False)),
114 'server': config.get('channelstream.server'),
114 'server': config.get('channelstream.server'),
115 'secret': config.get('channelstream.secret')
115 'secret': config.get('channelstream.secret')
116 }
116 }
117
117
118 set_available_permissions(config)
119 db_cfg = make_db_config(clear_session=True)
118 db_cfg = make_db_config(clear_session=True)
120
119
121 repos_path = list(db_cfg.items('paths'))[0][1]
120 repos_path = list(db_cfg.items('paths'))[0][1]
122 config['base_path'] = repos_path
121 config['base_path'] = repos_path
123
122
124 # store db config also in main global CONFIG
123 # store db config also in main global CONFIG
125 set_rhodecode_config(config)
124 set_rhodecode_config(config)
126
125
127 # configure instance id
126 # configure instance id
128 utils.set_instance_id(config)
127 utils.set_instance_id(config)
129
128
130 # CONFIGURATION OPTIONS HERE (note: all config options will override
129 # CONFIGURATION OPTIONS HERE (note: all config options will override
131 # any Pylons config options)
130 # any Pylons config options)
132
131
133 # store config reference into our module to skip import magic of pylons
132 # store config reference into our module to skip import magic of pylons
134 rhodecode.CONFIG.update(config)
133 rhodecode.CONFIG.update(config)
135
134
136 return config
135 return config
137
136
138
137
139 def load_pyramid_environment(global_config, settings):
138 def load_pyramid_environment(global_config, settings):
140 # Some parts of the code expect a merge of global and app settings.
139 # Some parts of the code expect a merge of global and app settings.
141 settings_merged = global_config.copy()
140 settings_merged = global_config.copy()
142 settings_merged.update(settings)
141 settings_merged.update(settings)
143
142
144 # Store the settings to make them available to other modules.
143 # Store the settings to make them available to other modules.
145 rhodecode.PYRAMID_SETTINGS = settings_merged
144 rhodecode.PYRAMID_SETTINGS = settings_merged
146 # NOTE(marcink): needs to be enabled after full port to pyramid
145 # NOTE(marcink): needs to be enabled after full port to pyramid
147 # rhodecode.CONFIG = config
146 # rhodecode.CONFIG = config
148
147
149 # If this is a test run we prepare the test environment like
148 # If this is a test run we prepare the test environment like
150 # creating a test database, test search index and test repositories.
149 # creating a test database, test search index and test repositories.
151 # This has to be done before the database connection is initialized.
150 # This has to be done before the database connection is initialized.
152 if settings['is_test']:
151 if settings['is_test']:
153 rhodecode.is_test = True
152 rhodecode.is_test = True
154 rhodecode.disable_error_handler = True
153 rhodecode.disable_error_handler = True
155
154
156 utils.initialize_test_environment(settings_merged)
155 utils.initialize_test_environment(settings_merged)
157
156
158 # Initialize the database connection.
157 # Initialize the database connection.
159 utils.initialize_database(settings_merged)
158 utils.initialize_database(settings_merged)
160
159
161 # Limit backends to `vcs.backends` from configuration
160 # Limit backends to `vcs.backends` from configuration
162 for alias in rhodecode.BACKENDS.keys():
161 for alias in rhodecode.BACKENDS.keys():
163 if alias not in settings['vcs.backends']:
162 if alias not in settings['vcs.backends']:
164 del rhodecode.BACKENDS[alias]
163 del rhodecode.BACKENDS[alias]
165 log.info('Enabled VCS backends: %s', rhodecode.BACKENDS.keys())
164 log.info('Enabled VCS backends: %s', rhodecode.BACKENDS.keys())
166
165
167 # initialize vcs client and optionally run the server if enabled
166 # initialize vcs client and optionally run the server if enabled
168 vcs_server_uri = settings['vcs.server']
167 vcs_server_uri = settings['vcs.server']
169 vcs_server_enabled = settings['vcs.server.enable']
168 vcs_server_enabled = settings['vcs.server.enable']
170 start_server = (
169 start_server = (
171 settings['vcs.start_server'] and
170 settings['vcs.start_server'] and
172 not int(os.environ.get('RC_VCSSERVER_TEST_DISABLE', '0')))
171 not int(os.environ.get('RC_VCSSERVER_TEST_DISABLE', '0')))
173
172
174 if vcs_server_enabled and start_server:
173 if vcs_server_enabled and start_server:
175 log.info("Starting vcsserver")
174 log.info("Starting vcsserver")
176 start_vcs_server(server_and_port=vcs_server_uri,
175 start_vcs_server(server_and_port=vcs_server_uri,
177 protocol=utils.get_vcs_server_protocol(settings),
176 protocol=utils.get_vcs_server_protocol(settings),
178 log_level=settings['vcs.server.log_level'])
177 log_level=settings['vcs.server.log_level'])
179
178
180 utils.configure_vcs(settings)
179 utils.configure_vcs(settings)
180
181 if vcs_server_enabled:
181 if vcs_server_enabled:
182 connect_vcs(vcs_server_uri, utils.get_vcs_server_protocol(settings))
182 connect_vcs(vcs_server_uri, utils.get_vcs_server_protocol(settings))
@@ -1,536 +1,542 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 import utils as config_utils
44 from rhodecode.config.routing import STATIC_FILE_PREFIX
45 from rhodecode.config.routing import STATIC_FILE_PREFIX
45 from rhodecode.config.environment import (
46 from rhodecode.config.environment import (
46 load_environment, load_pyramid_environment)
47 load_environment, load_pyramid_environment)
47
48
48 from rhodecode.lib.vcs import VCSCommunicationError
49 from rhodecode.lib.vcs import VCSCommunicationError
49 from rhodecode.lib.exceptions import VCSServerUnavailable
50 from rhodecode.lib.exceptions import VCSServerUnavailable
50 from rhodecode.lib.middleware.appenlight import wrap_in_appenlight_if_enabled
51 from rhodecode.lib.middleware.appenlight import wrap_in_appenlight_if_enabled
51 from rhodecode.lib.middleware.error_handling import (
52 from rhodecode.lib.middleware.error_handling import (
52 PylonsErrorHandlingMiddleware)
53 PylonsErrorHandlingMiddleware)
53 from rhodecode.lib.middleware.https_fixup import HttpsFixup
54 from rhodecode.lib.middleware.https_fixup import HttpsFixup
54 from rhodecode.lib.middleware.vcs import VCSMiddleware
55 from rhodecode.lib.middleware.vcs import VCSMiddleware
55 from rhodecode.lib.plugins.utils import register_rhodecode_plugin
56 from rhodecode.lib.plugins.utils import register_rhodecode_plugin
56 from rhodecode.lib.utils2 import aslist as rhodecode_aslist, AttributeDict
57 from rhodecode.lib.utils2 import aslist as rhodecode_aslist, AttributeDict
57 from rhodecode.subscribers import (
58 from rhodecode.subscribers import (
58 scan_repositories_if_enabled, write_js_routes_if_enabled,
59 scan_repositories_if_enabled, write_js_routes_if_enabled,
59 write_metadata_if_needed)
60 write_metadata_if_needed, inject_app_settings)
60
61
61
62
62 log = logging.getLogger(__name__)
63 log = logging.getLogger(__name__)
63
64
64
65
65 # this is used to avoid avoid the route lookup overhead in routesmiddleware
66 # 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
67 # 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
68 # it is only needed for the pylons migration and can be removed once complete
68 class SkippableRoutesMiddleware(RoutesMiddleware):
69 class SkippableRoutesMiddleware(RoutesMiddleware):
69 """ Routes middleware that allows you to skip prefixes """
70 """ Routes middleware that allows you to skip prefixes """
70
71
71 def __init__(self, *args, **kw):
72 def __init__(self, *args, **kw):
72 self.skip_prefixes = kw.pop('skip_prefixes', [])
73 self.skip_prefixes = kw.pop('skip_prefixes', [])
73 super(SkippableRoutesMiddleware, self).__init__(*args, **kw)
74 super(SkippableRoutesMiddleware, self).__init__(*args, **kw)
74
75
75 def __call__(self, environ, start_response):
76 def __call__(self, environ, start_response):
76 for prefix in self.skip_prefixes:
77 for prefix in self.skip_prefixes:
77 if environ['PATH_INFO'].startswith(prefix):
78 if environ['PATH_INFO'].startswith(prefix):
78 # added to avoid the case when a missing /_static route falls
79 # added to avoid the case when a missing /_static route falls
79 # through to pylons and causes an exception as pylons is
80 # through to pylons and causes an exception as pylons is
80 # expecting wsgiorg.routingargs to be set in the environ
81 # expecting wsgiorg.routingargs to be set in the environ
81 # by RoutesMiddleware.
82 # by RoutesMiddleware.
82 if 'wsgiorg.routing_args' not in environ:
83 if 'wsgiorg.routing_args' not in environ:
83 environ['wsgiorg.routing_args'] = (None, {})
84 environ['wsgiorg.routing_args'] = (None, {})
84 return self.app(environ, start_response)
85 return self.app(environ, start_response)
85
86
86 return super(SkippableRoutesMiddleware, self).__call__(
87 return super(SkippableRoutesMiddleware, self).__call__(
87 environ, start_response)
88 environ, start_response)
88
89
89
90
90 def make_app(global_conf, static_files=True, **app_conf):
91 def make_app(global_conf, static_files=True, **app_conf):
91 """Create a Pylons WSGI application and return it
92 """Create a Pylons WSGI application and return it
92
93
93 ``global_conf``
94 ``global_conf``
94 The inherited configuration for this application. Normally from
95 The inherited configuration for this application. Normally from
95 the [DEFAULT] section of the Paste ini file.
96 the [DEFAULT] section of the Paste ini file.
96
97
97 ``app_conf``
98 ``app_conf``
98 The application's local configuration. Normally specified in
99 The application's local configuration. Normally specified in
99 the [app:<name>] section of the Paste ini file (where <name>
100 the [app:<name>] section of the Paste ini file (where <name>
100 defaults to main).
101 defaults to main).
101
102
102 """
103 """
103 # Apply compatibility patches
104 # Apply compatibility patches
104 patches.kombu_1_5_1_python_2_7_11()
105 patches.kombu_1_5_1_python_2_7_11()
105 patches.inspect_getargspec()
106 patches.inspect_getargspec()
106
107
107 # Configure the Pylons environment
108 # Configure the Pylons environment
108 config = load_environment(global_conf, app_conf)
109 config = load_environment(global_conf, app_conf)
109
110
110 # The Pylons WSGI app
111 # The Pylons WSGI app
111 app = PylonsApp(config=config)
112 app = PylonsApp(config=config)
112
113
113 # Establish the Registry for this application
114 # Establish the Registry for this application
114 app = RegistryManager(app)
115 app = RegistryManager(app)
115
116
116 app.config = config
117 app.config = config
117
118
118 return app
119 return app
119
120
120
121
121 def make_pyramid_app(global_config, **settings):
122 def make_pyramid_app(global_config, **settings):
122 """
123 """
123 Constructs the WSGI application based on Pyramid and wraps the Pylons based
124 Constructs the WSGI application based on Pyramid and wraps the Pylons based
124 application.
125 application.
125
126
126 Specials:
127 Specials:
127
128
128 * We migrate from Pylons to Pyramid. While doing this, we keep both
129 * We migrate from Pylons to Pyramid. While doing this, we keep both
129 frameworks functional. This involves moving some WSGI middlewares around
130 frameworks functional. This involves moving some WSGI middlewares around
130 and providing access to some data internals, so that the old code is
131 and providing access to some data internals, so that the old code is
131 still functional.
132 still functional.
132
133
133 * The application can also be integrated like a plugin via the call to
134 * The application can also be integrated like a plugin via the call to
134 `includeme`. This is accompanied with the other utility functions which
135 `includeme`. This is accompanied with the other utility functions which
135 are called. Changing this should be done with great care to not break
136 are called. Changing this should be done with great care to not break
136 cases when these fragments are assembled from another place.
137 cases when these fragments are assembled from another place.
137
138
138 """
139 """
139 # The edition string should be available in pylons too, so we add it here
140 # The edition string should be available in pylons too, so we add it here
140 # before copying the settings.
141 # before copying the settings.
141 settings.setdefault('rhodecode.edition', 'Community Edition')
142 settings.setdefault('rhodecode.edition', 'Community Edition')
142
143
143 # As long as our Pylons application does expect "unprepared" settings, make
144 # As long as our Pylons application does expect "unprepared" settings, make
144 # sure that we keep an unmodified copy. This avoids unintentional change of
145 # sure that we keep an unmodified copy. This avoids unintentional change of
145 # behavior in the old application.
146 # behavior in the old application.
146 settings_pylons = settings.copy()
147 settings_pylons = settings.copy()
147
148
148 sanitize_settings_and_apply_defaults(settings)
149 sanitize_settings_and_apply_defaults(settings)
150
149 config = Configurator(settings=settings)
151 config = Configurator(settings=settings)
152 load_pyramid_environment(global_config, settings)
153
150 add_pylons_compat_data(config.registry, global_config, settings_pylons)
154 add_pylons_compat_data(config.registry, global_config, settings_pylons)
151
155
152 load_pyramid_environment(global_config, settings)
153
154 includeme_first(config)
156 includeme_first(config)
155 includeme(config)
157 includeme(config)
156
158
157 pyramid_app = config.make_wsgi_app()
159 pyramid_app = config.make_wsgi_app()
158 pyramid_app = wrap_app_in_wsgi_middlewares(pyramid_app, config)
160 pyramid_app = wrap_app_in_wsgi_middlewares(pyramid_app, config)
159 pyramid_app.config = config
161 pyramid_app.config = config
160
162
161 # creating the app uses a connection - return it after we are done
163 # creating the app uses a connection - return it after we are done
162 meta.Session.remove()
164 meta.Session.remove()
163
165
164 return pyramid_app
166 return pyramid_app
165
167
166
168
167 def make_not_found_view(config):
169 def make_not_found_view(config):
168 """
170 """
169 This creates the view which should be registered as not-found-view to
171 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.
172 pyramid. Basically it contains of the old pylons app, converted to a view.
171 Additionally it is wrapped by some other middlewares.
173 Additionally it is wrapped by some other middlewares.
172 """
174 """
173 settings = config.registry.settings
175 settings = config.registry.settings
174 vcs_server_enabled = settings['vcs.server.enable']
176 vcs_server_enabled = settings['vcs.server.enable']
175
177
176 # Make pylons app from unprepared settings.
178 # Make pylons app from unprepared settings.
177 pylons_app = make_app(
179 pylons_app = make_app(
178 config.registry._pylons_compat_global_config,
180 config.registry._pylons_compat_global_config,
179 **config.registry._pylons_compat_settings)
181 **config.registry._pylons_compat_settings)
180 config.registry._pylons_compat_config = pylons_app.config
182 config.registry._pylons_compat_config = pylons_app.config
181
183
182 # Appenlight monitoring.
184 # Appenlight monitoring.
183 pylons_app, appenlight_client = wrap_in_appenlight_if_enabled(
185 pylons_app, appenlight_client = wrap_in_appenlight_if_enabled(
184 pylons_app, settings)
186 pylons_app, settings)
185
187
186 # The pylons app is executed inside of the pyramid 404 exception handler.
188 # 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
189 # 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
190 # 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
191 # case of an exception or error response. This way we return proper error
190 # HTML pages in case of an error.
192 # HTML pages in case of an error.
191 reraise = (settings.get('debugtoolbar.enabled', False) or
193 reraise = (settings.get('debugtoolbar.enabled', False) or
192 rhodecode.disable_error_handler)
194 rhodecode.disable_error_handler)
193 pylons_app = PylonsErrorHandlingMiddleware(
195 pylons_app = PylonsErrorHandlingMiddleware(
194 pylons_app, error_handler, reraise)
196 pylons_app, error_handler, reraise)
195
197
196 # The VCSMiddleware shall operate like a fallback if pyramid doesn't find a
198 # 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
199 # 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
200 # 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
201 # 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.
202 # command line tools and the user won't get a meaningful error message.
201 if vcs_server_enabled:
203 if vcs_server_enabled:
202 pylons_app = VCSMiddleware(
204 pylons_app = VCSMiddleware(
203 pylons_app, settings, appenlight_client, registry=config.registry)
205 pylons_app, settings, appenlight_client, registry=config.registry)
204
206
205 # Convert WSGI app to pyramid view and return it.
207 # Convert WSGI app to pyramid view and return it.
206 return wsgiapp(pylons_app)
208 return wsgiapp(pylons_app)
207
209
208
210
209 def add_pylons_compat_data(registry, global_config, settings):
211 def add_pylons_compat_data(registry, global_config, settings):
210 """
212 """
211 Attach data to the registry to support the Pylons integration.
213 Attach data to the registry to support the Pylons integration.
212 """
214 """
213 registry._pylons_compat_global_config = global_config
215 registry._pylons_compat_global_config = global_config
214 registry._pylons_compat_settings = settings
216 registry._pylons_compat_settings = settings
215
217
216
218
217 def error_handler(exception, request):
219 def error_handler(exception, request):
218 import rhodecode
220 import rhodecode
219 from rhodecode.lib import helpers
221 from rhodecode.lib import helpers
220
222
221 rhodecode_title = rhodecode.CONFIG.get('rhodecode_title') or 'RhodeCode'
223 rhodecode_title = rhodecode.CONFIG.get('rhodecode_title') or 'RhodeCode'
222
224
223 base_response = HTTPInternalServerError()
225 base_response = HTTPInternalServerError()
224 # prefer original exception for the response since it may have headers set
226 # prefer original exception for the response since it may have headers set
225 if isinstance(exception, HTTPException):
227 if isinstance(exception, HTTPException):
226 base_response = exception
228 base_response = exception
227 elif isinstance(exception, VCSCommunicationError):
229 elif isinstance(exception, VCSCommunicationError):
228 base_response = VCSServerUnavailable()
230 base_response = VCSServerUnavailable()
229
231
230 def is_http_error(response):
232 def is_http_error(response):
231 # error which should have traceback
233 # error which should have traceback
232 return response.status_code > 499
234 return response.status_code > 499
233
235
234 if is_http_error(base_response):
236 if is_http_error(base_response):
235 log.exception(
237 log.exception(
236 'error occurred handling this request for path: %s', request.path)
238 'error occurred handling this request for path: %s', request.path)
237
239
238 c = AttributeDict()
240 c = AttributeDict()
239 c.error_message = base_response.status
241 c.error_message = base_response.status
240 c.error_explanation = base_response.explanation or str(base_response)
242 c.error_explanation = base_response.explanation or str(base_response)
241 c.visual = AttributeDict()
243 c.visual = AttributeDict()
242
244
243 c.visual.rhodecode_support_url = (
245 c.visual.rhodecode_support_url = (
244 request.registry.settings.get('rhodecode_support_url') or
246 request.registry.settings.get('rhodecode_support_url') or
245 request.route_url('rhodecode_support')
247 request.route_url('rhodecode_support')
246 )
248 )
247 c.redirect_time = 0
249 c.redirect_time = 0
248 c.rhodecode_name = rhodecode_title
250 c.rhodecode_name = rhodecode_title
249 if not c.rhodecode_name:
251 if not c.rhodecode_name:
250 c.rhodecode_name = 'Rhodecode'
252 c.rhodecode_name = 'Rhodecode'
251
253
252 c.causes = []
254 c.causes = []
253 if hasattr(base_response, 'causes'):
255 if hasattr(base_response, 'causes'):
254 c.causes = base_response.causes
256 c.causes = base_response.causes
255 c.messages = helpers.flash.pop_messages(request=request)
257 c.messages = helpers.flash.pop_messages(request=request)
256 c.traceback = traceback.format_exc()
258 c.traceback = traceback.format_exc()
257 response = render_to_response(
259 response = render_to_response(
258 '/errors/error_document.mako', {'c': c, 'h': helpers}, request=request,
260 '/errors/error_document.mako', {'c': c, 'h': helpers}, request=request,
259 response=base_response)
261 response=base_response)
260
262
261 return response
263 return response
262
264
263
265
264 def includeme(config):
266 def includeme(config):
265 settings = config.registry.settings
267 settings = config.registry.settings
266
268
267 # plugin information
269 # plugin information
268 config.registry.rhodecode_plugins = OrderedDict()
270 config.registry.rhodecode_plugins = OrderedDict()
269
271
270 config.add_directive(
272 config.add_directive(
271 'register_rhodecode_plugin', register_rhodecode_plugin)
273 'register_rhodecode_plugin', register_rhodecode_plugin)
272
274
273 if asbool(settings.get('appenlight', 'false')):
275 if asbool(settings.get('appenlight', 'false')):
274 config.include('appenlight_client.ext.pyramid_tween')
276 config.include('appenlight_client.ext.pyramid_tween')
275
277
276 if 'mako.default_filters' not in settings:
278 if 'mako.default_filters' not in settings:
277 # set custom default filters if we don't have it defined
279 # set custom default filters if we don't have it defined
278 settings['mako.imports'] = 'from rhodecode.lib.base import h_filter'
280 settings['mako.imports'] = 'from rhodecode.lib.base import h_filter'
279 settings['mako.default_filters'] = 'h_filter'
281 settings['mako.default_filters'] = 'h_filter'
280
282
281 # Includes which are required. The application would fail without them.
283 # Includes which are required. The application would fail without them.
282 config.include('pyramid_mako')
284 config.include('pyramid_mako')
283 config.include('pyramid_beaker')
285 config.include('pyramid_beaker')
284
286
285 config.include('rhodecode.authentication')
287 config.include('rhodecode.authentication')
286 config.include('rhodecode.integrations')
288 config.include('rhodecode.integrations')
287
289
288 # apps
290 # apps
289 config.include('rhodecode.apps._base')
291 config.include('rhodecode.apps._base')
290 config.include('rhodecode.apps.ops')
292 config.include('rhodecode.apps.ops')
291
293
292 config.include('rhodecode.apps.admin')
294 config.include('rhodecode.apps.admin')
293 config.include('rhodecode.apps.channelstream')
295 config.include('rhodecode.apps.channelstream')
294 config.include('rhodecode.apps.login')
296 config.include('rhodecode.apps.login')
295 config.include('rhodecode.apps.home')
297 config.include('rhodecode.apps.home')
296 config.include('rhodecode.apps.journal')
298 config.include('rhodecode.apps.journal')
297 config.include('rhodecode.apps.repository')
299 config.include('rhodecode.apps.repository')
298 config.include('rhodecode.apps.repo_group')
300 config.include('rhodecode.apps.repo_group')
299 config.include('rhodecode.apps.user_group')
301 config.include('rhodecode.apps.user_group')
300 config.include('rhodecode.apps.search')
302 config.include('rhodecode.apps.search')
301 config.include('rhodecode.apps.user_profile')
303 config.include('rhodecode.apps.user_profile')
302 config.include('rhodecode.apps.my_account')
304 config.include('rhodecode.apps.my_account')
303 config.include('rhodecode.apps.svn_support')
305 config.include('rhodecode.apps.svn_support')
304 config.include('rhodecode.apps.ssh_support')
306 config.include('rhodecode.apps.ssh_support')
305 config.include('rhodecode.apps.gist')
307 config.include('rhodecode.apps.gist')
306
308
307 config.include('rhodecode.apps.debug_style')
309 config.include('rhodecode.apps.debug_style')
308 config.include('rhodecode.tweens')
310 config.include('rhodecode.tweens')
309 config.include('rhodecode.api')
311 config.include('rhodecode.api')
310
312
311 config.add_route(
313 config.add_route(
312 'rhodecode_support', 'https://rhodecode.com/help/', static=True)
314 'rhodecode_support', 'https://rhodecode.com/help/', static=True)
313
315
314 config.add_translation_dirs('rhodecode:i18n/')
316 config.add_translation_dirs('rhodecode:i18n/')
315 settings['default_locale_name'] = settings.get('lang', 'en')
317 settings['default_locale_name'] = settings.get('lang', 'en')
316
318
317 # Add subscribers.
319 # Add subscribers.
320 config.add_subscriber(inject_app_settings, ApplicationCreated)
318 config.add_subscriber(scan_repositories_if_enabled, ApplicationCreated)
321 config.add_subscriber(scan_repositories_if_enabled, ApplicationCreated)
319 config.add_subscriber(write_metadata_if_needed, ApplicationCreated)
322 config.add_subscriber(write_metadata_if_needed, ApplicationCreated)
320 config.add_subscriber(write_js_routes_if_enabled, ApplicationCreated)
323 config.add_subscriber(write_js_routes_if_enabled, ApplicationCreated)
321
324
322 config.add_request_method(
325 config.add_request_method(
323 'rhodecode.lib.partial_renderer.get_partial_renderer',
326 'rhodecode.lib.partial_renderer.get_partial_renderer',
324 'get_partial_renderer')
327 'get_partial_renderer')
325
328
326 # events
329 # events
327 # TODO(marcink): this should be done when pyramid migration is finished
330 # TODO(marcink): this should be done when pyramid migration is finished
328 # config.add_subscriber(
331 # config.add_subscriber(
329 # 'rhodecode.integrations.integrations_event_handler',
332 # 'rhodecode.integrations.integrations_event_handler',
330 # 'rhodecode.events.RhodecodeEvent')
333 # 'rhodecode.events.RhodecodeEvent')
331
334
332 # Set the authorization policy.
335 # Set the authorization policy.
333 authz_policy = ACLAuthorizationPolicy()
336 authz_policy = ACLAuthorizationPolicy()
334 config.set_authorization_policy(authz_policy)
337 config.set_authorization_policy(authz_policy)
335
338
336 # Set the default renderer for HTML templates to mako.
339 # Set the default renderer for HTML templates to mako.
337 config.add_mako_renderer('.html')
340 config.add_mako_renderer('.html')
338
341
339 config.add_renderer(
342 config.add_renderer(
340 name='json_ext',
343 name='json_ext',
341 factory='rhodecode.lib.ext_json_renderer.pyramid_ext_json')
344 factory='rhodecode.lib.ext_json_renderer.pyramid_ext_json')
342
345
343 # include RhodeCode plugins
346 # include RhodeCode plugins
344 includes = aslist(settings.get('rhodecode.includes', []))
347 includes = aslist(settings.get('rhodecode.includes', []))
345 for inc in includes:
348 for inc in includes:
346 config.include(inc)
349 config.include(inc)
347
350
348 # This is the glue which allows us to migrate in chunks. By registering the
351 # This is the glue which allows us to migrate in chunks. By registering the
349 # pylons based application as the "Not Found" view in Pyramid, we will
352 # pylons based application as the "Not Found" view in Pyramid, we will
350 # fallback to the old application each time the new one does not yet know
353 # fallback to the old application each time the new one does not yet know
351 # how to handle a request.
354 # how to handle a request.
352 config.add_notfound_view(make_not_found_view(config))
355 config.add_notfound_view(make_not_found_view(config))
353
356
354 if not settings.get('debugtoolbar.enabled', False):
357 if not settings.get('debugtoolbar.enabled', False):
355 # disabled debugtoolbar handle all exceptions via the error_handlers
358 # disabled debugtoolbar handle all exceptions via the error_handlers
356 config.add_view(error_handler, context=Exception)
359 config.add_view(error_handler, context=Exception)
357
360
358 config.add_view(error_handler, context=HTTPError)
361 config.add_view(error_handler, context=HTTPError)
359
362
360
363
361 def includeme_first(config):
364 def includeme_first(config):
362 # redirect automatic browser favicon.ico requests to correct place
365 # redirect automatic browser favicon.ico requests to correct place
363 def favicon_redirect(context, request):
366 def favicon_redirect(context, request):
364 return HTTPFound(
367 return HTTPFound(
365 request.static_path('rhodecode:public/images/favicon.ico'))
368 request.static_path('rhodecode:public/images/favicon.ico'))
366
369
367 config.add_view(favicon_redirect, route_name='favicon')
370 config.add_view(favicon_redirect, route_name='favicon')
368 config.add_route('favicon', '/favicon.ico')
371 config.add_route('favicon', '/favicon.ico')
369
372
370 def robots_redirect(context, request):
373 def robots_redirect(context, request):
371 return HTTPFound(
374 return HTTPFound(
372 request.static_path('rhodecode:public/robots.txt'))
375 request.static_path('rhodecode:public/robots.txt'))
373
376
374 config.add_view(robots_redirect, route_name='robots')
377 config.add_view(robots_redirect, route_name='robots')
375 config.add_route('robots', '/robots.txt')
378 config.add_route('robots', '/robots.txt')
376
379
377 config.add_static_view(
380 config.add_static_view(
378 '_static/deform', 'deform:static')
381 '_static/deform', 'deform:static')
379 config.add_static_view(
382 config.add_static_view(
380 '_static/rhodecode', path='rhodecode:public', cache_max_age=3600 * 24)
383 '_static/rhodecode', path='rhodecode:public', cache_max_age=3600 * 24)
381
384
382
385
383 def wrap_app_in_wsgi_middlewares(pyramid_app, config):
386 def wrap_app_in_wsgi_middlewares(pyramid_app, config):
384 """
387 """
385 Apply outer WSGI middlewares around the application.
388 Apply outer WSGI middlewares around the application.
386
389
387 Part of this has been moved up from the Pylons layer, so that the
390 Part of this has been moved up from the Pylons layer, so that the
388 data is also available if old Pylons code is hit through an already ported
391 data is also available if old Pylons code is hit through an already ported
389 view.
392 view.
390 """
393 """
391 settings = config.registry.settings
394 settings = config.registry.settings
392
395
393 # enable https redirects based on HTTP_X_URL_SCHEME set by proxy
396 # enable https redirects based on HTTP_X_URL_SCHEME set by proxy
394 pyramid_app = HttpsFixup(pyramid_app, settings)
397 pyramid_app = HttpsFixup(pyramid_app, settings)
395
398
396 # Add RoutesMiddleware to support the pylons compatibility tween during
399 # Add RoutesMiddleware to support the pylons compatibility tween during
397 # migration to pyramid.
400 # migration to pyramid.
398
401
399 # TODO(marcink): remove after migration to pyramid
402 # TODO(marcink): remove after migration to pyramid
400 if hasattr(config.registry, '_pylons_compat_config'):
403 if hasattr(config.registry, '_pylons_compat_config'):
401 routes_map = config.registry._pylons_compat_config['routes.map']
404 routes_map = config.registry._pylons_compat_config['routes.map']
402 pyramid_app = SkippableRoutesMiddleware(
405 pyramid_app = SkippableRoutesMiddleware(
403 pyramid_app, routes_map,
406 pyramid_app, routes_map,
404 skip_prefixes=(STATIC_FILE_PREFIX, '/_debug_toolbar'))
407 skip_prefixes=(STATIC_FILE_PREFIX, '/_debug_toolbar'))
405
408
406 pyramid_app, _ = wrap_in_appenlight_if_enabled(pyramid_app, settings)
409 pyramid_app, _ = wrap_in_appenlight_if_enabled(pyramid_app, settings)
407
410
408 if settings['gzip_responses']:
411 if settings['gzip_responses']:
409 pyramid_app = make_gzip_middleware(
412 pyramid_app = make_gzip_middleware(
410 pyramid_app, settings, compress_level=1)
413 pyramid_app, settings, compress_level=1)
411
414
412 # this should be the outer most middleware in the wsgi stack since
415 # this should be the outer most middleware in the wsgi stack since
413 # middleware like Routes make database calls
416 # middleware like Routes make database calls
414 def pyramid_app_with_cleanup(environ, start_response):
417 def pyramid_app_with_cleanup(environ, start_response):
415 try:
418 try:
416 return pyramid_app(environ, start_response)
419 return pyramid_app(environ, start_response)
417 finally:
420 finally:
418 # Dispose current database session and rollback uncommitted
421 # Dispose current database session and rollback uncommitted
419 # transactions.
422 # transactions.
420 meta.Session.remove()
423 meta.Session.remove()
421
424
422 # In a single threaded mode server, on non sqlite db we should have
425 # In a single threaded mode server, on non sqlite db we should have
423 # '0 Current Checked out connections' at the end of a request,
426 # '0 Current Checked out connections' at the end of a request,
424 # if not, then something, somewhere is leaving a connection open
427 # if not, then something, somewhere is leaving a connection open
425 pool = meta.Base.metadata.bind.engine.pool
428 pool = meta.Base.metadata.bind.engine.pool
426 log.debug('sa pool status: %s', pool.status())
429 log.debug('sa pool status: %s', pool.status())
427
430
428 return pyramid_app_with_cleanup
431 return pyramid_app_with_cleanup
429
432
430
433
431 def sanitize_settings_and_apply_defaults(settings):
434 def sanitize_settings_and_apply_defaults(settings):
432 """
435 """
433 Applies settings defaults and does all type conversion.
436 Applies settings defaults and does all type conversion.
434
437
435 We would move all settings parsing and preparation into this place, so that
438 We would move all settings parsing and preparation into this place, so that
436 we have only one place left which deals with this part. The remaining parts
439 we have only one place left which deals with this part. The remaining parts
437 of the application would start to rely fully on well prepared settings.
440 of the application would start to rely fully on well prepared settings.
438
441
439 This piece would later be split up per topic to avoid a big fat monster
442 This piece would later be split up per topic to avoid a big fat monster
440 function.
443 function.
441 """
444 """
442
445
443 # Pyramid's mako renderer has to search in the templates folder so that the
446 # Pyramid's mako renderer has to search in the templates folder so that the
444 # old templates still work. Ported and new templates are expected to use
447 # old templates still work. Ported and new templates are expected to use
445 # real asset specifications for the includes.
448 # real asset specifications for the includes.
446 mako_directories = settings.setdefault('mako.directories', [
449 mako_directories = settings.setdefault('mako.directories', [
447 # Base templates of the original Pylons application
450 # Base templates of the original Pylons application
448 'rhodecode:templates',
451 'rhodecode:templates',
449 ])
452 ])
450 log.debug(
453 log.debug(
451 "Using the following Mako template directories: %s",
454 "Using the following Mako template directories: %s",
452 mako_directories)
455 mako_directories)
453
456
454 # Default includes, possible to change as a user
457 # Default includes, possible to change as a user
455 pyramid_includes = settings.setdefault('pyramid.includes', [
458 pyramid_includes = settings.setdefault('pyramid.includes', [
456 'rhodecode.lib.middleware.request_wrapper',
459 'rhodecode.lib.middleware.request_wrapper',
457 ])
460 ])
458 log.debug(
461 log.debug(
459 "Using the following pyramid.includes: %s",
462 "Using the following pyramid.includes: %s",
460 pyramid_includes)
463 pyramid_includes)
461
464
462 # TODO: johbo: Re-think this, usually the call to config.include
465 # TODO: johbo: Re-think this, usually the call to config.include
463 # should allow to pass in a prefix.
466 # should allow to pass in a prefix.
464 settings.setdefault('rhodecode.api.url', '/_admin/api')
467 settings.setdefault('rhodecode.api.url', '/_admin/api')
465
468
466 # Sanitize generic settings.
469 # Sanitize generic settings.
467 _list_setting(settings, 'default_encoding', 'UTF-8')
470 _list_setting(settings, 'default_encoding', 'UTF-8')
468 _bool_setting(settings, 'is_test', 'false')
471 _bool_setting(settings, 'is_test', 'false')
469 _bool_setting(settings, 'gzip_responses', 'false')
472 _bool_setting(settings, 'gzip_responses', 'false')
470
473
471 # Call split out functions that sanitize settings for each topic.
474 # Call split out functions that sanitize settings for each topic.
472 _sanitize_appenlight_settings(settings)
475 _sanitize_appenlight_settings(settings)
473 _sanitize_vcs_settings(settings)
476 _sanitize_vcs_settings(settings)
474
477
478 # configure instance id
479 config_utils.set_instance_id(settings)
480
475 return settings
481 return settings
476
482
477
483
478 def _sanitize_appenlight_settings(settings):
484 def _sanitize_appenlight_settings(settings):
479 _bool_setting(settings, 'appenlight', 'false')
485 _bool_setting(settings, 'appenlight', 'false')
480
486
481
487
482 def _sanitize_vcs_settings(settings):
488 def _sanitize_vcs_settings(settings):
483 """
489 """
484 Applies settings defaults and does type conversion for all VCS related
490 Applies settings defaults and does type conversion for all VCS related
485 settings.
491 settings.
486 """
492 """
487 _string_setting(settings, 'vcs.svn.compatible_version', '')
493 _string_setting(settings, 'vcs.svn.compatible_version', '')
488 _string_setting(settings, 'git_rev_filter', '--all')
494 _string_setting(settings, 'git_rev_filter', '--all')
489 _string_setting(settings, 'vcs.hooks.protocol', 'http')
495 _string_setting(settings, 'vcs.hooks.protocol', 'http')
490 _string_setting(settings, 'vcs.scm_app_implementation', 'http')
496 _string_setting(settings, 'vcs.scm_app_implementation', 'http')
491 _string_setting(settings, 'vcs.server', '')
497 _string_setting(settings, 'vcs.server', '')
492 _string_setting(settings, 'vcs.server.log_level', 'debug')
498 _string_setting(settings, 'vcs.server.log_level', 'debug')
493 _string_setting(settings, 'vcs.server.protocol', 'http')
499 _string_setting(settings, 'vcs.server.protocol', 'http')
494 _bool_setting(settings, 'startup.import_repos', 'false')
500 _bool_setting(settings, 'startup.import_repos', 'false')
495 _bool_setting(settings, 'vcs.hooks.direct_calls', 'false')
501 _bool_setting(settings, 'vcs.hooks.direct_calls', 'false')
496 _bool_setting(settings, 'vcs.server.enable', 'true')
502 _bool_setting(settings, 'vcs.server.enable', 'true')
497 _bool_setting(settings, 'vcs.start_server', 'false')
503 _bool_setting(settings, 'vcs.start_server', 'false')
498 _list_setting(settings, 'vcs.backends', 'hg, git, svn')
504 _list_setting(settings, 'vcs.backends', 'hg, git, svn')
499 _int_setting(settings, 'vcs.connection_timeout', 3600)
505 _int_setting(settings, 'vcs.connection_timeout', 3600)
500
506
501 # Support legacy values of vcs.scm_app_implementation. Legacy
507 # Support legacy values of vcs.scm_app_implementation. Legacy
502 # configurations may use 'rhodecode.lib.middleware.utils.scm_app_http'
508 # configurations may use 'rhodecode.lib.middleware.utils.scm_app_http'
503 # which is now mapped to 'http'.
509 # which is now mapped to 'http'.
504 scm_app_impl = settings['vcs.scm_app_implementation']
510 scm_app_impl = settings['vcs.scm_app_implementation']
505 if scm_app_impl == 'rhodecode.lib.middleware.utils.scm_app_http':
511 if scm_app_impl == 'rhodecode.lib.middleware.utils.scm_app_http':
506 settings['vcs.scm_app_implementation'] = 'http'
512 settings['vcs.scm_app_implementation'] = 'http'
507
513
508
514
509 def _int_setting(settings, name, default):
515 def _int_setting(settings, name, default):
510 settings[name] = int(settings.get(name, default))
516 settings[name] = int(settings.get(name, default))
511
517
512
518
513 def _bool_setting(settings, name, default):
519 def _bool_setting(settings, name, default):
514 input = settings.get(name, default)
520 input = settings.get(name, default)
515 if isinstance(input, unicode):
521 if isinstance(input, unicode):
516 input = input.encode('utf8')
522 input = input.encode('utf8')
517 settings[name] = asbool(input)
523 settings[name] = asbool(input)
518
524
519
525
520 def _list_setting(settings, name, default):
526 def _list_setting(settings, name, default):
521 raw_value = settings.get(name, default)
527 raw_value = settings.get(name, default)
522
528
523 old_separator = ','
529 old_separator = ','
524 if old_separator in raw_value:
530 if old_separator in raw_value:
525 # If we get a comma separated list, pass it to our own function.
531 # If we get a comma separated list, pass it to our own function.
526 settings[name] = rhodecode_aslist(raw_value, sep=old_separator)
532 settings[name] = rhodecode_aslist(raw_value, sep=old_separator)
527 else:
533 else:
528 # Otherwise we assume it uses pyramids space/newline separation.
534 # Otherwise we assume it uses pyramids space/newline separation.
529 settings[name] = aslist(raw_value)
535 settings[name] = aslist(raw_value)
530
536
531
537
532 def _string_setting(settings, name, default, lower=True):
538 def _string_setting(settings, name, default, lower=True):
533 value = settings.get(name, default)
539 value = settings.get(name, default)
534 if lower:
540 if lower:
535 value = value.lower()
541 value = value.lower()
536 settings[name] = value
542 settings[name] = value
@@ -1,343 +1,311 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 Routes configuration
22 Routes configuration
23
23
24 The more specific and detailed routes should be defined first so they
24 The more specific and detailed routes should be defined first so they
25 may take precedent over the more generic routes. For more information
25 may take precedent over the more generic routes. For more information
26 refer to the routes manual at http://routes.groovie.org/docs/
26 refer to the routes manual at http://routes.groovie.org/docs/
27
27
28 IMPORTANT: if you change any routing here, make sure to take a look at lib/base.py
28 IMPORTANT: if you change any routing here, make sure to take a look at lib/base.py
29 and _route_name variable which uses some of stored naming here to do redirects.
29 and _route_name variable which uses some of stored naming here to do redirects.
30 """
30 """
31 import os
31 import os
32 import re
32 import re
33 from routes import Mapper
33 from routes import Mapper
34
34
35 # prefix for non repository related links needs to be prefixed with `/`
35 # prefix for non repository related links needs to be prefixed with `/`
36 ADMIN_PREFIX = '/_admin'
36 ADMIN_PREFIX = '/_admin'
37 STATIC_FILE_PREFIX = '/_static'
37 STATIC_FILE_PREFIX = '/_static'
38
38
39 # Default requirements for URL parts
39 # Default requirements for URL parts
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 class JSRoutesMapper(Mapper):
54 class JSRoutesMapper(Mapper):
55 """
55 """
56 Wrapper for routes.Mapper to make pyroutes compatible url definitions
56 Wrapper for routes.Mapper to make pyroutes compatible url definitions
57 """
57 """
58 _named_route_regex = re.compile(r'^[a-z-_0-9A-Z]+$')
58 _named_route_regex = re.compile(r'^[a-z-_0-9A-Z]+$')
59 _argument_prog = re.compile('\{(.*?)\}|:\((.*)\)')
59 _argument_prog = re.compile('\{(.*?)\}|:\((.*)\)')
60 def __init__(self, *args, **kw):
60 def __init__(self, *args, **kw):
61 super(JSRoutesMapper, self).__init__(*args, **kw)
61 super(JSRoutesMapper, self).__init__(*args, **kw)
62 self._jsroutes = []
62 self._jsroutes = []
63
63
64 def connect(self, *args, **kw):
64 def connect(self, *args, **kw):
65 """
65 """
66 Wrapper for connect to take an extra argument jsroute=True
66 Wrapper for connect to take an extra argument jsroute=True
67
67
68 :param jsroute: boolean, if True will add the route to the pyroutes list
68 :param jsroute: boolean, if True will add the route to the pyroutes list
69 """
69 """
70 if kw.pop('jsroute', False):
70 if kw.pop('jsroute', False):
71 if not self._named_route_regex.match(args[0]):
71 if not self._named_route_regex.match(args[0]):
72 raise Exception('only named routes can be added to pyroutes')
72 raise Exception('only named routes can be added to pyroutes')
73 self._jsroutes.append(args[0])
73 self._jsroutes.append(args[0])
74
74
75 super(JSRoutesMapper, self).connect(*args, **kw)
75 super(JSRoutesMapper, self).connect(*args, **kw)
76
76
77 def _extract_route_information(self, route):
77 def _extract_route_information(self, route):
78 """
78 """
79 Convert a route into tuple(name, path, args), eg:
79 Convert a route into tuple(name, path, args), eg:
80 ('show_user', '/profile/%(username)s', ['username'])
80 ('show_user', '/profile/%(username)s', ['username'])
81 """
81 """
82 routepath = route.routepath
82 routepath = route.routepath
83 def replace(matchobj):
83 def replace(matchobj):
84 if matchobj.group(1):
84 if matchobj.group(1):
85 return "%%(%s)s" % matchobj.group(1).split(':')[0]
85 return "%%(%s)s" % matchobj.group(1).split(':')[0]
86 else:
86 else:
87 return "%%(%s)s" % matchobj.group(2)
87 return "%%(%s)s" % matchobj.group(2)
88
88
89 routepath = self._argument_prog.sub(replace, routepath)
89 routepath = self._argument_prog.sub(replace, routepath)
90 return (
90 return (
91 route.name,
91 route.name,
92 routepath,
92 routepath,
93 [(arg[0].split(':')[0] if arg[0] != '' else arg[1])
93 [(arg[0].split(':')[0] if arg[0] != '' else arg[1])
94 for arg in self._argument_prog.findall(route.routepath)]
94 for arg in self._argument_prog.findall(route.routepath)]
95 )
95 )
96
96
97 def jsroutes(self):
97 def jsroutes(self):
98 """
98 """
99 Return a list of pyroutes.js compatible routes
99 Return a list of pyroutes.js compatible routes
100 """
100 """
101 for route_name in self._jsroutes:
101 for route_name in self._jsroutes:
102 yield self._extract_route_information(self._routenames[route_name])
102 yield self._extract_route_information(self._routenames[route_name])
103
103
104
104
105 def make_map(config):
105 def make_map(config):
106 """Create, configure and return the routes Mapper"""
106 """Create, configure and return the routes Mapper"""
107 rmap = JSRoutesMapper(
107 rmap = JSRoutesMapper(
108 directory=config['pylons.paths']['controllers'],
108 directory=config['pylons.paths']['controllers'],
109 always_scan=config['debug'])
109 always_scan=config['debug'])
110 rmap.minimization = False
110 rmap.minimization = False
111 rmap.explicit = False
111 rmap.explicit = False
112
112
113 from rhodecode.lib.utils2 import str2bool
113 from rhodecode.lib.utils2 import str2bool
114 from rhodecode.model import repo, repo_group
114 from rhodecode.model import repo, repo_group
115
115
116 def check_repo(environ, match_dict):
116 def check_repo(environ, match_dict):
117 """
117 """
118 check for valid repository for proper 404 handling
118 check for valid repository for proper 404 handling
119
119
120 :param environ:
120 :param environ:
121 :param match_dict:
121 :param match_dict:
122 """
122 """
123 repo_name = match_dict.get('repo_name')
123 repo_name = match_dict.get('repo_name')
124
124
125 if match_dict.get('f_path'):
125 if match_dict.get('f_path'):
126 # fix for multiple initial slashes that causes errors
126 # fix for multiple initial slashes that causes errors
127 match_dict['f_path'] = match_dict['f_path'].lstrip('/')
127 match_dict['f_path'] = match_dict['f_path'].lstrip('/')
128 repo_model = repo.RepoModel()
128 repo_model = repo.RepoModel()
129 by_name_match = repo_model.get_by_repo_name(repo_name)
129 by_name_match = repo_model.get_by_repo_name(repo_name)
130 # if we match quickly from database, short circuit the operation,
130 # if we match quickly from database, short circuit the operation,
131 # and validate repo based on the type.
131 # and validate repo based on the type.
132 if by_name_match:
132 if by_name_match:
133 return True
133 return True
134
134
135 by_id_match = repo_model.get_repo_by_id(repo_name)
135 by_id_match = repo_model.get_repo_by_id(repo_name)
136 if by_id_match:
136 if by_id_match:
137 repo_name = by_id_match.repo_name
137 repo_name = by_id_match.repo_name
138 match_dict['repo_name'] = repo_name
138 match_dict['repo_name'] = repo_name
139 return True
139 return True
140
140
141 return False
141 return False
142
142
143 def check_group(environ, match_dict):
143 def check_group(environ, match_dict):
144 """
144 """
145 check for valid repository group path for proper 404 handling
145 check for valid repository group path for proper 404 handling
146
146
147 :param environ:
147 :param environ:
148 :param match_dict:
148 :param match_dict:
149 """
149 """
150 repo_group_name = match_dict.get('group_name')
150 repo_group_name = match_dict.get('group_name')
151 repo_group_model = repo_group.RepoGroupModel()
151 repo_group_model = repo_group.RepoGroupModel()
152 by_name_match = repo_group_model.get_by_group_name(repo_group_name)
152 by_name_match = repo_group_model.get_by_group_name(repo_group_name)
153 if by_name_match:
153 if by_name_match:
154 return True
154 return True
155
155
156 return False
156 return False
157
157
158 def check_user_group(environ, match_dict):
158 def check_user_group(environ, match_dict):
159 """
159 """
160 check for valid user group for proper 404 handling
160 check for valid user group for proper 404 handling
161
161
162 :param environ:
162 :param environ:
163 :param match_dict:
163 :param match_dict:
164 """
164 """
165 return True
165 return True
166
166
167 def check_int(environ, match_dict):
167 def check_int(environ, match_dict):
168 return match_dict.get('id').isdigit()
168 return match_dict.get('id').isdigit()
169
169
170
170
171 #==========================================================================
171 #==========================================================================
172 # CUSTOM ROUTES HERE
172 # CUSTOM ROUTES HERE
173 #==========================================================================
173 #==========================================================================
174
174
175 # ADMIN REPOSITORY GROUPS ROUTES
175 # ADMIN REPOSITORY GROUPS ROUTES
176 with rmap.submapper(path_prefix=ADMIN_PREFIX,
176 with rmap.submapper(path_prefix=ADMIN_PREFIX,
177 controller='admin/repo_groups') as m:
177 controller='admin/repo_groups') as m:
178 m.connect('repo_groups', '/repo_groups',
178 m.connect('repo_groups', '/repo_groups',
179 action='create', conditions={'method': ['POST']})
179 action='create', conditions={'method': ['POST']})
180 m.connect('repo_groups', '/repo_groups',
180 m.connect('repo_groups', '/repo_groups',
181 action='index', conditions={'method': ['GET']})
181 action='index', conditions={'method': ['GET']})
182 m.connect('new_repo_group', '/repo_groups/new',
182 m.connect('new_repo_group', '/repo_groups/new',
183 action='new', conditions={'method': ['GET']})
183 action='new', conditions={'method': ['GET']})
184 m.connect('update_repo_group', '/repo_groups/{group_name}',
184 m.connect('update_repo_group', '/repo_groups/{group_name}',
185 action='update', conditions={'method': ['PUT'],
185 action='update', conditions={'method': ['PUT'],
186 'function': check_group},
186 'function': check_group},
187 requirements=URL_NAME_REQUIREMENTS)
187 requirements=URL_NAME_REQUIREMENTS)
188
188
189 # EXTRAS REPO GROUP ROUTES
189 # EXTRAS REPO GROUP ROUTES
190 m.connect('edit_repo_group', '/repo_groups/{group_name}/edit',
190 m.connect('edit_repo_group', '/repo_groups/{group_name}/edit',
191 action='edit',
191 action='edit',
192 conditions={'method': ['GET'], 'function': check_group},
192 conditions={'method': ['GET'], 'function': check_group},
193 requirements=URL_NAME_REQUIREMENTS)
193 requirements=URL_NAME_REQUIREMENTS)
194 m.connect('edit_repo_group', '/repo_groups/{group_name}/edit',
194 m.connect('edit_repo_group', '/repo_groups/{group_name}/edit',
195 action='edit',
195 action='edit',
196 conditions={'method': ['PUT'], 'function': check_group},
196 conditions={'method': ['PUT'], 'function': check_group},
197 requirements=URL_NAME_REQUIREMENTS)
197 requirements=URL_NAME_REQUIREMENTS)
198
198
199 m.connect('edit_repo_group_advanced', '/repo_groups/{group_name}/edit/advanced',
199 m.connect('edit_repo_group_advanced', '/repo_groups/{group_name}/edit/advanced',
200 action='edit_repo_group_advanced',
200 action='edit_repo_group_advanced',
201 conditions={'method': ['GET'], 'function': check_group},
201 conditions={'method': ['GET'], 'function': check_group},
202 requirements=URL_NAME_REQUIREMENTS)
202 requirements=URL_NAME_REQUIREMENTS)
203 m.connect('edit_repo_group_advanced', '/repo_groups/{group_name}/edit/advanced',
203 m.connect('edit_repo_group_advanced', '/repo_groups/{group_name}/edit/advanced',
204 action='edit_repo_group_advanced',
204 action='edit_repo_group_advanced',
205 conditions={'method': ['PUT'], 'function': check_group},
205 conditions={'method': ['PUT'], 'function': check_group},
206 requirements=URL_NAME_REQUIREMENTS)
206 requirements=URL_NAME_REQUIREMENTS)
207
207
208 m.connect('edit_repo_group_perms', '/repo_groups/{group_name}/edit/permissions',
208 m.connect('edit_repo_group_perms', '/repo_groups/{group_name}/edit/permissions',
209 action='edit_repo_group_perms',
209 action='edit_repo_group_perms',
210 conditions={'method': ['GET'], 'function': check_group},
210 conditions={'method': ['GET'], 'function': check_group},
211 requirements=URL_NAME_REQUIREMENTS)
211 requirements=URL_NAME_REQUIREMENTS)
212 m.connect('edit_repo_group_perms', '/repo_groups/{group_name}/edit/permissions',
212 m.connect('edit_repo_group_perms', '/repo_groups/{group_name}/edit/permissions',
213 action='update_perms',
213 action='update_perms',
214 conditions={'method': ['PUT'], 'function': check_group},
214 conditions={'method': ['PUT'], 'function': check_group},
215 requirements=URL_NAME_REQUIREMENTS)
215 requirements=URL_NAME_REQUIREMENTS)
216
216
217 m.connect('delete_repo_group', '/repo_groups/{group_name}',
217 m.connect('delete_repo_group', '/repo_groups/{group_name}',
218 action='delete', conditions={'method': ['DELETE'],
218 action='delete', conditions={'method': ['DELETE'],
219 'function': check_group},
219 'function': check_group},
220 requirements=URL_NAME_REQUIREMENTS)
220 requirements=URL_NAME_REQUIREMENTS)
221
221
222 # ADMIN USER ROUTES
223 with rmap.submapper(path_prefix=ADMIN_PREFIX,
224 controller='admin/users') as m:
225 m.connect('users', '/users',
226 action='create', conditions={'method': ['POST']})
227 m.connect('new_user', '/users/new',
228 action='new', conditions={'method': ['GET']})
229 m.connect('update_user', '/users/{user_id}',
230 action='update', conditions={'method': ['PUT']})
231 m.connect('delete_user', '/users/{user_id}',
232 action='delete', conditions={'method': ['DELETE']})
233 m.connect('edit_user', '/users/{user_id}/edit',
234 action='edit', conditions={'method': ['GET']}, jsroute=True)
235 m.connect('user', '/users/{user_id}',
236 action='show', conditions={'method': ['GET']})
237 m.connect('force_password_reset_user', '/users/{user_id}/password_reset',
238 action='reset_password', conditions={'method': ['POST']})
239 m.connect('create_personal_repo_group', '/users/{user_id}/create_repo_group',
240 action='create_personal_repo_group', conditions={'method': ['POST']})
241
242 # EXTRAS USER ROUTES
243 m.connect('edit_user_advanced', '/users/{user_id}/edit/advanced',
244 action='edit_advanced', conditions={'method': ['GET']})
245 m.connect('edit_user_advanced', '/users/{user_id}/edit/advanced',
246 action='update_advanced', conditions={'method': ['PUT']})
247
248 m.connect('edit_user_global_perms', '/users/{user_id}/edit/global_permissions',
249 action='edit_global_perms', conditions={'method': ['GET']})
250 m.connect('edit_user_global_perms', '/users/{user_id}/edit/global_permissions',
251 action='update_global_perms', conditions={'method': ['PUT']})
252
253 # ADMIN SETTINGS ROUTES
222 # ADMIN SETTINGS ROUTES
254 with rmap.submapper(path_prefix=ADMIN_PREFIX,
223 with rmap.submapper(path_prefix=ADMIN_PREFIX,
255 controller='admin/settings') as m:
224 controller='admin/settings') as m:
256
225
257 # default
226 # default
258 m.connect('admin_settings', '/settings',
227 m.connect('admin_settings', '/settings',
259 action='settings_global_update',
228 action='settings_global_update',
260 conditions={'method': ['POST']})
229 conditions={'method': ['POST']})
261 m.connect('admin_settings', '/settings',
230 m.connect('admin_settings', '/settings',
262 action='settings_global', conditions={'method': ['GET']})
231 action='settings_global', conditions={'method': ['GET']})
263
232
264 m.connect('admin_settings_vcs', '/settings/vcs',
233 m.connect('admin_settings_vcs', '/settings/vcs',
265 action='settings_vcs_update',
234 action='settings_vcs_update',
266 conditions={'method': ['POST']})
235 conditions={'method': ['POST']})
267 m.connect('admin_settings_vcs', '/settings/vcs',
236 m.connect('admin_settings_vcs', '/settings/vcs',
268 action='settings_vcs',
237 action='settings_vcs',
269 conditions={'method': ['GET']})
238 conditions={'method': ['GET']})
270 m.connect('admin_settings_vcs', '/settings/vcs',
239 m.connect('admin_settings_vcs', '/settings/vcs',
271 action='delete_svn_pattern',
240 action='delete_svn_pattern',
272 conditions={'method': ['DELETE']})
241 conditions={'method': ['DELETE']})
273
242
274 m.connect('admin_settings_mapping', '/settings/mapping',
243 m.connect('admin_settings_mapping', '/settings/mapping',
275 action='settings_mapping_update',
244 action='settings_mapping_update',
276 conditions={'method': ['POST']})
245 conditions={'method': ['POST']})
277 m.connect('admin_settings_mapping', '/settings/mapping',
246 m.connect('admin_settings_mapping', '/settings/mapping',
278 action='settings_mapping', conditions={'method': ['GET']})
247 action='settings_mapping', conditions={'method': ['GET']})
279
248
280 m.connect('admin_settings_global', '/settings/global',
249 m.connect('admin_settings_global', '/settings/global',
281 action='settings_global_update',
250 action='settings_global_update',
282 conditions={'method': ['POST']})
251 conditions={'method': ['POST']})
283 m.connect('admin_settings_global', '/settings/global',
252 m.connect('admin_settings_global', '/settings/global',
284 action='settings_global', conditions={'method': ['GET']})
253 action='settings_global', conditions={'method': ['GET']})
285
254
286 m.connect('admin_settings_visual', '/settings/visual',
255 m.connect('admin_settings_visual', '/settings/visual',
287 action='settings_visual_update',
256 action='settings_visual_update',
288 conditions={'method': ['POST']})
257 conditions={'method': ['POST']})
289 m.connect('admin_settings_visual', '/settings/visual',
258 m.connect('admin_settings_visual', '/settings/visual',
290 action='settings_visual', conditions={'method': ['GET']})
259 action='settings_visual', conditions={'method': ['GET']})
291
260
292 m.connect('admin_settings_issuetracker',
261 m.connect('admin_settings_issuetracker',
293 '/settings/issue-tracker', action='settings_issuetracker',
262 '/settings/issue-tracker', action='settings_issuetracker',
294 conditions={'method': ['GET']})
263 conditions={'method': ['GET']})
295 m.connect('admin_settings_issuetracker_save',
264 m.connect('admin_settings_issuetracker_save',
296 '/settings/issue-tracker/save',
265 '/settings/issue-tracker/save',
297 action='settings_issuetracker_save',
266 action='settings_issuetracker_save',
298 conditions={'method': ['POST']})
267 conditions={'method': ['POST']})
299 m.connect('admin_issuetracker_test', '/settings/issue-tracker/test',
268 m.connect('admin_issuetracker_test', '/settings/issue-tracker/test',
300 action='settings_issuetracker_test',
269 action='settings_issuetracker_test',
301 conditions={'method': ['POST']})
270 conditions={'method': ['POST']})
302 m.connect('admin_issuetracker_delete',
271 m.connect('admin_issuetracker_delete',
303 '/settings/issue-tracker/delete',
272 '/settings/issue-tracker/delete',
304 action='settings_issuetracker_delete',
273 action='settings_issuetracker_delete',
305 conditions={'method': ['DELETE']})
274 conditions={'method': ['DELETE']})
306
275
307 m.connect('admin_settings_email', '/settings/email',
276 m.connect('admin_settings_email', '/settings/email',
308 action='settings_email_update',
277 action='settings_email_update',
309 conditions={'method': ['POST']})
278 conditions={'method': ['POST']})
310 m.connect('admin_settings_email', '/settings/email',
279 m.connect('admin_settings_email', '/settings/email',
311 action='settings_email', conditions={'method': ['GET']})
280 action='settings_email', conditions={'method': ['GET']})
312
281
313 m.connect('admin_settings_hooks', '/settings/hooks',
282 m.connect('admin_settings_hooks', '/settings/hooks',
314 action='settings_hooks_update',
283 action='settings_hooks_update',
315 conditions={'method': ['POST', 'DELETE']})
284 conditions={'method': ['POST', 'DELETE']})
316 m.connect('admin_settings_hooks', '/settings/hooks',
285 m.connect('admin_settings_hooks', '/settings/hooks',
317 action='settings_hooks', conditions={'method': ['GET']})
286 action='settings_hooks', conditions={'method': ['GET']})
318
287
319 m.connect('admin_settings_search', '/settings/search',
288 m.connect('admin_settings_search', '/settings/search',
320 action='settings_search', conditions={'method': ['GET']})
289 action='settings_search', conditions={'method': ['GET']})
321
290
322 m.connect('admin_settings_supervisor', '/settings/supervisor',
291 m.connect('admin_settings_supervisor', '/settings/supervisor',
323 action='settings_supervisor', conditions={'method': ['GET']})
292 action='settings_supervisor', conditions={'method': ['GET']})
324 m.connect('admin_settings_supervisor_log', '/settings/supervisor/{procid}/log',
293 m.connect('admin_settings_supervisor_log', '/settings/supervisor/{procid}/log',
325 action='settings_supervisor_log', conditions={'method': ['GET']})
294 action='settings_supervisor_log', conditions={'method': ['GET']})
326
295
327 m.connect('admin_settings_labs', '/settings/labs',
296 m.connect('admin_settings_labs', '/settings/labs',
328 action='settings_labs_update',
297 action='settings_labs_update',
329 conditions={'method': ['POST']})
298 conditions={'method': ['POST']})
330 m.connect('admin_settings_labs', '/settings/labs',
299 m.connect('admin_settings_labs', '/settings/labs',
331 action='settings_labs', conditions={'method': ['GET']})
300 action='settings_labs', conditions={'method': ['GET']})
332
301
333 # ADMIN MY ACCOUNT
302 # ADMIN MY ACCOUNT
334 with rmap.submapper(path_prefix=ADMIN_PREFIX,
303 with rmap.submapper(path_prefix=ADMIN_PREFIX,
335 controller='admin/my_account') as m:
304 controller='admin/my_account') as m:
336
305
337 # NOTE(marcink): this needs to be kept for password force flag to be
306 # NOTE(marcink): this needs to be kept for password force flag to be
338 # handled in pylons controllers, remove after full migration to pyramid
307 # handled in pylons controllers, remove after full migration to pyramid
339 m.connect('my_account_password', '/my_account/password',
308 m.connect('my_account_password', '/my_account/password',
340 action='my_account_password', conditions={'method': ['GET']})
309 action='my_account_password', conditions={'method': ['GET']})
341
310
342
343 return rmap
311 return rmap
@@ -1,2170 +1,2174 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 beaker.cache import cache_region
37 from beaker.cache import cache_region
38 from pyramid.httpexceptions import HTTPForbidden, HTTPFound, HTTPNotFound
38 from pyramid.httpexceptions import HTTPForbidden, HTTPFound, HTTPNotFound
39 from pylons.i18n.translation import _
39 from pylons.i18n.translation import _
40 # NOTE(marcink): this has to be removed only after pyramid migration,
40 # NOTE(marcink): this has to be removed only after pyramid migration,
41 # replace with _ = request.translate
41 # replace with _ = request.translate
42 from sqlalchemy.orm.exc import ObjectDeletedError
42 from sqlalchemy.orm.exc import ObjectDeletedError
43 from sqlalchemy.orm import joinedload
43 from sqlalchemy.orm import joinedload
44 from zope.cachedescriptors.property import Lazy as LazyProperty
44 from zope.cachedescriptors.property import Lazy as LazyProperty
45
45
46 import rhodecode
46 import rhodecode
47 from rhodecode.model import meta
47 from rhodecode.model import meta
48 from rhodecode.model.meta import Session
48 from rhodecode.model.meta import Session
49 from rhodecode.model.user import UserModel
49 from rhodecode.model.user import UserModel
50 from rhodecode.model.db import (
50 from rhodecode.model.db import (
51 User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember,
51 User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember,
52 UserIpMap, UserApiKeys, RepoGroup, UserGroup)
52 UserIpMap, UserApiKeys, RepoGroup, UserGroup)
53 from rhodecode.lib import caches
53 from rhodecode.lib import caches
54 from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5
54 from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5
55 from rhodecode.lib.utils import (
55 from rhodecode.lib.utils import (
56 get_repo_slug, get_repo_group_slug, get_user_group_slug)
56 get_repo_slug, get_repo_group_slug, get_user_group_slug)
57 from rhodecode.lib.caching_query import FromCache
57 from rhodecode.lib.caching_query import FromCache
58
58
59
59
60 if rhodecode.is_unix:
60 if rhodecode.is_unix:
61 import bcrypt
61 import bcrypt
62
62
63 log = logging.getLogger(__name__)
63 log = logging.getLogger(__name__)
64
64
65 csrf_token_key = "csrf_token"
65 csrf_token_key = "csrf_token"
66
66
67
67
68 class PasswordGenerator(object):
68 class PasswordGenerator(object):
69 """
69 """
70 This is a simple class for generating password from different sets of
70 This is a simple class for generating password from different sets of
71 characters
71 characters
72 usage::
72 usage::
73
73
74 passwd_gen = PasswordGenerator()
74 passwd_gen = PasswordGenerator()
75 #print 8-letter password containing only big and small letters
75 #print 8-letter password containing only big and small letters
76 of alphabet
76 of alphabet
77 passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
77 passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
78 """
78 """
79 ALPHABETS_NUM = r'''1234567890'''
79 ALPHABETS_NUM = r'''1234567890'''
80 ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
80 ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
81 ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
81 ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
82 ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
82 ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
83 ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
83 ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
84 + ALPHABETS_NUM + ALPHABETS_SPECIAL
84 + ALPHABETS_NUM + ALPHABETS_SPECIAL
85 ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
85 ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
86 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
86 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
87 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
87 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
88 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
88 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
89
89
90 def __init__(self, passwd=''):
90 def __init__(self, passwd=''):
91 self.passwd = passwd
91 self.passwd = passwd
92
92
93 def gen_password(self, length, type_=None):
93 def gen_password(self, length, type_=None):
94 if type_ is None:
94 if type_ is None:
95 type_ = self.ALPHABETS_FULL
95 type_ = self.ALPHABETS_FULL
96 self.passwd = ''.join([random.choice(type_) for _ in xrange(length)])
96 self.passwd = ''.join([random.choice(type_) for _ in xrange(length)])
97 return self.passwd
97 return self.passwd
98
98
99
99
100 class _RhodeCodeCryptoBase(object):
100 class _RhodeCodeCryptoBase(object):
101 ENC_PREF = None
101 ENC_PREF = None
102
102
103 def hash_create(self, str_):
103 def hash_create(self, str_):
104 """
104 """
105 hash the string using
105 hash the string using
106
106
107 :param str_: password to hash
107 :param str_: password to hash
108 """
108 """
109 raise NotImplementedError
109 raise NotImplementedError
110
110
111 def hash_check_with_upgrade(self, password, hashed):
111 def hash_check_with_upgrade(self, password, hashed):
112 """
112 """
113 Returns tuple in which first element is boolean that states that
113 Returns tuple in which first element is boolean that states that
114 given password matches it's hashed version, and the second is new hash
114 given password matches it's hashed version, and the second is new hash
115 of the password, in case this password should be migrated to new
115 of the password, in case this password should be migrated to new
116 cipher.
116 cipher.
117 """
117 """
118 checked_hash = self.hash_check(password, hashed)
118 checked_hash = self.hash_check(password, hashed)
119 return checked_hash, None
119 return checked_hash, None
120
120
121 def hash_check(self, password, hashed):
121 def hash_check(self, password, hashed):
122 """
122 """
123 Checks matching password with it's hashed value.
123 Checks matching password with it's hashed value.
124
124
125 :param password: password
125 :param password: password
126 :param hashed: password in hashed form
126 :param hashed: password in hashed form
127 """
127 """
128 raise NotImplementedError
128 raise NotImplementedError
129
129
130 def _assert_bytes(self, value):
130 def _assert_bytes(self, value):
131 """
131 """
132 Passing in an `unicode` object can lead to hard to detect issues
132 Passing in an `unicode` object can lead to hard to detect issues
133 if passwords contain non-ascii characters. Doing a type check
133 if passwords contain non-ascii characters. Doing a type check
134 during runtime, so that such mistakes are detected early on.
134 during runtime, so that such mistakes are detected early on.
135 """
135 """
136 if not isinstance(value, str):
136 if not isinstance(value, str):
137 raise TypeError(
137 raise TypeError(
138 "Bytestring required as input, got %r." % (value, ))
138 "Bytestring required as input, got %r." % (value, ))
139
139
140
140
141 class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase):
141 class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase):
142 ENC_PREF = ('$2a$10', '$2b$10')
142 ENC_PREF = ('$2a$10', '$2b$10')
143
143
144 def hash_create(self, str_):
144 def hash_create(self, str_):
145 self._assert_bytes(str_)
145 self._assert_bytes(str_)
146 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
146 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
147
147
148 def hash_check_with_upgrade(self, password, hashed):
148 def hash_check_with_upgrade(self, password, hashed):
149 """
149 """
150 Returns tuple in which first element is boolean that states that
150 Returns tuple in which first element is boolean that states that
151 given password matches it's hashed version, and the second is new hash
151 given password matches it's hashed version, and the second is new hash
152 of the password, in case this password should be migrated to new
152 of the password, in case this password should be migrated to new
153 cipher.
153 cipher.
154
154
155 This implements special upgrade logic which works like that:
155 This implements special upgrade logic which works like that:
156 - check if the given password == bcrypted hash, if yes then we
156 - check if the given password == bcrypted hash, if yes then we
157 properly used password and it was already in bcrypt. Proceed
157 properly used password and it was already in bcrypt. Proceed
158 without any changes
158 without any changes
159 - if bcrypt hash check is not working try with sha256. If hash compare
159 - if bcrypt hash check is not working try with sha256. If hash compare
160 is ok, it means we using correct but old hashed password. indicate
160 is ok, it means we using correct but old hashed password. indicate
161 hash change and proceed
161 hash change and proceed
162 """
162 """
163
163
164 new_hash = None
164 new_hash = None
165
165
166 # regular pw check
166 # regular pw check
167 password_match_bcrypt = self.hash_check(password, hashed)
167 password_match_bcrypt = self.hash_check(password, hashed)
168
168
169 # now we want to know if the password was maybe from sha256
169 # now we want to know if the password was maybe from sha256
170 # basically calling _RhodeCodeCryptoSha256().hash_check()
170 # basically calling _RhodeCodeCryptoSha256().hash_check()
171 if not password_match_bcrypt:
171 if not password_match_bcrypt:
172 if _RhodeCodeCryptoSha256().hash_check(password, hashed):
172 if _RhodeCodeCryptoSha256().hash_check(password, hashed):
173 new_hash = self.hash_create(password) # make new bcrypt hash
173 new_hash = self.hash_create(password) # make new bcrypt hash
174 password_match_bcrypt = True
174 password_match_bcrypt = True
175
175
176 return password_match_bcrypt, new_hash
176 return password_match_bcrypt, new_hash
177
177
178 def hash_check(self, password, hashed):
178 def hash_check(self, password, hashed):
179 """
179 """
180 Checks matching password with it's hashed value.
180 Checks matching password with it's hashed value.
181
181
182 :param password: password
182 :param password: password
183 :param hashed: password in hashed form
183 :param hashed: password in hashed form
184 """
184 """
185 self._assert_bytes(password)
185 self._assert_bytes(password)
186 try:
186 try:
187 return bcrypt.hashpw(password, hashed) == hashed
187 return bcrypt.hashpw(password, hashed) == hashed
188 except ValueError as e:
188 except ValueError as e:
189 # we're having a invalid salt here probably, we should not crash
189 # we're having a invalid salt here probably, we should not crash
190 # just return with False as it would be a wrong password.
190 # just return with False as it would be a wrong password.
191 log.debug('Failed to check password hash using bcrypt %s',
191 log.debug('Failed to check password hash using bcrypt %s',
192 safe_str(e))
192 safe_str(e))
193
193
194 return False
194 return False
195
195
196
196
197 class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase):
197 class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase):
198 ENC_PREF = '_'
198 ENC_PREF = '_'
199
199
200 def hash_create(self, str_):
200 def hash_create(self, str_):
201 self._assert_bytes(str_)
201 self._assert_bytes(str_)
202 return hashlib.sha256(str_).hexdigest()
202 return hashlib.sha256(str_).hexdigest()
203
203
204 def hash_check(self, password, hashed):
204 def hash_check(self, password, hashed):
205 """
205 """
206 Checks matching password with it's hashed value.
206 Checks matching password with it's hashed value.
207
207
208 :param password: password
208 :param password: password
209 :param hashed: password in hashed form
209 :param hashed: password in hashed form
210 """
210 """
211 self._assert_bytes(password)
211 self._assert_bytes(password)
212 return hashlib.sha256(password).hexdigest() == hashed
212 return hashlib.sha256(password).hexdigest() == hashed
213
213
214
214
215 class _RhodeCodeCryptoMd5(_RhodeCodeCryptoBase):
215 class _RhodeCodeCryptoMd5(_RhodeCodeCryptoBase):
216 ENC_PREF = '_'
216 ENC_PREF = '_'
217
217
218 def hash_create(self, str_):
218 def hash_create(self, str_):
219 self._assert_bytes(str_)
219 self._assert_bytes(str_)
220 return hashlib.md5(str_).hexdigest()
220 return hashlib.md5(str_).hexdigest()
221
221
222 def hash_check(self, password, hashed):
222 def hash_check(self, password, hashed):
223 """
223 """
224 Checks matching password with it's hashed value.
224 Checks matching password with it's hashed value.
225
225
226 :param password: password
226 :param password: password
227 :param hashed: password in hashed form
227 :param hashed: password in hashed form
228 """
228 """
229 self._assert_bytes(password)
229 self._assert_bytes(password)
230 return hashlib.md5(password).hexdigest() == hashed
230 return hashlib.md5(password).hexdigest() == hashed
231
231
232
232
233 def crypto_backend():
233 def crypto_backend():
234 """
234 """
235 Return the matching crypto backend.
235 Return the matching crypto backend.
236
236
237 Selection is based on if we run tests or not, we pick md5 backend to run
237 Selection is based on if we run tests or not, we pick md5 backend to run
238 tests faster since BCRYPT is expensive to calculate
238 tests faster since BCRYPT is expensive to calculate
239 """
239 """
240 if rhodecode.is_test:
240 if rhodecode.is_test:
241 RhodeCodeCrypto = _RhodeCodeCryptoMd5()
241 RhodeCodeCrypto = _RhodeCodeCryptoMd5()
242 else:
242 else:
243 RhodeCodeCrypto = _RhodeCodeCryptoBCrypt()
243 RhodeCodeCrypto = _RhodeCodeCryptoBCrypt()
244
244
245 return RhodeCodeCrypto
245 return RhodeCodeCrypto
246
246
247
247
248 def get_crypt_password(password):
248 def get_crypt_password(password):
249 """
249 """
250 Create the hash of `password` with the active crypto backend.
250 Create the hash of `password` with the active crypto backend.
251
251
252 :param password: The cleartext password.
252 :param password: The cleartext password.
253 :type password: unicode
253 :type password: unicode
254 """
254 """
255 password = safe_str(password)
255 password = safe_str(password)
256 return crypto_backend().hash_create(password)
256 return crypto_backend().hash_create(password)
257
257
258
258
259 def check_password(password, hashed):
259 def check_password(password, hashed):
260 """
260 """
261 Check if the value in `password` matches the hash in `hashed`.
261 Check if the value in `password` matches the hash in `hashed`.
262
262
263 :param password: The cleartext password.
263 :param password: The cleartext password.
264 :type password: unicode
264 :type password: unicode
265
265
266 :param hashed: The expected hashed version of the password.
266 :param hashed: The expected hashed version of the password.
267 :type hashed: The hash has to be passed in in text representation.
267 :type hashed: The hash has to be passed in in text representation.
268 """
268 """
269 password = safe_str(password)
269 password = safe_str(password)
270 return crypto_backend().hash_check(password, hashed)
270 return crypto_backend().hash_check(password, hashed)
271
271
272
272
273 def generate_auth_token(data, salt=None):
273 def generate_auth_token(data, salt=None):
274 """
274 """
275 Generates API KEY from given string
275 Generates API KEY from given string
276 """
276 """
277
277
278 if salt is None:
278 if salt is None:
279 salt = os.urandom(16)
279 salt = os.urandom(16)
280 return hashlib.sha1(safe_str(data) + salt).hexdigest()
280 return hashlib.sha1(safe_str(data) + salt).hexdigest()
281
281
282
282
283 def get_came_from(request):
283 def get_came_from(request):
284 """
284 """
285 get query_string+path from request sanitized after removing auth_token
285 get query_string+path from request sanitized after removing auth_token
286 """
286 """
287 _req = request
287 _req = request
288
288
289 path = _req.path
289 path = _req.path
290 if 'auth_token' in _req.GET:
290 if 'auth_token' in _req.GET:
291 # sanitize the request and remove auth_token for redirection
291 # sanitize the request and remove auth_token for redirection
292 _req.GET.pop('auth_token')
292 _req.GET.pop('auth_token')
293 qs = _req.query_string
293 qs = _req.query_string
294 if qs:
294 if qs:
295 path += '?' + qs
295 path += '?' + qs
296
296
297 return path
297 return path
298
298
299
299
300 class CookieStoreWrapper(object):
300 class CookieStoreWrapper(object):
301
301
302 def __init__(self, cookie_store):
302 def __init__(self, cookie_store):
303 self.cookie_store = cookie_store
303 self.cookie_store = cookie_store
304
304
305 def __repr__(self):
305 def __repr__(self):
306 return 'CookieStore<%s>' % (self.cookie_store)
306 return 'CookieStore<%s>' % (self.cookie_store)
307
307
308 def get(self, key, other=None):
308 def get(self, key, other=None):
309 if isinstance(self.cookie_store, dict):
309 if isinstance(self.cookie_store, dict):
310 return self.cookie_store.get(key, other)
310 return self.cookie_store.get(key, other)
311 elif isinstance(self.cookie_store, AuthUser):
311 elif isinstance(self.cookie_store, AuthUser):
312 return self.cookie_store.__dict__.get(key, other)
312 return self.cookie_store.__dict__.get(key, other)
313
313
314
314
315 def _cached_perms_data(user_id, scope, user_is_admin,
315 def _cached_perms_data(user_id, scope, user_is_admin,
316 user_inherit_default_permissions, explicit, algo,
316 user_inherit_default_permissions, explicit, algo,
317 calculate_super_admin):
317 calculate_super_admin):
318
318
319 permissions = PermissionCalculator(
319 permissions = PermissionCalculator(
320 user_id, scope, user_is_admin, user_inherit_default_permissions,
320 user_id, scope, user_is_admin, user_inherit_default_permissions,
321 explicit, algo, calculate_super_admin)
321 explicit, algo, calculate_super_admin)
322 return permissions.calculate()
322 return permissions.calculate()
323
323
324
324
325 class PermOrigin(object):
325 class PermOrigin(object):
326 SUPER_ADMIN = 'superadmin'
326 SUPER_ADMIN = 'superadmin'
327
327
328 REPO_USER = 'user:%s'
328 REPO_USER = 'user:%s'
329 REPO_USERGROUP = 'usergroup:%s'
329 REPO_USERGROUP = 'usergroup:%s'
330 REPO_OWNER = 'repo.owner'
330 REPO_OWNER = 'repo.owner'
331 REPO_DEFAULT = 'repo.default'
331 REPO_DEFAULT = 'repo.default'
332 REPO_DEFAULT_NO_INHERIT = 'repo.default.no.inherit'
332 REPO_DEFAULT_NO_INHERIT = 'repo.default.no.inherit'
333 REPO_PRIVATE = 'repo.private'
333 REPO_PRIVATE = 'repo.private'
334
334
335 REPOGROUP_USER = 'user:%s'
335 REPOGROUP_USER = 'user:%s'
336 REPOGROUP_USERGROUP = 'usergroup:%s'
336 REPOGROUP_USERGROUP = 'usergroup:%s'
337 REPOGROUP_OWNER = 'group.owner'
337 REPOGROUP_OWNER = 'group.owner'
338 REPOGROUP_DEFAULT = 'group.default'
338 REPOGROUP_DEFAULT = 'group.default'
339 REPOGROUP_DEFAULT_NO_INHERIT = 'group.default.no.inherit'
339 REPOGROUP_DEFAULT_NO_INHERIT = 'group.default.no.inherit'
340
340
341 USERGROUP_USER = 'user:%s'
341 USERGROUP_USER = 'user:%s'
342 USERGROUP_USERGROUP = 'usergroup:%s'
342 USERGROUP_USERGROUP = 'usergroup:%s'
343 USERGROUP_OWNER = 'usergroup.owner'
343 USERGROUP_OWNER = 'usergroup.owner'
344 USERGROUP_DEFAULT = 'usergroup.default'
344 USERGROUP_DEFAULT = 'usergroup.default'
345 USERGROUP_DEFAULT_NO_INHERIT = 'usergroup.default.no.inherit'
345 USERGROUP_DEFAULT_NO_INHERIT = 'usergroup.default.no.inherit'
346
346
347
347
348 class PermOriginDict(dict):
348 class PermOriginDict(dict):
349 """
349 """
350 A special dict used for tracking permissions along with their origins.
350 A special dict used for tracking permissions along with their origins.
351
351
352 `__setitem__` has been overridden to expect a tuple(perm, origin)
352 `__setitem__` has been overridden to expect a tuple(perm, origin)
353 `__getitem__` will return only the perm
353 `__getitem__` will return only the perm
354 `.perm_origin_stack` will return the stack of (perm, origin) set per key
354 `.perm_origin_stack` will return the stack of (perm, origin) set per key
355
355
356 >>> perms = PermOriginDict()
356 >>> perms = PermOriginDict()
357 >>> perms['resource'] = 'read', 'default'
357 >>> perms['resource'] = 'read', 'default'
358 >>> perms['resource']
358 >>> perms['resource']
359 'read'
359 'read'
360 >>> perms['resource'] = 'write', 'admin'
360 >>> perms['resource'] = 'write', 'admin'
361 >>> perms['resource']
361 >>> perms['resource']
362 'write'
362 'write'
363 >>> perms.perm_origin_stack
363 >>> perms.perm_origin_stack
364 {'resource': [('read', 'default'), ('write', 'admin')]}
364 {'resource': [('read', 'default'), ('write', 'admin')]}
365 """
365 """
366
366
367 def __init__(self, *args, **kw):
367 def __init__(self, *args, **kw):
368 dict.__init__(self, *args, **kw)
368 dict.__init__(self, *args, **kw)
369 self.perm_origin_stack = collections.OrderedDict()
369 self.perm_origin_stack = collections.OrderedDict()
370
370
371 def __setitem__(self, key, (perm, origin)):
371 def __setitem__(self, key, (perm, origin)):
372 self.perm_origin_stack.setdefault(key, []).append((perm, origin))
372 self.perm_origin_stack.setdefault(key, []).append((perm, origin))
373 dict.__setitem__(self, key, perm)
373 dict.__setitem__(self, key, perm)
374
374
375
375
376 class PermissionCalculator(object):
376 class PermissionCalculator(object):
377
377
378 def __init__(
378 def __init__(
379 self, user_id, scope, user_is_admin,
379 self, user_id, scope, user_is_admin,
380 user_inherit_default_permissions, explicit, algo,
380 user_inherit_default_permissions, explicit, algo,
381 calculate_super_admin=False):
381 calculate_super_admin=False):
382
382
383 self.user_id = user_id
383 self.user_id = user_id
384 self.user_is_admin = user_is_admin
384 self.user_is_admin = user_is_admin
385 self.inherit_default_permissions = user_inherit_default_permissions
385 self.inherit_default_permissions = user_inherit_default_permissions
386 self.explicit = explicit
386 self.explicit = explicit
387 self.algo = algo
387 self.algo = algo
388 self.calculate_super_admin = calculate_super_admin
388 self.calculate_super_admin = calculate_super_admin
389
389
390 scope = scope or {}
390 scope = scope or {}
391 self.scope_repo_id = scope.get('repo_id')
391 self.scope_repo_id = scope.get('repo_id')
392 self.scope_repo_group_id = scope.get('repo_group_id')
392 self.scope_repo_group_id = scope.get('repo_group_id')
393 self.scope_user_group_id = scope.get('user_group_id')
393 self.scope_user_group_id = scope.get('user_group_id')
394
394
395 self.default_user_id = User.get_default_user(cache=True).user_id
395 self.default_user_id = User.get_default_user(cache=True).user_id
396
396
397 self.permissions_repositories = PermOriginDict()
397 self.permissions_repositories = PermOriginDict()
398 self.permissions_repository_groups = PermOriginDict()
398 self.permissions_repository_groups = PermOriginDict()
399 self.permissions_user_groups = PermOriginDict()
399 self.permissions_user_groups = PermOriginDict()
400 self.permissions_global = set()
400 self.permissions_global = set()
401
401
402 self.default_repo_perms = Permission.get_default_repo_perms(
402 self.default_repo_perms = Permission.get_default_repo_perms(
403 self.default_user_id, self.scope_repo_id)
403 self.default_user_id, self.scope_repo_id)
404 self.default_repo_groups_perms = Permission.get_default_group_perms(
404 self.default_repo_groups_perms = Permission.get_default_group_perms(
405 self.default_user_id, self.scope_repo_group_id)
405 self.default_user_id, self.scope_repo_group_id)
406 self.default_user_group_perms = \
406 self.default_user_group_perms = \
407 Permission.get_default_user_group_perms(
407 Permission.get_default_user_group_perms(
408 self.default_user_id, self.scope_user_group_id)
408 self.default_user_id, self.scope_user_group_id)
409
409
410 def calculate(self):
410 def calculate(self):
411 if self.user_is_admin and not self.calculate_super_admin:
411 if self.user_is_admin and not self.calculate_super_admin:
412 return self._admin_permissions()
412 return self._admin_permissions()
413
413
414 self._calculate_global_default_permissions()
414 self._calculate_global_default_permissions()
415 self._calculate_global_permissions()
415 self._calculate_global_permissions()
416 self._calculate_default_permissions()
416 self._calculate_default_permissions()
417 self._calculate_repository_permissions()
417 self._calculate_repository_permissions()
418 self._calculate_repository_group_permissions()
418 self._calculate_repository_group_permissions()
419 self._calculate_user_group_permissions()
419 self._calculate_user_group_permissions()
420 return self._permission_structure()
420 return self._permission_structure()
421
421
422 def _admin_permissions(self):
422 def _admin_permissions(self):
423 """
423 """
424 admin user have all default rights for repositories
424 admin user have all default rights for repositories
425 and groups set to admin
425 and groups set to admin
426 """
426 """
427 self.permissions_global.add('hg.admin')
427 self.permissions_global.add('hg.admin')
428 self.permissions_global.add('hg.create.write_on_repogroup.true')
428 self.permissions_global.add('hg.create.write_on_repogroup.true')
429
429
430 # repositories
430 # repositories
431 for perm in self.default_repo_perms:
431 for perm in self.default_repo_perms:
432 r_k = perm.UserRepoToPerm.repository.repo_name
432 r_k = perm.UserRepoToPerm.repository.repo_name
433 p = 'repository.admin'
433 p = 'repository.admin'
434 self.permissions_repositories[r_k] = p, PermOrigin.SUPER_ADMIN
434 self.permissions_repositories[r_k] = p, PermOrigin.SUPER_ADMIN
435
435
436 # repository groups
436 # repository groups
437 for perm in self.default_repo_groups_perms:
437 for perm in self.default_repo_groups_perms:
438 rg_k = perm.UserRepoGroupToPerm.group.group_name
438 rg_k = perm.UserRepoGroupToPerm.group.group_name
439 p = 'group.admin'
439 p = 'group.admin'
440 self.permissions_repository_groups[rg_k] = p, PermOrigin.SUPER_ADMIN
440 self.permissions_repository_groups[rg_k] = p, PermOrigin.SUPER_ADMIN
441
441
442 # user groups
442 # user groups
443 for perm in self.default_user_group_perms:
443 for perm in self.default_user_group_perms:
444 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
444 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
445 p = 'usergroup.admin'
445 p = 'usergroup.admin'
446 self.permissions_user_groups[u_k] = p, PermOrigin.SUPER_ADMIN
446 self.permissions_user_groups[u_k] = p, PermOrigin.SUPER_ADMIN
447
447
448 return self._permission_structure()
448 return self._permission_structure()
449
449
450 def _calculate_global_default_permissions(self):
450 def _calculate_global_default_permissions(self):
451 """
451 """
452 global permissions taken from the default user
452 global permissions taken from the default user
453 """
453 """
454 default_global_perms = UserToPerm.query()\
454 default_global_perms = UserToPerm.query()\
455 .filter(UserToPerm.user_id == self.default_user_id)\
455 .filter(UserToPerm.user_id == self.default_user_id)\
456 .options(joinedload(UserToPerm.permission))
456 .options(joinedload(UserToPerm.permission))
457
457
458 for perm in default_global_perms:
458 for perm in default_global_perms:
459 self.permissions_global.add(perm.permission.permission_name)
459 self.permissions_global.add(perm.permission.permission_name)
460
460
461 if self.user_is_admin:
461 if self.user_is_admin:
462 self.permissions_global.add('hg.admin')
462 self.permissions_global.add('hg.admin')
463 self.permissions_global.add('hg.create.write_on_repogroup.true')
463 self.permissions_global.add('hg.create.write_on_repogroup.true')
464
464
465 def _calculate_global_permissions(self):
465 def _calculate_global_permissions(self):
466 """
466 """
467 Set global system permissions with user permissions or permissions
467 Set global system permissions with user permissions or permissions
468 taken from the user groups of the current user.
468 taken from the user groups of the current user.
469
469
470 The permissions include repo creating, repo group creating, forking
470 The permissions include repo creating, repo group creating, forking
471 etc.
471 etc.
472 """
472 """
473
473
474 # now we read the defined permissions and overwrite what we have set
474 # now we read the defined permissions and overwrite what we have set
475 # before those can be configured from groups or users explicitly.
475 # before those can be configured from groups or users explicitly.
476
476
477 # TODO: johbo: This seems to be out of sync, find out the reason
477 # TODO: johbo: This seems to be out of sync, find out the reason
478 # for the comment below and update it.
478 # for the comment below and update it.
479
479
480 # In case we want to extend this list we should be always in sync with
480 # In case we want to extend this list we should be always in sync with
481 # User.DEFAULT_USER_PERMISSIONS definitions
481 # User.DEFAULT_USER_PERMISSIONS definitions
482 _configurable = frozenset([
482 _configurable = frozenset([
483 'hg.fork.none', 'hg.fork.repository',
483 'hg.fork.none', 'hg.fork.repository',
484 'hg.create.none', 'hg.create.repository',
484 'hg.create.none', 'hg.create.repository',
485 'hg.usergroup.create.false', 'hg.usergroup.create.true',
485 'hg.usergroup.create.false', 'hg.usergroup.create.true',
486 'hg.repogroup.create.false', 'hg.repogroup.create.true',
486 'hg.repogroup.create.false', 'hg.repogroup.create.true',
487 'hg.create.write_on_repogroup.false',
487 'hg.create.write_on_repogroup.false',
488 'hg.create.write_on_repogroup.true',
488 'hg.create.write_on_repogroup.true',
489 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true'
489 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true'
490 ])
490 ])
491
491
492 # USER GROUPS comes first user group global permissions
492 # USER GROUPS comes first user group global permissions
493 user_perms_from_users_groups = Session().query(UserGroupToPerm)\
493 user_perms_from_users_groups = Session().query(UserGroupToPerm)\
494 .options(joinedload(UserGroupToPerm.permission))\
494 .options(joinedload(UserGroupToPerm.permission))\
495 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
495 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
496 UserGroupMember.users_group_id))\
496 UserGroupMember.users_group_id))\
497 .filter(UserGroupMember.user_id == self.user_id)\
497 .filter(UserGroupMember.user_id == self.user_id)\
498 .order_by(UserGroupToPerm.users_group_id)\
498 .order_by(UserGroupToPerm.users_group_id)\
499 .all()
499 .all()
500
500
501 # need to group here by groups since user can be in more than
501 # need to group here by groups since user can be in more than
502 # one group, so we get all groups
502 # one group, so we get all groups
503 _explicit_grouped_perms = [
503 _explicit_grouped_perms = [
504 [x, list(y)] for x, y in
504 [x, list(y)] for x, y in
505 itertools.groupby(user_perms_from_users_groups,
505 itertools.groupby(user_perms_from_users_groups,
506 lambda _x: _x.users_group)]
506 lambda _x: _x.users_group)]
507
507
508 for gr, perms in _explicit_grouped_perms:
508 for gr, perms in _explicit_grouped_perms:
509 # since user can be in multiple groups iterate over them and
509 # since user can be in multiple groups iterate over them and
510 # select the lowest permissions first (more explicit)
510 # select the lowest permissions first (more explicit)
511 # TODO: marcink: do this^^
511 # TODO: marcink: do this^^
512
512
513 # group doesn't inherit default permissions so we actually set them
513 # group doesn't inherit default permissions so we actually set them
514 if not gr.inherit_default_permissions:
514 if not gr.inherit_default_permissions:
515 # NEED TO IGNORE all previously set configurable permissions
515 # NEED TO IGNORE all previously set configurable permissions
516 # and replace them with explicitly set from this user
516 # and replace them with explicitly set from this user
517 # group permissions
517 # group permissions
518 self.permissions_global = self.permissions_global.difference(
518 self.permissions_global = self.permissions_global.difference(
519 _configurable)
519 _configurable)
520 for perm in perms:
520 for perm in perms:
521 self.permissions_global.add(perm.permission.permission_name)
521 self.permissions_global.add(perm.permission.permission_name)
522
522
523 # user explicit global permissions
523 # user explicit global permissions
524 user_perms = Session().query(UserToPerm)\
524 user_perms = Session().query(UserToPerm)\
525 .options(joinedload(UserToPerm.permission))\
525 .options(joinedload(UserToPerm.permission))\
526 .filter(UserToPerm.user_id == self.user_id).all()
526 .filter(UserToPerm.user_id == self.user_id).all()
527
527
528 if not self.inherit_default_permissions:
528 if not self.inherit_default_permissions:
529 # NEED TO IGNORE all configurable permissions and
529 # NEED TO IGNORE all configurable permissions and
530 # replace them with explicitly set from this user permissions
530 # replace them with explicitly set from this user permissions
531 self.permissions_global = self.permissions_global.difference(
531 self.permissions_global = self.permissions_global.difference(
532 _configurable)
532 _configurable)
533 for perm in user_perms:
533 for perm in user_perms:
534 self.permissions_global.add(perm.permission.permission_name)
534 self.permissions_global.add(perm.permission.permission_name)
535
535
536 def _calculate_default_permissions(self):
536 def _calculate_default_permissions(self):
537 """
537 """
538 Set default user permissions for repositories, repository groups
538 Set default user permissions for repositories, repository groups
539 taken from the default user.
539 taken from the default user.
540
540
541 Calculate inheritance of object permissions based on what we have now
541 Calculate inheritance of object permissions based on what we have now
542 in GLOBAL permissions. We check if .false is in GLOBAL since this is
542 in GLOBAL permissions. We check if .false is in GLOBAL since this is
543 explicitly set. Inherit is the opposite of .false being there.
543 explicitly set. Inherit is the opposite of .false being there.
544
544
545 .. note::
545 .. note::
546
546
547 the syntax is little bit odd but what we need to check here is
547 the syntax is little bit odd but what we need to check here is
548 the opposite of .false permission being in the list so even for
548 the opposite of .false permission being in the list so even for
549 inconsistent state when both .true/.false is there
549 inconsistent state when both .true/.false is there
550 .false is more important
550 .false is more important
551
551
552 """
552 """
553 user_inherit_object_permissions = not ('hg.inherit_default_perms.false'
553 user_inherit_object_permissions = not ('hg.inherit_default_perms.false'
554 in self.permissions_global)
554 in self.permissions_global)
555
555
556 # defaults for repositories, taken from `default` user permissions
556 # defaults for repositories, taken from `default` user permissions
557 # on given repo
557 # on given repo
558 for perm in self.default_repo_perms:
558 for perm in self.default_repo_perms:
559 r_k = perm.UserRepoToPerm.repository.repo_name
559 r_k = perm.UserRepoToPerm.repository.repo_name
560 p = perm.Permission.permission_name
560 p = perm.Permission.permission_name
561 o = PermOrigin.REPO_DEFAULT
561 o = PermOrigin.REPO_DEFAULT
562 self.permissions_repositories[r_k] = p, o
562 self.permissions_repositories[r_k] = p, o
563
563
564 # if we decide this user isn't inheriting permissions from
564 # if we decide this user isn't inheriting permissions from
565 # default user we set him to .none so only explicit
565 # default user we set him to .none so only explicit
566 # permissions work
566 # permissions work
567 if not user_inherit_object_permissions:
567 if not user_inherit_object_permissions:
568 p = 'repository.none'
568 p = 'repository.none'
569 o = PermOrigin.REPO_DEFAULT_NO_INHERIT
569 o = PermOrigin.REPO_DEFAULT_NO_INHERIT
570 self.permissions_repositories[r_k] = p, o
570 self.permissions_repositories[r_k] = p, o
571
571
572 if perm.Repository.private and not (
572 if perm.Repository.private and not (
573 perm.Repository.user_id == self.user_id):
573 perm.Repository.user_id == self.user_id):
574 # disable defaults for private repos,
574 # disable defaults for private repos,
575 p = 'repository.none'
575 p = 'repository.none'
576 o = PermOrigin.REPO_PRIVATE
576 o = PermOrigin.REPO_PRIVATE
577 self.permissions_repositories[r_k] = p, o
577 self.permissions_repositories[r_k] = p, o
578
578
579 elif perm.Repository.user_id == self.user_id:
579 elif perm.Repository.user_id == self.user_id:
580 # set admin if owner
580 # set admin if owner
581 p = 'repository.admin'
581 p = 'repository.admin'
582 o = PermOrigin.REPO_OWNER
582 o = PermOrigin.REPO_OWNER
583 self.permissions_repositories[r_k] = p, o
583 self.permissions_repositories[r_k] = p, o
584
584
585 if self.user_is_admin:
585 if self.user_is_admin:
586 p = 'repository.admin'
586 p = 'repository.admin'
587 o = PermOrigin.SUPER_ADMIN
587 o = PermOrigin.SUPER_ADMIN
588 self.permissions_repositories[r_k] = p, o
588 self.permissions_repositories[r_k] = p, o
589
589
590 # defaults for repository groups taken from `default` user permission
590 # defaults for repository groups taken from `default` user permission
591 # on given group
591 # on given group
592 for perm in self.default_repo_groups_perms:
592 for perm in self.default_repo_groups_perms:
593 rg_k = perm.UserRepoGroupToPerm.group.group_name
593 rg_k = perm.UserRepoGroupToPerm.group.group_name
594 p = perm.Permission.permission_name
594 p = perm.Permission.permission_name
595 o = PermOrigin.REPOGROUP_DEFAULT
595 o = PermOrigin.REPOGROUP_DEFAULT
596 self.permissions_repository_groups[rg_k] = p, o
596 self.permissions_repository_groups[rg_k] = p, o
597
597
598 # if we decide this user isn't inheriting permissions from default
598 # if we decide this user isn't inheriting permissions from default
599 # user we set him to .none so only explicit permissions work
599 # user we set him to .none so only explicit permissions work
600 if not user_inherit_object_permissions:
600 if not user_inherit_object_permissions:
601 p = 'group.none'
601 p = 'group.none'
602 o = PermOrigin.REPOGROUP_DEFAULT_NO_INHERIT
602 o = PermOrigin.REPOGROUP_DEFAULT_NO_INHERIT
603 self.permissions_repository_groups[rg_k] = p, o
603 self.permissions_repository_groups[rg_k] = p, o
604
604
605 if perm.RepoGroup.user_id == self.user_id:
605 if perm.RepoGroup.user_id == self.user_id:
606 # set admin if owner
606 # set admin if owner
607 p = 'group.admin'
607 p = 'group.admin'
608 o = PermOrigin.REPOGROUP_OWNER
608 o = PermOrigin.REPOGROUP_OWNER
609 self.permissions_repository_groups[rg_k] = p, o
609 self.permissions_repository_groups[rg_k] = p, o
610
610
611 if self.user_is_admin:
611 if self.user_is_admin:
612 p = 'group.admin'
612 p = 'group.admin'
613 o = PermOrigin.SUPER_ADMIN
613 o = PermOrigin.SUPER_ADMIN
614 self.permissions_repository_groups[rg_k] = p, o
614 self.permissions_repository_groups[rg_k] = p, o
615
615
616 # defaults for user groups taken from `default` user permission
616 # defaults for user groups taken from `default` user permission
617 # on given user group
617 # on given user group
618 for perm in self.default_user_group_perms:
618 for perm in self.default_user_group_perms:
619 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
619 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
620 p = perm.Permission.permission_name
620 p = perm.Permission.permission_name
621 o = PermOrigin.USERGROUP_DEFAULT
621 o = PermOrigin.USERGROUP_DEFAULT
622 self.permissions_user_groups[u_k] = p, o
622 self.permissions_user_groups[u_k] = p, o
623
623
624 # if we decide this user isn't inheriting permissions from default
624 # if we decide this user isn't inheriting permissions from default
625 # user we set him to .none so only explicit permissions work
625 # user we set him to .none so only explicit permissions work
626 if not user_inherit_object_permissions:
626 if not user_inherit_object_permissions:
627 p = 'usergroup.none'
627 p = 'usergroup.none'
628 o = PermOrigin.USERGROUP_DEFAULT_NO_INHERIT
628 o = PermOrigin.USERGROUP_DEFAULT_NO_INHERIT
629 self.permissions_user_groups[u_k] = p, o
629 self.permissions_user_groups[u_k] = p, o
630
630
631 if perm.UserGroup.user_id == self.user_id:
631 if perm.UserGroup.user_id == self.user_id:
632 # set admin if owner
632 # set admin if owner
633 p = 'usergroup.admin'
633 p = 'usergroup.admin'
634 o = PermOrigin.USERGROUP_OWNER
634 o = PermOrigin.USERGROUP_OWNER
635 self.permissions_user_groups[u_k] = p, o
635 self.permissions_user_groups[u_k] = p, o
636
636
637 if self.user_is_admin:
637 if self.user_is_admin:
638 p = 'usergroup.admin'
638 p = 'usergroup.admin'
639 o = PermOrigin.SUPER_ADMIN
639 o = PermOrigin.SUPER_ADMIN
640 self.permissions_user_groups[u_k] = p, o
640 self.permissions_user_groups[u_k] = p, o
641
641
642 def _calculate_repository_permissions(self):
642 def _calculate_repository_permissions(self):
643 """
643 """
644 Repository permissions for the current user.
644 Repository permissions for the current user.
645
645
646 Check if the user is part of user groups for this repository and
646 Check if the user is part of user groups for this repository and
647 fill in the permission from it. `_choose_permission` decides of which
647 fill in the permission from it. `_choose_permission` decides of which
648 permission should be selected based on selected method.
648 permission should be selected based on selected method.
649 """
649 """
650
650
651 # user group for repositories permissions
651 # user group for repositories permissions
652 user_repo_perms_from_user_group = Permission\
652 user_repo_perms_from_user_group = Permission\
653 .get_default_repo_perms_from_user_group(
653 .get_default_repo_perms_from_user_group(
654 self.user_id, self.scope_repo_id)
654 self.user_id, self.scope_repo_id)
655
655
656 multiple_counter = collections.defaultdict(int)
656 multiple_counter = collections.defaultdict(int)
657 for perm in user_repo_perms_from_user_group:
657 for perm in user_repo_perms_from_user_group:
658 r_k = perm.UserGroupRepoToPerm.repository.repo_name
658 r_k = perm.UserGroupRepoToPerm.repository.repo_name
659 multiple_counter[r_k] += 1
659 multiple_counter[r_k] += 1
660 p = perm.Permission.permission_name
660 p = perm.Permission.permission_name
661 o = PermOrigin.REPO_USERGROUP % perm.UserGroupRepoToPerm\
661 o = PermOrigin.REPO_USERGROUP % perm.UserGroupRepoToPerm\
662 .users_group.users_group_name
662 .users_group.users_group_name
663
663
664 if multiple_counter[r_k] > 1:
664 if multiple_counter[r_k] > 1:
665 cur_perm = self.permissions_repositories[r_k]
665 cur_perm = self.permissions_repositories[r_k]
666 p = self._choose_permission(p, cur_perm)
666 p = self._choose_permission(p, cur_perm)
667
667
668 self.permissions_repositories[r_k] = p, o
668 self.permissions_repositories[r_k] = p, o
669
669
670 if perm.Repository.user_id == self.user_id:
670 if perm.Repository.user_id == self.user_id:
671 # set admin if owner
671 # set admin if owner
672 p = 'repository.admin'
672 p = 'repository.admin'
673 o = PermOrigin.REPO_OWNER
673 o = PermOrigin.REPO_OWNER
674 self.permissions_repositories[r_k] = p, o
674 self.permissions_repositories[r_k] = p, o
675
675
676 if self.user_is_admin:
676 if self.user_is_admin:
677 p = 'repository.admin'
677 p = 'repository.admin'
678 o = PermOrigin.SUPER_ADMIN
678 o = PermOrigin.SUPER_ADMIN
679 self.permissions_repositories[r_k] = p, o
679 self.permissions_repositories[r_k] = p, o
680
680
681 # user explicit permissions for repositories, overrides any specified
681 # user explicit permissions for repositories, overrides any specified
682 # by the group permission
682 # by the group permission
683 user_repo_perms = Permission.get_default_repo_perms(
683 user_repo_perms = Permission.get_default_repo_perms(
684 self.user_id, self.scope_repo_id)
684 self.user_id, self.scope_repo_id)
685 for perm in user_repo_perms:
685 for perm in user_repo_perms:
686 r_k = perm.UserRepoToPerm.repository.repo_name
686 r_k = perm.UserRepoToPerm.repository.repo_name
687 p = perm.Permission.permission_name
687 p = perm.Permission.permission_name
688 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
688 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
689
689
690 if not self.explicit:
690 if not self.explicit:
691 cur_perm = self.permissions_repositories.get(
691 cur_perm = self.permissions_repositories.get(
692 r_k, 'repository.none')
692 r_k, 'repository.none')
693 p = self._choose_permission(p, cur_perm)
693 p = self._choose_permission(p, cur_perm)
694
694
695 self.permissions_repositories[r_k] = p, o
695 self.permissions_repositories[r_k] = p, o
696
696
697 if perm.Repository.user_id == self.user_id:
697 if perm.Repository.user_id == self.user_id:
698 # set admin if owner
698 # set admin if owner
699 p = 'repository.admin'
699 p = 'repository.admin'
700 o = PermOrigin.REPO_OWNER
700 o = PermOrigin.REPO_OWNER
701 self.permissions_repositories[r_k] = p, o
701 self.permissions_repositories[r_k] = p, o
702
702
703 if self.user_is_admin:
703 if self.user_is_admin:
704 p = 'repository.admin'
704 p = 'repository.admin'
705 o = PermOrigin.SUPER_ADMIN
705 o = PermOrigin.SUPER_ADMIN
706 self.permissions_repositories[r_k] = p, o
706 self.permissions_repositories[r_k] = p, o
707
707
708 def _calculate_repository_group_permissions(self):
708 def _calculate_repository_group_permissions(self):
709 """
709 """
710 Repository group permissions for the current user.
710 Repository group permissions for the current user.
711
711
712 Check if the user is part of user groups for repository groups and
712 Check if the user is part of user groups for repository groups and
713 fill in the permissions from it. `_choose_permission` decides of which
713 fill in the permissions from it. `_choose_permission` decides of which
714 permission should be selected based on selected method.
714 permission should be selected based on selected method.
715 """
715 """
716 # user group for repo groups permissions
716 # user group for repo groups permissions
717 user_repo_group_perms_from_user_group = Permission\
717 user_repo_group_perms_from_user_group = Permission\
718 .get_default_group_perms_from_user_group(
718 .get_default_group_perms_from_user_group(
719 self.user_id, self.scope_repo_group_id)
719 self.user_id, self.scope_repo_group_id)
720
720
721 multiple_counter = collections.defaultdict(int)
721 multiple_counter = collections.defaultdict(int)
722 for perm in user_repo_group_perms_from_user_group:
722 for perm in user_repo_group_perms_from_user_group:
723 rg_k = perm.UserGroupRepoGroupToPerm.group.group_name
723 rg_k = perm.UserGroupRepoGroupToPerm.group.group_name
724 multiple_counter[rg_k] += 1
724 multiple_counter[rg_k] += 1
725 o = PermOrigin.REPOGROUP_USERGROUP % perm.UserGroupRepoGroupToPerm\
725 o = PermOrigin.REPOGROUP_USERGROUP % perm.UserGroupRepoGroupToPerm\
726 .users_group.users_group_name
726 .users_group.users_group_name
727 p = perm.Permission.permission_name
727 p = perm.Permission.permission_name
728
728
729 if multiple_counter[rg_k] > 1:
729 if multiple_counter[rg_k] > 1:
730 cur_perm = self.permissions_repository_groups[rg_k]
730 cur_perm = self.permissions_repository_groups[rg_k]
731 p = self._choose_permission(p, cur_perm)
731 p = self._choose_permission(p, cur_perm)
732 self.permissions_repository_groups[rg_k] = p, o
732 self.permissions_repository_groups[rg_k] = p, o
733
733
734 if perm.RepoGroup.user_id == self.user_id:
734 if perm.RepoGroup.user_id == self.user_id:
735 # set admin if owner, even for member of other user group
735 # set admin if owner, even for member of other user group
736 p = 'group.admin'
736 p = 'group.admin'
737 o = PermOrigin.REPOGROUP_OWNER
737 o = PermOrigin.REPOGROUP_OWNER
738 self.permissions_repository_groups[rg_k] = p, o
738 self.permissions_repository_groups[rg_k] = p, o
739
739
740 if self.user_is_admin:
740 if self.user_is_admin:
741 p = 'group.admin'
741 p = 'group.admin'
742 o = PermOrigin.SUPER_ADMIN
742 o = PermOrigin.SUPER_ADMIN
743 self.permissions_repository_groups[rg_k] = p, o
743 self.permissions_repository_groups[rg_k] = p, o
744
744
745 # user explicit permissions for repository groups
745 # user explicit permissions for repository groups
746 user_repo_groups_perms = Permission.get_default_group_perms(
746 user_repo_groups_perms = Permission.get_default_group_perms(
747 self.user_id, self.scope_repo_group_id)
747 self.user_id, self.scope_repo_group_id)
748 for perm in user_repo_groups_perms:
748 for perm in user_repo_groups_perms:
749 rg_k = perm.UserRepoGroupToPerm.group.group_name
749 rg_k = perm.UserRepoGroupToPerm.group.group_name
750 o = PermOrigin.REPOGROUP_USER % perm.UserRepoGroupToPerm\
750 o = PermOrigin.REPOGROUP_USER % perm.UserRepoGroupToPerm\
751 .user.username
751 .user.username
752 p = perm.Permission.permission_name
752 p = perm.Permission.permission_name
753
753
754 if not self.explicit:
754 if not self.explicit:
755 cur_perm = self.permissions_repository_groups.get(
755 cur_perm = self.permissions_repository_groups.get(
756 rg_k, 'group.none')
756 rg_k, 'group.none')
757 p = self._choose_permission(p, cur_perm)
757 p = self._choose_permission(p, cur_perm)
758
758
759 self.permissions_repository_groups[rg_k] = p, o
759 self.permissions_repository_groups[rg_k] = p, o
760
760
761 if perm.RepoGroup.user_id == self.user_id:
761 if perm.RepoGroup.user_id == self.user_id:
762 # set admin if owner
762 # set admin if owner
763 p = 'group.admin'
763 p = 'group.admin'
764 o = PermOrigin.REPOGROUP_OWNER
764 o = PermOrigin.REPOGROUP_OWNER
765 self.permissions_repository_groups[rg_k] = p, o
765 self.permissions_repository_groups[rg_k] = p, o
766
766
767 if self.user_is_admin:
767 if self.user_is_admin:
768 p = 'group.admin'
768 p = 'group.admin'
769 o = PermOrigin.SUPER_ADMIN
769 o = PermOrigin.SUPER_ADMIN
770 self.permissions_repository_groups[rg_k] = p, o
770 self.permissions_repository_groups[rg_k] = p, o
771
771
772 def _calculate_user_group_permissions(self):
772 def _calculate_user_group_permissions(self):
773 """
773 """
774 User group permissions for the current user.
774 User group permissions for the current user.
775 """
775 """
776 # user group for user group permissions
776 # user group for user group permissions
777 user_group_from_user_group = Permission\
777 user_group_from_user_group = Permission\
778 .get_default_user_group_perms_from_user_group(
778 .get_default_user_group_perms_from_user_group(
779 self.user_id, self.scope_user_group_id)
779 self.user_id, self.scope_user_group_id)
780
780
781 multiple_counter = collections.defaultdict(int)
781 multiple_counter = collections.defaultdict(int)
782 for perm in user_group_from_user_group:
782 for perm in user_group_from_user_group:
783 ug_k = perm.UserGroupUserGroupToPerm\
783 ug_k = perm.UserGroupUserGroupToPerm\
784 .target_user_group.users_group_name
784 .target_user_group.users_group_name
785 multiple_counter[ug_k] += 1
785 multiple_counter[ug_k] += 1
786 o = PermOrigin.USERGROUP_USERGROUP % perm.UserGroupUserGroupToPerm\
786 o = PermOrigin.USERGROUP_USERGROUP % perm.UserGroupUserGroupToPerm\
787 .user_group.users_group_name
787 .user_group.users_group_name
788 p = perm.Permission.permission_name
788 p = perm.Permission.permission_name
789
789
790 if multiple_counter[ug_k] > 1:
790 if multiple_counter[ug_k] > 1:
791 cur_perm = self.permissions_user_groups[ug_k]
791 cur_perm = self.permissions_user_groups[ug_k]
792 p = self._choose_permission(p, cur_perm)
792 p = self._choose_permission(p, cur_perm)
793
793
794 self.permissions_user_groups[ug_k] = p, o
794 self.permissions_user_groups[ug_k] = p, o
795
795
796 if perm.UserGroup.user_id == self.user_id:
796 if perm.UserGroup.user_id == self.user_id:
797 # set admin if owner, even for member of other user group
797 # set admin if owner, even for member of other user group
798 p = 'usergroup.admin'
798 p = 'usergroup.admin'
799 o = PermOrigin.USERGROUP_OWNER
799 o = PermOrigin.USERGROUP_OWNER
800 self.permissions_user_groups[ug_k] = p, o
800 self.permissions_user_groups[ug_k] = p, o
801
801
802 if self.user_is_admin:
802 if self.user_is_admin:
803 p = 'usergroup.admin'
803 p = 'usergroup.admin'
804 o = PermOrigin.SUPER_ADMIN
804 o = PermOrigin.SUPER_ADMIN
805 self.permissions_user_groups[ug_k] = p, o
805 self.permissions_user_groups[ug_k] = p, o
806
806
807 # user explicit permission for user groups
807 # user explicit permission for user groups
808 user_user_groups_perms = Permission.get_default_user_group_perms(
808 user_user_groups_perms = Permission.get_default_user_group_perms(
809 self.user_id, self.scope_user_group_id)
809 self.user_id, self.scope_user_group_id)
810 for perm in user_user_groups_perms:
810 for perm in user_user_groups_perms:
811 ug_k = perm.UserUserGroupToPerm.user_group.users_group_name
811 ug_k = perm.UserUserGroupToPerm.user_group.users_group_name
812 o = PermOrigin.USERGROUP_USER % perm.UserUserGroupToPerm\
812 o = PermOrigin.USERGROUP_USER % perm.UserUserGroupToPerm\
813 .user.username
813 .user.username
814 p = perm.Permission.permission_name
814 p = perm.Permission.permission_name
815
815
816 if not self.explicit:
816 if not self.explicit:
817 cur_perm = self.permissions_user_groups.get(
817 cur_perm = self.permissions_user_groups.get(
818 ug_k, 'usergroup.none')
818 ug_k, 'usergroup.none')
819 p = self._choose_permission(p, cur_perm)
819 p = self._choose_permission(p, cur_perm)
820
820
821 self.permissions_user_groups[ug_k] = p, o
821 self.permissions_user_groups[ug_k] = p, o
822
822
823 if perm.UserGroup.user_id == self.user_id:
823 if perm.UserGroup.user_id == self.user_id:
824 # set admin if owner
824 # set admin if owner
825 p = 'usergroup.admin'
825 p = 'usergroup.admin'
826 o = PermOrigin.USERGROUP_OWNER
826 o = PermOrigin.USERGROUP_OWNER
827 self.permissions_user_groups[ug_k] = p, o
827 self.permissions_user_groups[ug_k] = p, o
828
828
829 if self.user_is_admin:
829 if self.user_is_admin:
830 p = 'usergroup.admin'
830 p = 'usergroup.admin'
831 o = PermOrigin.SUPER_ADMIN
831 o = PermOrigin.SUPER_ADMIN
832 self.permissions_user_groups[ug_k] = p, o
832 self.permissions_user_groups[ug_k] = p, o
833
833
834 def _choose_permission(self, new_perm, cur_perm):
834 def _choose_permission(self, new_perm, cur_perm):
835 new_perm_val = Permission.PERM_WEIGHTS[new_perm]
835 new_perm_val = Permission.PERM_WEIGHTS[new_perm]
836 cur_perm_val = Permission.PERM_WEIGHTS[cur_perm]
836 cur_perm_val = Permission.PERM_WEIGHTS[cur_perm]
837 if self.algo == 'higherwin':
837 if self.algo == 'higherwin':
838 if new_perm_val > cur_perm_val:
838 if new_perm_val > cur_perm_val:
839 return new_perm
839 return new_perm
840 return cur_perm
840 return cur_perm
841 elif self.algo == 'lowerwin':
841 elif self.algo == 'lowerwin':
842 if new_perm_val < cur_perm_val:
842 if new_perm_val < cur_perm_val:
843 return new_perm
843 return new_perm
844 return cur_perm
844 return cur_perm
845
845
846 def _permission_structure(self):
846 def _permission_structure(self):
847 return {
847 return {
848 'global': self.permissions_global,
848 'global': self.permissions_global,
849 'repositories': self.permissions_repositories,
849 'repositories': self.permissions_repositories,
850 'repositories_groups': self.permissions_repository_groups,
850 'repositories_groups': self.permissions_repository_groups,
851 'user_groups': self.permissions_user_groups,
851 'user_groups': self.permissions_user_groups,
852 }
852 }
853
853
854
854
855 def allowed_auth_token_access(view_name, auth_token, whitelist=None):
855 def allowed_auth_token_access(view_name, auth_token, whitelist=None):
856 """
856 """
857 Check if given controller_name is in whitelist of auth token access
857 Check if given controller_name is in whitelist of auth token access
858 """
858 """
859 if not whitelist:
859 if not whitelist:
860 from rhodecode import CONFIG
860 from rhodecode import CONFIG
861 whitelist = aslist(
861 whitelist = aslist(
862 CONFIG.get('api_access_controllers_whitelist'), sep=',')
862 CONFIG.get('api_access_controllers_whitelist'), sep=',')
863 # backward compat translation
863 # backward compat translation
864 compat = {
864 compat = {
865 # old controller, new VIEW
865 # old controller, new VIEW
866 'ChangesetController:*': 'RepoCommitsView:*',
866 'ChangesetController:*': 'RepoCommitsView:*',
867 'ChangesetController:changeset_patch': 'RepoCommitsView:repo_commit_patch',
867 'ChangesetController:changeset_patch': 'RepoCommitsView:repo_commit_patch',
868 'ChangesetController:changeset_raw': 'RepoCommitsView:repo_commit_raw',
868 'ChangesetController:changeset_raw': 'RepoCommitsView:repo_commit_raw',
869 'FilesController:raw': 'RepoCommitsView:repo_commit_raw',
869 'FilesController:raw': 'RepoCommitsView:repo_commit_raw',
870 'FilesController:archivefile': 'RepoFilesView:repo_archivefile',
870 'FilesController:archivefile': 'RepoFilesView:repo_archivefile',
871 'GistsController:*': 'GistView:*',
871 'GistsController:*': 'GistView:*',
872 }
872 }
873
873
874 log.debug(
874 log.debug(
875 'Allowed views for AUTH TOKEN access: %s' % (whitelist,))
875 'Allowed views for AUTH TOKEN access: %s' % (whitelist,))
876 auth_token_access_valid = False
876 auth_token_access_valid = False
877
877
878 for entry in whitelist:
878 for entry in whitelist:
879 token_match = True
879 token_match = True
880 if entry in compat:
880 if entry in compat:
881 # translate from old Controllers to Pyramid Views
881 # translate from old Controllers to Pyramid Views
882 entry = compat[entry]
882 entry = compat[entry]
883
883
884 if '@' in entry:
884 if '@' in entry:
885 # specific AuthToken
885 # specific AuthToken
886 entry, allowed_token = entry.split('@', 1)
886 entry, allowed_token = entry.split('@', 1)
887 token_match = auth_token == allowed_token
887 token_match = auth_token == allowed_token
888
888
889 if fnmatch.fnmatch(view_name, entry) and token_match:
889 if fnmatch.fnmatch(view_name, entry) and token_match:
890 auth_token_access_valid = True
890 auth_token_access_valid = True
891 break
891 break
892
892
893 if auth_token_access_valid:
893 if auth_token_access_valid:
894 log.debug('view: `%s` matches entry in whitelist: %s'
894 log.debug('view: `%s` matches entry in whitelist: %s'
895 % (view_name, whitelist))
895 % (view_name, whitelist))
896 else:
896 else:
897 msg = ('view: `%s` does *NOT* match any entry in whitelist: %s'
897 msg = ('view: `%s` does *NOT* match any entry in whitelist: %s'
898 % (view_name, whitelist))
898 % (view_name, whitelist))
899 if auth_token:
899 if auth_token:
900 # if we use auth token key and don't have access it's a warning
900 # if we use auth token key and don't have access it's a warning
901 log.warning(msg)
901 log.warning(msg)
902 else:
902 else:
903 log.debug(msg)
903 log.debug(msg)
904
904
905 return auth_token_access_valid
905 return auth_token_access_valid
906
906
907
907
908 class AuthUser(object):
908 class AuthUser(object):
909 """
909 """
910 A simple object that handles all attributes of user in RhodeCode
910 A simple object that handles all attributes of user in RhodeCode
911
911
912 It does lookup based on API key,given user, or user present in session
912 It does lookup based on API key,given user, or user present in session
913 Then it fills all required information for such user. It also checks if
913 Then it fills all required information for such user. It also checks if
914 anonymous access is enabled and if so, it returns default user as logged in
914 anonymous access is enabled and if so, it returns default user as logged in
915 """
915 """
916 GLOBAL_PERMS = [x[0] for x in Permission.PERMS]
916 GLOBAL_PERMS = [x[0] for x in Permission.PERMS]
917
917
918 def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None):
918 def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None):
919
919
920 self.user_id = user_id
920 self.user_id = user_id
921 self._api_key = api_key
921 self._api_key = api_key
922
922
923 self.api_key = None
923 self.api_key = None
924 self.feed_token = ''
924 self.feed_token = ''
925 self.username = username
925 self.username = username
926 self.ip_addr = ip_addr
926 self.ip_addr = ip_addr
927 self.name = ''
927 self.name = ''
928 self.lastname = ''
928 self.lastname = ''
929 self.first_name = ''
929 self.first_name = ''
930 self.last_name = ''
930 self.last_name = ''
931 self.email = ''
931 self.email = ''
932 self.is_authenticated = False
932 self.is_authenticated = False
933 self.admin = False
933 self.admin = False
934 self.inherit_default_permissions = False
934 self.inherit_default_permissions = False
935 self.password = ''
935 self.password = ''
936
936
937 self.anonymous_user = None # propagated on propagate_data
937 self.anonymous_user = None # propagated on propagate_data
938 self.propagate_data()
938 self.propagate_data()
939 self._instance = None
939 self._instance = None
940 self._permissions_scoped_cache = {} # used to bind scoped calculation
940 self._permissions_scoped_cache = {} # used to bind scoped calculation
941
941
942 @LazyProperty
942 @LazyProperty
943 def permissions(self):
943 def permissions(self):
944 return self.get_perms(user=self, cache=False)
944 return self.get_perms(user=self, cache=False)
945
945
946 @LazyProperty
946 @LazyProperty
947 def permissions_full_details(self):
947 def permissions_full_details(self):
948 return self.get_perms(
948 return self.get_perms(
949 user=self, cache=False, calculate_super_admin=True)
949 user=self, cache=False, calculate_super_admin=True)
950
950
951 def permissions_with_scope(self, scope):
951 def permissions_with_scope(self, scope):
952 """
952 """
953 Call the get_perms function with scoped data. The scope in that function
953 Call the get_perms function with scoped data. The scope in that function
954 narrows the SQL calls to the given ID of objects resulting in fetching
954 narrows the SQL calls to the given ID of objects resulting in fetching
955 Just particular permission we want to obtain. If scope is an empty dict
955 Just particular permission we want to obtain. If scope is an empty dict
956 then it basically narrows the scope to GLOBAL permissions only.
956 then it basically narrows the scope to GLOBAL permissions only.
957
957
958 :param scope: dict
958 :param scope: dict
959 """
959 """
960 if 'repo_name' in scope:
960 if 'repo_name' in scope:
961 obj = Repository.get_by_repo_name(scope['repo_name'])
961 obj = Repository.get_by_repo_name(scope['repo_name'])
962 if obj:
962 if obj:
963 scope['repo_id'] = obj.repo_id
963 scope['repo_id'] = obj.repo_id
964 _scope = {
964 _scope = {
965 'repo_id': -1,
965 'repo_id': -1,
966 'user_group_id': -1,
966 'user_group_id': -1,
967 'repo_group_id': -1,
967 'repo_group_id': -1,
968 }
968 }
969 _scope.update(scope)
969 _scope.update(scope)
970 cache_key = "_".join(map(safe_str, reduce(lambda a, b: a+b,
970 cache_key = "_".join(map(safe_str, reduce(lambda a, b: a+b,
971 _scope.items())))
971 _scope.items())))
972 if cache_key not in self._permissions_scoped_cache:
972 if cache_key not in self._permissions_scoped_cache:
973 # store in cache to mimic how the @LazyProperty works,
973 # store in cache to mimic how the @LazyProperty works,
974 # the difference here is that we use the unique key calculated
974 # the difference here is that we use the unique key calculated
975 # from params and values
975 # from params and values
976 res = self.get_perms(user=self, cache=False, scope=_scope)
976 res = self.get_perms(user=self, cache=False, scope=_scope)
977 self._permissions_scoped_cache[cache_key] = res
977 self._permissions_scoped_cache[cache_key] = res
978 return self._permissions_scoped_cache[cache_key]
978 return self._permissions_scoped_cache[cache_key]
979
979
980 def get_instance(self):
980 def get_instance(self):
981 return User.get(self.user_id)
981 return User.get(self.user_id)
982
982
983 def update_lastactivity(self):
983 def update_lastactivity(self):
984 if self.user_id:
984 if self.user_id:
985 User.get(self.user_id).update_lastactivity()
985 User.get(self.user_id).update_lastactivity()
986
986
987 def propagate_data(self):
987 def propagate_data(self):
988 """
988 """
989 Fills in user data and propagates values to this instance. Maps fetched
989 Fills in user data and propagates values to this instance. Maps fetched
990 user attributes to this class instance attributes
990 user attributes to this class instance attributes
991 """
991 """
992 log.debug('AuthUser: starting data propagation for new potential user')
992 log.debug('AuthUser: starting data propagation for new potential user')
993 user_model = UserModel()
993 user_model = UserModel()
994 anon_user = self.anonymous_user = User.get_default_user(cache=True)
994 anon_user = self.anonymous_user = User.get_default_user(cache=True)
995 is_user_loaded = False
995 is_user_loaded = False
996
996
997 # lookup by userid
997 # lookup by userid
998 if self.user_id is not None and self.user_id != anon_user.user_id:
998 if self.user_id is not None and self.user_id != anon_user.user_id:
999 log.debug('Trying Auth User lookup by USER ID: `%s`', self.user_id)
999 log.debug('Trying Auth User lookup by USER ID: `%s`', self.user_id)
1000 is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
1000 is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
1001
1001
1002 # try go get user by api key
1002 # try go get user by api key
1003 elif self._api_key and self._api_key != anon_user.api_key:
1003 elif self._api_key and self._api_key != anon_user.api_key:
1004 log.debug('Trying Auth User lookup by API KEY: `%s`', self._api_key)
1004 log.debug('Trying Auth User lookup by API KEY: `%s`', self._api_key)
1005 is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
1005 is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
1006
1006
1007 # lookup by username
1007 # lookup by username
1008 elif self.username:
1008 elif self.username:
1009 log.debug('Trying Auth User lookup by USER NAME: `%s`', self.username)
1009 log.debug('Trying Auth User lookup by USER NAME: `%s`', self.username)
1010 is_user_loaded = user_model.fill_data(self, username=self.username)
1010 is_user_loaded = user_model.fill_data(self, username=self.username)
1011 else:
1011 else:
1012 log.debug('No data in %s that could been used to log in', self)
1012 log.debug('No data in %s that could been used to log in', self)
1013
1013
1014 if not is_user_loaded:
1014 if not is_user_loaded:
1015 log.debug('Failed to load user. Fallback to default user')
1015 log.debug(
1016 'Failed to load user. Fallback to default user %s', anon_user)
1016 # if we cannot authenticate user try anonymous
1017 # if we cannot authenticate user try anonymous
1017 if anon_user.active:
1018 if anon_user.active:
1019 log.debug('default user is active, using it as a session user')
1018 user_model.fill_data(self, user_id=anon_user.user_id)
1020 user_model.fill_data(self, user_id=anon_user.user_id)
1019 # then we set this user is logged in
1021 # then we set this user is logged in
1020 self.is_authenticated = True
1022 self.is_authenticated = True
1021 else:
1023 else:
1024 log.debug('default user is NOT active')
1022 # in case of disabled anonymous user we reset some of the
1025 # in case of disabled anonymous user we reset some of the
1023 # parameters so such user is "corrupted", skipping the fill_data
1026 # parameters so such user is "corrupted", skipping the fill_data
1024 for attr in ['user_id', 'username', 'admin', 'active']:
1027 for attr in ['user_id', 'username', 'admin', 'active']:
1025 setattr(self, attr, None)
1028 setattr(self, attr, None)
1026 self.is_authenticated = False
1029 self.is_authenticated = False
1027
1030
1028 if not self.username:
1031 if not self.username:
1029 self.username = 'None'
1032 self.username = 'None'
1030
1033
1031 log.debug('AuthUser: propagated user is now %s', self)
1034 log.debug('AuthUser: propagated user is now %s', self)
1032
1035
1033 def get_perms(self, user, scope=None, explicit=True, algo='higherwin',
1036 def get_perms(self, user, scope=None, explicit=True, algo='higherwin',
1034 calculate_super_admin=False, cache=False):
1037 calculate_super_admin=False, cache=False):
1035 """
1038 """
1036 Fills user permission attribute with permissions taken from database
1039 Fills user permission attribute with permissions taken from database
1037 works for permissions given for repositories, and for permissions that
1040 works for permissions given for repositories, and for permissions that
1038 are granted to groups
1041 are granted to groups
1039
1042
1040 :param user: instance of User object from database
1043 :param user: instance of User object from database
1041 :param explicit: In case there are permissions both for user and a group
1044 :param explicit: In case there are permissions both for user and a group
1042 that user is part of, explicit flag will defiine if user will
1045 that user is part of, explicit flag will defiine if user will
1043 explicitly override permissions from group, if it's False it will
1046 explicitly override permissions from group, if it's False it will
1044 make decision based on the algo
1047 make decision based on the algo
1045 :param algo: algorithm to decide what permission should be choose if
1048 :param algo: algorithm to decide what permission should be choose if
1046 it's multiple defined, eg user in two different groups. It also
1049 it's multiple defined, eg user in two different groups. It also
1047 decides if explicit flag is turned off how to specify the permission
1050 decides if explicit flag is turned off how to specify the permission
1048 for case when user is in a group + have defined separate permission
1051 for case when user is in a group + have defined separate permission
1049 """
1052 """
1050 user_id = user.user_id
1053 user_id = user.user_id
1051 user_is_admin = user.is_admin
1054 user_is_admin = user.is_admin
1052
1055
1053 # inheritance of global permissions like create repo/fork repo etc
1056 # inheritance of global permissions like create repo/fork repo etc
1054 user_inherit_default_permissions = user.inherit_default_permissions
1057 user_inherit_default_permissions = user.inherit_default_permissions
1055
1058
1056 log.debug('Computing PERMISSION tree for scope %s' % (scope, ))
1059 log.debug('Computing PERMISSION tree for scope %s' % (scope, ))
1057 compute = caches.conditional_cache(
1060 compute = caches.conditional_cache(
1058 'short_term', 'cache_desc',
1061 'short_term', 'cache_desc',
1059 condition=cache, func=_cached_perms_data)
1062 condition=cache, func=_cached_perms_data)
1060 result = compute(user_id, scope, user_is_admin,
1063 result = compute(user_id, scope, user_is_admin,
1061 user_inherit_default_permissions, explicit, algo,
1064 user_inherit_default_permissions, explicit, algo,
1062 calculate_super_admin)
1065 calculate_super_admin)
1063
1066
1064 result_repr = []
1067 result_repr = []
1065 for k in result:
1068 for k in result:
1066 result_repr.append((k, len(result[k])))
1069 result_repr.append((k, len(result[k])))
1067
1070
1068 log.debug('PERMISSION tree computed %s' % (result_repr,))
1071 log.debug('PERMISSION tree computed %s' % (result_repr,))
1069 return result
1072 return result
1070
1073
1071 @property
1074 @property
1072 def is_default(self):
1075 def is_default(self):
1073 return self.username == User.DEFAULT_USER
1076 return self.username == User.DEFAULT_USER
1074
1077
1075 @property
1078 @property
1076 def is_admin(self):
1079 def is_admin(self):
1077 return self.admin
1080 return self.admin
1078
1081
1079 @property
1082 @property
1080 def is_user_object(self):
1083 def is_user_object(self):
1081 return self.user_id is not None
1084 return self.user_id is not None
1082
1085
1083 @property
1086 @property
1084 def repositories_admin(self):
1087 def repositories_admin(self):
1085 """
1088 """
1086 Returns list of repositories you're an admin of
1089 Returns list of repositories you're an admin of
1087 """
1090 """
1088 return [
1091 return [
1089 x[0] for x in self.permissions['repositories'].iteritems()
1092 x[0] for x in self.permissions['repositories'].iteritems()
1090 if x[1] == 'repository.admin']
1093 if x[1] == 'repository.admin']
1091
1094
1092 @property
1095 @property
1093 def repository_groups_admin(self):
1096 def repository_groups_admin(self):
1094 """
1097 """
1095 Returns list of repository groups you're an admin of
1098 Returns list of repository groups you're an admin of
1096 """
1099 """
1097 return [
1100 return [
1098 x[0] for x in self.permissions['repositories_groups'].iteritems()
1101 x[0] for x in self.permissions['repositories_groups'].iteritems()
1099 if x[1] == 'group.admin']
1102 if x[1] == 'group.admin']
1100
1103
1101 @property
1104 @property
1102 def user_groups_admin(self):
1105 def user_groups_admin(self):
1103 """
1106 """
1104 Returns list of user groups you're an admin of
1107 Returns list of user groups you're an admin of
1105 """
1108 """
1106 return [
1109 return [
1107 x[0] for x in self.permissions['user_groups'].iteritems()
1110 x[0] for x in self.permissions['user_groups'].iteritems()
1108 if x[1] == 'usergroup.admin']
1111 if x[1] == 'usergroup.admin']
1109
1112
1110 def repo_acl_ids(self, perms=None, name_filter=None, cache=False):
1113 def repo_acl_ids(self, perms=None, name_filter=None, cache=False):
1111 """
1114 """
1112 Returns list of repository ids that user have access to based on given
1115 Returns list of repository ids that user have access to based on given
1113 perms. The cache flag should be only used in cases that are used for
1116 perms. The cache flag should be only used in cases that are used for
1114 display purposes, NOT IN ANY CASE for permission checks.
1117 display purposes, NOT IN ANY CASE for permission checks.
1115 """
1118 """
1116 from rhodecode.model.scm import RepoList
1119 from rhodecode.model.scm import RepoList
1117 if not perms:
1120 if not perms:
1118 perms = [
1121 perms = [
1119 'repository.read', 'repository.write', 'repository.admin']
1122 'repository.read', 'repository.write', 'repository.admin']
1120
1123
1121 def _cached_repo_acl(user_id, perm_def, name_filter):
1124 def _cached_repo_acl(user_id, perm_def, name_filter):
1122 qry = Repository.query()
1125 qry = Repository.query()
1123 if name_filter:
1126 if name_filter:
1124 ilike_expression = u'%{}%'.format(safe_unicode(name_filter))
1127 ilike_expression = u'%{}%'.format(safe_unicode(name_filter))
1125 qry = qry.filter(
1128 qry = qry.filter(
1126 Repository.repo_name.ilike(ilike_expression))
1129 Repository.repo_name.ilike(ilike_expression))
1127
1130
1128 return [x.repo_id for x in
1131 return [x.repo_id for x in
1129 RepoList(qry, perm_set=perm_def)]
1132 RepoList(qry, perm_set=perm_def)]
1130
1133
1131 compute = caches.conditional_cache(
1134 compute = caches.conditional_cache(
1132 'long_term', 'repo_acl_ids',
1135 'long_term', 'repo_acl_ids',
1133 condition=cache, func=_cached_repo_acl)
1136 condition=cache, func=_cached_repo_acl)
1134 return compute(self.user_id, perms, name_filter)
1137 return compute(self.user_id, perms, name_filter)
1135
1138
1136 def repo_group_acl_ids(self, perms=None, name_filter=None, cache=False):
1139 def repo_group_acl_ids(self, perms=None, name_filter=None, cache=False):
1137 """
1140 """
1138 Returns list of repository group ids that user have access to based on given
1141 Returns list of repository group ids that user have access to based on given
1139 perms. The cache flag should be only used in cases that are used for
1142 perms. The cache flag should be only used in cases that are used for
1140 display purposes, NOT IN ANY CASE for permission checks.
1143 display purposes, NOT IN ANY CASE for permission checks.
1141 """
1144 """
1142 from rhodecode.model.scm import RepoGroupList
1145 from rhodecode.model.scm import RepoGroupList
1143 if not perms:
1146 if not perms:
1144 perms = [
1147 perms = [
1145 'group.read', 'group.write', 'group.admin']
1148 'group.read', 'group.write', 'group.admin']
1146
1149
1147 def _cached_repo_group_acl(user_id, perm_def, name_filter):
1150 def _cached_repo_group_acl(user_id, perm_def, name_filter):
1148 qry = RepoGroup.query()
1151 qry = RepoGroup.query()
1149 if name_filter:
1152 if name_filter:
1150 ilike_expression = u'%{}%'.format(safe_unicode(name_filter))
1153 ilike_expression = u'%{}%'.format(safe_unicode(name_filter))
1151 qry = qry.filter(
1154 qry = qry.filter(
1152 RepoGroup.group_name.ilike(ilike_expression))
1155 RepoGroup.group_name.ilike(ilike_expression))
1153
1156
1154 return [x.group_id for x in
1157 return [x.group_id for x in
1155 RepoGroupList(qry, perm_set=perm_def)]
1158 RepoGroupList(qry, perm_set=perm_def)]
1156
1159
1157 compute = caches.conditional_cache(
1160 compute = caches.conditional_cache(
1158 'long_term', 'repo_group_acl_ids',
1161 'long_term', 'repo_group_acl_ids',
1159 condition=cache, func=_cached_repo_group_acl)
1162 condition=cache, func=_cached_repo_group_acl)
1160 return compute(self.user_id, perms, name_filter)
1163 return compute(self.user_id, perms, name_filter)
1161
1164
1162 def user_group_acl_ids(self, perms=None, name_filter=None, cache=False):
1165 def user_group_acl_ids(self, perms=None, name_filter=None, cache=False):
1163 """
1166 """
1164 Returns list of user group ids that user have access to based on given
1167 Returns list of user group ids that user have access to based on given
1165 perms. The cache flag should be only used in cases that are used for
1168 perms. The cache flag should be only used in cases that are used for
1166 display purposes, NOT IN ANY CASE for permission checks.
1169 display purposes, NOT IN ANY CASE for permission checks.
1167 """
1170 """
1168 from rhodecode.model.scm import UserGroupList
1171 from rhodecode.model.scm import UserGroupList
1169 if not perms:
1172 if not perms:
1170 perms = [
1173 perms = [
1171 'usergroup.read', 'usergroup.write', 'usergroup.admin']
1174 'usergroup.read', 'usergroup.write', 'usergroup.admin']
1172
1175
1173 def _cached_user_group_acl(user_id, perm_def, name_filter):
1176 def _cached_user_group_acl(user_id, perm_def, name_filter):
1174 qry = UserGroup.query()
1177 qry = UserGroup.query()
1175 if name_filter:
1178 if name_filter:
1176 ilike_expression = u'%{}%'.format(safe_unicode(name_filter))
1179 ilike_expression = u'%{}%'.format(safe_unicode(name_filter))
1177 qry = qry.filter(
1180 qry = qry.filter(
1178 UserGroup.users_group_name.ilike(ilike_expression))
1181 UserGroup.users_group_name.ilike(ilike_expression))
1179
1182
1180 return [x.users_group_id for x in
1183 return [x.users_group_id for x in
1181 UserGroupList(qry, perm_set=perm_def)]
1184 UserGroupList(qry, perm_set=perm_def)]
1182
1185
1183 compute = caches.conditional_cache(
1186 compute = caches.conditional_cache(
1184 'long_term', 'user_group_acl_ids',
1187 'long_term', 'user_group_acl_ids',
1185 condition=cache, func=_cached_user_group_acl)
1188 condition=cache, func=_cached_user_group_acl)
1186 return compute(self.user_id, perms, name_filter)
1189 return compute(self.user_id, perms, name_filter)
1187
1190
1188 @property
1191 @property
1189 def ip_allowed(self):
1192 def ip_allowed(self):
1190 """
1193 """
1191 Checks if ip_addr used in constructor is allowed from defined list of
1194 Checks if ip_addr used in constructor is allowed from defined list of
1192 allowed ip_addresses for user
1195 allowed ip_addresses for user
1193
1196
1194 :returns: boolean, True if ip is in allowed ip range
1197 :returns: boolean, True if ip is in allowed ip range
1195 """
1198 """
1196 # check IP
1199 # check IP
1197 inherit = self.inherit_default_permissions
1200 inherit = self.inherit_default_permissions
1198 return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
1201 return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
1199 inherit_from_default=inherit)
1202 inherit_from_default=inherit)
1200 @property
1203 @property
1201 def personal_repo_group(self):
1204 def personal_repo_group(self):
1202 return RepoGroup.get_user_personal_repo_group(self.user_id)
1205 return RepoGroup.get_user_personal_repo_group(self.user_id)
1203
1206
1204 @classmethod
1207 @classmethod
1205 def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
1208 def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
1206 allowed_ips = AuthUser.get_allowed_ips(
1209 allowed_ips = AuthUser.get_allowed_ips(
1207 user_id, cache=True, inherit_from_default=inherit_from_default)
1210 user_id, cache=True, inherit_from_default=inherit_from_default)
1208 if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
1211 if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
1209 log.debug('IP:%s is in range of %s' % (ip_addr, allowed_ips))
1212 log.debug('IP:%s is in range of %s' % (ip_addr, allowed_ips))
1210 return True
1213 return True
1211 else:
1214 else:
1212 log.info('Access for IP:%s forbidden, '
1215 log.info('Access for IP:%s forbidden, '
1213 'not in %s' % (ip_addr, allowed_ips))
1216 'not in %s' % (ip_addr, allowed_ips))
1214 return False
1217 return False
1215
1218
1216 def __repr__(self):
1219 def __repr__(self):
1217 return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
1220 return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
1218 % (self.user_id, self.username, self.ip_addr, self.is_authenticated)
1221 % (self.user_id, self.username, self.ip_addr, self.is_authenticated)
1219
1222
1220 def set_authenticated(self, authenticated=True):
1223 def set_authenticated(self, authenticated=True):
1221 if self.user_id != self.anonymous_user.user_id:
1224 if self.user_id != self.anonymous_user.user_id:
1222 self.is_authenticated = authenticated
1225 self.is_authenticated = authenticated
1223
1226
1224 def get_cookie_store(self):
1227 def get_cookie_store(self):
1225 return {
1228 return {
1226 'username': self.username,
1229 'username': self.username,
1227 'password': md5(self.password),
1230 'password': md5(self.password),
1228 'user_id': self.user_id,
1231 'user_id': self.user_id,
1229 'is_authenticated': self.is_authenticated
1232 'is_authenticated': self.is_authenticated
1230 }
1233 }
1231
1234
1232 @classmethod
1235 @classmethod
1233 def from_cookie_store(cls, cookie_store):
1236 def from_cookie_store(cls, cookie_store):
1234 """
1237 """
1235 Creates AuthUser from a cookie store
1238 Creates AuthUser from a cookie store
1236
1239
1237 :param cls:
1240 :param cls:
1238 :param cookie_store:
1241 :param cookie_store:
1239 """
1242 """
1240 user_id = cookie_store.get('user_id')
1243 user_id = cookie_store.get('user_id')
1241 username = cookie_store.get('username')
1244 username = cookie_store.get('username')
1242 api_key = cookie_store.get('api_key')
1245 api_key = cookie_store.get('api_key')
1243 return AuthUser(user_id, api_key, username)
1246 return AuthUser(user_id, api_key, username)
1244
1247
1245 @classmethod
1248 @classmethod
1246 def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
1249 def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
1247 _set = set()
1250 _set = set()
1248
1251
1249 if inherit_from_default:
1252 if inherit_from_default:
1250 default_ips = UserIpMap.query().filter(
1253 default_ips = UserIpMap.query().filter(
1251 UserIpMap.user == User.get_default_user(cache=True))
1254 UserIpMap.user == User.get_default_user(cache=True))
1252 if cache:
1255 if cache:
1253 default_ips = default_ips.options(
1256 default_ips = default_ips.options(
1254 FromCache("sql_cache_short", "get_user_ips_default"))
1257 FromCache("sql_cache_short", "get_user_ips_default"))
1255
1258
1256 # populate from default user
1259 # populate from default user
1257 for ip in default_ips:
1260 for ip in default_ips:
1258 try:
1261 try:
1259 _set.add(ip.ip_addr)
1262 _set.add(ip.ip_addr)
1260 except ObjectDeletedError:
1263 except ObjectDeletedError:
1261 # since we use heavy caching sometimes it happens that
1264 # since we use heavy caching sometimes it happens that
1262 # we get deleted objects here, we just skip them
1265 # we get deleted objects here, we just skip them
1263 pass
1266 pass
1264
1267
1265 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
1268 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
1266 if cache:
1269 if cache:
1267 user_ips = user_ips.options(
1270 user_ips = user_ips.options(
1268 FromCache("sql_cache_short", "get_user_ips_%s" % user_id))
1271 FromCache("sql_cache_short", "get_user_ips_%s" % user_id))
1269
1272
1270 for ip in user_ips:
1273 for ip in user_ips:
1271 try:
1274 try:
1272 _set.add(ip.ip_addr)
1275 _set.add(ip.ip_addr)
1273 except ObjectDeletedError:
1276 except ObjectDeletedError:
1274 # since we use heavy caching sometimes it happens that we get
1277 # since we use heavy caching sometimes it happens that we get
1275 # deleted objects here, we just skip them
1278 # deleted objects here, we just skip them
1276 pass
1279 pass
1277 return _set or set(['0.0.0.0/0', '::/0'])
1280 return _set or set(['0.0.0.0/0', '::/0'])
1278
1281
1279
1282
1280 def set_available_permissions(config):
1283 def set_available_permissions(settings):
1281 """
1284 """
1282 This function will propagate pylons globals with all available defined
1285 This function will propagate pyramid settings with all available defined
1283 permission given in db. We don't want to check each time from db for new
1286 permission given in db. We don't want to check each time from db for new
1284 permissions since adding a new permission also requires application restart
1287 permissions since adding a new permission also requires application restart
1285 ie. to decorate new views with the newly created permission
1288 ie. to decorate new views with the newly created permission
1286
1289
1287 :param config: current pylons config instance
1290 :param settings: current pyramid registry.settings
1288
1291
1289 """
1292 """
1290 log.info('getting information about all available permissions')
1293 log.debug('auth: getting information about all available permissions')
1291 try:
1294 try:
1292 sa = meta.Session
1295 sa = meta.Session
1293 all_perms = sa.query(Permission).all()
1296 all_perms = sa.query(Permission).all()
1294 config['available_permissions'] = [x.permission_name for x in all_perms]
1297 settings.setdefault('available_permissions',
1298 [x.permission_name for x in all_perms])
1299 log.debug('auth: set available permissions')
1295 except Exception:
1300 except Exception:
1296 log.error(traceback.format_exc())
1301 log.exception('Failed to fetch permissions from the database.')
1297 finally:
1302 raise
1298 meta.Session.remove()
1299
1303
1300
1304
1301 def get_csrf_token(session, force_new=False, save_if_missing=True):
1305 def get_csrf_token(session, force_new=False, save_if_missing=True):
1302 """
1306 """
1303 Return the current authentication token, creating one if one doesn't
1307 Return the current authentication token, creating one if one doesn't
1304 already exist and the save_if_missing flag is present.
1308 already exist and the save_if_missing flag is present.
1305
1309
1306 :param session: pass in the pylons session, else we use the global ones
1310 :param session: pass in the pylons session, else we use the global ones
1307 :param force_new: force to re-generate the token and store it in session
1311 :param force_new: force to re-generate the token and store it in session
1308 :param save_if_missing: save the newly generated token if it's missing in
1312 :param save_if_missing: save the newly generated token if it's missing in
1309 session
1313 session
1310 """
1314 """
1311 # NOTE(marcink): probably should be replaced with below one from pyramid 1.9
1315 # NOTE(marcink): probably should be replaced with below one from pyramid 1.9
1312 # from pyramid.csrf import get_csrf_token
1316 # from pyramid.csrf import get_csrf_token
1313
1317
1314 if (csrf_token_key not in session and save_if_missing) or force_new:
1318 if (csrf_token_key not in session and save_if_missing) or force_new:
1315 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
1319 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
1316 session[csrf_token_key] = token
1320 session[csrf_token_key] = token
1317 if hasattr(session, 'save'):
1321 if hasattr(session, 'save'):
1318 session.save()
1322 session.save()
1319 return session.get(csrf_token_key)
1323 return session.get(csrf_token_key)
1320
1324
1321
1325
1322 def get_request(perm_class_instance):
1326 def get_request(perm_class_instance):
1323 from pyramid.threadlocal import get_current_request
1327 from pyramid.threadlocal import get_current_request
1324 pyramid_request = get_current_request()
1328 pyramid_request = get_current_request()
1325 if not pyramid_request:
1329 if not pyramid_request:
1326 # return global request of pylons in case pyramid isn't available
1330 # return global request of pylons in case pyramid isn't available
1327 # NOTE(marcink): this should be removed after migration to pyramid
1331 # NOTE(marcink): this should be removed after migration to pyramid
1328 from pylons import request
1332 from pylons import request
1329 return request
1333 return request
1330 return pyramid_request
1334 return pyramid_request
1331
1335
1332
1336
1333 # CHECK DECORATORS
1337 # CHECK DECORATORS
1334 class CSRFRequired(object):
1338 class CSRFRequired(object):
1335 """
1339 """
1336 Decorator for authenticating a form
1340 Decorator for authenticating a form
1337
1341
1338 This decorator uses an authorization token stored in the client's
1342 This decorator uses an authorization token stored in the client's
1339 session for prevention of certain Cross-site request forgery (CSRF)
1343 session for prevention of certain Cross-site request forgery (CSRF)
1340 attacks (See
1344 attacks (See
1341 http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
1345 http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
1342 information).
1346 information).
1343
1347
1344 For use with the ``webhelpers.secure_form`` helper functions.
1348 For use with the ``webhelpers.secure_form`` helper functions.
1345
1349
1346 """
1350 """
1347 def __init__(self, token=csrf_token_key, header='X-CSRF-Token',
1351 def __init__(self, token=csrf_token_key, header='X-CSRF-Token',
1348 except_methods=None):
1352 except_methods=None):
1349 self.token = token
1353 self.token = token
1350 self.header = header
1354 self.header = header
1351 self.except_methods = except_methods or []
1355 self.except_methods = except_methods or []
1352
1356
1353 def __call__(self, func):
1357 def __call__(self, func):
1354 return get_cython_compat_decorator(self.__wrapper, func)
1358 return get_cython_compat_decorator(self.__wrapper, func)
1355
1359
1356 def _get_csrf(self, _request):
1360 def _get_csrf(self, _request):
1357 return _request.POST.get(self.token, _request.headers.get(self.header))
1361 return _request.POST.get(self.token, _request.headers.get(self.header))
1358
1362
1359 def check_csrf(self, _request, cur_token):
1363 def check_csrf(self, _request, cur_token):
1360 supplied_token = self._get_csrf(_request)
1364 supplied_token = self._get_csrf(_request)
1361 return supplied_token and supplied_token == cur_token
1365 return supplied_token and supplied_token == cur_token
1362
1366
1363 def _get_request(self):
1367 def _get_request(self):
1364 return get_request(self)
1368 return get_request(self)
1365
1369
1366 def __wrapper(self, func, *fargs, **fkwargs):
1370 def __wrapper(self, func, *fargs, **fkwargs):
1367 request = self._get_request()
1371 request = self._get_request()
1368
1372
1369 if request.method in self.except_methods:
1373 if request.method in self.except_methods:
1370 return func(*fargs, **fkwargs)
1374 return func(*fargs, **fkwargs)
1371
1375
1372 cur_token = get_csrf_token(request.session, save_if_missing=False)
1376 cur_token = get_csrf_token(request.session, save_if_missing=False)
1373 if self.check_csrf(request, cur_token):
1377 if self.check_csrf(request, cur_token):
1374 if request.POST.get(self.token):
1378 if request.POST.get(self.token):
1375 del request.POST[self.token]
1379 del request.POST[self.token]
1376 return func(*fargs, **fkwargs)
1380 return func(*fargs, **fkwargs)
1377 else:
1381 else:
1378 reason = 'token-missing'
1382 reason = 'token-missing'
1379 supplied_token = self._get_csrf(request)
1383 supplied_token = self._get_csrf(request)
1380 if supplied_token and cur_token != supplied_token:
1384 if supplied_token and cur_token != supplied_token:
1381 reason = 'token-mismatch [%s:%s]' % (
1385 reason = 'token-mismatch [%s:%s]' % (
1382 cur_token or ''[:6], supplied_token or ''[:6])
1386 cur_token or ''[:6], supplied_token or ''[:6])
1383
1387
1384 csrf_message = \
1388 csrf_message = \
1385 ("Cross-site request forgery detected, request denied. See "
1389 ("Cross-site request forgery detected, request denied. See "
1386 "http://en.wikipedia.org/wiki/Cross-site_request_forgery for "
1390 "http://en.wikipedia.org/wiki/Cross-site_request_forgery for "
1387 "more information.")
1391 "more information.")
1388 log.warn('Cross-site request forgery detected, request %r DENIED: %s '
1392 log.warn('Cross-site request forgery detected, request %r DENIED: %s '
1389 'REMOTE_ADDR:%s, HEADERS:%s' % (
1393 'REMOTE_ADDR:%s, HEADERS:%s' % (
1390 request, reason, request.remote_addr, request.headers))
1394 request, reason, request.remote_addr, request.headers))
1391
1395
1392 raise HTTPForbidden(explanation=csrf_message)
1396 raise HTTPForbidden(explanation=csrf_message)
1393
1397
1394
1398
1395 class LoginRequired(object):
1399 class LoginRequired(object):
1396 """
1400 """
1397 Must be logged in to execute this function else
1401 Must be logged in to execute this function else
1398 redirect to login page
1402 redirect to login page
1399
1403
1400 :param api_access: if enabled this checks only for valid auth token
1404 :param api_access: if enabled this checks only for valid auth token
1401 and grants access based on valid token
1405 and grants access based on valid token
1402 """
1406 """
1403 def __init__(self, auth_token_access=None):
1407 def __init__(self, auth_token_access=None):
1404 self.auth_token_access = auth_token_access
1408 self.auth_token_access = auth_token_access
1405
1409
1406 def __call__(self, func):
1410 def __call__(self, func):
1407 return get_cython_compat_decorator(self.__wrapper, func)
1411 return get_cython_compat_decorator(self.__wrapper, func)
1408
1412
1409 def _get_request(self):
1413 def _get_request(self):
1410 return get_request(self)
1414 return get_request(self)
1411
1415
1412 def __wrapper(self, func, *fargs, **fkwargs):
1416 def __wrapper(self, func, *fargs, **fkwargs):
1413 from rhodecode.lib import helpers as h
1417 from rhodecode.lib import helpers as h
1414 cls = fargs[0]
1418 cls = fargs[0]
1415 user = cls._rhodecode_user
1419 user = cls._rhodecode_user
1416 request = self._get_request()
1420 request = self._get_request()
1417
1421
1418 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1422 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1419 log.debug('Starting login restriction checks for user: %s' % (user,))
1423 log.debug('Starting login restriction checks for user: %s' % (user,))
1420 # check if our IP is allowed
1424 # check if our IP is allowed
1421 ip_access_valid = True
1425 ip_access_valid = True
1422 if not user.ip_allowed:
1426 if not user.ip_allowed:
1423 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1427 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1424 category='warning')
1428 category='warning')
1425 ip_access_valid = False
1429 ip_access_valid = False
1426
1430
1427 # check if we used an APIKEY and it's a valid one
1431 # check if we used an APIKEY and it's a valid one
1428 # defined white-list of controllers which API access will be enabled
1432 # defined white-list of controllers which API access will be enabled
1429 _auth_token = request.GET.get(
1433 _auth_token = request.GET.get(
1430 'auth_token', '') or request.GET.get('api_key', '')
1434 'auth_token', '') or request.GET.get('api_key', '')
1431 auth_token_access_valid = allowed_auth_token_access(
1435 auth_token_access_valid = allowed_auth_token_access(
1432 loc, auth_token=_auth_token)
1436 loc, auth_token=_auth_token)
1433
1437
1434 # explicit controller is enabled or API is in our whitelist
1438 # explicit controller is enabled or API is in our whitelist
1435 if self.auth_token_access or auth_token_access_valid:
1439 if self.auth_token_access or auth_token_access_valid:
1436 log.debug('Checking AUTH TOKEN access for %s' % (cls,))
1440 log.debug('Checking AUTH TOKEN access for %s' % (cls,))
1437 db_user = user.get_instance()
1441 db_user = user.get_instance()
1438
1442
1439 if db_user:
1443 if db_user:
1440 if self.auth_token_access:
1444 if self.auth_token_access:
1441 roles = self.auth_token_access
1445 roles = self.auth_token_access
1442 else:
1446 else:
1443 roles = [UserApiKeys.ROLE_HTTP]
1447 roles = [UserApiKeys.ROLE_HTTP]
1444 token_match = db_user.authenticate_by_token(
1448 token_match = db_user.authenticate_by_token(
1445 _auth_token, roles=roles)
1449 _auth_token, roles=roles)
1446 else:
1450 else:
1447 log.debug('Unable to fetch db instance for auth user: %s', user)
1451 log.debug('Unable to fetch db instance for auth user: %s', user)
1448 token_match = False
1452 token_match = False
1449
1453
1450 if _auth_token and token_match:
1454 if _auth_token and token_match:
1451 auth_token_access_valid = True
1455 auth_token_access_valid = True
1452 log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],))
1456 log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],))
1453 else:
1457 else:
1454 auth_token_access_valid = False
1458 auth_token_access_valid = False
1455 if not _auth_token:
1459 if not _auth_token:
1456 log.debug("AUTH TOKEN *NOT* present in request")
1460 log.debug("AUTH TOKEN *NOT* present in request")
1457 else:
1461 else:
1458 log.warning(
1462 log.warning(
1459 "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:])
1463 "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:])
1460
1464
1461 log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
1465 log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
1462 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1466 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1463 else 'AUTH_TOKEN_AUTH'
1467 else 'AUTH_TOKEN_AUTH'
1464
1468
1465 if ip_access_valid and (
1469 if ip_access_valid and (
1466 user.is_authenticated or auth_token_access_valid):
1470 user.is_authenticated or auth_token_access_valid):
1467 log.info(
1471 log.info(
1468 'user %s authenticating with:%s IS authenticated on func %s'
1472 'user %s authenticating with:%s IS authenticated on func %s'
1469 % (user, reason, loc))
1473 % (user, reason, loc))
1470
1474
1471 # update user data to check last activity
1475 # update user data to check last activity
1472 user.update_lastactivity()
1476 user.update_lastactivity()
1473 Session().commit()
1477 Session().commit()
1474 return func(*fargs, **fkwargs)
1478 return func(*fargs, **fkwargs)
1475 else:
1479 else:
1476 log.warning(
1480 log.warning(
1477 'user %s authenticating with:%s NOT authenticated on '
1481 'user %s authenticating with:%s NOT authenticated on '
1478 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s'
1482 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s'
1479 % (user, reason, loc, ip_access_valid,
1483 % (user, reason, loc, ip_access_valid,
1480 auth_token_access_valid))
1484 auth_token_access_valid))
1481 # we preserve the get PARAM
1485 # we preserve the get PARAM
1482 came_from = get_came_from(request)
1486 came_from = get_came_from(request)
1483
1487
1484 log.debug('redirecting to login page with %s' % (came_from,))
1488 log.debug('redirecting to login page with %s' % (came_from,))
1485 raise HTTPFound(
1489 raise HTTPFound(
1486 h.route_path('login', _query={'came_from': came_from}))
1490 h.route_path('login', _query={'came_from': came_from}))
1487
1491
1488
1492
1489 class NotAnonymous(object):
1493 class NotAnonymous(object):
1490 """
1494 """
1491 Must be logged in to execute this function else
1495 Must be logged in to execute this function else
1492 redirect to login page
1496 redirect to login page
1493 """
1497 """
1494
1498
1495 def __call__(self, func):
1499 def __call__(self, func):
1496 return get_cython_compat_decorator(self.__wrapper, func)
1500 return get_cython_compat_decorator(self.__wrapper, func)
1497
1501
1498 def _get_request(self):
1502 def _get_request(self):
1499 return get_request(self)
1503 return get_request(self)
1500
1504
1501 def __wrapper(self, func, *fargs, **fkwargs):
1505 def __wrapper(self, func, *fargs, **fkwargs):
1502 import rhodecode.lib.helpers as h
1506 import rhodecode.lib.helpers as h
1503 cls = fargs[0]
1507 cls = fargs[0]
1504 self.user = cls._rhodecode_user
1508 self.user = cls._rhodecode_user
1505 request = self._get_request()
1509 request = self._get_request()
1506
1510
1507 log.debug('Checking if user is not anonymous @%s' % cls)
1511 log.debug('Checking if user is not anonymous @%s' % cls)
1508
1512
1509 anonymous = self.user.username == User.DEFAULT_USER
1513 anonymous = self.user.username == User.DEFAULT_USER
1510
1514
1511 if anonymous:
1515 if anonymous:
1512 came_from = get_came_from(request)
1516 came_from = get_came_from(request)
1513 h.flash(_('You need to be a registered user to '
1517 h.flash(_('You need to be a registered user to '
1514 'perform this action'),
1518 'perform this action'),
1515 category='warning')
1519 category='warning')
1516 raise HTTPFound(
1520 raise HTTPFound(
1517 h.route_path('login', _query={'came_from': came_from}))
1521 h.route_path('login', _query={'came_from': came_from}))
1518 else:
1522 else:
1519 return func(*fargs, **fkwargs)
1523 return func(*fargs, **fkwargs)
1520
1524
1521
1525
1522 class PermsDecorator(object):
1526 class PermsDecorator(object):
1523 """
1527 """
1524 Base class for controller decorators, we extract the current user from
1528 Base class for controller decorators, we extract the current user from
1525 the class itself, which has it stored in base controllers
1529 the class itself, which has it stored in base controllers
1526 """
1530 """
1527
1531
1528 def __init__(self, *required_perms):
1532 def __init__(self, *required_perms):
1529 self.required_perms = set(required_perms)
1533 self.required_perms = set(required_perms)
1530
1534
1531 def __call__(self, func):
1535 def __call__(self, func):
1532 return get_cython_compat_decorator(self.__wrapper, func)
1536 return get_cython_compat_decorator(self.__wrapper, func)
1533
1537
1534 def _get_request(self):
1538 def _get_request(self):
1535 return get_request(self)
1539 return get_request(self)
1536
1540
1537 def __wrapper(self, func, *fargs, **fkwargs):
1541 def __wrapper(self, func, *fargs, **fkwargs):
1538 import rhodecode.lib.helpers as h
1542 import rhodecode.lib.helpers as h
1539 cls = fargs[0]
1543 cls = fargs[0]
1540 _user = cls._rhodecode_user
1544 _user = cls._rhodecode_user
1541
1545
1542 log.debug('checking %s permissions %s for %s %s',
1546 log.debug('checking %s permissions %s for %s %s',
1543 self.__class__.__name__, self.required_perms, cls, _user)
1547 self.__class__.__name__, self.required_perms, cls, _user)
1544
1548
1545 if self.check_permissions(_user):
1549 if self.check_permissions(_user):
1546 log.debug('Permission granted for %s %s', cls, _user)
1550 log.debug('Permission granted for %s %s', cls, _user)
1547 return func(*fargs, **fkwargs)
1551 return func(*fargs, **fkwargs)
1548
1552
1549 else:
1553 else:
1550 log.debug('Permission denied for %s %s', cls, _user)
1554 log.debug('Permission denied for %s %s', cls, _user)
1551 anonymous = _user.username == User.DEFAULT_USER
1555 anonymous = _user.username == User.DEFAULT_USER
1552
1556
1553 if anonymous:
1557 if anonymous:
1554 came_from = get_came_from(self._get_request())
1558 came_from = get_came_from(self._get_request())
1555 h.flash(_('You need to be signed in to view this page'),
1559 h.flash(_('You need to be signed in to view this page'),
1556 category='warning')
1560 category='warning')
1557 raise HTTPFound(
1561 raise HTTPFound(
1558 h.route_path('login', _query={'came_from': came_from}))
1562 h.route_path('login', _query={'came_from': came_from}))
1559
1563
1560 else:
1564 else:
1561 # redirect with 404 to prevent resource discovery
1565 # redirect with 404 to prevent resource discovery
1562 raise HTTPNotFound()
1566 raise HTTPNotFound()
1563
1567
1564 def check_permissions(self, user):
1568 def check_permissions(self, user):
1565 """Dummy function for overriding"""
1569 """Dummy function for overriding"""
1566 raise NotImplementedError(
1570 raise NotImplementedError(
1567 'You have to write this function in child class')
1571 'You have to write this function in child class')
1568
1572
1569
1573
1570 class HasPermissionAllDecorator(PermsDecorator):
1574 class HasPermissionAllDecorator(PermsDecorator):
1571 """
1575 """
1572 Checks for access permission for all given predicates. All of them
1576 Checks for access permission for all given predicates. All of them
1573 have to be meet in order to fulfill the request
1577 have to be meet in order to fulfill the request
1574 """
1578 """
1575
1579
1576 def check_permissions(self, user):
1580 def check_permissions(self, user):
1577 perms = user.permissions_with_scope({})
1581 perms = user.permissions_with_scope({})
1578 if self.required_perms.issubset(perms['global']):
1582 if self.required_perms.issubset(perms['global']):
1579 return True
1583 return True
1580 return False
1584 return False
1581
1585
1582
1586
1583 class HasPermissionAnyDecorator(PermsDecorator):
1587 class HasPermissionAnyDecorator(PermsDecorator):
1584 """
1588 """
1585 Checks for access permission for any of given predicates. In order to
1589 Checks for access permission for any of given predicates. In order to
1586 fulfill the request any of predicates must be meet
1590 fulfill the request any of predicates must be meet
1587 """
1591 """
1588
1592
1589 def check_permissions(self, user):
1593 def check_permissions(self, user):
1590 perms = user.permissions_with_scope({})
1594 perms = user.permissions_with_scope({})
1591 if self.required_perms.intersection(perms['global']):
1595 if self.required_perms.intersection(perms['global']):
1592 return True
1596 return True
1593 return False
1597 return False
1594
1598
1595
1599
1596 class HasRepoPermissionAllDecorator(PermsDecorator):
1600 class HasRepoPermissionAllDecorator(PermsDecorator):
1597 """
1601 """
1598 Checks for access permission for all given predicates for specific
1602 Checks for access permission for all given predicates for specific
1599 repository. All of them have to be meet in order to fulfill the request
1603 repository. All of them have to be meet in order to fulfill the request
1600 """
1604 """
1601 def _get_repo_name(self):
1605 def _get_repo_name(self):
1602 _request = self._get_request()
1606 _request = self._get_request()
1603 return get_repo_slug(_request)
1607 return get_repo_slug(_request)
1604
1608
1605 def check_permissions(self, user):
1609 def check_permissions(self, user):
1606 perms = user.permissions
1610 perms = user.permissions
1607 repo_name = self._get_repo_name()
1611 repo_name = self._get_repo_name()
1608
1612
1609 try:
1613 try:
1610 user_perms = set([perms['repositories'][repo_name]])
1614 user_perms = set([perms['repositories'][repo_name]])
1611 except KeyError:
1615 except KeyError:
1612 log.debug('cannot locate repo with name: `%s` in permissions defs',
1616 log.debug('cannot locate repo with name: `%s` in permissions defs',
1613 repo_name)
1617 repo_name)
1614 return False
1618 return False
1615
1619
1616 log.debug('checking `%s` permissions for repo `%s`',
1620 log.debug('checking `%s` permissions for repo `%s`',
1617 user_perms, repo_name)
1621 user_perms, repo_name)
1618 if self.required_perms.issubset(user_perms):
1622 if self.required_perms.issubset(user_perms):
1619 return True
1623 return True
1620 return False
1624 return False
1621
1625
1622
1626
1623 class HasRepoPermissionAnyDecorator(PermsDecorator):
1627 class HasRepoPermissionAnyDecorator(PermsDecorator):
1624 """
1628 """
1625 Checks for access permission for any of given predicates for specific
1629 Checks for access permission for any of given predicates for specific
1626 repository. In order to fulfill the request any of predicates must be meet
1630 repository. In order to fulfill the request any of predicates must be meet
1627 """
1631 """
1628 def _get_repo_name(self):
1632 def _get_repo_name(self):
1629 _request = self._get_request()
1633 _request = self._get_request()
1630 return get_repo_slug(_request)
1634 return get_repo_slug(_request)
1631
1635
1632 def check_permissions(self, user):
1636 def check_permissions(self, user):
1633 perms = user.permissions
1637 perms = user.permissions
1634 repo_name = self._get_repo_name()
1638 repo_name = self._get_repo_name()
1635
1639
1636 try:
1640 try:
1637 user_perms = set([perms['repositories'][repo_name]])
1641 user_perms = set([perms['repositories'][repo_name]])
1638 except KeyError:
1642 except KeyError:
1639 log.debug(
1643 log.debug(
1640 'cannot locate repo with name: `%s` in permissions defs',
1644 'cannot locate repo with name: `%s` in permissions defs',
1641 repo_name)
1645 repo_name)
1642 return False
1646 return False
1643
1647
1644 log.debug('checking `%s` permissions for repo `%s`',
1648 log.debug('checking `%s` permissions for repo `%s`',
1645 user_perms, repo_name)
1649 user_perms, repo_name)
1646 if self.required_perms.intersection(user_perms):
1650 if self.required_perms.intersection(user_perms):
1647 return True
1651 return True
1648 return False
1652 return False
1649
1653
1650
1654
1651 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1655 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1652 """
1656 """
1653 Checks for access permission for all given predicates for specific
1657 Checks for access permission for all given predicates for specific
1654 repository group. All of them have to be meet in order to
1658 repository group. All of them have to be meet in order to
1655 fulfill the request
1659 fulfill the request
1656 """
1660 """
1657 def _get_repo_group_name(self):
1661 def _get_repo_group_name(self):
1658 _request = self._get_request()
1662 _request = self._get_request()
1659 return get_repo_group_slug(_request)
1663 return get_repo_group_slug(_request)
1660
1664
1661 def check_permissions(self, user):
1665 def check_permissions(self, user):
1662 perms = user.permissions
1666 perms = user.permissions
1663 group_name = self._get_repo_group_name()
1667 group_name = self._get_repo_group_name()
1664 try:
1668 try:
1665 user_perms = set([perms['repositories_groups'][group_name]])
1669 user_perms = set([perms['repositories_groups'][group_name]])
1666 except KeyError:
1670 except KeyError:
1667 log.debug(
1671 log.debug(
1668 'cannot locate repo group with name: `%s` in permissions defs',
1672 'cannot locate repo group with name: `%s` in permissions defs',
1669 group_name)
1673 group_name)
1670 return False
1674 return False
1671
1675
1672 log.debug('checking `%s` permissions for repo group `%s`',
1676 log.debug('checking `%s` permissions for repo group `%s`',
1673 user_perms, group_name)
1677 user_perms, group_name)
1674 if self.required_perms.issubset(user_perms):
1678 if self.required_perms.issubset(user_perms):
1675 return True
1679 return True
1676 return False
1680 return False
1677
1681
1678
1682
1679 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1683 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1680 """
1684 """
1681 Checks for access permission for any of given predicates for specific
1685 Checks for access permission for any of given predicates for specific
1682 repository group. In order to fulfill the request any
1686 repository group. In order to fulfill the request any
1683 of predicates must be met
1687 of predicates must be met
1684 """
1688 """
1685 def _get_repo_group_name(self):
1689 def _get_repo_group_name(self):
1686 _request = self._get_request()
1690 _request = self._get_request()
1687 return get_repo_group_slug(_request)
1691 return get_repo_group_slug(_request)
1688
1692
1689 def check_permissions(self, user):
1693 def check_permissions(self, user):
1690 perms = user.permissions
1694 perms = user.permissions
1691 group_name = self._get_repo_group_name()
1695 group_name = self._get_repo_group_name()
1692
1696
1693 try:
1697 try:
1694 user_perms = set([perms['repositories_groups'][group_name]])
1698 user_perms = set([perms['repositories_groups'][group_name]])
1695 except KeyError:
1699 except KeyError:
1696 log.debug(
1700 log.debug(
1697 'cannot locate repo group with name: `%s` in permissions defs',
1701 'cannot locate repo group with name: `%s` in permissions defs',
1698 group_name)
1702 group_name)
1699 return False
1703 return False
1700
1704
1701 log.debug('checking `%s` permissions for repo group `%s`',
1705 log.debug('checking `%s` permissions for repo group `%s`',
1702 user_perms, group_name)
1706 user_perms, group_name)
1703 if self.required_perms.intersection(user_perms):
1707 if self.required_perms.intersection(user_perms):
1704 return True
1708 return True
1705 return False
1709 return False
1706
1710
1707
1711
1708 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1712 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1709 """
1713 """
1710 Checks for access permission for all given predicates for specific
1714 Checks for access permission for all given predicates for specific
1711 user group. All of them have to be meet in order to fulfill the request
1715 user group. All of them have to be meet in order to fulfill the request
1712 """
1716 """
1713 def _get_user_group_name(self):
1717 def _get_user_group_name(self):
1714 _request = self._get_request()
1718 _request = self._get_request()
1715 return get_user_group_slug(_request)
1719 return get_user_group_slug(_request)
1716
1720
1717 def check_permissions(self, user):
1721 def check_permissions(self, user):
1718 perms = user.permissions
1722 perms = user.permissions
1719 group_name = self._get_user_group_name()
1723 group_name = self._get_user_group_name()
1720 try:
1724 try:
1721 user_perms = set([perms['user_groups'][group_name]])
1725 user_perms = set([perms['user_groups'][group_name]])
1722 except KeyError:
1726 except KeyError:
1723 return False
1727 return False
1724
1728
1725 if self.required_perms.issubset(user_perms):
1729 if self.required_perms.issubset(user_perms):
1726 return True
1730 return True
1727 return False
1731 return False
1728
1732
1729
1733
1730 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1734 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1731 """
1735 """
1732 Checks for access permission for any of given predicates for specific
1736 Checks for access permission for any of given predicates for specific
1733 user group. In order to fulfill the request any of predicates must be meet
1737 user group. In order to fulfill the request any of predicates must be meet
1734 """
1738 """
1735 def _get_user_group_name(self):
1739 def _get_user_group_name(self):
1736 _request = self._get_request()
1740 _request = self._get_request()
1737 return get_user_group_slug(_request)
1741 return get_user_group_slug(_request)
1738
1742
1739 def check_permissions(self, user):
1743 def check_permissions(self, user):
1740 perms = user.permissions
1744 perms = user.permissions
1741 group_name = self._get_user_group_name()
1745 group_name = self._get_user_group_name()
1742 try:
1746 try:
1743 user_perms = set([perms['user_groups'][group_name]])
1747 user_perms = set([perms['user_groups'][group_name]])
1744 except KeyError:
1748 except KeyError:
1745 return False
1749 return False
1746
1750
1747 if self.required_perms.intersection(user_perms):
1751 if self.required_perms.intersection(user_perms):
1748 return True
1752 return True
1749 return False
1753 return False
1750
1754
1751
1755
1752 # CHECK FUNCTIONS
1756 # CHECK FUNCTIONS
1753 class PermsFunction(object):
1757 class PermsFunction(object):
1754 """Base function for other check functions"""
1758 """Base function for other check functions"""
1755
1759
1756 def __init__(self, *perms):
1760 def __init__(self, *perms):
1757 self.required_perms = set(perms)
1761 self.required_perms = set(perms)
1758 self.repo_name = None
1762 self.repo_name = None
1759 self.repo_group_name = None
1763 self.repo_group_name = None
1760 self.user_group_name = None
1764 self.user_group_name = None
1761
1765
1762 def __bool__(self):
1766 def __bool__(self):
1763 frame = inspect.currentframe()
1767 frame = inspect.currentframe()
1764 stack_trace = traceback.format_stack(frame)
1768 stack_trace = traceback.format_stack(frame)
1765 log.error('Checking bool value on a class instance of perm '
1769 log.error('Checking bool value on a class instance of perm '
1766 'function is not allowed: %s' % ''.join(stack_trace))
1770 'function is not allowed: %s' % ''.join(stack_trace))
1767 # rather than throwing errors, here we always return False so if by
1771 # rather than throwing errors, here we always return False so if by
1768 # accident someone checks truth for just an instance it will always end
1772 # accident someone checks truth for just an instance it will always end
1769 # up in returning False
1773 # up in returning False
1770 return False
1774 return False
1771 __nonzero__ = __bool__
1775 __nonzero__ = __bool__
1772
1776
1773 def __call__(self, check_location='', user=None):
1777 def __call__(self, check_location='', user=None):
1774 if not user:
1778 if not user:
1775 log.debug('Using user attribute from global request')
1779 log.debug('Using user attribute from global request')
1776 # TODO: remove this someday,put as user as attribute here
1780 # TODO: remove this someday,put as user as attribute here
1777 request = self._get_request()
1781 request = self._get_request()
1778 user = request.user
1782 user = request.user
1779
1783
1780 # init auth user if not already given
1784 # init auth user if not already given
1781 if not isinstance(user, AuthUser):
1785 if not isinstance(user, AuthUser):
1782 log.debug('Wrapping user %s into AuthUser', user)
1786 log.debug('Wrapping user %s into AuthUser', user)
1783 user = AuthUser(user.user_id)
1787 user = AuthUser(user.user_id)
1784
1788
1785 cls_name = self.__class__.__name__
1789 cls_name = self.__class__.__name__
1786 check_scope = self._get_check_scope(cls_name)
1790 check_scope = self._get_check_scope(cls_name)
1787 check_location = check_location or 'unspecified location'
1791 check_location = check_location or 'unspecified location'
1788
1792
1789 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1793 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1790 self.required_perms, user, check_scope, check_location)
1794 self.required_perms, user, check_scope, check_location)
1791 if not user:
1795 if not user:
1792 log.warning('Empty user given for permission check')
1796 log.warning('Empty user given for permission check')
1793 return False
1797 return False
1794
1798
1795 if self.check_permissions(user):
1799 if self.check_permissions(user):
1796 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1800 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1797 check_scope, user, check_location)
1801 check_scope, user, check_location)
1798 return True
1802 return True
1799
1803
1800 else:
1804 else:
1801 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1805 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1802 check_scope, user, check_location)
1806 check_scope, user, check_location)
1803 return False
1807 return False
1804
1808
1805 def _get_request(self):
1809 def _get_request(self):
1806 return get_request(self)
1810 return get_request(self)
1807
1811
1808 def _get_check_scope(self, cls_name):
1812 def _get_check_scope(self, cls_name):
1809 return {
1813 return {
1810 'HasPermissionAll': 'GLOBAL',
1814 'HasPermissionAll': 'GLOBAL',
1811 'HasPermissionAny': 'GLOBAL',
1815 'HasPermissionAny': 'GLOBAL',
1812 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
1816 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
1813 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
1817 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
1814 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
1818 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
1815 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
1819 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
1816 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
1820 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
1817 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
1821 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
1818 }.get(cls_name, '?:%s' % cls_name)
1822 }.get(cls_name, '?:%s' % cls_name)
1819
1823
1820 def check_permissions(self, user):
1824 def check_permissions(self, user):
1821 """Dummy function for overriding"""
1825 """Dummy function for overriding"""
1822 raise Exception('You have to write this function in child class')
1826 raise Exception('You have to write this function in child class')
1823
1827
1824
1828
1825 class HasPermissionAll(PermsFunction):
1829 class HasPermissionAll(PermsFunction):
1826 def check_permissions(self, user):
1830 def check_permissions(self, user):
1827 perms = user.permissions_with_scope({})
1831 perms = user.permissions_with_scope({})
1828 if self.required_perms.issubset(perms.get('global')):
1832 if self.required_perms.issubset(perms.get('global')):
1829 return True
1833 return True
1830 return False
1834 return False
1831
1835
1832
1836
1833 class HasPermissionAny(PermsFunction):
1837 class HasPermissionAny(PermsFunction):
1834 def check_permissions(self, user):
1838 def check_permissions(self, user):
1835 perms = user.permissions_with_scope({})
1839 perms = user.permissions_with_scope({})
1836 if self.required_perms.intersection(perms.get('global')):
1840 if self.required_perms.intersection(perms.get('global')):
1837 return True
1841 return True
1838 return False
1842 return False
1839
1843
1840
1844
1841 class HasRepoPermissionAll(PermsFunction):
1845 class HasRepoPermissionAll(PermsFunction):
1842 def __call__(self, repo_name=None, check_location='', user=None):
1846 def __call__(self, repo_name=None, check_location='', user=None):
1843 self.repo_name = repo_name
1847 self.repo_name = repo_name
1844 return super(HasRepoPermissionAll, self).__call__(check_location, user)
1848 return super(HasRepoPermissionAll, self).__call__(check_location, user)
1845
1849
1846 def _get_repo_name(self):
1850 def _get_repo_name(self):
1847 if not self.repo_name:
1851 if not self.repo_name:
1848 _request = self._get_request()
1852 _request = self._get_request()
1849 self.repo_name = get_repo_slug(_request)
1853 self.repo_name = get_repo_slug(_request)
1850 return self.repo_name
1854 return self.repo_name
1851
1855
1852 def check_permissions(self, user):
1856 def check_permissions(self, user):
1853 self.repo_name = self._get_repo_name()
1857 self.repo_name = self._get_repo_name()
1854 perms = user.permissions
1858 perms = user.permissions
1855 try:
1859 try:
1856 user_perms = set([perms['repositories'][self.repo_name]])
1860 user_perms = set([perms['repositories'][self.repo_name]])
1857 except KeyError:
1861 except KeyError:
1858 return False
1862 return False
1859 if self.required_perms.issubset(user_perms):
1863 if self.required_perms.issubset(user_perms):
1860 return True
1864 return True
1861 return False
1865 return False
1862
1866
1863
1867
1864 class HasRepoPermissionAny(PermsFunction):
1868 class HasRepoPermissionAny(PermsFunction):
1865 def __call__(self, repo_name=None, check_location='', user=None):
1869 def __call__(self, repo_name=None, check_location='', user=None):
1866 self.repo_name = repo_name
1870 self.repo_name = repo_name
1867 return super(HasRepoPermissionAny, self).__call__(check_location, user)
1871 return super(HasRepoPermissionAny, self).__call__(check_location, user)
1868
1872
1869 def _get_repo_name(self):
1873 def _get_repo_name(self):
1870 if not self.repo_name:
1874 if not self.repo_name:
1871 _request = self._get_request()
1875 _request = self._get_request()
1872 self.repo_name = get_repo_slug(_request)
1876 self.repo_name = get_repo_slug(_request)
1873 return self.repo_name
1877 return self.repo_name
1874
1878
1875 def check_permissions(self, user):
1879 def check_permissions(self, user):
1876 self.repo_name = self._get_repo_name()
1880 self.repo_name = self._get_repo_name()
1877 perms = user.permissions
1881 perms = user.permissions
1878 try:
1882 try:
1879 user_perms = set([perms['repositories'][self.repo_name]])
1883 user_perms = set([perms['repositories'][self.repo_name]])
1880 except KeyError:
1884 except KeyError:
1881 return False
1885 return False
1882 if self.required_perms.intersection(user_perms):
1886 if self.required_perms.intersection(user_perms):
1883 return True
1887 return True
1884 return False
1888 return False
1885
1889
1886
1890
1887 class HasRepoGroupPermissionAny(PermsFunction):
1891 class HasRepoGroupPermissionAny(PermsFunction):
1888 def __call__(self, group_name=None, check_location='', user=None):
1892 def __call__(self, group_name=None, check_location='', user=None):
1889 self.repo_group_name = group_name
1893 self.repo_group_name = group_name
1890 return super(HasRepoGroupPermissionAny, self).__call__(
1894 return super(HasRepoGroupPermissionAny, self).__call__(
1891 check_location, user)
1895 check_location, user)
1892
1896
1893 def check_permissions(self, user):
1897 def check_permissions(self, user):
1894 perms = user.permissions
1898 perms = user.permissions
1895 try:
1899 try:
1896 user_perms = set(
1900 user_perms = set(
1897 [perms['repositories_groups'][self.repo_group_name]])
1901 [perms['repositories_groups'][self.repo_group_name]])
1898 except KeyError:
1902 except KeyError:
1899 return False
1903 return False
1900 if self.required_perms.intersection(user_perms):
1904 if self.required_perms.intersection(user_perms):
1901 return True
1905 return True
1902 return False
1906 return False
1903
1907
1904
1908
1905 class HasRepoGroupPermissionAll(PermsFunction):
1909 class HasRepoGroupPermissionAll(PermsFunction):
1906 def __call__(self, group_name=None, check_location='', user=None):
1910 def __call__(self, group_name=None, check_location='', user=None):
1907 self.repo_group_name = group_name
1911 self.repo_group_name = group_name
1908 return super(HasRepoGroupPermissionAll, self).__call__(
1912 return super(HasRepoGroupPermissionAll, self).__call__(
1909 check_location, user)
1913 check_location, user)
1910
1914
1911 def check_permissions(self, user):
1915 def check_permissions(self, user):
1912 perms = user.permissions
1916 perms = user.permissions
1913 try:
1917 try:
1914 user_perms = set(
1918 user_perms = set(
1915 [perms['repositories_groups'][self.repo_group_name]])
1919 [perms['repositories_groups'][self.repo_group_name]])
1916 except KeyError:
1920 except KeyError:
1917 return False
1921 return False
1918 if self.required_perms.issubset(user_perms):
1922 if self.required_perms.issubset(user_perms):
1919 return True
1923 return True
1920 return False
1924 return False
1921
1925
1922
1926
1923 class HasUserGroupPermissionAny(PermsFunction):
1927 class HasUserGroupPermissionAny(PermsFunction):
1924 def __call__(self, user_group_name=None, check_location='', user=None):
1928 def __call__(self, user_group_name=None, check_location='', user=None):
1925 self.user_group_name = user_group_name
1929 self.user_group_name = user_group_name
1926 return super(HasUserGroupPermissionAny, self).__call__(
1930 return super(HasUserGroupPermissionAny, self).__call__(
1927 check_location, user)
1931 check_location, user)
1928
1932
1929 def check_permissions(self, user):
1933 def check_permissions(self, user):
1930 perms = user.permissions
1934 perms = user.permissions
1931 try:
1935 try:
1932 user_perms = set([perms['user_groups'][self.user_group_name]])
1936 user_perms = set([perms['user_groups'][self.user_group_name]])
1933 except KeyError:
1937 except KeyError:
1934 return False
1938 return False
1935 if self.required_perms.intersection(user_perms):
1939 if self.required_perms.intersection(user_perms):
1936 return True
1940 return True
1937 return False
1941 return False
1938
1942
1939
1943
1940 class HasUserGroupPermissionAll(PermsFunction):
1944 class HasUserGroupPermissionAll(PermsFunction):
1941 def __call__(self, user_group_name=None, check_location='', user=None):
1945 def __call__(self, user_group_name=None, check_location='', user=None):
1942 self.user_group_name = user_group_name
1946 self.user_group_name = user_group_name
1943 return super(HasUserGroupPermissionAll, self).__call__(
1947 return super(HasUserGroupPermissionAll, self).__call__(
1944 check_location, user)
1948 check_location, user)
1945
1949
1946 def check_permissions(self, user):
1950 def check_permissions(self, user):
1947 perms = user.permissions
1951 perms = user.permissions
1948 try:
1952 try:
1949 user_perms = set([perms['user_groups'][self.user_group_name]])
1953 user_perms = set([perms['user_groups'][self.user_group_name]])
1950 except KeyError:
1954 except KeyError:
1951 return False
1955 return False
1952 if self.required_perms.issubset(user_perms):
1956 if self.required_perms.issubset(user_perms):
1953 return True
1957 return True
1954 return False
1958 return False
1955
1959
1956
1960
1957 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
1961 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
1958 class HasPermissionAnyMiddleware(object):
1962 class HasPermissionAnyMiddleware(object):
1959 def __init__(self, *perms):
1963 def __init__(self, *perms):
1960 self.required_perms = set(perms)
1964 self.required_perms = set(perms)
1961
1965
1962 def __call__(self, user, repo_name):
1966 def __call__(self, user, repo_name):
1963 # repo_name MUST be unicode, since we handle keys in permission
1967 # repo_name MUST be unicode, since we handle keys in permission
1964 # dict by unicode
1968 # dict by unicode
1965 repo_name = safe_unicode(repo_name)
1969 repo_name = safe_unicode(repo_name)
1966 user = AuthUser(user.user_id)
1970 user = AuthUser(user.user_id)
1967 log.debug(
1971 log.debug(
1968 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
1972 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
1969 self.required_perms, user, repo_name)
1973 self.required_perms, user, repo_name)
1970
1974
1971 if self.check_permissions(user, repo_name):
1975 if self.check_permissions(user, repo_name):
1972 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
1976 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
1973 repo_name, user, 'PermissionMiddleware')
1977 repo_name, user, 'PermissionMiddleware')
1974 return True
1978 return True
1975
1979
1976 else:
1980 else:
1977 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
1981 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
1978 repo_name, user, 'PermissionMiddleware')
1982 repo_name, user, 'PermissionMiddleware')
1979 return False
1983 return False
1980
1984
1981 def check_permissions(self, user, repo_name):
1985 def check_permissions(self, user, repo_name):
1982 perms = user.permissions_with_scope({'repo_name': repo_name})
1986 perms = user.permissions_with_scope({'repo_name': repo_name})
1983
1987
1984 try:
1988 try:
1985 user_perms = set([perms['repositories'][repo_name]])
1989 user_perms = set([perms['repositories'][repo_name]])
1986 except Exception:
1990 except Exception:
1987 log.exception('Error while accessing user permissions')
1991 log.exception('Error while accessing user permissions')
1988 return False
1992 return False
1989
1993
1990 if self.required_perms.intersection(user_perms):
1994 if self.required_perms.intersection(user_perms):
1991 return True
1995 return True
1992 return False
1996 return False
1993
1997
1994
1998
1995 # SPECIAL VERSION TO HANDLE API AUTH
1999 # SPECIAL VERSION TO HANDLE API AUTH
1996 class _BaseApiPerm(object):
2000 class _BaseApiPerm(object):
1997 def __init__(self, *perms):
2001 def __init__(self, *perms):
1998 self.required_perms = set(perms)
2002 self.required_perms = set(perms)
1999
2003
2000 def __call__(self, check_location=None, user=None, repo_name=None,
2004 def __call__(self, check_location=None, user=None, repo_name=None,
2001 group_name=None, user_group_name=None):
2005 group_name=None, user_group_name=None):
2002 cls_name = self.__class__.__name__
2006 cls_name = self.__class__.__name__
2003 check_scope = 'global:%s' % (self.required_perms,)
2007 check_scope = 'global:%s' % (self.required_perms,)
2004 if repo_name:
2008 if repo_name:
2005 check_scope += ', repo_name:%s' % (repo_name,)
2009 check_scope += ', repo_name:%s' % (repo_name,)
2006
2010
2007 if group_name:
2011 if group_name:
2008 check_scope += ', repo_group_name:%s' % (group_name,)
2012 check_scope += ', repo_group_name:%s' % (group_name,)
2009
2013
2010 if user_group_name:
2014 if user_group_name:
2011 check_scope += ', user_group_name:%s' % (user_group_name,)
2015 check_scope += ', user_group_name:%s' % (user_group_name,)
2012
2016
2013 log.debug(
2017 log.debug(
2014 'checking cls:%s %s %s @ %s'
2018 'checking cls:%s %s %s @ %s'
2015 % (cls_name, self.required_perms, check_scope, check_location))
2019 % (cls_name, self.required_perms, check_scope, check_location))
2016 if not user:
2020 if not user:
2017 log.debug('Empty User passed into arguments')
2021 log.debug('Empty User passed into arguments')
2018 return False
2022 return False
2019
2023
2020 # process user
2024 # process user
2021 if not isinstance(user, AuthUser):
2025 if not isinstance(user, AuthUser):
2022 user = AuthUser(user.user_id)
2026 user = AuthUser(user.user_id)
2023 if not check_location:
2027 if not check_location:
2024 check_location = 'unspecified'
2028 check_location = 'unspecified'
2025 if self.check_permissions(user.permissions, repo_name, group_name,
2029 if self.check_permissions(user.permissions, repo_name, group_name,
2026 user_group_name):
2030 user_group_name):
2027 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
2031 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
2028 check_scope, user, check_location)
2032 check_scope, user, check_location)
2029 return True
2033 return True
2030
2034
2031 else:
2035 else:
2032 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
2036 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
2033 check_scope, user, check_location)
2037 check_scope, user, check_location)
2034 return False
2038 return False
2035
2039
2036 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2040 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2037 user_group_name=None):
2041 user_group_name=None):
2038 """
2042 """
2039 implement in child class should return True if permissions are ok,
2043 implement in child class should return True if permissions are ok,
2040 False otherwise
2044 False otherwise
2041
2045
2042 :param perm_defs: dict with permission definitions
2046 :param perm_defs: dict with permission definitions
2043 :param repo_name: repo name
2047 :param repo_name: repo name
2044 """
2048 """
2045 raise NotImplementedError()
2049 raise NotImplementedError()
2046
2050
2047
2051
2048 class HasPermissionAllApi(_BaseApiPerm):
2052 class HasPermissionAllApi(_BaseApiPerm):
2049 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2053 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2050 user_group_name=None):
2054 user_group_name=None):
2051 if self.required_perms.issubset(perm_defs.get('global')):
2055 if self.required_perms.issubset(perm_defs.get('global')):
2052 return True
2056 return True
2053 return False
2057 return False
2054
2058
2055
2059
2056 class HasPermissionAnyApi(_BaseApiPerm):
2060 class HasPermissionAnyApi(_BaseApiPerm):
2057 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2061 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2058 user_group_name=None):
2062 user_group_name=None):
2059 if self.required_perms.intersection(perm_defs.get('global')):
2063 if self.required_perms.intersection(perm_defs.get('global')):
2060 return True
2064 return True
2061 return False
2065 return False
2062
2066
2063
2067
2064 class HasRepoPermissionAllApi(_BaseApiPerm):
2068 class HasRepoPermissionAllApi(_BaseApiPerm):
2065 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2069 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2066 user_group_name=None):
2070 user_group_name=None):
2067 try:
2071 try:
2068 _user_perms = set([perm_defs['repositories'][repo_name]])
2072 _user_perms = set([perm_defs['repositories'][repo_name]])
2069 except KeyError:
2073 except KeyError:
2070 log.warning(traceback.format_exc())
2074 log.warning(traceback.format_exc())
2071 return False
2075 return False
2072 if self.required_perms.issubset(_user_perms):
2076 if self.required_perms.issubset(_user_perms):
2073 return True
2077 return True
2074 return False
2078 return False
2075
2079
2076
2080
2077 class HasRepoPermissionAnyApi(_BaseApiPerm):
2081 class HasRepoPermissionAnyApi(_BaseApiPerm):
2078 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2082 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2079 user_group_name=None):
2083 user_group_name=None):
2080 try:
2084 try:
2081 _user_perms = set([perm_defs['repositories'][repo_name]])
2085 _user_perms = set([perm_defs['repositories'][repo_name]])
2082 except KeyError:
2086 except KeyError:
2083 log.warning(traceback.format_exc())
2087 log.warning(traceback.format_exc())
2084 return False
2088 return False
2085 if self.required_perms.intersection(_user_perms):
2089 if self.required_perms.intersection(_user_perms):
2086 return True
2090 return True
2087 return False
2091 return False
2088
2092
2089
2093
2090 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
2094 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
2091 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2095 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2092 user_group_name=None):
2096 user_group_name=None):
2093 try:
2097 try:
2094 _user_perms = set([perm_defs['repositories_groups'][group_name]])
2098 _user_perms = set([perm_defs['repositories_groups'][group_name]])
2095 except KeyError:
2099 except KeyError:
2096 log.warning(traceback.format_exc())
2100 log.warning(traceback.format_exc())
2097 return False
2101 return False
2098 if self.required_perms.intersection(_user_perms):
2102 if self.required_perms.intersection(_user_perms):
2099 return True
2103 return True
2100 return False
2104 return False
2101
2105
2102
2106
2103 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
2107 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
2104 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2108 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2105 user_group_name=None):
2109 user_group_name=None):
2106 try:
2110 try:
2107 _user_perms = set([perm_defs['repositories_groups'][group_name]])
2111 _user_perms = set([perm_defs['repositories_groups'][group_name]])
2108 except KeyError:
2112 except KeyError:
2109 log.warning(traceback.format_exc())
2113 log.warning(traceback.format_exc())
2110 return False
2114 return False
2111 if self.required_perms.issubset(_user_perms):
2115 if self.required_perms.issubset(_user_perms):
2112 return True
2116 return True
2113 return False
2117 return False
2114
2118
2115
2119
2116 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
2120 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
2117 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2121 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2118 user_group_name=None):
2122 user_group_name=None):
2119 try:
2123 try:
2120 _user_perms = set([perm_defs['user_groups'][user_group_name]])
2124 _user_perms = set([perm_defs['user_groups'][user_group_name]])
2121 except KeyError:
2125 except KeyError:
2122 log.warning(traceback.format_exc())
2126 log.warning(traceback.format_exc())
2123 return False
2127 return False
2124 if self.required_perms.intersection(_user_perms):
2128 if self.required_perms.intersection(_user_perms):
2125 return True
2129 return True
2126 return False
2130 return False
2127
2131
2128
2132
2129 def check_ip_access(source_ip, allowed_ips=None):
2133 def check_ip_access(source_ip, allowed_ips=None):
2130 """
2134 """
2131 Checks if source_ip is a subnet of any of allowed_ips.
2135 Checks if source_ip is a subnet of any of allowed_ips.
2132
2136
2133 :param source_ip:
2137 :param source_ip:
2134 :param allowed_ips: list of allowed ips together with mask
2138 :param allowed_ips: list of allowed ips together with mask
2135 """
2139 """
2136 log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips))
2140 log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips))
2137 source_ip_address = ipaddress.ip_address(safe_unicode(source_ip))
2141 source_ip_address = ipaddress.ip_address(safe_unicode(source_ip))
2138 if isinstance(allowed_ips, (tuple, list, set)):
2142 if isinstance(allowed_ips, (tuple, list, set)):
2139 for ip in allowed_ips:
2143 for ip in allowed_ips:
2140 ip = safe_unicode(ip)
2144 ip = safe_unicode(ip)
2141 try:
2145 try:
2142 network_address = ipaddress.ip_network(ip, strict=False)
2146 network_address = ipaddress.ip_network(ip, strict=False)
2143 if source_ip_address in network_address:
2147 if source_ip_address in network_address:
2144 log.debug('IP %s is network %s' %
2148 log.debug('IP %s is network %s' %
2145 (source_ip_address, network_address))
2149 (source_ip_address, network_address))
2146 return True
2150 return True
2147 # for any case we cannot determine the IP, don't crash just
2151 # for any case we cannot determine the IP, don't crash just
2148 # skip it and log as error, we want to say forbidden still when
2152 # skip it and log as error, we want to say forbidden still when
2149 # sending bad IP
2153 # sending bad IP
2150 except Exception:
2154 except Exception:
2151 log.error(traceback.format_exc())
2155 log.error(traceback.format_exc())
2152 continue
2156 continue
2153 return False
2157 return False
2154
2158
2155
2159
2156 def get_cython_compat_decorator(wrapper, func):
2160 def get_cython_compat_decorator(wrapper, func):
2157 """
2161 """
2158 Creates a cython compatible decorator. The previously used
2162 Creates a cython compatible decorator. The previously used
2159 decorator.decorator() function seems to be incompatible with cython.
2163 decorator.decorator() function seems to be incompatible with cython.
2160
2164
2161 :param wrapper: __wrapper method of the decorator class
2165 :param wrapper: __wrapper method of the decorator class
2162 :param func: decorated function
2166 :param func: decorated function
2163 """
2167 """
2164 @wraps(func)
2168 @wraps(func)
2165 def local_wrapper(*args, **kwds):
2169 def local_wrapper(*args, **kwds):
2166 return wrapper(func, *args, **kwds)
2170 return wrapper(func, *args, **kwds)
2167 local_wrapper.__wrapped__ = func
2171 local_wrapper.__wrapped__ = func
2168 return local_wrapper
2172 return local_wrapper
2169
2173
2170
2174
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,635 +1,641 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2011-2017 RhodeCode GmbH
3 # Copyright (C) 2011-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 import traceback
22 import traceback
23
23
24 from rhodecode.lib.utils2 import safe_str, safe_unicode
24 from rhodecode.lib.utils2 import safe_str, safe_unicode
25 from rhodecode.lib.exceptions import (
25 from rhodecode.lib.exceptions import (
26 UserGroupAssignedException, RepoGroupAssignmentError)
26 UserGroupAssignedException, RepoGroupAssignmentError)
27 from rhodecode.lib.utils2 import (
27 from rhodecode.lib.utils2 import (
28 get_current_rhodecode_user, action_logger_generic)
28 get_current_rhodecode_user, action_logger_generic)
29 from rhodecode.model import BaseModel
29 from rhodecode.model import BaseModel
30 from rhodecode.model.scm import UserGroupList
30 from rhodecode.model.scm import UserGroupList
31 from rhodecode.model.db import (
31 from rhodecode.model.db import (
32 true, func, User, UserGroupMember, UserGroup,
32 true, func, User, UserGroupMember, UserGroup,
33 UserGroupRepoToPerm, Permission, UserGroupToPerm, UserUserGroupToPerm,
33 UserGroupRepoToPerm, Permission, UserGroupToPerm, UserUserGroupToPerm,
34 UserGroupUserGroupToPerm, UserGroupRepoGroupToPerm)
34 UserGroupUserGroupToPerm, UserGroupRepoGroupToPerm)
35
35
36
36
37 log = logging.getLogger(__name__)
37 log = logging.getLogger(__name__)
38
38
39
39
40 class UserGroupModel(BaseModel):
40 class UserGroupModel(BaseModel):
41
41
42 cls = UserGroup
42 cls = UserGroup
43
43
44 def _get_user_group(self, user_group):
44 def _get_user_group(self, user_group):
45 return self._get_instance(UserGroup, user_group,
45 return self._get_instance(UserGroup, user_group,
46 callback=UserGroup.get_by_group_name)
46 callback=UserGroup.get_by_group_name)
47
47
48 def _create_default_perms(self, user_group):
48 def _create_default_perms(self, user_group):
49 # create default permission
49 # create default permission
50 default_perm = 'usergroup.read'
50 default_perm = 'usergroup.read'
51 def_user = User.get_default_user()
51 def_user = User.get_default_user()
52 for p in def_user.user_perms:
52 for p in def_user.user_perms:
53 if p.permission.permission_name.startswith('usergroup.'):
53 if p.permission.permission_name.startswith('usergroup.'):
54 default_perm = p.permission.permission_name
54 default_perm = p.permission.permission_name
55 break
55 break
56
56
57 user_group_to_perm = UserUserGroupToPerm()
57 user_group_to_perm = UserUserGroupToPerm()
58 user_group_to_perm.permission = Permission.get_by_key(default_perm)
58 user_group_to_perm.permission = Permission.get_by_key(default_perm)
59
59
60 user_group_to_perm.user_group = user_group
60 user_group_to_perm.user_group = user_group
61 user_group_to_perm.user_id = def_user.user_id
61 user_group_to_perm.user_id = def_user.user_id
62 return user_group_to_perm
62 return user_group_to_perm
63
63
64 def update_permissions(
64 def update_permissions(
65 self, user_group, perm_additions=None, perm_updates=None,
65 self, user_group, perm_additions=None, perm_updates=None,
66 perm_deletions=None, check_perms=True, cur_user=None):
66 perm_deletions=None, check_perms=True, cur_user=None):
67
67
68 from rhodecode.lib.auth import HasUserGroupPermissionAny
68 from rhodecode.lib.auth import HasUserGroupPermissionAny
69 if not perm_additions:
69 if not perm_additions:
70 perm_additions = []
70 perm_additions = []
71 if not perm_updates:
71 if not perm_updates:
72 perm_updates = []
72 perm_updates = []
73 if not perm_deletions:
73 if not perm_deletions:
74 perm_deletions = []
74 perm_deletions = []
75
75
76 req_perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin')
76 req_perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin')
77
77
78 changes = {
78 changes = {
79 'added': [],
79 'added': [],
80 'updated': [],
80 'updated': [],
81 'deleted': []
81 'deleted': []
82 }
82 }
83 # update permissions
83 # update permissions
84 for member_id, perm, member_type in perm_updates:
84 for member_id, perm, member_type in perm_updates:
85 member_id = int(member_id)
85 member_id = int(member_id)
86 if member_type == 'user':
86 if member_type == 'user':
87 member_name = User.get(member_id).username
87 member_name = User.get(member_id).username
88 # this updates existing one
88 # this updates existing one
89 self.grant_user_permission(
89 self.grant_user_permission(
90 user_group=user_group, user=member_id, perm=perm
90 user_group=user_group, user=member_id, perm=perm
91 )
91 )
92 else:
92 else:
93 # check if we have permissions to alter this usergroup
93 # check if we have permissions to alter this usergroup
94 member_name = UserGroup.get(member_id).users_group_name
94 member_name = UserGroup.get(member_id).users_group_name
95 if not check_perms or HasUserGroupPermissionAny(
95 if not check_perms or HasUserGroupPermissionAny(
96 *req_perms)(member_name, user=cur_user):
96 *req_perms)(member_name, user=cur_user):
97 self.grant_user_group_permission(
97 self.grant_user_group_permission(
98 target_user_group=user_group, user_group=member_id, perm=perm)
98 target_user_group=user_group, user_group=member_id, perm=perm)
99
99
100 changes['updated'].append({'type': member_type, 'id': member_id,
100 changes['updated'].append({'type': member_type, 'id': member_id,
101 'name': member_name, 'new_perm': perm})
101 'name': member_name, 'new_perm': perm})
102
102
103 # set new permissions
103 # set new permissions
104 for member_id, perm, member_type in perm_additions:
104 for member_id, perm, member_type in perm_additions:
105 member_id = int(member_id)
105 member_id = int(member_id)
106 if member_type == 'user':
106 if member_type == 'user':
107 member_name = User.get(member_id).username
107 member_name = User.get(member_id).username
108 self.grant_user_permission(
108 self.grant_user_permission(
109 user_group=user_group, user=member_id, perm=perm)
109 user_group=user_group, user=member_id, perm=perm)
110 else:
110 else:
111 # check if we have permissions to alter this usergroup
111 # check if we have permissions to alter this usergroup
112 member_name = UserGroup.get(member_id).users_group_name
112 member_name = UserGroup.get(member_id).users_group_name
113 if not check_perms or HasUserGroupPermissionAny(
113 if not check_perms or HasUserGroupPermissionAny(
114 *req_perms)(member_name, user=cur_user):
114 *req_perms)(member_name, user=cur_user):
115 self.grant_user_group_permission(
115 self.grant_user_group_permission(
116 target_user_group=user_group, user_group=member_id, perm=perm)
116 target_user_group=user_group, user_group=member_id, perm=perm)
117
117
118 changes['added'].append({'type': member_type, 'id': member_id,
118 changes['added'].append({'type': member_type, 'id': member_id,
119 'name': member_name, 'new_perm': perm})
119 'name': member_name, 'new_perm': perm})
120
120
121 # delete permissions
121 # delete permissions
122 for member_id, perm, member_type in perm_deletions:
122 for member_id, perm, member_type in perm_deletions:
123 member_id = int(member_id)
123 member_id = int(member_id)
124 if member_type == 'user':
124 if member_type == 'user':
125 member_name = User.get(member_id).username
125 member_name = User.get(member_id).username
126 self.revoke_user_permission(user_group=user_group, user=member_id)
126 self.revoke_user_permission(user_group=user_group, user=member_id)
127 else:
127 else:
128 # check if we have permissions to alter this usergroup
128 # check if we have permissions to alter this usergroup
129 member_name = UserGroup.get(member_id).users_group_name
129 member_name = UserGroup.get(member_id).users_group_name
130 if not check_perms or HasUserGroupPermissionAny(
130 if not check_perms or HasUserGroupPermissionAny(
131 *req_perms)(member_name, user=cur_user):
131 *req_perms)(member_name, user=cur_user):
132 self.revoke_user_group_permission(
132 self.revoke_user_group_permission(
133 target_user_group=user_group, user_group=member_id)
133 target_user_group=user_group, user_group=member_id)
134
134
135 changes['deleted'].append({'type': member_type, 'id': member_id,
135 changes['deleted'].append({'type': member_type, 'id': member_id,
136 'name': member_name, 'new_perm': perm})
136 'name': member_name, 'new_perm': perm})
137 return changes
137 return changes
138
138
139 def get(self, user_group_id, cache=False):
139 def get(self, user_group_id, cache=False):
140 return UserGroup.get(user_group_id)
140 return UserGroup.get(user_group_id)
141
141
142 def get_group(self, user_group):
142 def get_group(self, user_group):
143 return self._get_user_group(user_group)
143 return self._get_user_group(user_group)
144
144
145 def get_by_name(self, name, cache=False, case_insensitive=False):
145 def get_by_name(self, name, cache=False, case_insensitive=False):
146 return UserGroup.get_by_group_name(name, cache, case_insensitive)
146 return UserGroup.get_by_group_name(name, cache, case_insensitive)
147
147
148 def create(self, name, description, owner, active=True, group_data=None):
148 def create(self, name, description, owner, active=True, group_data=None):
149 try:
149 try:
150 new_user_group = UserGroup()
150 new_user_group = UserGroup()
151 new_user_group.user = self._get_user(owner)
151 new_user_group.user = self._get_user(owner)
152 new_user_group.users_group_name = name
152 new_user_group.users_group_name = name
153 new_user_group.user_group_description = description
153 new_user_group.user_group_description = description
154 new_user_group.users_group_active = active
154 new_user_group.users_group_active = active
155 if group_data:
155 if group_data:
156 new_user_group.group_data = group_data
156 new_user_group.group_data = group_data
157 self.sa.add(new_user_group)
157 self.sa.add(new_user_group)
158 perm_obj = self._create_default_perms(new_user_group)
158 perm_obj = self._create_default_perms(new_user_group)
159 self.sa.add(perm_obj)
159 self.sa.add(perm_obj)
160
160
161 self.grant_user_permission(user_group=new_user_group,
161 self.grant_user_permission(user_group=new_user_group,
162 user=owner, perm='usergroup.admin')
162 user=owner, perm='usergroup.admin')
163
163
164 return new_user_group
164 return new_user_group
165 except Exception:
165 except Exception:
166 log.error(traceback.format_exc())
166 log.error(traceback.format_exc())
167 raise
167 raise
168
168
169 def _get_memberships_for_user_ids(self, user_group, user_id_list):
169 def _get_memberships_for_user_ids(self, user_group, user_id_list):
170 members = []
170 members = []
171 for user_id in user_id_list:
171 for user_id in user_id_list:
172 member = self._get_membership(user_group.users_group_id, user_id)
172 member = self._get_membership(user_group.users_group_id, user_id)
173 members.append(member)
173 members.append(member)
174 return members
174 return members
175
175
176 def _get_added_and_removed_user_ids(self, user_group, user_id_list):
176 def _get_added_and_removed_user_ids(self, user_group, user_id_list):
177 current_members = user_group.members or []
177 current_members = user_group.members or []
178 current_members_ids = [m.user.user_id for m in current_members]
178 current_members_ids = [m.user.user_id for m in current_members]
179
179
180 added_members = [
180 added_members = [
181 user_id for user_id in user_id_list
181 user_id for user_id in user_id_list
182 if user_id not in current_members_ids]
182 if user_id not in current_members_ids]
183 if user_id_list == []:
183 if user_id_list == []:
184 # all members were deleted
184 # all members were deleted
185 deleted_members = current_members_ids
185 deleted_members = current_members_ids
186 else:
186 else:
187 deleted_members = [
187 deleted_members = [
188 user_id for user_id in current_members_ids
188 user_id for user_id in current_members_ids
189 if user_id not in user_id_list]
189 if user_id not in user_id_list]
190
190
191 return added_members, deleted_members
191 return added_members, deleted_members
192
192
193 def _set_users_as_members(self, user_group, user_ids):
193 def _set_users_as_members(self, user_group, user_ids):
194 user_group.members = []
194 user_group.members = []
195 self.sa.flush()
195 self.sa.flush()
196 members = self._get_memberships_for_user_ids(
196 members = self._get_memberships_for_user_ids(
197 user_group, user_ids)
197 user_group, user_ids)
198 user_group.members = members
198 user_group.members = members
199 self.sa.add(user_group)
199 self.sa.add(user_group)
200
200
201 def _update_members_from_user_ids(self, user_group, user_ids):
201 def _update_members_from_user_ids(self, user_group, user_ids):
202 added, removed = self._get_added_and_removed_user_ids(
202 added, removed = self._get_added_and_removed_user_ids(
203 user_group, user_ids)
203 user_group, user_ids)
204 self._set_users_as_members(user_group, user_ids)
204 self._set_users_as_members(user_group, user_ids)
205 self._log_user_changes('added to', user_group, added)
205 self._log_user_changes('added to', user_group, added)
206 self._log_user_changes('removed from', user_group, removed)
206 self._log_user_changes('removed from', user_group, removed)
207 return added, removed
207 return added, removed
208
208
209 def _clean_members_data(self, members_data):
209 def _clean_members_data(self, members_data):
210 if not members_data:
210 if not members_data:
211 members_data = []
211 members_data = []
212
212
213 members = []
213 members = []
214 for user in members_data:
214 for user in members_data:
215 uid = int(user['member_user_id'])
215 uid = int(user['member_user_id'])
216 if uid not in members and user['type'] in ['new', 'existing']:
216 if uid not in members and user['type'] in ['new', 'existing']:
217 members.append(uid)
217 members.append(uid)
218 return members
218 return members
219
219
220 def update(self, user_group, form_data):
220 def update(self, user_group, form_data):
221 user_group = self._get_user_group(user_group)
221 user_group = self._get_user_group(user_group)
222 if 'users_group_name' in form_data:
222 if 'users_group_name' in form_data:
223 user_group.users_group_name = form_data['users_group_name']
223 user_group.users_group_name = form_data['users_group_name']
224 if 'users_group_active' in form_data:
224 if 'users_group_active' in form_data:
225 user_group.users_group_active = form_data['users_group_active']
225 user_group.users_group_active = form_data['users_group_active']
226 if 'user_group_description' in form_data:
226 if 'user_group_description' in form_data:
227 user_group.user_group_description = form_data[
227 user_group.user_group_description = form_data[
228 'user_group_description']
228 'user_group_description']
229
229
230 # handle owner change
230 # handle owner change
231 if 'user' in form_data:
231 if 'user' in form_data:
232 owner = form_data['user']
232 owner = form_data['user']
233 if isinstance(owner, basestring):
233 if isinstance(owner, basestring):
234 owner = User.get_by_username(form_data['user'])
234 owner = User.get_by_username(form_data['user'])
235
235
236 if not isinstance(owner, User):
236 if not isinstance(owner, User):
237 raise ValueError(
237 raise ValueError(
238 'invalid owner for user group: %s' % form_data['user'])
238 'invalid owner for user group: %s' % form_data['user'])
239
239
240 user_group.user = owner
240 user_group.user = owner
241
241
242 added_user_ids = []
242 added_user_ids = []
243 removed_user_ids = []
243 removed_user_ids = []
244 if 'users_group_members' in form_data:
244 if 'users_group_members' in form_data:
245 members_id_list = self._clean_members_data(
245 members_id_list = self._clean_members_data(
246 form_data['users_group_members'])
246 form_data['users_group_members'])
247 added_user_ids, removed_user_ids = \
247 added_user_ids, removed_user_ids = \
248 self._update_members_from_user_ids(user_group, members_id_list)
248 self._update_members_from_user_ids(user_group, members_id_list)
249
249
250 self.sa.add(user_group)
250 self.sa.add(user_group)
251 return user_group, added_user_ids, removed_user_ids
251 return user_group, added_user_ids, removed_user_ids
252
252
253 def delete(self, user_group, force=False):
253 def delete(self, user_group, force=False):
254 """
254 """
255 Deletes repository group, unless force flag is used
255 Deletes repository group, unless force flag is used
256 raises exception if there are members in that group, else deletes
256 raises exception if there are members in that group, else deletes
257 group and users
257 group and users
258
258
259 :param user_group:
259 :param user_group:
260 :param force:
260 :param force:
261 """
261 """
262 user_group = self._get_user_group(user_group)
262 user_group = self._get_user_group(user_group)
263 if not user_group:
263 if not user_group:
264 return
264 return
265
265
266 try:
266 try:
267 # check if this group is not assigned to repo
267 # check if this group is not assigned to repo
268 assigned_to_repo = [x.repository for x in UserGroupRepoToPerm.query()\
268 assigned_to_repo = [x.repository for x in UserGroupRepoToPerm.query()\
269 .filter(UserGroupRepoToPerm.users_group == user_group).all()]
269 .filter(UserGroupRepoToPerm.users_group == user_group).all()]
270 # check if this group is not assigned to repo
270 # check if this group is not assigned to repo
271 assigned_to_repo_group = [x.group for x in UserGroupRepoGroupToPerm.query()\
271 assigned_to_repo_group = [x.group for x in UserGroupRepoGroupToPerm.query()\
272 .filter(UserGroupRepoGroupToPerm.users_group == user_group).all()]
272 .filter(UserGroupRepoGroupToPerm.users_group == user_group).all()]
273
273
274 if (assigned_to_repo or assigned_to_repo_group) and not force:
274 if (assigned_to_repo or assigned_to_repo_group) and not force:
275 assigned = ','.join(map(safe_str,
275 assigned = ','.join(map(safe_str,
276 assigned_to_repo+assigned_to_repo_group))
276 assigned_to_repo+assigned_to_repo_group))
277
277
278 raise UserGroupAssignedException(
278 raise UserGroupAssignedException(
279 'UserGroup assigned to %s' % (assigned,))
279 'UserGroup assigned to %s' % (assigned,))
280 self.sa.delete(user_group)
280 self.sa.delete(user_group)
281 except Exception:
281 except Exception:
282 log.error(traceback.format_exc())
282 log.error(traceback.format_exc())
283 raise
283 raise
284
284
285 def _log_user_changes(self, action, user_group, user_or_users):
285 def _log_user_changes(self, action, user_group, user_or_users):
286 users = user_or_users
286 users = user_or_users
287 if not isinstance(users, (list, tuple)):
287 if not isinstance(users, (list, tuple)):
288 users = [users]
288 users = [users]
289
289
290 group_name = user_group.users_group_name
290 group_name = user_group.users_group_name
291
291
292 for user_or_user_id in users:
292 for user_or_user_id in users:
293 user = self._get_user(user_or_user_id)
293 user = self._get_user(user_or_user_id)
294 log_text = 'User {user} {action} {group}'.format(
294 log_text = 'User {user} {action} {group}'.format(
295 action=action, user=user.username, group=group_name)
295 action=action, user=user.username, group=group_name)
296 action_logger_generic(log_text)
296 action_logger_generic(log_text)
297
297
298 def _find_user_in_group(self, user, user_group):
298 def _find_user_in_group(self, user, user_group):
299 user_group_member = None
299 user_group_member = None
300 for m in user_group.members:
300 for m in user_group.members:
301 if m.user_id == user.user_id:
301 if m.user_id == user.user_id:
302 # Found this user's membership row
302 # Found this user's membership row
303 user_group_member = m
303 user_group_member = m
304 break
304 break
305
305
306 return user_group_member
306 return user_group_member
307
307
308 def _get_membership(self, user_group_id, user_id):
308 def _get_membership(self, user_group_id, user_id):
309 user_group_member = UserGroupMember(user_group_id, user_id)
309 user_group_member = UserGroupMember(user_group_id, user_id)
310 return user_group_member
310 return user_group_member
311
311
312 def add_user_to_group(self, user_group, user):
312 def add_user_to_group(self, user_group, user):
313 user_group = self._get_user_group(user_group)
313 user_group = self._get_user_group(user_group)
314 user = self._get_user(user)
314 user = self._get_user(user)
315 user_member = self._find_user_in_group(user, user_group)
315 user_member = self._find_user_in_group(user, user_group)
316 if user_member:
316 if user_member:
317 # user already in the group, skip
317 # user already in the group, skip
318 return True
318 return True
319
319
320 member = self._get_membership(
320 member = self._get_membership(
321 user_group.users_group_id, user.user_id)
321 user_group.users_group_id, user.user_id)
322 user_group.members.append(member)
322 user_group.members.append(member)
323
323
324 try:
324 try:
325 self.sa.add(member)
325 self.sa.add(member)
326 except Exception:
326 except Exception:
327 # what could go wrong here?
327 # what could go wrong here?
328 log.error(traceback.format_exc())
328 log.error(traceback.format_exc())
329 raise
329 raise
330
330
331 self._log_user_changes('added to', user_group, user)
331 self._log_user_changes('added to', user_group, user)
332 return member
332 return member
333
333
334 def remove_user_from_group(self, user_group, user):
334 def remove_user_from_group(self, user_group, user):
335 user_group = self._get_user_group(user_group)
335 user_group = self._get_user_group(user_group)
336 user = self._get_user(user)
336 user = self._get_user(user)
337 user_group_member = self._find_user_in_group(user, user_group)
337 user_group_member = self._find_user_in_group(user, user_group)
338
338
339 if not user_group_member:
339 if not user_group_member:
340 # User isn't in that group
340 # User isn't in that group
341 return False
341 return False
342
342
343 try:
343 try:
344 self.sa.delete(user_group_member)
344 self.sa.delete(user_group_member)
345 except Exception:
345 except Exception:
346 log.error(traceback.format_exc())
346 log.error(traceback.format_exc())
347 raise
347 raise
348
348
349 self._log_user_changes('removed from', user_group, user)
349 self._log_user_changes('removed from', user_group, user)
350 return True
350 return True
351
351
352 def has_perm(self, user_group, perm):
352 def has_perm(self, user_group, perm):
353 user_group = self._get_user_group(user_group)
353 user_group = self._get_user_group(user_group)
354 perm = self._get_perm(perm)
354 perm = self._get_perm(perm)
355
355
356 return UserGroupToPerm.query()\
356 return UserGroupToPerm.query()\
357 .filter(UserGroupToPerm.users_group == user_group)\
357 .filter(UserGroupToPerm.users_group == user_group)\
358 .filter(UserGroupToPerm.permission == perm).scalar() is not None
358 .filter(UserGroupToPerm.permission == perm).scalar() is not None
359
359
360 def grant_perm(self, user_group, perm):
360 def grant_perm(self, user_group, perm):
361 user_group = self._get_user_group(user_group)
361 user_group = self._get_user_group(user_group)
362 perm = self._get_perm(perm)
362 perm = self._get_perm(perm)
363
363
364 # if this permission is already granted skip it
364 # if this permission is already granted skip it
365 _perm = UserGroupToPerm.query()\
365 _perm = UserGroupToPerm.query()\
366 .filter(UserGroupToPerm.users_group == user_group)\
366 .filter(UserGroupToPerm.users_group == user_group)\
367 .filter(UserGroupToPerm.permission == perm)\
367 .filter(UserGroupToPerm.permission == perm)\
368 .scalar()
368 .scalar()
369 if _perm:
369 if _perm:
370 return
370 return
371
371
372 new = UserGroupToPerm()
372 new = UserGroupToPerm()
373 new.users_group = user_group
373 new.users_group = user_group
374 new.permission = perm
374 new.permission = perm
375 self.sa.add(new)
375 self.sa.add(new)
376 return new
376 return new
377
377
378 def revoke_perm(self, user_group, perm):
378 def revoke_perm(self, user_group, perm):
379 user_group = self._get_user_group(user_group)
379 user_group = self._get_user_group(user_group)
380 perm = self._get_perm(perm)
380 perm = self._get_perm(perm)
381
381
382 obj = UserGroupToPerm.query()\
382 obj = UserGroupToPerm.query()\
383 .filter(UserGroupToPerm.users_group == user_group)\
383 .filter(UserGroupToPerm.users_group == user_group)\
384 .filter(UserGroupToPerm.permission == perm).scalar()
384 .filter(UserGroupToPerm.permission == perm).scalar()
385 if obj:
385 if obj:
386 self.sa.delete(obj)
386 self.sa.delete(obj)
387
387
388 def grant_user_permission(self, user_group, user, perm):
388 def grant_user_permission(self, user_group, user, perm):
389 """
389 """
390 Grant permission for user on given user group, or update
390 Grant permission for user on given user group, or update
391 existing one if found
391 existing one if found
392
392
393 :param user_group: Instance of UserGroup, users_group_id,
393 :param user_group: Instance of UserGroup, users_group_id,
394 or users_group_name
394 or users_group_name
395 :param user: Instance of User, user_id or username
395 :param user: Instance of User, user_id or username
396 :param perm: Instance of Permission, or permission_name
396 :param perm: Instance of Permission, or permission_name
397 """
397 """
398
398
399 user_group = self._get_user_group(user_group)
399 user_group = self._get_user_group(user_group)
400 user = self._get_user(user)
400 user = self._get_user(user)
401 permission = self._get_perm(perm)
401 permission = self._get_perm(perm)
402
402
403 # check if we have that permission already
403 # check if we have that permission already
404 obj = self.sa.query(UserUserGroupToPerm)\
404 obj = self.sa.query(UserUserGroupToPerm)\
405 .filter(UserUserGroupToPerm.user == user)\
405 .filter(UserUserGroupToPerm.user == user)\
406 .filter(UserUserGroupToPerm.user_group == user_group)\
406 .filter(UserUserGroupToPerm.user_group == user_group)\
407 .scalar()
407 .scalar()
408 if obj is None:
408 if obj is None:
409 # create new !
409 # create new !
410 obj = UserUserGroupToPerm()
410 obj = UserUserGroupToPerm()
411 obj.user_group = user_group
411 obj.user_group = user_group
412 obj.user = user
412 obj.user = user
413 obj.permission = permission
413 obj.permission = permission
414 self.sa.add(obj)
414 self.sa.add(obj)
415 log.debug('Granted perm %s to %s on %s', perm, user, user_group)
415 log.debug('Granted perm %s to %s on %s', perm, user, user_group)
416 action_logger_generic(
416 action_logger_generic(
417 'granted permission: {} to user: {} on usergroup: {}'.format(
417 'granted permission: {} to user: {} on usergroup: {}'.format(
418 perm, user, user_group), namespace='security.usergroup')
418 perm, user, user_group), namespace='security.usergroup')
419
419
420 return obj
420 return obj
421
421
422 def revoke_user_permission(self, user_group, user):
422 def revoke_user_permission(self, user_group, user):
423 """
423 """
424 Revoke permission for user on given user group
424 Revoke permission for user on given user group
425
425
426 :param user_group: Instance of UserGroup, users_group_id,
426 :param user_group: Instance of UserGroup, users_group_id,
427 or users_group name
427 or users_group name
428 :param user: Instance of User, user_id or username
428 :param user: Instance of User, user_id or username
429 """
429 """
430
430
431 user_group = self._get_user_group(user_group)
431 user_group = self._get_user_group(user_group)
432 user = self._get_user(user)
432 user = self._get_user(user)
433
433
434 obj = self.sa.query(UserUserGroupToPerm)\
434 obj = self.sa.query(UserUserGroupToPerm)\
435 .filter(UserUserGroupToPerm.user == user)\
435 .filter(UserUserGroupToPerm.user == user)\
436 .filter(UserUserGroupToPerm.user_group == user_group)\
436 .filter(UserUserGroupToPerm.user_group == user_group)\
437 .scalar()
437 .scalar()
438 if obj:
438 if obj:
439 self.sa.delete(obj)
439 self.sa.delete(obj)
440 log.debug('Revoked perm on %s on %s', user_group, user)
440 log.debug('Revoked perm on %s on %s', user_group, user)
441 action_logger_generic(
441 action_logger_generic(
442 'revoked permission from user: {} on usergroup: {}'.format(
442 'revoked permission from user: {} on usergroup: {}'.format(
443 user, user_group), namespace='security.usergroup')
443 user, user_group), namespace='security.usergroup')
444
444
445 def grant_user_group_permission(self, target_user_group, user_group, perm):
445 def grant_user_group_permission(self, target_user_group, user_group, perm):
446 """
446 """
447 Grant user group permission for given target_user_group
447 Grant user group permission for given target_user_group
448
448
449 :param target_user_group:
449 :param target_user_group:
450 :param user_group:
450 :param user_group:
451 :param perm:
451 :param perm:
452 """
452 """
453 target_user_group = self._get_user_group(target_user_group)
453 target_user_group = self._get_user_group(target_user_group)
454 user_group = self._get_user_group(user_group)
454 user_group = self._get_user_group(user_group)
455 permission = self._get_perm(perm)
455 permission = self._get_perm(perm)
456 # forbid assigning same user group to itself
456 # forbid assigning same user group to itself
457 if target_user_group == user_group:
457 if target_user_group == user_group:
458 raise RepoGroupAssignmentError('target repo:%s cannot be '
458 raise RepoGroupAssignmentError('target repo:%s cannot be '
459 'assigned to itself' % target_user_group)
459 'assigned to itself' % target_user_group)
460
460
461 # check if we have that permission already
461 # check if we have that permission already
462 obj = self.sa.query(UserGroupUserGroupToPerm)\
462 obj = self.sa.query(UserGroupUserGroupToPerm)\
463 .filter(UserGroupUserGroupToPerm.target_user_group == target_user_group)\
463 .filter(UserGroupUserGroupToPerm.target_user_group == target_user_group)\
464 .filter(UserGroupUserGroupToPerm.user_group == user_group)\
464 .filter(UserGroupUserGroupToPerm.user_group == user_group)\
465 .scalar()
465 .scalar()
466 if obj is None:
466 if obj is None:
467 # create new !
467 # create new !
468 obj = UserGroupUserGroupToPerm()
468 obj = UserGroupUserGroupToPerm()
469 obj.user_group = user_group
469 obj.user_group = user_group
470 obj.target_user_group = target_user_group
470 obj.target_user_group = target_user_group
471 obj.permission = permission
471 obj.permission = permission
472 self.sa.add(obj)
472 self.sa.add(obj)
473 log.debug(
473 log.debug(
474 'Granted perm %s to %s on %s', perm, target_user_group, user_group)
474 'Granted perm %s to %s on %s', perm, target_user_group, user_group)
475 action_logger_generic(
475 action_logger_generic(
476 'granted permission: {} to usergroup: {} on usergroup: {}'.format(
476 'granted permission: {} to usergroup: {} on usergroup: {}'.format(
477 perm, user_group, target_user_group),
477 perm, user_group, target_user_group),
478 namespace='security.usergroup')
478 namespace='security.usergroup')
479
479
480 return obj
480 return obj
481
481
482 def revoke_user_group_permission(self, target_user_group, user_group):
482 def revoke_user_group_permission(self, target_user_group, user_group):
483 """
483 """
484 Revoke user group permission for given target_user_group
484 Revoke user group permission for given target_user_group
485
485
486 :param target_user_group:
486 :param target_user_group:
487 :param user_group:
487 :param user_group:
488 """
488 """
489 target_user_group = self._get_user_group(target_user_group)
489 target_user_group = self._get_user_group(target_user_group)
490 user_group = self._get_user_group(user_group)
490 user_group = self._get_user_group(user_group)
491
491
492 obj = self.sa.query(UserGroupUserGroupToPerm)\
492 obj = self.sa.query(UserGroupUserGroupToPerm)\
493 .filter(UserGroupUserGroupToPerm.target_user_group == target_user_group)\
493 .filter(UserGroupUserGroupToPerm.target_user_group == target_user_group)\
494 .filter(UserGroupUserGroupToPerm.user_group == user_group)\
494 .filter(UserGroupUserGroupToPerm.user_group == user_group)\
495 .scalar()
495 .scalar()
496 if obj:
496 if obj:
497 self.sa.delete(obj)
497 self.sa.delete(obj)
498 log.debug(
498 log.debug(
499 'Revoked perm on %s on %s', target_user_group, user_group)
499 'Revoked perm on %s on %s', target_user_group, user_group)
500 action_logger_generic(
500 action_logger_generic(
501 'revoked permission from usergroup: {} on usergroup: {}'.format(
501 'revoked permission from usergroup: {} on usergroup: {}'.format(
502 user_group, target_user_group),
502 user_group, target_user_group),
503 namespace='security.repogroup')
503 namespace='security.repogroup')
504
504
505 def enforce_groups(self, user, groups, extern_type=None):
505 def enforce_groups(self, user, groups, extern_type=None):
506 user = self._get_user(user)
506 user = self._get_user(user)
507 log.debug('Enforcing groups %s on user %s', groups, user)
507 log.debug('Enforcing groups %s on user %s', groups, user)
508 current_groups = user.group_member
508 current_groups = user.group_member
509 # find the external created groups
509 # find the external created groups
510 externals = [x.users_group for x in current_groups
510 externals = [x.users_group for x in current_groups
511 if 'extern_type' in x.users_group.group_data]
511 if 'extern_type' in x.users_group.group_data]
512
512
513 # calculate from what groups user should be removed
513 # calculate from what groups user should be removed
514 # externals that are not in groups
514 # externals that are not in groups
515 for gr in externals:
515 for gr in externals:
516 if gr.users_group_name not in groups:
516 if gr.users_group_name not in groups:
517 log.debug('Removing user %s from user group %s', user, gr)
517 log.debug('Removing user %s from user group %s', user, gr)
518 self.remove_user_from_group(gr, user)
518 self.remove_user_from_group(gr, user)
519
519
520 # now we calculate in which groups user should be == groups params
520 # now we calculate in which groups user should be == groups params
521 owner = User.get_first_super_admin().username
521 owner = User.get_first_super_admin().username
522 for gr in set(groups):
522 for gr in set(groups):
523 existing_group = UserGroup.get_by_group_name(gr)
523 existing_group = UserGroup.get_by_group_name(gr)
524 if not existing_group:
524 if not existing_group:
525 desc = 'Automatically created from plugin:%s' % extern_type
525 desc = 'Automatically created from plugin:%s' % extern_type
526 # we use first admin account to set the owner of the group
526 # we use first admin account to set the owner of the group
527 existing_group = UserGroupModel().create(
527 existing_group = UserGroupModel().create(
528 gr, desc, owner, group_data={'extern_type': extern_type})
528 gr, desc, owner, group_data={'extern_type': extern_type})
529
529
530 # we can only add users to special groups created via plugins
530 # we can only add users to special groups created via plugins
531 managed = 'extern_type' in existing_group.group_data
531 managed = 'extern_type' in existing_group.group_data
532 if managed:
532 if managed:
533 log.debug('Adding user %s to user group %s', user, gr)
533 log.debug('Adding user %s to user group %s', user, gr)
534 UserGroupModel().add_user_to_group(existing_group, user)
534 UserGroupModel().add_user_to_group(existing_group, user)
535 else:
535 else:
536 log.debug('Skipping addition to group %s since it is '
536 log.debug('Skipping addition to group %s since it is '
537 'not set to be automatically synchronized' % gr)
537 'not set to be automatically synchronized' % gr)
538
538
539 def change_groups(self, user, groups):
539 def change_groups(self, user, groups):
540 """
540 """
541 This method changes user group assignment
541 This method changes user group assignment
542 :param user: User
542 :param user: User
543 :param groups: array of UserGroupModel
543 :param groups: array of UserGroupModel
544 """
544 """
545 user = self._get_user(user)
545 user = self._get_user(user)
546 log.debug('Changing user(%s) assignment to groups(%s)', user, groups)
546 log.debug('Changing user(%s) assignment to groups(%s)', user, groups)
547 current_groups = user.group_member
547 current_groups = user.group_member
548 current_groups = [x.users_group for x in current_groups]
548 current_groups = [x.users_group for x in current_groups]
549
549
550 # calculate from what groups user should be removed/add
550 # calculate from what groups user should be removed/add
551 groups = set(groups)
551 groups = set(groups)
552 current_groups = set(current_groups)
552 current_groups = set(current_groups)
553
553
554 groups_to_remove = current_groups - groups
554 groups_to_remove = current_groups - groups
555 groups_to_add = groups - current_groups
555 groups_to_add = groups - current_groups
556
556
557 removed_from_groups = []
558 added_to_groups = []
557 for gr in groups_to_remove:
559 for gr in groups_to_remove:
558 log.debug('Removing user %s from user group %s',
560 log.debug('Removing user %s from user group %s',
559 user.username, gr.users_group_name)
561 user.username, gr.users_group_name)
562 removed_from_groups.append(gr.users_group_id)
560 self.remove_user_from_group(gr.users_group_name, user.username)
563 self.remove_user_from_group(gr.users_group_name, user.username)
561 for gr in groups_to_add:
564 for gr in groups_to_add:
562 log.debug('Adding user %s to user group %s',
565 log.debug('Adding user %s to user group %s',
563 user.username, gr.users_group_name)
566 user.username, gr.users_group_name)
567 added_to_groups.append(gr.users_group_id)
564 UserGroupModel().add_user_to_group(
568 UserGroupModel().add_user_to_group(
565 gr.users_group_name, user.username)
569 gr.users_group_name, user.username)
566
570
571 return added_to_groups, removed_from_groups
572
567 def _serialize_user_group(self, user_group):
573 def _serialize_user_group(self, user_group):
568 import rhodecode.lib.helpers as h
574 import rhodecode.lib.helpers as h
569 return {
575 return {
570 'id': user_group.users_group_id,
576 'id': user_group.users_group_id,
571 # TODO: marcink figure out a way to generate the url for the
577 # TODO: marcink figure out a way to generate the url for the
572 # icon
578 # icon
573 'icon_link': '',
579 'icon_link': '',
574 'value_display': 'Group: %s (%d members)' % (
580 'value_display': 'Group: %s (%d members)' % (
575 user_group.users_group_name, len(user_group.members),),
581 user_group.users_group_name, len(user_group.members),),
576 'value': user_group.users_group_name,
582 'value': user_group.users_group_name,
577 'description': user_group.user_group_description,
583 'description': user_group.user_group_description,
578 'owner': user_group.user.username,
584 'owner': user_group.user.username,
579
585
580 'owner_icon': h.gravatar_url(user_group.user.email, 30),
586 'owner_icon': h.gravatar_url(user_group.user.email, 30),
581 'value_display_owner': h.person(user_group.user.email),
587 'value_display_owner': h.person(user_group.user.email),
582
588
583 'value_type': 'user_group',
589 'value_type': 'user_group',
584 'active': user_group.users_group_active,
590 'active': user_group.users_group_active,
585 }
591 }
586
592
587 def get_user_groups(self, name_contains=None, limit=20, only_active=True,
593 def get_user_groups(self, name_contains=None, limit=20, only_active=True,
588 expand_groups=False):
594 expand_groups=False):
589 query = self.sa.query(UserGroup)
595 query = self.sa.query(UserGroup)
590 if only_active:
596 if only_active:
591 query = query.filter(UserGroup.users_group_active == true())
597 query = query.filter(UserGroup.users_group_active == true())
592
598
593 if name_contains:
599 if name_contains:
594 ilike_expression = u'%{}%'.format(safe_unicode(name_contains))
600 ilike_expression = u'%{}%'.format(safe_unicode(name_contains))
595 query = query.filter(
601 query = query.filter(
596 UserGroup.users_group_name.ilike(ilike_expression))\
602 UserGroup.users_group_name.ilike(ilike_expression))\
597 .order_by(func.length(UserGroup.users_group_name))\
603 .order_by(func.length(UserGroup.users_group_name))\
598 .order_by(UserGroup.users_group_name)
604 .order_by(UserGroup.users_group_name)
599
605
600 query = query.limit(limit)
606 query = query.limit(limit)
601 user_groups = query.all()
607 user_groups = query.all()
602 perm_set = ['usergroup.read', 'usergroup.write', 'usergroup.admin']
608 perm_set = ['usergroup.read', 'usergroup.write', 'usergroup.admin']
603 user_groups = UserGroupList(user_groups, perm_set=perm_set)
609 user_groups = UserGroupList(user_groups, perm_set=perm_set)
604
610
605 # store same serialize method to extract data from User
611 # store same serialize method to extract data from User
606 from rhodecode.model.user import UserModel
612 from rhodecode.model.user import UserModel
607 serialize_user = UserModel()._serialize_user
613 serialize_user = UserModel()._serialize_user
608
614
609 _groups = []
615 _groups = []
610 for group in user_groups:
616 for group in user_groups:
611 entry = self._serialize_user_group(group)
617 entry = self._serialize_user_group(group)
612 if expand_groups:
618 if expand_groups:
613 expanded_members = []
619 expanded_members = []
614 for member in group.members:
620 for member in group.members:
615 expanded_members.append(serialize_user(member.user))
621 expanded_members.append(serialize_user(member.user))
616 entry['members'] = expanded_members
622 entry['members'] = expanded_members
617 _groups.append(entry)
623 _groups.append(entry)
618 return _groups
624 return _groups
619
625
620 @staticmethod
626 @staticmethod
621 def get_user_groups_as_dict(user_group):
627 def get_user_groups_as_dict(user_group):
622 import rhodecode.lib.helpers as h
628 import rhodecode.lib.helpers as h
623
629
624 data = {
630 data = {
625 'users_group_id': user_group.users_group_id,
631 'users_group_id': user_group.users_group_id,
626 'group_name': user_group.users_group_name,
632 'group_name': user_group.users_group_name,
627 'group_description': user_group.user_group_description,
633 'group_description': user_group.user_group_description,
628 'active': user_group.users_group_active,
634 'active': user_group.users_group_active,
629 "owner": user_group.user.username,
635 "owner": user_group.user.username,
630 'owner_icon': h.gravatar_url(user_group.user.email, 30),
636 'owner_icon': h.gravatar_url(user_group.user.email, 30),
631 "owner_data": {
637 "owner_data": {
632 'owner': user_group.user.username,
638 'owner': user_group.user.username,
633 'owner_icon': h.gravatar_url(user_group.user.email, 30)}
639 'owner_icon': h.gravatar_url(user_group.user.email, 30)}
634 }
640 }
635 return data
641 return data
@@ -1,274 +1,283 b''
1
1
2 /******************************************************************************
2 /******************************************************************************
3 * *
3 * *
4 * DO NOT CHANGE THIS FILE MANUALLY *
4 * DO NOT CHANGE THIS FILE MANUALLY *
5 * *
5 * *
6 * *
6 * *
7 * This file is automatically generated when the app starts up with *
7 * This file is automatically generated when the app starts up with *
8 * generate_js_files = true *
8 * generate_js_files = true *
9 * *
9 * *
10 * To add a route here pass jsroute=True to the route definition in the app *
10 * To add a route here pass jsroute=True to the route definition in the app *
11 * *
11 * *
12 ******************************************************************************/
12 ******************************************************************************/
13 function registerRCRoutes() {
13 function registerRCRoutes() {
14 // routes registration
14 // routes registration
15 pyroutes.register('edit_user', '/_admin/users/%(user_id)s/edit', ['user_id']);
16 pyroutes.register('favicon', '/favicon.ico', []);
15 pyroutes.register('favicon', '/favicon.ico', []);
17 pyroutes.register('robots', '/robots.txt', []);
16 pyroutes.register('robots', '/robots.txt', []);
18 pyroutes.register('auth_home', '/_admin/auth*traverse', []);
17 pyroutes.register('auth_home', '/_admin/auth*traverse', []);
19 pyroutes.register('global_integrations_new', '/_admin/integrations/new', []);
18 pyroutes.register('global_integrations_new', '/_admin/integrations/new', []);
20 pyroutes.register('global_integrations_home', '/_admin/integrations', []);
19 pyroutes.register('global_integrations_home', '/_admin/integrations', []);
21 pyroutes.register('global_integrations_list', '/_admin/integrations/%(integration)s', ['integration']);
20 pyroutes.register('global_integrations_list', '/_admin/integrations/%(integration)s', ['integration']);
22 pyroutes.register('global_integrations_create', '/_admin/integrations/%(integration)s/new', ['integration']);
21 pyroutes.register('global_integrations_create', '/_admin/integrations/%(integration)s/new', ['integration']);
23 pyroutes.register('global_integrations_edit', '/_admin/integrations/%(integration)s/%(integration_id)s', ['integration', 'integration_id']);
22 pyroutes.register('global_integrations_edit', '/_admin/integrations/%(integration)s/%(integration_id)s', ['integration', 'integration_id']);
24 pyroutes.register('repo_group_integrations_home', '/%(repo_group_name)s/settings/integrations', ['repo_group_name']);
23 pyroutes.register('repo_group_integrations_home', '/%(repo_group_name)s/settings/integrations', ['repo_group_name']);
25 pyroutes.register('repo_group_integrations_new', '/%(repo_group_name)s/settings/integrations/new', ['repo_group_name']);
24 pyroutes.register('repo_group_integrations_new', '/%(repo_group_name)s/settings/integrations/new', ['repo_group_name']);
26 pyroutes.register('repo_group_integrations_list', '/%(repo_group_name)s/settings/integrations/%(integration)s', ['repo_group_name', 'integration']);
25 pyroutes.register('repo_group_integrations_list', '/%(repo_group_name)s/settings/integrations/%(integration)s', ['repo_group_name', 'integration']);
27 pyroutes.register('repo_group_integrations_create', '/%(repo_group_name)s/settings/integrations/%(integration)s/new', ['repo_group_name', 'integration']);
26 pyroutes.register('repo_group_integrations_create', '/%(repo_group_name)s/settings/integrations/%(integration)s/new', ['repo_group_name', 'integration']);
28 pyroutes.register('repo_group_integrations_edit', '/%(repo_group_name)s/settings/integrations/%(integration)s/%(integration_id)s', ['repo_group_name', 'integration', 'integration_id']);
27 pyroutes.register('repo_group_integrations_edit', '/%(repo_group_name)s/settings/integrations/%(integration)s/%(integration_id)s', ['repo_group_name', 'integration', 'integration_id']);
29 pyroutes.register('repo_integrations_home', '/%(repo_name)s/settings/integrations', ['repo_name']);
28 pyroutes.register('repo_integrations_home', '/%(repo_name)s/settings/integrations', ['repo_name']);
30 pyroutes.register('repo_integrations_new', '/%(repo_name)s/settings/integrations/new', ['repo_name']);
29 pyroutes.register('repo_integrations_new', '/%(repo_name)s/settings/integrations/new', ['repo_name']);
31 pyroutes.register('repo_integrations_list', '/%(repo_name)s/settings/integrations/%(integration)s', ['repo_name', 'integration']);
30 pyroutes.register('repo_integrations_list', '/%(repo_name)s/settings/integrations/%(integration)s', ['repo_name', 'integration']);
32 pyroutes.register('repo_integrations_create', '/%(repo_name)s/settings/integrations/%(integration)s/new', ['repo_name', 'integration']);
31 pyroutes.register('repo_integrations_create', '/%(repo_name)s/settings/integrations/%(integration)s/new', ['repo_name', 'integration']);
33 pyroutes.register('repo_integrations_edit', '/%(repo_name)s/settings/integrations/%(integration)s/%(integration_id)s', ['repo_name', 'integration', 'integration_id']);
32 pyroutes.register('repo_integrations_edit', '/%(repo_name)s/settings/integrations/%(integration)s/%(integration_id)s', ['repo_name', 'integration', 'integration_id']);
34 pyroutes.register('ops_ping', '/_admin/ops/ping', []);
33 pyroutes.register('ops_ping', '/_admin/ops/ping', []);
35 pyroutes.register('ops_error_test', '/_admin/ops/error', []);
34 pyroutes.register('ops_error_test', '/_admin/ops/error', []);
36 pyroutes.register('ops_redirect_test', '/_admin/ops/redirect', []);
35 pyroutes.register('ops_redirect_test', '/_admin/ops/redirect', []);
37 pyroutes.register('ops_ping_legacy', '/_admin/ping', []);
36 pyroutes.register('ops_ping_legacy', '/_admin/ping', []);
38 pyroutes.register('ops_error_test_legacy', '/_admin/error_test', []);
37 pyroutes.register('ops_error_test_legacy', '/_admin/error_test', []);
39 pyroutes.register('admin_home', '/_admin', []);
38 pyroutes.register('admin_home', '/_admin', []);
40 pyroutes.register('admin_audit_logs', '/_admin/audit_logs', []);
39 pyroutes.register('admin_audit_logs', '/_admin/audit_logs', []);
41 pyroutes.register('admin_audit_log_entry', '/_admin/audit_logs/%(audit_log_id)s', ['audit_log_id']);
40 pyroutes.register('admin_audit_log_entry', '/_admin/audit_logs/%(audit_log_id)s', ['audit_log_id']);
42 pyroutes.register('pull_requests_global_0', '/_admin/pull_requests/%(pull_request_id)s', ['pull_request_id']);
41 pyroutes.register('pull_requests_global_0', '/_admin/pull_requests/%(pull_request_id)s', ['pull_request_id']);
43 pyroutes.register('pull_requests_global_1', '/_admin/pull-requests/%(pull_request_id)s', ['pull_request_id']);
42 pyroutes.register('pull_requests_global_1', '/_admin/pull-requests/%(pull_request_id)s', ['pull_request_id']);
44 pyroutes.register('pull_requests_global', '/_admin/pull-request/%(pull_request_id)s', ['pull_request_id']);
43 pyroutes.register('pull_requests_global', '/_admin/pull-request/%(pull_request_id)s', ['pull_request_id']);
45 pyroutes.register('admin_settings_open_source', '/_admin/settings/open_source', []);
44 pyroutes.register('admin_settings_open_source', '/_admin/settings/open_source', []);
46 pyroutes.register('admin_settings_vcs_svn_generate_cfg', '/_admin/settings/vcs/svn_generate_cfg', []);
45 pyroutes.register('admin_settings_vcs_svn_generate_cfg', '/_admin/settings/vcs/svn_generate_cfg', []);
47 pyroutes.register('admin_settings_system', '/_admin/settings/system', []);
46 pyroutes.register('admin_settings_system', '/_admin/settings/system', []);
48 pyroutes.register('admin_settings_system_update', '/_admin/settings/system/updates', []);
47 pyroutes.register('admin_settings_system_update', '/_admin/settings/system/updates', []);
49 pyroutes.register('admin_settings_sessions', '/_admin/settings/sessions', []);
48 pyroutes.register('admin_settings_sessions', '/_admin/settings/sessions', []);
50 pyroutes.register('admin_settings_sessions_cleanup', '/_admin/settings/sessions/cleanup', []);
49 pyroutes.register('admin_settings_sessions_cleanup', '/_admin/settings/sessions/cleanup', []);
51 pyroutes.register('admin_settings_process_management', '/_admin/settings/process_management', []);
50 pyroutes.register('admin_settings_process_management', '/_admin/settings/process_management', []);
52 pyroutes.register('admin_settings_process_management_signal', '/_admin/settings/process_management/signal', []);
51 pyroutes.register('admin_settings_process_management_signal', '/_admin/settings/process_management/signal', []);
53 pyroutes.register('admin_defaults_repositories', '/_admin/defaults/repositories', []);
52 pyroutes.register('admin_defaults_repositories', '/_admin/defaults/repositories', []);
54 pyroutes.register('admin_defaults_repositories_update', '/_admin/defaults/repositories/update', []);
53 pyroutes.register('admin_defaults_repositories_update', '/_admin/defaults/repositories/update', []);
55 pyroutes.register('admin_permissions_application', '/_admin/permissions/application', []);
54 pyroutes.register('admin_permissions_application', '/_admin/permissions/application', []);
56 pyroutes.register('admin_permissions_application_update', '/_admin/permissions/application/update', []);
55 pyroutes.register('admin_permissions_application_update', '/_admin/permissions/application/update', []);
57 pyroutes.register('admin_permissions_global', '/_admin/permissions/global', []);
56 pyroutes.register('admin_permissions_global', '/_admin/permissions/global', []);
58 pyroutes.register('admin_permissions_global_update', '/_admin/permissions/global/update', []);
57 pyroutes.register('admin_permissions_global_update', '/_admin/permissions/global/update', []);
59 pyroutes.register('admin_permissions_object', '/_admin/permissions/object', []);
58 pyroutes.register('admin_permissions_object', '/_admin/permissions/object', []);
60 pyroutes.register('admin_permissions_object_update', '/_admin/permissions/object/update', []);
59 pyroutes.register('admin_permissions_object_update', '/_admin/permissions/object/update', []);
61 pyroutes.register('admin_permissions_ips', '/_admin/permissions/ips', []);
60 pyroutes.register('admin_permissions_ips', '/_admin/permissions/ips', []);
62 pyroutes.register('admin_permissions_overview', '/_admin/permissions/overview', []);
61 pyroutes.register('admin_permissions_overview', '/_admin/permissions/overview', []);
63 pyroutes.register('admin_permissions_auth_token_access', '/_admin/permissions/auth_token_access', []);
62 pyroutes.register('admin_permissions_auth_token_access', '/_admin/permissions/auth_token_access', []);
64 pyroutes.register('admin_permissions_ssh_keys', '/_admin/permissions/ssh_keys', []);
63 pyroutes.register('admin_permissions_ssh_keys', '/_admin/permissions/ssh_keys', []);
65 pyroutes.register('admin_permissions_ssh_keys_data', '/_admin/permissions/ssh_keys/data', []);
64 pyroutes.register('admin_permissions_ssh_keys_data', '/_admin/permissions/ssh_keys/data', []);
66 pyroutes.register('admin_permissions_ssh_keys_update', '/_admin/permissions/ssh_keys/update', []);
65 pyroutes.register('admin_permissions_ssh_keys_update', '/_admin/permissions/ssh_keys/update', []);
67 pyroutes.register('users', '/_admin/users', []);
66 pyroutes.register('users', '/_admin/users', []);
68 pyroutes.register('users_data', '/_admin/users_data', []);
67 pyroutes.register('users_data', '/_admin/users_data', []);
68 pyroutes.register('users_create', '/_admin/users/create', []);
69 pyroutes.register('users_new', '/_admin/users/new', []);
70 pyroutes.register('user_edit', '/_admin/users/%(user_id)s/edit', ['user_id']);
71 pyroutes.register('user_edit_advanced', '/_admin/users/%(user_id)s/edit/advanced', ['user_id']);
72 pyroutes.register('user_edit_global_perms', '/_admin/users/%(user_id)s/edit/global_permissions', ['user_id']);
73 pyroutes.register('user_edit_global_perms_update', '/_admin/users/%(user_id)s/edit/global_permissions/update', ['user_id']);
74 pyroutes.register('user_update', '/_admin/users/%(user_id)s/update', ['user_id']);
75 pyroutes.register('user_delete', '/_admin/users/%(user_id)s/delete', ['user_id']);
76 pyroutes.register('user_force_password_reset', '/_admin/users/%(user_id)s/password_reset', ['user_id']);
77 pyroutes.register('user_create_personal_repo_group', '/_admin/users/%(user_id)s/create_repo_group', ['user_id']);
69 pyroutes.register('edit_user_auth_tokens', '/_admin/users/%(user_id)s/edit/auth_tokens', ['user_id']);
78 pyroutes.register('edit_user_auth_tokens', '/_admin/users/%(user_id)s/edit/auth_tokens', ['user_id']);
70 pyroutes.register('edit_user_auth_tokens_add', '/_admin/users/%(user_id)s/edit/auth_tokens/new', ['user_id']);
79 pyroutes.register('edit_user_auth_tokens_add', '/_admin/users/%(user_id)s/edit/auth_tokens/new', ['user_id']);
71 pyroutes.register('edit_user_auth_tokens_delete', '/_admin/users/%(user_id)s/edit/auth_tokens/delete', ['user_id']);
80 pyroutes.register('edit_user_auth_tokens_delete', '/_admin/users/%(user_id)s/edit/auth_tokens/delete', ['user_id']);
72 pyroutes.register('edit_user_ssh_keys', '/_admin/users/%(user_id)s/edit/ssh_keys', ['user_id']);
81 pyroutes.register('edit_user_ssh_keys', '/_admin/users/%(user_id)s/edit/ssh_keys', ['user_id']);
73 pyroutes.register('edit_user_ssh_keys_generate_keypair', '/_admin/users/%(user_id)s/edit/ssh_keys/generate', ['user_id']);
82 pyroutes.register('edit_user_ssh_keys_generate_keypair', '/_admin/users/%(user_id)s/edit/ssh_keys/generate', ['user_id']);
74 pyroutes.register('edit_user_ssh_keys_add', '/_admin/users/%(user_id)s/edit/ssh_keys/new', ['user_id']);
83 pyroutes.register('edit_user_ssh_keys_add', '/_admin/users/%(user_id)s/edit/ssh_keys/new', ['user_id']);
75 pyroutes.register('edit_user_ssh_keys_delete', '/_admin/users/%(user_id)s/edit/ssh_keys/delete', ['user_id']);
84 pyroutes.register('edit_user_ssh_keys_delete', '/_admin/users/%(user_id)s/edit/ssh_keys/delete', ['user_id']);
76 pyroutes.register('edit_user_emails', '/_admin/users/%(user_id)s/edit/emails', ['user_id']);
85 pyroutes.register('edit_user_emails', '/_admin/users/%(user_id)s/edit/emails', ['user_id']);
77 pyroutes.register('edit_user_emails_add', '/_admin/users/%(user_id)s/edit/emails/new', ['user_id']);
86 pyroutes.register('edit_user_emails_add', '/_admin/users/%(user_id)s/edit/emails/new', ['user_id']);
78 pyroutes.register('edit_user_emails_delete', '/_admin/users/%(user_id)s/edit/emails/delete', ['user_id']);
87 pyroutes.register('edit_user_emails_delete', '/_admin/users/%(user_id)s/edit/emails/delete', ['user_id']);
79 pyroutes.register('edit_user_ips', '/_admin/users/%(user_id)s/edit/ips', ['user_id']);
88 pyroutes.register('edit_user_ips', '/_admin/users/%(user_id)s/edit/ips', ['user_id']);
80 pyroutes.register('edit_user_ips_add', '/_admin/users/%(user_id)s/edit/ips/new', ['user_id']);
89 pyroutes.register('edit_user_ips_add', '/_admin/users/%(user_id)s/edit/ips/new', ['user_id']);
81 pyroutes.register('edit_user_ips_delete', '/_admin/users/%(user_id)s/edit/ips/delete', ['user_id']);
90 pyroutes.register('edit_user_ips_delete', '/_admin/users/%(user_id)s/edit/ips/delete', ['user_id']);
82 pyroutes.register('edit_user_perms_summary', '/_admin/users/%(user_id)s/edit/permissions_summary', ['user_id']);
91 pyroutes.register('edit_user_perms_summary', '/_admin/users/%(user_id)s/edit/permissions_summary', ['user_id']);
83 pyroutes.register('edit_user_perms_summary_json', '/_admin/users/%(user_id)s/edit/permissions_summary/json', ['user_id']);
92 pyroutes.register('edit_user_perms_summary_json', '/_admin/users/%(user_id)s/edit/permissions_summary/json', ['user_id']);
84 pyroutes.register('edit_user_groups_management', '/_admin/users/%(user_id)s/edit/groups_management', ['user_id']);
93 pyroutes.register('edit_user_groups_management', '/_admin/users/%(user_id)s/edit/groups_management', ['user_id']);
85 pyroutes.register('edit_user_groups_management_updates', '/_admin/users/%(user_id)s/edit/edit_user_groups_management/updates', ['user_id']);
94 pyroutes.register('edit_user_groups_management_updates', '/_admin/users/%(user_id)s/edit/edit_user_groups_management/updates', ['user_id']);
86 pyroutes.register('edit_user_audit_logs', '/_admin/users/%(user_id)s/edit/audit', ['user_id']);
95 pyroutes.register('edit_user_audit_logs', '/_admin/users/%(user_id)s/edit/audit', ['user_id']);
87 pyroutes.register('user_groups', '/_admin/user_groups', []);
96 pyroutes.register('user_groups', '/_admin/user_groups', []);
88 pyroutes.register('user_groups_data', '/_admin/user_groups_data', []);
97 pyroutes.register('user_groups_data', '/_admin/user_groups_data', []);
89 pyroutes.register('user_groups_new', '/_admin/user_groups/new', []);
98 pyroutes.register('user_groups_new', '/_admin/user_groups/new', []);
90 pyroutes.register('user_groups_create', '/_admin/user_groups/create', []);
99 pyroutes.register('user_groups_create', '/_admin/user_groups/create', []);
91 pyroutes.register('repos', '/_admin/repos', []);
100 pyroutes.register('repos', '/_admin/repos', []);
92 pyroutes.register('repo_new', '/_admin/repos/new', []);
101 pyroutes.register('repo_new', '/_admin/repos/new', []);
93 pyroutes.register('repo_create', '/_admin/repos/create', []);
102 pyroutes.register('repo_create', '/_admin/repos/create', []);
94 pyroutes.register('channelstream_connect', '/_admin/channelstream/connect', []);
103 pyroutes.register('channelstream_connect', '/_admin/channelstream/connect', []);
95 pyroutes.register('channelstream_subscribe', '/_admin/channelstream/subscribe', []);
104 pyroutes.register('channelstream_subscribe', '/_admin/channelstream/subscribe', []);
96 pyroutes.register('channelstream_proxy', '/_channelstream', []);
105 pyroutes.register('channelstream_proxy', '/_channelstream', []);
97 pyroutes.register('login', '/_admin/login', []);
106 pyroutes.register('login', '/_admin/login', []);
98 pyroutes.register('logout', '/_admin/logout', []);
107 pyroutes.register('logout', '/_admin/logout', []);
99 pyroutes.register('register', '/_admin/register', []);
108 pyroutes.register('register', '/_admin/register', []);
100 pyroutes.register('reset_password', '/_admin/password_reset', []);
109 pyroutes.register('reset_password', '/_admin/password_reset', []);
101 pyroutes.register('reset_password_confirmation', '/_admin/password_reset_confirmation', []);
110 pyroutes.register('reset_password_confirmation', '/_admin/password_reset_confirmation', []);
102 pyroutes.register('home', '/', []);
111 pyroutes.register('home', '/', []);
103 pyroutes.register('user_autocomplete_data', '/_users', []);
112 pyroutes.register('user_autocomplete_data', '/_users', []);
104 pyroutes.register('user_group_autocomplete_data', '/_user_groups', []);
113 pyroutes.register('user_group_autocomplete_data', '/_user_groups', []);
105 pyroutes.register('repo_list_data', '/_repos', []);
114 pyroutes.register('repo_list_data', '/_repos', []);
106 pyroutes.register('goto_switcher_data', '/_goto_data', []);
115 pyroutes.register('goto_switcher_data', '/_goto_data', []);
107 pyroutes.register('journal', '/_admin/journal', []);
116 pyroutes.register('journal', '/_admin/journal', []);
108 pyroutes.register('journal_rss', '/_admin/journal/rss', []);
117 pyroutes.register('journal_rss', '/_admin/journal/rss', []);
109 pyroutes.register('journal_atom', '/_admin/journal/atom', []);
118 pyroutes.register('journal_atom', '/_admin/journal/atom', []);
110 pyroutes.register('journal_public', '/_admin/public_journal', []);
119 pyroutes.register('journal_public', '/_admin/public_journal', []);
111 pyroutes.register('journal_public_atom', '/_admin/public_journal/atom', []);
120 pyroutes.register('journal_public_atom', '/_admin/public_journal/atom', []);
112 pyroutes.register('journal_public_atom_old', '/_admin/public_journal_atom', []);
121 pyroutes.register('journal_public_atom_old', '/_admin/public_journal_atom', []);
113 pyroutes.register('journal_public_rss', '/_admin/public_journal/rss', []);
122 pyroutes.register('journal_public_rss', '/_admin/public_journal/rss', []);
114 pyroutes.register('journal_public_rss_old', '/_admin/public_journal_rss', []);
123 pyroutes.register('journal_public_rss_old', '/_admin/public_journal_rss', []);
115 pyroutes.register('toggle_following', '/_admin/toggle_following', []);
124 pyroutes.register('toggle_following', '/_admin/toggle_following', []);
116 pyroutes.register('repo_creating', '/%(repo_name)s/repo_creating', ['repo_name']);
125 pyroutes.register('repo_creating', '/%(repo_name)s/repo_creating', ['repo_name']);
117 pyroutes.register('repo_creating_check', '/%(repo_name)s/repo_creating_check', ['repo_name']);
126 pyroutes.register('repo_creating_check', '/%(repo_name)s/repo_creating_check', ['repo_name']);
118 pyroutes.register('repo_summary_explicit', '/%(repo_name)s/summary', ['repo_name']);
127 pyroutes.register('repo_summary_explicit', '/%(repo_name)s/summary', ['repo_name']);
119 pyroutes.register('repo_summary_commits', '/%(repo_name)s/summary-commits', ['repo_name']);
128 pyroutes.register('repo_summary_commits', '/%(repo_name)s/summary-commits', ['repo_name']);
120 pyroutes.register('repo_commit', '/%(repo_name)s/changeset/%(commit_id)s', ['repo_name', 'commit_id']);
129 pyroutes.register('repo_commit', '/%(repo_name)s/changeset/%(commit_id)s', ['repo_name', 'commit_id']);
121 pyroutes.register('repo_commit_children', '/%(repo_name)s/changeset_children/%(commit_id)s', ['repo_name', 'commit_id']);
130 pyroutes.register('repo_commit_children', '/%(repo_name)s/changeset_children/%(commit_id)s', ['repo_name', 'commit_id']);
122 pyroutes.register('repo_commit_parents', '/%(repo_name)s/changeset_parents/%(commit_id)s', ['repo_name', 'commit_id']);
131 pyroutes.register('repo_commit_parents', '/%(repo_name)s/changeset_parents/%(commit_id)s', ['repo_name', 'commit_id']);
123 pyroutes.register('repo_commit_raw', '/%(repo_name)s/changeset-diff/%(commit_id)s', ['repo_name', 'commit_id']);
132 pyroutes.register('repo_commit_raw', '/%(repo_name)s/changeset-diff/%(commit_id)s', ['repo_name', 'commit_id']);
124 pyroutes.register('repo_commit_patch', '/%(repo_name)s/changeset-patch/%(commit_id)s', ['repo_name', 'commit_id']);
133 pyroutes.register('repo_commit_patch', '/%(repo_name)s/changeset-patch/%(commit_id)s', ['repo_name', 'commit_id']);
125 pyroutes.register('repo_commit_download', '/%(repo_name)s/changeset-download/%(commit_id)s', ['repo_name', 'commit_id']);
134 pyroutes.register('repo_commit_download', '/%(repo_name)s/changeset-download/%(commit_id)s', ['repo_name', 'commit_id']);
126 pyroutes.register('repo_commit_data', '/%(repo_name)s/changeset-data/%(commit_id)s', ['repo_name', 'commit_id']);
135 pyroutes.register('repo_commit_data', '/%(repo_name)s/changeset-data/%(commit_id)s', ['repo_name', 'commit_id']);
127 pyroutes.register('repo_commit_comment_create', '/%(repo_name)s/changeset/%(commit_id)s/comment/create', ['repo_name', 'commit_id']);
136 pyroutes.register('repo_commit_comment_create', '/%(repo_name)s/changeset/%(commit_id)s/comment/create', ['repo_name', 'commit_id']);
128 pyroutes.register('repo_commit_comment_preview', '/%(repo_name)s/changeset/%(commit_id)s/comment/preview', ['repo_name', 'commit_id']);
137 pyroutes.register('repo_commit_comment_preview', '/%(repo_name)s/changeset/%(commit_id)s/comment/preview', ['repo_name', 'commit_id']);
129 pyroutes.register('repo_commit_comment_delete', '/%(repo_name)s/changeset/%(commit_id)s/comment/%(comment_id)s/delete', ['repo_name', 'commit_id', 'comment_id']);
138 pyroutes.register('repo_commit_comment_delete', '/%(repo_name)s/changeset/%(commit_id)s/comment/%(comment_id)s/delete', ['repo_name', 'commit_id', 'comment_id']);
130 pyroutes.register('repo_commit_raw_deprecated', '/%(repo_name)s/raw-changeset/%(commit_id)s', ['repo_name', 'commit_id']);
139 pyroutes.register('repo_commit_raw_deprecated', '/%(repo_name)s/raw-changeset/%(commit_id)s', ['repo_name', 'commit_id']);
131 pyroutes.register('repo_archivefile', '/%(repo_name)s/archive/%(fname)s', ['repo_name', 'fname']);
140 pyroutes.register('repo_archivefile', '/%(repo_name)s/archive/%(fname)s', ['repo_name', 'fname']);
132 pyroutes.register('repo_files_diff', '/%(repo_name)s/diff/%(f_path)s', ['repo_name', 'f_path']);
141 pyroutes.register('repo_files_diff', '/%(repo_name)s/diff/%(f_path)s', ['repo_name', 'f_path']);
133 pyroutes.register('repo_files_diff_2way_redirect', '/%(repo_name)s/diff-2way/%(f_path)s', ['repo_name', 'f_path']);
142 pyroutes.register('repo_files_diff_2way_redirect', '/%(repo_name)s/diff-2way/%(f_path)s', ['repo_name', 'f_path']);
134 pyroutes.register('repo_files', '/%(repo_name)s/files/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
143 pyroutes.register('repo_files', '/%(repo_name)s/files/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
135 pyroutes.register('repo_files:default_path', '/%(repo_name)s/files/%(commit_id)s/', ['repo_name', 'commit_id']);
144 pyroutes.register('repo_files:default_path', '/%(repo_name)s/files/%(commit_id)s/', ['repo_name', 'commit_id']);
136 pyroutes.register('repo_files:default_commit', '/%(repo_name)s/files', ['repo_name']);
145 pyroutes.register('repo_files:default_commit', '/%(repo_name)s/files', ['repo_name']);
137 pyroutes.register('repo_files:rendered', '/%(repo_name)s/render/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
146 pyroutes.register('repo_files:rendered', '/%(repo_name)s/render/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
138 pyroutes.register('repo_files:annotated', '/%(repo_name)s/annotate/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
147 pyroutes.register('repo_files:annotated', '/%(repo_name)s/annotate/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
139 pyroutes.register('repo_files:annotated_previous', '/%(repo_name)s/annotate-previous/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
148 pyroutes.register('repo_files:annotated_previous', '/%(repo_name)s/annotate-previous/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
140 pyroutes.register('repo_nodetree_full', '/%(repo_name)s/nodetree_full/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
149 pyroutes.register('repo_nodetree_full', '/%(repo_name)s/nodetree_full/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
141 pyroutes.register('repo_nodetree_full:default_path', '/%(repo_name)s/nodetree_full/%(commit_id)s/', ['repo_name', 'commit_id']);
150 pyroutes.register('repo_nodetree_full:default_path', '/%(repo_name)s/nodetree_full/%(commit_id)s/', ['repo_name', 'commit_id']);
142 pyroutes.register('repo_files_nodelist', '/%(repo_name)s/nodelist/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
151 pyroutes.register('repo_files_nodelist', '/%(repo_name)s/nodelist/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
143 pyroutes.register('repo_file_raw', '/%(repo_name)s/raw/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
152 pyroutes.register('repo_file_raw', '/%(repo_name)s/raw/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
144 pyroutes.register('repo_file_download', '/%(repo_name)s/download/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
153 pyroutes.register('repo_file_download', '/%(repo_name)s/download/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
145 pyroutes.register('repo_file_download:legacy', '/%(repo_name)s/rawfile/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
154 pyroutes.register('repo_file_download:legacy', '/%(repo_name)s/rawfile/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
146 pyroutes.register('repo_file_history', '/%(repo_name)s/history/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
155 pyroutes.register('repo_file_history', '/%(repo_name)s/history/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
147 pyroutes.register('repo_file_authors', '/%(repo_name)s/authors/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
156 pyroutes.register('repo_file_authors', '/%(repo_name)s/authors/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
148 pyroutes.register('repo_files_remove_file', '/%(repo_name)s/remove_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
157 pyroutes.register('repo_files_remove_file', '/%(repo_name)s/remove_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
149 pyroutes.register('repo_files_delete_file', '/%(repo_name)s/delete_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
158 pyroutes.register('repo_files_delete_file', '/%(repo_name)s/delete_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
150 pyroutes.register('repo_files_edit_file', '/%(repo_name)s/edit_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
159 pyroutes.register('repo_files_edit_file', '/%(repo_name)s/edit_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
151 pyroutes.register('repo_files_update_file', '/%(repo_name)s/update_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
160 pyroutes.register('repo_files_update_file', '/%(repo_name)s/update_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
152 pyroutes.register('repo_files_add_file', '/%(repo_name)s/add_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
161 pyroutes.register('repo_files_add_file', '/%(repo_name)s/add_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
153 pyroutes.register('repo_files_create_file', '/%(repo_name)s/create_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
162 pyroutes.register('repo_files_create_file', '/%(repo_name)s/create_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
154 pyroutes.register('repo_refs_data', '/%(repo_name)s/refs-data', ['repo_name']);
163 pyroutes.register('repo_refs_data', '/%(repo_name)s/refs-data', ['repo_name']);
155 pyroutes.register('repo_refs_changelog_data', '/%(repo_name)s/refs-data-changelog', ['repo_name']);
164 pyroutes.register('repo_refs_changelog_data', '/%(repo_name)s/refs-data-changelog', ['repo_name']);
156 pyroutes.register('repo_stats', '/%(repo_name)s/repo_stats/%(commit_id)s', ['repo_name', 'commit_id']);
165 pyroutes.register('repo_stats', '/%(repo_name)s/repo_stats/%(commit_id)s', ['repo_name', 'commit_id']);
157 pyroutes.register('repo_changelog', '/%(repo_name)s/changelog', ['repo_name']);
166 pyroutes.register('repo_changelog', '/%(repo_name)s/changelog', ['repo_name']);
158 pyroutes.register('repo_changelog_file', '/%(repo_name)s/changelog/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
167 pyroutes.register('repo_changelog_file', '/%(repo_name)s/changelog/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
159 pyroutes.register('repo_changelog_elements', '/%(repo_name)s/changelog_elements', ['repo_name']);
168 pyroutes.register('repo_changelog_elements', '/%(repo_name)s/changelog_elements', ['repo_name']);
160 pyroutes.register('repo_compare_select', '/%(repo_name)s/compare', ['repo_name']);
169 pyroutes.register('repo_compare_select', '/%(repo_name)s/compare', ['repo_name']);
161 pyroutes.register('repo_compare', '/%(repo_name)s/compare/%(source_ref_type)s@%(source_ref)s...%(target_ref_type)s@%(target_ref)s', ['repo_name', 'source_ref_type', 'source_ref', 'target_ref_type', 'target_ref']);
170 pyroutes.register('repo_compare', '/%(repo_name)s/compare/%(source_ref_type)s@%(source_ref)s...%(target_ref_type)s@%(target_ref)s', ['repo_name', 'source_ref_type', 'source_ref', 'target_ref_type', 'target_ref']);
162 pyroutes.register('tags_home', '/%(repo_name)s/tags', ['repo_name']);
171 pyroutes.register('tags_home', '/%(repo_name)s/tags', ['repo_name']);
163 pyroutes.register('branches_home', '/%(repo_name)s/branches', ['repo_name']);
172 pyroutes.register('branches_home', '/%(repo_name)s/branches', ['repo_name']);
164 pyroutes.register('bookmarks_home', '/%(repo_name)s/bookmarks', ['repo_name']);
173 pyroutes.register('bookmarks_home', '/%(repo_name)s/bookmarks', ['repo_name']);
165 pyroutes.register('repo_fork_new', '/%(repo_name)s/fork', ['repo_name']);
174 pyroutes.register('repo_fork_new', '/%(repo_name)s/fork', ['repo_name']);
166 pyroutes.register('repo_fork_create', '/%(repo_name)s/fork/create', ['repo_name']);
175 pyroutes.register('repo_fork_create', '/%(repo_name)s/fork/create', ['repo_name']);
167 pyroutes.register('repo_forks_show_all', '/%(repo_name)s/forks', ['repo_name']);
176 pyroutes.register('repo_forks_show_all', '/%(repo_name)s/forks', ['repo_name']);
168 pyroutes.register('repo_forks_data', '/%(repo_name)s/forks/data', ['repo_name']);
177 pyroutes.register('repo_forks_data', '/%(repo_name)s/forks/data', ['repo_name']);
169 pyroutes.register('pullrequest_show', '/%(repo_name)s/pull-request/%(pull_request_id)s', ['repo_name', 'pull_request_id']);
178 pyroutes.register('pullrequest_show', '/%(repo_name)s/pull-request/%(pull_request_id)s', ['repo_name', 'pull_request_id']);
170 pyroutes.register('pullrequest_show_all', '/%(repo_name)s/pull-request', ['repo_name']);
179 pyroutes.register('pullrequest_show_all', '/%(repo_name)s/pull-request', ['repo_name']);
171 pyroutes.register('pullrequest_show_all_data', '/%(repo_name)s/pull-request-data', ['repo_name']);
180 pyroutes.register('pullrequest_show_all_data', '/%(repo_name)s/pull-request-data', ['repo_name']);
172 pyroutes.register('pullrequest_repo_refs', '/%(repo_name)s/pull-request/refs/%(target_repo_name)s', ['repo_name', 'target_repo_name']);
181 pyroutes.register('pullrequest_repo_refs', '/%(repo_name)s/pull-request/refs/%(target_repo_name)s', ['repo_name', 'target_repo_name']);
173 pyroutes.register('pullrequest_repo_destinations', '/%(repo_name)s/pull-request/repo-destinations', ['repo_name']);
182 pyroutes.register('pullrequest_repo_destinations', '/%(repo_name)s/pull-request/repo-destinations', ['repo_name']);
174 pyroutes.register('pullrequest_new', '/%(repo_name)s/pull-request/new', ['repo_name']);
183 pyroutes.register('pullrequest_new', '/%(repo_name)s/pull-request/new', ['repo_name']);
175 pyroutes.register('pullrequest_create', '/%(repo_name)s/pull-request/create', ['repo_name']);
184 pyroutes.register('pullrequest_create', '/%(repo_name)s/pull-request/create', ['repo_name']);
176 pyroutes.register('pullrequest_update', '/%(repo_name)s/pull-request/%(pull_request_id)s/update', ['repo_name', 'pull_request_id']);
185 pyroutes.register('pullrequest_update', '/%(repo_name)s/pull-request/%(pull_request_id)s/update', ['repo_name', 'pull_request_id']);
177 pyroutes.register('pullrequest_merge', '/%(repo_name)s/pull-request/%(pull_request_id)s/merge', ['repo_name', 'pull_request_id']);
186 pyroutes.register('pullrequest_merge', '/%(repo_name)s/pull-request/%(pull_request_id)s/merge', ['repo_name', 'pull_request_id']);
178 pyroutes.register('pullrequest_delete', '/%(repo_name)s/pull-request/%(pull_request_id)s/delete', ['repo_name', 'pull_request_id']);
187 pyroutes.register('pullrequest_delete', '/%(repo_name)s/pull-request/%(pull_request_id)s/delete', ['repo_name', 'pull_request_id']);
179 pyroutes.register('pullrequest_comment_create', '/%(repo_name)s/pull-request/%(pull_request_id)s/comment', ['repo_name', 'pull_request_id']);
188 pyroutes.register('pullrequest_comment_create', '/%(repo_name)s/pull-request/%(pull_request_id)s/comment', ['repo_name', 'pull_request_id']);
180 pyroutes.register('pullrequest_comment_delete', '/%(repo_name)s/pull-request/%(pull_request_id)s/comment/%(comment_id)s/delete', ['repo_name', 'pull_request_id', 'comment_id']);
189 pyroutes.register('pullrequest_comment_delete', '/%(repo_name)s/pull-request/%(pull_request_id)s/comment/%(comment_id)s/delete', ['repo_name', 'pull_request_id', 'comment_id']);
181 pyroutes.register('edit_repo', '/%(repo_name)s/settings', ['repo_name']);
190 pyroutes.register('edit_repo', '/%(repo_name)s/settings', ['repo_name']);
182 pyroutes.register('edit_repo_advanced', '/%(repo_name)s/settings/advanced', ['repo_name']);
191 pyroutes.register('edit_repo_advanced', '/%(repo_name)s/settings/advanced', ['repo_name']);
183 pyroutes.register('edit_repo_advanced_delete', '/%(repo_name)s/settings/advanced/delete', ['repo_name']);
192 pyroutes.register('edit_repo_advanced_delete', '/%(repo_name)s/settings/advanced/delete', ['repo_name']);
184 pyroutes.register('edit_repo_advanced_locking', '/%(repo_name)s/settings/advanced/locking', ['repo_name']);
193 pyroutes.register('edit_repo_advanced_locking', '/%(repo_name)s/settings/advanced/locking', ['repo_name']);
185 pyroutes.register('edit_repo_advanced_journal', '/%(repo_name)s/settings/advanced/journal', ['repo_name']);
194 pyroutes.register('edit_repo_advanced_journal', '/%(repo_name)s/settings/advanced/journal', ['repo_name']);
186 pyroutes.register('edit_repo_advanced_fork', '/%(repo_name)s/settings/advanced/fork', ['repo_name']);
195 pyroutes.register('edit_repo_advanced_fork', '/%(repo_name)s/settings/advanced/fork', ['repo_name']);
187 pyroutes.register('edit_repo_caches', '/%(repo_name)s/settings/caches', ['repo_name']);
196 pyroutes.register('edit_repo_caches', '/%(repo_name)s/settings/caches', ['repo_name']);
188 pyroutes.register('edit_repo_perms', '/%(repo_name)s/settings/permissions', ['repo_name']);
197 pyroutes.register('edit_repo_perms', '/%(repo_name)s/settings/permissions', ['repo_name']);
189 pyroutes.register('edit_repo_maintenance', '/%(repo_name)s/settings/maintenance', ['repo_name']);
198 pyroutes.register('edit_repo_maintenance', '/%(repo_name)s/settings/maintenance', ['repo_name']);
190 pyroutes.register('edit_repo_maintenance_execute', '/%(repo_name)s/settings/maintenance/execute', ['repo_name']);
199 pyroutes.register('edit_repo_maintenance_execute', '/%(repo_name)s/settings/maintenance/execute', ['repo_name']);
191 pyroutes.register('edit_repo_fields', '/%(repo_name)s/settings/fields', ['repo_name']);
200 pyroutes.register('edit_repo_fields', '/%(repo_name)s/settings/fields', ['repo_name']);
192 pyroutes.register('edit_repo_fields_create', '/%(repo_name)s/settings/fields/create', ['repo_name']);
201 pyroutes.register('edit_repo_fields_create', '/%(repo_name)s/settings/fields/create', ['repo_name']);
193 pyroutes.register('edit_repo_fields_delete', '/%(repo_name)s/settings/fields/%(field_id)s/delete', ['repo_name', 'field_id']);
202 pyroutes.register('edit_repo_fields_delete', '/%(repo_name)s/settings/fields/%(field_id)s/delete', ['repo_name', 'field_id']);
194 pyroutes.register('repo_edit_toggle_locking', '/%(repo_name)s/settings/toggle_locking', ['repo_name']);
203 pyroutes.register('repo_edit_toggle_locking', '/%(repo_name)s/settings/toggle_locking', ['repo_name']);
195 pyroutes.register('edit_repo_remote', '/%(repo_name)s/settings/remote', ['repo_name']);
204 pyroutes.register('edit_repo_remote', '/%(repo_name)s/settings/remote', ['repo_name']);
196 pyroutes.register('edit_repo_remote_pull', '/%(repo_name)s/settings/remote/pull', ['repo_name']);
205 pyroutes.register('edit_repo_remote_pull', '/%(repo_name)s/settings/remote/pull', ['repo_name']);
197 pyroutes.register('edit_repo_statistics', '/%(repo_name)s/settings/statistics', ['repo_name']);
206 pyroutes.register('edit_repo_statistics', '/%(repo_name)s/settings/statistics', ['repo_name']);
198 pyroutes.register('edit_repo_statistics_reset', '/%(repo_name)s/settings/statistics/update', ['repo_name']);
207 pyroutes.register('edit_repo_statistics_reset', '/%(repo_name)s/settings/statistics/update', ['repo_name']);
199 pyroutes.register('edit_repo_issuetracker', '/%(repo_name)s/settings/issue_trackers', ['repo_name']);
208 pyroutes.register('edit_repo_issuetracker', '/%(repo_name)s/settings/issue_trackers', ['repo_name']);
200 pyroutes.register('edit_repo_issuetracker_test', '/%(repo_name)s/settings/issue_trackers/test', ['repo_name']);
209 pyroutes.register('edit_repo_issuetracker_test', '/%(repo_name)s/settings/issue_trackers/test', ['repo_name']);
201 pyroutes.register('edit_repo_issuetracker_delete', '/%(repo_name)s/settings/issue_trackers/delete', ['repo_name']);
210 pyroutes.register('edit_repo_issuetracker_delete', '/%(repo_name)s/settings/issue_trackers/delete', ['repo_name']);
202 pyroutes.register('edit_repo_issuetracker_update', '/%(repo_name)s/settings/issue_trackers/update', ['repo_name']);
211 pyroutes.register('edit_repo_issuetracker_update', '/%(repo_name)s/settings/issue_trackers/update', ['repo_name']);
203 pyroutes.register('edit_repo_vcs', '/%(repo_name)s/settings/vcs', ['repo_name']);
212 pyroutes.register('edit_repo_vcs', '/%(repo_name)s/settings/vcs', ['repo_name']);
204 pyroutes.register('edit_repo_vcs_update', '/%(repo_name)s/settings/vcs/update', ['repo_name']);
213 pyroutes.register('edit_repo_vcs_update', '/%(repo_name)s/settings/vcs/update', ['repo_name']);
205 pyroutes.register('edit_repo_vcs_svn_pattern_delete', '/%(repo_name)s/settings/vcs/svn_pattern/delete', ['repo_name']);
214 pyroutes.register('edit_repo_vcs_svn_pattern_delete', '/%(repo_name)s/settings/vcs/svn_pattern/delete', ['repo_name']);
206 pyroutes.register('repo_reviewers', '/%(repo_name)s/settings/review/rules', ['repo_name']);
215 pyroutes.register('repo_reviewers', '/%(repo_name)s/settings/review/rules', ['repo_name']);
207 pyroutes.register('repo_default_reviewers_data', '/%(repo_name)s/settings/review/default-reviewers', ['repo_name']);
216 pyroutes.register('repo_default_reviewers_data', '/%(repo_name)s/settings/review/default-reviewers', ['repo_name']);
208 pyroutes.register('edit_repo_strip', '/%(repo_name)s/settings/strip', ['repo_name']);
217 pyroutes.register('edit_repo_strip', '/%(repo_name)s/settings/strip', ['repo_name']);
209 pyroutes.register('strip_check', '/%(repo_name)s/settings/strip_check', ['repo_name']);
218 pyroutes.register('strip_check', '/%(repo_name)s/settings/strip_check', ['repo_name']);
210 pyroutes.register('strip_execute', '/%(repo_name)s/settings/strip_execute', ['repo_name']);
219 pyroutes.register('strip_execute', '/%(repo_name)s/settings/strip_execute', ['repo_name']);
211 pyroutes.register('rss_feed_home', '/%(repo_name)s/feed/rss', ['repo_name']);
220 pyroutes.register('rss_feed_home', '/%(repo_name)s/feed/rss', ['repo_name']);
212 pyroutes.register('atom_feed_home', '/%(repo_name)s/feed/atom', ['repo_name']);
221 pyroutes.register('atom_feed_home', '/%(repo_name)s/feed/atom', ['repo_name']);
213 pyroutes.register('repo_summary', '/%(repo_name)s', ['repo_name']);
222 pyroutes.register('repo_summary', '/%(repo_name)s', ['repo_name']);
214 pyroutes.register('repo_summary_slash', '/%(repo_name)s/', ['repo_name']);
223 pyroutes.register('repo_summary_slash', '/%(repo_name)s/', ['repo_name']);
215 pyroutes.register('repo_group_home', '/%(repo_group_name)s', ['repo_group_name']);
224 pyroutes.register('repo_group_home', '/%(repo_group_name)s', ['repo_group_name']);
216 pyroutes.register('repo_group_home_slash', '/%(repo_group_name)s/', ['repo_group_name']);
225 pyroutes.register('repo_group_home_slash', '/%(repo_group_name)s/', ['repo_group_name']);
217 pyroutes.register('user_group_members_data', '/_admin/user_groups/%(user_group_id)s/members', ['user_group_id']);
226 pyroutes.register('user_group_members_data', '/_admin/user_groups/%(user_group_id)s/members', ['user_group_id']);
218 pyroutes.register('edit_user_group_perms_summary', '/_admin/user_groups/%(user_group_id)s/edit/permissions_summary', ['user_group_id']);
227 pyroutes.register('edit_user_group_perms_summary', '/_admin/user_groups/%(user_group_id)s/edit/permissions_summary', ['user_group_id']);
219 pyroutes.register('edit_user_group_perms_summary_json', '/_admin/user_groups/%(user_group_id)s/edit/permissions_summary/json', ['user_group_id']);
228 pyroutes.register('edit_user_group_perms_summary_json', '/_admin/user_groups/%(user_group_id)s/edit/permissions_summary/json', ['user_group_id']);
220 pyroutes.register('edit_user_group', '/_admin/user_groups/%(user_group_id)s/edit', ['user_group_id']);
229 pyroutes.register('edit_user_group', '/_admin/user_groups/%(user_group_id)s/edit', ['user_group_id']);
221 pyroutes.register('user_groups_update', '/_admin/user_groups/%(user_group_id)s/update', ['user_group_id']);
230 pyroutes.register('user_groups_update', '/_admin/user_groups/%(user_group_id)s/update', ['user_group_id']);
222 pyroutes.register('edit_user_group_global_perms', '/_admin/user_groups/%(user_group_id)s/edit/global_permissions', ['user_group_id']);
231 pyroutes.register('edit_user_group_global_perms', '/_admin/user_groups/%(user_group_id)s/edit/global_permissions', ['user_group_id']);
223 pyroutes.register('edit_user_group_global_perms_update', '/_admin/user_groups/%(user_group_id)s/edit/global_permissions/update', ['user_group_id']);
232 pyroutes.register('edit_user_group_global_perms_update', '/_admin/user_groups/%(user_group_id)s/edit/global_permissions/update', ['user_group_id']);
224 pyroutes.register('edit_user_group_perms', '/_admin/user_groups/%(user_group_id)s/edit/permissions', ['user_group_id']);
233 pyroutes.register('edit_user_group_perms', '/_admin/user_groups/%(user_group_id)s/edit/permissions', ['user_group_id']);
225 pyroutes.register('edit_user_group_perms_update', '/_admin/user_groups/%(user_group_id)s/edit/permissions/update', ['user_group_id']);
234 pyroutes.register('edit_user_group_perms_update', '/_admin/user_groups/%(user_group_id)s/edit/permissions/update', ['user_group_id']);
226 pyroutes.register('edit_user_group_advanced', '/_admin/user_groups/%(user_group_id)s/edit/advanced', ['user_group_id']);
235 pyroutes.register('edit_user_group_advanced', '/_admin/user_groups/%(user_group_id)s/edit/advanced', ['user_group_id']);
227 pyroutes.register('edit_user_group_advanced_sync', '/_admin/user_groups/%(user_group_id)s/edit/advanced/sync', ['user_group_id']);
236 pyroutes.register('edit_user_group_advanced_sync', '/_admin/user_groups/%(user_group_id)s/edit/advanced/sync', ['user_group_id']);
228 pyroutes.register('user_groups_delete', '/_admin/user_groups/%(user_group_id)s/delete', ['user_group_id']);
237 pyroutes.register('user_groups_delete', '/_admin/user_groups/%(user_group_id)s/delete', ['user_group_id']);
229 pyroutes.register('search', '/_admin/search', []);
238 pyroutes.register('search', '/_admin/search', []);
230 pyroutes.register('search_repo', '/%(repo_name)s/search', ['repo_name']);
239 pyroutes.register('search_repo', '/%(repo_name)s/search', ['repo_name']);
231 pyroutes.register('user_profile', '/_profiles/%(username)s', ['username']);
240 pyroutes.register('user_profile', '/_profiles/%(username)s', ['username']);
232 pyroutes.register('my_account_profile', '/_admin/my_account/profile', []);
241 pyroutes.register('my_account_profile', '/_admin/my_account/profile', []);
233 pyroutes.register('my_account_edit', '/_admin/my_account/edit', []);
242 pyroutes.register('my_account_edit', '/_admin/my_account/edit', []);
234 pyroutes.register('my_account_update', '/_admin/my_account/update', []);
243 pyroutes.register('my_account_update', '/_admin/my_account/update', []);
235 pyroutes.register('my_account_password', '/_admin/my_account/password', []);
244 pyroutes.register('my_account_password', '/_admin/my_account/password', []);
236 pyroutes.register('my_account_password_update', '/_admin/my_account/password/update', []);
245 pyroutes.register('my_account_password_update', '/_admin/my_account/password/update', []);
237 pyroutes.register('my_account_auth_tokens', '/_admin/my_account/auth_tokens', []);
246 pyroutes.register('my_account_auth_tokens', '/_admin/my_account/auth_tokens', []);
238 pyroutes.register('my_account_auth_tokens_add', '/_admin/my_account/auth_tokens/new', []);
247 pyroutes.register('my_account_auth_tokens_add', '/_admin/my_account/auth_tokens/new', []);
239 pyroutes.register('my_account_auth_tokens_delete', '/_admin/my_account/auth_tokens/delete', []);
248 pyroutes.register('my_account_auth_tokens_delete', '/_admin/my_account/auth_tokens/delete', []);
240 pyroutes.register('my_account_ssh_keys', '/_admin/my_account/ssh_keys', []);
249 pyroutes.register('my_account_ssh_keys', '/_admin/my_account/ssh_keys', []);
241 pyroutes.register('my_account_ssh_keys_generate', '/_admin/my_account/ssh_keys/generate', []);
250 pyroutes.register('my_account_ssh_keys_generate', '/_admin/my_account/ssh_keys/generate', []);
242 pyroutes.register('my_account_ssh_keys_add', '/_admin/my_account/ssh_keys/new', []);
251 pyroutes.register('my_account_ssh_keys_add', '/_admin/my_account/ssh_keys/new', []);
243 pyroutes.register('my_account_ssh_keys_delete', '/_admin/my_account/ssh_keys/delete', []);
252 pyroutes.register('my_account_ssh_keys_delete', '/_admin/my_account/ssh_keys/delete', []);
244 pyroutes.register('my_account_emails', '/_admin/my_account/emails', []);
253 pyroutes.register('my_account_emails', '/_admin/my_account/emails', []);
245 pyroutes.register('my_account_emails_add', '/_admin/my_account/emails/new', []);
254 pyroutes.register('my_account_emails_add', '/_admin/my_account/emails/new', []);
246 pyroutes.register('my_account_emails_delete', '/_admin/my_account/emails/delete', []);
255 pyroutes.register('my_account_emails_delete', '/_admin/my_account/emails/delete', []);
247 pyroutes.register('my_account_repos', '/_admin/my_account/repos', []);
256 pyroutes.register('my_account_repos', '/_admin/my_account/repos', []);
248 pyroutes.register('my_account_watched', '/_admin/my_account/watched', []);
257 pyroutes.register('my_account_watched', '/_admin/my_account/watched', []);
249 pyroutes.register('my_account_perms', '/_admin/my_account/perms', []);
258 pyroutes.register('my_account_perms', '/_admin/my_account/perms', []);
250 pyroutes.register('my_account_notifications', '/_admin/my_account/notifications', []);
259 pyroutes.register('my_account_notifications', '/_admin/my_account/notifications', []);
251 pyroutes.register('my_account_notifications_toggle_visibility', '/_admin/my_account/toggle_visibility', []);
260 pyroutes.register('my_account_notifications_toggle_visibility', '/_admin/my_account/toggle_visibility', []);
252 pyroutes.register('my_account_pullrequests', '/_admin/my_account/pull_requests', []);
261 pyroutes.register('my_account_pullrequests', '/_admin/my_account/pull_requests', []);
253 pyroutes.register('my_account_pullrequests_data', '/_admin/my_account/pull_requests/data', []);
262 pyroutes.register('my_account_pullrequests_data', '/_admin/my_account/pull_requests/data', []);
254 pyroutes.register('notifications_show_all', '/_admin/notifications', []);
263 pyroutes.register('notifications_show_all', '/_admin/notifications', []);
255 pyroutes.register('notifications_mark_all_read', '/_admin/notifications/mark_all_read', []);
264 pyroutes.register('notifications_mark_all_read', '/_admin/notifications/mark_all_read', []);
256 pyroutes.register('notifications_show', '/_admin/notifications/%(notification_id)s', ['notification_id']);
265 pyroutes.register('notifications_show', '/_admin/notifications/%(notification_id)s', ['notification_id']);
257 pyroutes.register('notifications_update', '/_admin/notifications/%(notification_id)s/update', ['notification_id']);
266 pyroutes.register('notifications_update', '/_admin/notifications/%(notification_id)s/update', ['notification_id']);
258 pyroutes.register('notifications_delete', '/_admin/notifications/%(notification_id)s/delete', ['notification_id']);
267 pyroutes.register('notifications_delete', '/_admin/notifications/%(notification_id)s/delete', ['notification_id']);
259 pyroutes.register('my_account_notifications_test_channelstream', '/_admin/my_account/test_channelstream', []);
268 pyroutes.register('my_account_notifications_test_channelstream', '/_admin/my_account/test_channelstream', []);
260 pyroutes.register('gists_show', '/_admin/gists', []);
269 pyroutes.register('gists_show', '/_admin/gists', []);
261 pyroutes.register('gists_new', '/_admin/gists/new', []);
270 pyroutes.register('gists_new', '/_admin/gists/new', []);
262 pyroutes.register('gists_create', '/_admin/gists/create', []);
271 pyroutes.register('gists_create', '/_admin/gists/create', []);
263 pyroutes.register('gist_show', '/_admin/gists/%(gist_id)s', ['gist_id']);
272 pyroutes.register('gist_show', '/_admin/gists/%(gist_id)s', ['gist_id']);
264 pyroutes.register('gist_delete', '/_admin/gists/%(gist_id)s/delete', ['gist_id']);
273 pyroutes.register('gist_delete', '/_admin/gists/%(gist_id)s/delete', ['gist_id']);
265 pyroutes.register('gist_edit', '/_admin/gists/%(gist_id)s/edit', ['gist_id']);
274 pyroutes.register('gist_edit', '/_admin/gists/%(gist_id)s/edit', ['gist_id']);
266 pyroutes.register('gist_edit_check_revision', '/_admin/gists/%(gist_id)s/edit/check_revision', ['gist_id']);
275 pyroutes.register('gist_edit_check_revision', '/_admin/gists/%(gist_id)s/edit/check_revision', ['gist_id']);
267 pyroutes.register('gist_update', '/_admin/gists/%(gist_id)s/update', ['gist_id']);
276 pyroutes.register('gist_update', '/_admin/gists/%(gist_id)s/update', ['gist_id']);
268 pyroutes.register('gist_show_rev', '/_admin/gists/%(gist_id)s/%(revision)s', ['gist_id', 'revision']);
277 pyroutes.register('gist_show_rev', '/_admin/gists/%(gist_id)s/%(revision)s', ['gist_id', 'revision']);
269 pyroutes.register('gist_show_formatted', '/_admin/gists/%(gist_id)s/%(revision)s/%(format)s', ['gist_id', 'revision', 'format']);
278 pyroutes.register('gist_show_formatted', '/_admin/gists/%(gist_id)s/%(revision)s/%(format)s', ['gist_id', 'revision', 'format']);
270 pyroutes.register('gist_show_formatted_path', '/_admin/gists/%(gist_id)s/%(revision)s/%(format)s/%(f_path)s', ['gist_id', 'revision', 'format', 'f_path']);
279 pyroutes.register('gist_show_formatted_path', '/_admin/gists/%(gist_id)s/%(revision)s/%(format)s/%(f_path)s', ['gist_id', 'revision', 'format', 'f_path']);
271 pyroutes.register('debug_style_home', '/_admin/debug_style', []);
280 pyroutes.register('debug_style_home', '/_admin/debug_style', []);
272 pyroutes.register('debug_style_template', '/_admin/debug_style/t/%(t_path)s', ['t_path']);
281 pyroutes.register('debug_style_template', '/_admin/debug_style/t/%(t_path)s', ['t_path']);
273 pyroutes.register('apiv2', '/_admin/api', []);
282 pyroutes.register('apiv2', '/_admin/api', []);
274 }
283 }
@@ -1,332 +1,339 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 import io
20 import io
21 import re
21 import re
22 import datetime
22 import datetime
23 import logging
23 import logging
24 import pylons
24 import pylons
25 import Queue
25 import Queue
26 import subprocess32
26 import subprocess32
27 import os
27 import os
28
28
29 from pyramid.i18n import get_localizer
29 from pyramid.i18n import get_localizer
30 from pyramid.threadlocal import get_current_request
30 from pyramid.threadlocal import get_current_request
31 from pyramid.interfaces import IRoutesMapper
31 from pyramid.interfaces import IRoutesMapper
32 from pyramid.settings import asbool
32 from pyramid.settings import asbool
33 from pyramid.path import AssetResolver
33 from pyramid.path import AssetResolver
34 from threading import Thread
34 from threading import Thread
35
35
36 from rhodecode.translation import _ as tsf
36 from rhodecode.translation import _ as tsf
37 from rhodecode.config.jsroutes import generate_jsroutes_content
37 from rhodecode.config.jsroutes import generate_jsroutes_content
38 from rhodecode.lib import auth
38
39
39 import rhodecode
40 import rhodecode
40
41
41 from pylons.i18n.translation import _get_translator
42 from pylons.i18n.translation import _get_translator
42 from pylons.util import ContextObj
43 from pylons.util import ContextObj
43 from routes.util import URLGenerator
44 from routes.util import URLGenerator
44
45
45 from rhodecode.lib.base import attach_context_attributes, get_auth_user
46 from rhodecode.lib.base import attach_context_attributes, get_auth_user
46
47
47 log = logging.getLogger(__name__)
48 log = logging.getLogger(__name__)
48
49
49
50
50 def add_renderer_globals(event):
51 def add_renderer_globals(event):
51 from rhodecode.lib import helpers
52 from rhodecode.lib import helpers
52
53
53 # NOTE(marcink):
54 # NOTE(marcink):
54 # Put pylons stuff into the context. This will be removed as soon as
55 # Put pylons stuff into the context. This will be removed as soon as
55 # migration to pyramid is finished.
56 # migration to pyramid is finished.
56 event['c'] = pylons.tmpl_context
57 event['c'] = pylons.tmpl_context
57
58
58 # TODO: When executed in pyramid view context the request is not available
59 # TODO: When executed in pyramid view context the request is not available
59 # in the event. Find a better solution to get the request.
60 # in the event. Find a better solution to get the request.
60 request = event['request'] or get_current_request()
61 request = event['request'] or get_current_request()
61
62
62 # Add Pyramid translation as '_' to context
63 # Add Pyramid translation as '_' to context
63 event['_'] = request.translate
64 event['_'] = request.translate
64 event['_ungettext'] = request.plularize
65 event['_ungettext'] = request.plularize
65 event['h'] = helpers
66 event['h'] = helpers
66
67
67
68
68 def add_localizer(event):
69 def add_localizer(event):
69 request = event.request
70 request = event.request
70 localizer = get_localizer(request)
71 localizer = get_localizer(request)
71
72
72 def auto_translate(*args, **kwargs):
73 def auto_translate(*args, **kwargs):
73 return localizer.translate(tsf(*args, **kwargs))
74 return localizer.translate(tsf(*args, **kwargs))
74
75
75 request.localizer = localizer
76 request.localizer = localizer
76 request.translate = auto_translate
77 request.translate = auto_translate
77 request.plularize = localizer.pluralize
78 request.plularize = localizer.pluralize
78
79
79
80
80 def set_user_lang(event):
81 def set_user_lang(event):
81 request = event.request
82 request = event.request
82 cur_user = getattr(request, 'user', None)
83 cur_user = getattr(request, 'user', None)
83
84
84 if cur_user:
85 if cur_user:
85 user_lang = cur_user.get_instance().user_data.get('language')
86 user_lang = cur_user.get_instance().user_data.get('language')
86 if user_lang:
87 if user_lang:
87 log.debug('lang: setting current user:%s language to: %s', cur_user, user_lang)
88 log.debug('lang: setting current user:%s language to: %s', cur_user, user_lang)
88 event.request._LOCALE_ = user_lang
89 event.request._LOCALE_ = user_lang
89
90
90
91
91 def add_request_user_context(event):
92 def add_request_user_context(event):
92 """
93 """
93 Adds auth user into request context
94 Adds auth user into request context
94 """
95 """
95 request = event.request
96 request = event.request
96
97
97 if hasattr(request, 'vcs_call'):
98 if hasattr(request, 'vcs_call'):
98 # skip vcs calls
99 # skip vcs calls
99 return
100 return
100
101
101 if hasattr(request, 'rpc_method'):
102 if hasattr(request, 'rpc_method'):
102 # skip api calls
103 # skip api calls
103 return
104 return
104
105
105 auth_user = get_auth_user(request)
106 auth_user = get_auth_user(request)
106 request.user = auth_user
107 request.user = auth_user
107 request.environ['rc_auth_user'] = auth_user
108 request.environ['rc_auth_user'] = auth_user
108
109
109
110
110 def add_pylons_context(event):
111 def add_pylons_context(event):
111 request = event.request
112 request = event.request
112
113
113 config = rhodecode.CONFIG
114 config = rhodecode.CONFIG
114 environ = request.environ
115 environ = request.environ
115 session = request.session
116 session = request.session
116
117
117 if hasattr(request, 'vcs_call'):
118 if hasattr(request, 'vcs_call'):
118 # skip vcs calls
119 # skip vcs calls
119 return
120 return
120
121
121 # Setup pylons globals.
122 # Setup pylons globals.
122 pylons.config._push_object(config)
123 pylons.config._push_object(config)
123 pylons.request._push_object(request)
124 pylons.request._push_object(request)
124 pylons.session._push_object(session)
125 pylons.session._push_object(session)
125 pylons.translator._push_object(_get_translator(config.get('lang')))
126 pylons.translator._push_object(_get_translator(config.get('lang')))
126
127
127 pylons.url._push_object(URLGenerator(config['routes.map'], environ))
128 pylons.url._push_object(URLGenerator(config['routes.map'], environ))
128 session_key = (
129 session_key = (
129 config['pylons.environ_config'].get('session', 'beaker.session'))
130 config['pylons.environ_config'].get('session', 'beaker.session'))
130 environ[session_key] = session
131 environ[session_key] = session
131
132
132 if hasattr(request, 'rpc_method'):
133 if hasattr(request, 'rpc_method'):
133 # skip api calls
134 # skip api calls
134 return
135 return
135
136
136 # Setup the pylons context object ('c')
137 # Setup the pylons context object ('c')
137 context = ContextObj()
138 context = ContextObj()
138 context.rhodecode_user = request.user
139 context.rhodecode_user = request.user
139 attach_context_attributes(context, request, request.user.user_id)
140 attach_context_attributes(context, request, request.user.user_id)
140 pylons.tmpl_context._push_object(context)
141 pylons.tmpl_context._push_object(context)
141
142
142
143
144 def inject_app_settings(event):
145 settings = event.app.registry.settings
146 # inject info about available permissions
147 auth.set_available_permissions(settings)
148
149
143 def scan_repositories_if_enabled(event):
150 def scan_repositories_if_enabled(event):
144 """
151 """
145 This is subscribed to the `pyramid.events.ApplicationCreated` event. It
152 This is subscribed to the `pyramid.events.ApplicationCreated` event. It
146 does a repository scan if enabled in the settings.
153 does a repository scan if enabled in the settings.
147 """
154 """
148 settings = event.app.registry.settings
155 settings = event.app.registry.settings
149 vcs_server_enabled = settings['vcs.server.enable']
156 vcs_server_enabled = settings['vcs.server.enable']
150 import_on_startup = settings['startup.import_repos']
157 import_on_startup = settings['startup.import_repos']
151 if vcs_server_enabled and import_on_startup:
158 if vcs_server_enabled and import_on_startup:
152 from rhodecode.model.scm import ScmModel
159 from rhodecode.model.scm import ScmModel
153 from rhodecode.lib.utils import repo2db_mapper, get_rhodecode_base_path
160 from rhodecode.lib.utils import repo2db_mapper, get_rhodecode_base_path
154 repositories = ScmModel().repo_scan(get_rhodecode_base_path())
161 repositories = ScmModel().repo_scan(get_rhodecode_base_path())
155 repo2db_mapper(repositories, remove_obsolete=False)
162 repo2db_mapper(repositories, remove_obsolete=False)
156
163
157
164
158 def write_metadata_if_needed(event):
165 def write_metadata_if_needed(event):
159 """
166 """
160 Writes upgrade metadata
167 Writes upgrade metadata
161 """
168 """
162 import rhodecode
169 import rhodecode
163 from rhodecode.lib import system_info
170 from rhodecode.lib import system_info
164 from rhodecode.lib import ext_json
171 from rhodecode.lib import ext_json
165
172
166 def write():
173 def write():
167 fname = '.rcmetadata.json'
174 fname = '.rcmetadata.json'
168 ini_loc = os.path.dirname(rhodecode.CONFIG.get('__file__'))
175 ini_loc = os.path.dirname(rhodecode.CONFIG.get('__file__'))
169 metadata_destination = os.path.join(ini_loc, fname)
176 metadata_destination = os.path.join(ini_loc, fname)
170
177
171 configuration = system_info.SysInfo(
178 configuration = system_info.SysInfo(
172 system_info.rhodecode_config)()['value']
179 system_info.rhodecode_config)()['value']
173 license_token = configuration['config']['license_token']
180 license_token = configuration['config']['license_token']
174 dbinfo = system_info.SysInfo(system_info.database_info)()['value']
181 dbinfo = system_info.SysInfo(system_info.database_info)()['value']
175 del dbinfo['url']
182 del dbinfo['url']
176 metadata = dict(
183 metadata = dict(
177 desc='upgrade metadata info',
184 desc='upgrade metadata info',
178 license_token=license_token,
185 license_token=license_token,
179 created_on=datetime.datetime.utcnow().isoformat(),
186 created_on=datetime.datetime.utcnow().isoformat(),
180 usage=system_info.SysInfo(system_info.usage_info)()['value'],
187 usage=system_info.SysInfo(system_info.usage_info)()['value'],
181 platform=system_info.SysInfo(system_info.platform_type)()['value'],
188 platform=system_info.SysInfo(system_info.platform_type)()['value'],
182 database=dbinfo,
189 database=dbinfo,
183 cpu=system_info.SysInfo(system_info.cpu)()['value'],
190 cpu=system_info.SysInfo(system_info.cpu)()['value'],
184 memory=system_info.SysInfo(system_info.memory)()['value'],
191 memory=system_info.SysInfo(system_info.memory)()['value'],
185 )
192 )
186
193
187 with open(metadata_destination, 'wb') as f:
194 with open(metadata_destination, 'wb') as f:
188 f.write(ext_json.json.dumps(metadata))
195 f.write(ext_json.json.dumps(metadata))
189
196
190 settings = event.app.registry.settings
197 settings = event.app.registry.settings
191 if settings.get('metadata.skip'):
198 if settings.get('metadata.skip'):
192 return
199 return
193
200
194 try:
201 try:
195 write()
202 write()
196 except Exception:
203 except Exception:
197 pass
204 pass
198
205
199
206
200 def write_js_routes_if_enabled(event):
207 def write_js_routes_if_enabled(event):
201 registry = event.app.registry
208 registry = event.app.registry
202
209
203 mapper = registry.queryUtility(IRoutesMapper)
210 mapper = registry.queryUtility(IRoutesMapper)
204 _argument_prog = re.compile('\{(.*?)\}|:\((.*)\)')
211 _argument_prog = re.compile('\{(.*?)\}|:\((.*)\)')
205
212
206 def _extract_route_information(route):
213 def _extract_route_information(route):
207 """
214 """
208 Convert a route into tuple(name, path, args), eg:
215 Convert a route into tuple(name, path, args), eg:
209 ('show_user', '/profile/%(username)s', ['username'])
216 ('show_user', '/profile/%(username)s', ['username'])
210 """
217 """
211
218
212 routepath = route.pattern
219 routepath = route.pattern
213 pattern = route.pattern
220 pattern = route.pattern
214
221
215 def replace(matchobj):
222 def replace(matchobj):
216 if matchobj.group(1):
223 if matchobj.group(1):
217 return "%%(%s)s" % matchobj.group(1).split(':')[0]
224 return "%%(%s)s" % matchobj.group(1).split(':')[0]
218 else:
225 else:
219 return "%%(%s)s" % matchobj.group(2)
226 return "%%(%s)s" % matchobj.group(2)
220
227
221 routepath = _argument_prog.sub(replace, routepath)
228 routepath = _argument_prog.sub(replace, routepath)
222
229
223 if not routepath.startswith('/'):
230 if not routepath.startswith('/'):
224 routepath = '/'+routepath
231 routepath = '/'+routepath
225
232
226 return (
233 return (
227 route.name,
234 route.name,
228 routepath,
235 routepath,
229 [(arg[0].split(':')[0] if arg[0] != '' else arg[1])
236 [(arg[0].split(':')[0] if arg[0] != '' else arg[1])
230 for arg in _argument_prog.findall(pattern)]
237 for arg in _argument_prog.findall(pattern)]
231 )
238 )
232
239
233 def get_routes():
240 def get_routes():
234 # pylons routes
241 # pylons routes
235 # TODO(marcink): remove when pyramid migration is finished
242 # TODO(marcink): remove when pyramid migration is finished
236 if 'routes.map' in rhodecode.CONFIG:
243 if 'routes.map' in rhodecode.CONFIG:
237 for route in rhodecode.CONFIG['routes.map'].jsroutes():
244 for route in rhodecode.CONFIG['routes.map'].jsroutes():
238 yield route
245 yield route
239
246
240 # pyramid routes
247 # pyramid routes
241 for route in mapper.get_routes():
248 for route in mapper.get_routes():
242 if not route.name.startswith('__'):
249 if not route.name.startswith('__'):
243 yield _extract_route_information(route)
250 yield _extract_route_information(route)
244
251
245 if asbool(registry.settings.get('generate_js_files', 'false')):
252 if asbool(registry.settings.get('generate_js_files', 'false')):
246 static_path = AssetResolver().resolve('rhodecode:public').abspath()
253 static_path = AssetResolver().resolve('rhodecode:public').abspath()
247 jsroutes = get_routes()
254 jsroutes = get_routes()
248 jsroutes_file_content = generate_jsroutes_content(jsroutes)
255 jsroutes_file_content = generate_jsroutes_content(jsroutes)
249 jsroutes_file_path = os.path.join(
256 jsroutes_file_path = os.path.join(
250 static_path, 'js', 'rhodecode', 'routes.js')
257 static_path, 'js', 'rhodecode', 'routes.js')
251
258
252 with io.open(jsroutes_file_path, 'w', encoding='utf-8') as f:
259 with io.open(jsroutes_file_path, 'w', encoding='utf-8') as f:
253 f.write(jsroutes_file_content)
260 f.write(jsroutes_file_content)
254
261
255
262
256 class Subscriber(object):
263 class Subscriber(object):
257 """
264 """
258 Base class for subscribers to the pyramid event system.
265 Base class for subscribers to the pyramid event system.
259 """
266 """
260 def __call__(self, event):
267 def __call__(self, event):
261 self.run(event)
268 self.run(event)
262
269
263 def run(self, event):
270 def run(self, event):
264 raise NotImplementedError('Subclass has to implement this.')
271 raise NotImplementedError('Subclass has to implement this.')
265
272
266
273
267 class AsyncSubscriber(Subscriber):
274 class AsyncSubscriber(Subscriber):
268 """
275 """
269 Subscriber that handles the execution of events in a separate task to not
276 Subscriber that handles the execution of events in a separate task to not
270 block the execution of the code which triggers the event. It puts the
277 block the execution of the code which triggers the event. It puts the
271 received events into a queue from which the worker process takes them in
278 received events into a queue from which the worker process takes them in
272 order.
279 order.
273 """
280 """
274 def __init__(self):
281 def __init__(self):
275 self._stop = False
282 self._stop = False
276 self._eventq = Queue.Queue()
283 self._eventq = Queue.Queue()
277 self._worker = self.create_worker()
284 self._worker = self.create_worker()
278 self._worker.start()
285 self._worker.start()
279
286
280 def __call__(self, event):
287 def __call__(self, event):
281 self._eventq.put(event)
288 self._eventq.put(event)
282
289
283 def create_worker(self):
290 def create_worker(self):
284 worker = Thread(target=self.do_work)
291 worker = Thread(target=self.do_work)
285 worker.daemon = True
292 worker.daemon = True
286 return worker
293 return worker
287
294
288 def stop_worker(self):
295 def stop_worker(self):
289 self._stop = False
296 self._stop = False
290 self._eventq.put(None)
297 self._eventq.put(None)
291 self._worker.join()
298 self._worker.join()
292
299
293 def do_work(self):
300 def do_work(self):
294 while not self._stop:
301 while not self._stop:
295 event = self._eventq.get()
302 event = self._eventq.get()
296 if event is not None:
303 if event is not None:
297 self.run(event)
304 self.run(event)
298
305
299
306
300 class AsyncSubprocessSubscriber(AsyncSubscriber):
307 class AsyncSubprocessSubscriber(AsyncSubscriber):
301 """
308 """
302 Subscriber that uses the subprocess32 module to execute a command if an
309 Subscriber that uses the subprocess32 module to execute a command if an
303 event is received. Events are handled asynchronously.
310 event is received. Events are handled asynchronously.
304 """
311 """
305
312
306 def __init__(self, cmd, timeout=None):
313 def __init__(self, cmd, timeout=None):
307 super(AsyncSubprocessSubscriber, self).__init__()
314 super(AsyncSubprocessSubscriber, self).__init__()
308 self._cmd = cmd
315 self._cmd = cmd
309 self._timeout = timeout
316 self._timeout = timeout
310
317
311 def run(self, event):
318 def run(self, event):
312 cmd = self._cmd
319 cmd = self._cmd
313 timeout = self._timeout
320 timeout = self._timeout
314 log.debug('Executing command %s.', cmd)
321 log.debug('Executing command %s.', cmd)
315
322
316 try:
323 try:
317 output = subprocess32.check_output(
324 output = subprocess32.check_output(
318 cmd, timeout=timeout, stderr=subprocess32.STDOUT)
325 cmd, timeout=timeout, stderr=subprocess32.STDOUT)
319 log.debug('Command finished %s', cmd)
326 log.debug('Command finished %s', cmd)
320 if output:
327 if output:
321 log.debug('Command output: %s', output)
328 log.debug('Command output: %s', output)
322 except subprocess32.TimeoutExpired as e:
329 except subprocess32.TimeoutExpired as e:
323 log.exception('Timeout while executing command.')
330 log.exception('Timeout while executing command.')
324 if e.output:
331 if e.output:
325 log.error('Command output: %s', e.output)
332 log.error('Command output: %s', e.output)
326 except subprocess32.CalledProcessError as e:
333 except subprocess32.CalledProcessError as e:
327 log.exception('Error while executing command.')
334 log.exception('Error while executing command.')
328 if e.output:
335 if e.output:
329 log.error('Command output: %s', e.output)
336 log.error('Command output: %s', e.output)
330 except:
337 except:
331 log.exception(
338 log.exception(
332 'Exception while executing command %s.', cmd)
339 'Exception while executing command %s.', cmd)
@@ -1,180 +1,179 b''
1 <div class="panel panel-default">
1 <div class="panel panel-default">
2 <div class="panel-heading">
2 <div class="panel-heading">
3 <h3 class="panel-title">${_('Authentication Tokens')}</h3>
3 <h3 class="panel-title">${_('Authentication Tokens')}</h3>
4 </div>
4 </div>
5 <div class="panel-body">
5 <div class="panel-body">
6 <div class="apikeys_wrap">
6 <div class="apikeys_wrap">
7 <p>
7 <p>
8 ${_('Each token can have a role. Token with a role can be used only in given context, '
8 ${_('Each token can have a role. Token with a role can be used only in given context, '
9 'e.g. VCS tokens can be used together with the authtoken auth plugin for git/hg/svn operations only.')}
9 'e.g. VCS tokens can be used together with the authtoken auth plugin for git/hg/svn operations only.')}
10 </p>
10 </p>
11 <table class="rctable auth_tokens">
11 <table class="rctable auth_tokens">
12 <tr>
12 <tr>
13 <th>${_('Token')}</th>
13 <th>${_('Token')}</th>
14 <th>${_('Scope')}</th>
14 <th>${_('Scope')}</th>
15 <th>${_('Description')}</th>
15 <th>${_('Description')}</th>
16 <th>${_('Role')}</th>
16 <th>${_('Role')}</th>
17 <th>${_('Expiration')}</th>
17 <th>${_('Expiration')}</th>
18 <th>${_('Action')}</th>
18 <th>${_('Action')}</th>
19 </tr>
19 </tr>
20 %if c.user_auth_tokens:
20 %if c.user_auth_tokens:
21 %for auth_token in c.user_auth_tokens:
21 %for auth_token in c.user_auth_tokens:
22 <tr class="${'expired' if auth_token.expired else ''}">
22 <tr class="${'expired' if auth_token.expired else ''}">
23 <td class="truncate-wrap td-authtoken">
23 <td class="truncate-wrap td-authtoken">
24 <div class="user_auth_tokens truncate autoexpand">
24 <div class="user_auth_tokens truncate autoexpand">
25 <code>${auth_token.api_key}</code>
25 <code>${auth_token.api_key}</code>
26 </div>
26 </div>
27 </td>
27 </td>
28 <td class="td">${auth_token.scope_humanized}</td>
28 <td class="td">${auth_token.scope_humanized}</td>
29 <td class="td-wrap">${auth_token.description}</td>
29 <td class="td-wrap">${auth_token.description}</td>
30 <td class="td-tags">
30 <td class="td-tags">
31 <span class="tag disabled">${auth_token.role_humanized}</span>
31 <span class="tag disabled">${auth_token.role_humanized}</span>
32 </td>
32 </td>
33 <td class="td-exp">
33 <td class="td-exp">
34 %if auth_token.expires == -1:
34 %if auth_token.expires == -1:
35 ${_('never')}
35 ${_('never')}
36 %else:
36 %else:
37 %if auth_token.expired:
37 %if auth_token.expired:
38 <span style="text-decoration: line-through">${h.age_component(h.time_to_utcdatetime(auth_token.expires))}</span>
38 <span style="text-decoration: line-through">${h.age_component(h.time_to_utcdatetime(auth_token.expires))}</span>
39 %else:
39 %else:
40 ${h.age_component(h.time_to_utcdatetime(auth_token.expires))}
40 ${h.age_component(h.time_to_utcdatetime(auth_token.expires))}
41 %endif
41 %endif
42 %endif
42 %endif
43 </td>
43 </td>
44 <td class="td-action">
44 <td class="td-action">
45 ${h.secure_form(h.route_path('my_account_auth_tokens_delete'), request=request)}
45 ${h.secure_form(h.route_path('my_account_auth_tokens_delete'), request=request)}
46 ${h.hidden('del_auth_token', auth_token.user_api_key_id)}
46 ${h.hidden('del_auth_token', auth_token.user_api_key_id)}
47 <button class="btn btn-link btn-danger" type="submit"
47 <button class="btn btn-link btn-danger" type="submit"
48 onclick="return confirm('${_('Confirm to remove this auth token: %s') % auth_token.token_obfuscated}');">
48 onclick="return confirm('${_('Confirm to remove this auth token: %s') % auth_token.token_obfuscated}');">
49 ${_('Delete')}
49 ${_('Delete')}
50 </button>
50 </button>
51 ${h.end_form()}
51 ${h.end_form()}
52 </td>
52 </td>
53 </tr>
53 </tr>
54 %endfor
54 %endfor
55 %else:
55 %else:
56 <tr><td><div class="ip">${_('No additional auth tokens specified')}</div></td></tr>
56 <tr><td><div class="ip">${_('No additional auth tokens specified')}</div></td></tr>
57 %endif
57 %endif
58 </table>
58 </table>
59 </div>
59 </div>
60
60
61 <div class="user_auth_tokens">
61 <div class="user_auth_tokens">
62 ${h.secure_form(h.route_path('my_account_auth_tokens_add'), request=request)}
62 ${h.secure_form(h.route_path('my_account_auth_tokens_add'), request=request)}
63 <div class="form form-vertical">
63 <div class="form form-vertical">
64 <!-- fields -->
64 <!-- fields -->
65 <div class="fields">
65 <div class="fields">
66 <div class="field">
66 <div class="field">
67 <div class="label">
67 <div class="label">
68 <label for="new_email">${_('New authentication token')}:</label>
68 <label for="new_email">${_('New authentication token')}:</label>
69 </div>
69 </div>
70 <div class="input">
70 <div class="input">
71 ${h.text('description', class_='medium', placeholder=_('Description'))}
71 ${h.text('description', class_='medium', placeholder=_('Description'))}
72 ${h.hidden('lifetime')}
72 ${h.hidden('lifetime')}
73 ${h.select('role', '', c.role_options)}
73 ${h.select('role', '', c.role_options)}
74
74
75 % if c.allow_scoped_tokens:
75 % if c.allow_scoped_tokens:
76 ${h.hidden('scope_repo_id')}
76 ${h.hidden('scope_repo_id')}
77 % else:
77 % else:
78 ${h.select('scope_repo_id_disabled', '', ['Scopes available in EE edition'], disabled='disabled')}
78 ${h.select('scope_repo_id_disabled', '', ['Scopes available in EE edition'], disabled='disabled')}
79 % endif
79 % endif
80 </div>
80 </div>
81 <p class="help-block">
81 <p class="help-block">
82 ${_('Repository scope works only with tokens with VCS type.')}
82 ${_('Repository scope works only with tokens with VCS type.')}
83 </p>
83 </p>
84 </div>
84 </div>
85 <div class="buttons">
85 <div class="buttons">
86 ${h.submit('save',_('Add'),class_="btn")}
86 ${h.submit('save',_('Add'),class_="btn")}
87 ${h.reset('reset',_('Reset'),class_="btn")}
87 ${h.reset('reset',_('Reset'),class_="btn")}
88 </div>
88 </div>
89 </div>
89 </div>
90 </div>
90 </div>
91 ${h.end_form()}
91 ${h.end_form()}
92 </div>
92 </div>
93 </div>
93 </div>
94 </div>
94 </div>
95 <script>
95 <script>
96 $(document).ready(function(){
96 $(document).ready(function(){
97
97
98 var select2Options = {
98 var select2Options = {
99 'containerCssClass': "drop-menu",
99 'containerCssClass': "drop-menu",
100 'dropdownCssClass': "drop-menu-dropdown",
100 'dropdownCssClass': "drop-menu-dropdown",
101 'dropdownAutoWidth': true
101 'dropdownAutoWidth': true
102 };
102 };
103 $("#role").select2(select2Options);
103 $("#role").select2(select2Options);
104
104
105
106 var preloadData = {
105 var preloadData = {
107 results: [
106 results: [
108 % for entry in c.lifetime_values:
107 % for entry in c.lifetime_values:
109 {id:${entry[0]}, text:"${entry[1]}"}${'' if loop.last else ','}
108 {id:${entry[0]}, text:"${entry[1]}"}${'' if loop.last else ','}
110 % endfor
109 % endfor
111 ]
110 ]
112 };
111 };
113
112
114 $("#lifetime").select2({
113 $("#lifetime").select2({
115 containerCssClass: "drop-menu",
114 containerCssClass: "drop-menu",
116 dropdownCssClass: "drop-menu-dropdown",
115 dropdownCssClass: "drop-menu-dropdown",
117 dropdownAutoWidth: true,
116 dropdownAutoWidth: true,
118 data: preloadData,
117 data: preloadData,
119 placeholder: "${_('Select or enter expiration date')}",
118 placeholder: "${_('Select or enter expiration date')}",
120 query: function(query) {
119 query: function(query) {
121 feedLifetimeOptions(query, preloadData);
120 feedLifetimeOptions(query, preloadData);
122 }
121 }
123 });
122 });
124
123
125
124
126 var repoFilter = function(data) {
125 var repoFilter = function(data) {
127 var results = [];
126 var results = [];
128
127
129 if (!data.results[0]) {
128 if (!data.results[0]) {
130 return data
129 return data
131 }
130 }
132
131
133 $.each(data.results[0].children, function() {
132 $.each(data.results[0].children, function() {
134 // replace name to ID for submision
133 // replace name to ID for submision
135 this.id = this.obj.repo_id;
134 this.id = this.obj.repo_id;
136 results.push(this);
135 results.push(this);
137 });
136 });
138
137
139 data.results[0].children = results;
138 data.results[0].children = results;
140 return data;
139 return data;
141 };
140 };
142
141
143 $("#scope_repo_id_disabled").select2(select2Options);
142 $("#scope_repo_id_disabled").select2(select2Options);
144
143
145 $("#scope_repo_id").select2({
144 $("#scope_repo_id").select2({
146 cachedDataSource: {},
145 cachedDataSource: {},
147 minimumInputLength: 2,
146 minimumInputLength: 2,
148 placeholder: "${_('repository scope')}",
147 placeholder: "${_('repository scope')}",
149 dropdownAutoWidth: true,
148 dropdownAutoWidth: true,
150 containerCssClass: "drop-menu",
149 containerCssClass: "drop-menu",
151 dropdownCssClass: "drop-menu-dropdown",
150 dropdownCssClass: "drop-menu-dropdown",
152 formatResult: formatResult,
151 formatResult: formatResult,
153 query: $.debounce(250, function(query){
152 query: $.debounce(250, function(query){
154 self = this;
153 self = this;
155 var cacheKey = query.term;
154 var cacheKey = query.term;
156 var cachedData = self.cachedDataSource[cacheKey];
155 var cachedData = self.cachedDataSource[cacheKey];
157
156
158 if (cachedData) {
157 if (cachedData) {
159 query.callback({results: cachedData.results});
158 query.callback({results: cachedData.results});
160 } else {
159 } else {
161 $.ajax({
160 $.ajax({
162 url: pyroutes.url('repo_list_data'),
161 url: pyroutes.url('repo_list_data'),
163 data: {'query': query.term},
162 data: {'query': query.term},
164 dataType: 'json',
163 dataType: 'json',
165 type: 'GET',
164 type: 'GET',
166 success: function(data) {
165 success: function(data) {
167 data = repoFilter(data);
166 data = repoFilter(data);
168 self.cachedDataSource[cacheKey] = data;
167 self.cachedDataSource[cacheKey] = data;
169 query.callback({results: data.results});
168 query.callback({results: data.results});
170 },
169 },
171 error: function(data, textStatus, errorThrown) {
170 error: function(data, textStatus, errorThrown) {
172 alert("Error while fetching entries.\nError code {0} ({1}).".format(data.status, data.statusText));
171 alert("Error while fetching entries.\nError code {0} ({1}).".format(data.status, data.statusText));
173 }
172 }
174 })
173 })
175 }
174 }
176 })
175 })
177 });
176 });
178
177
179 });
178 });
180 </script>
179 </script>
@@ -1,186 +1,186 b''
1 ## -*- coding: utf-8 -*-
1 ## -*- coding: utf-8 -*-
2 <%namespace name="base" file="/base/base.mako"/>
2 <%namespace name="base" file="/base/base.mako"/>
3
3
4 <div class="panel panel-default">
4 <div class="panel panel-default">
5 <div class="panel-heading">
5 <div class="panel-heading">
6 <h3 class="panel-title">${_('User Group: %s') % c.user_group.users_group_name}</h3>
6 <h3 class="panel-title">${_('User Group: %s') % c.user_group.users_group_name}</h3>
7 </div>
7 </div>
8 <div class="panel-body">
8 <div class="panel-body">
9 ${h.secure_form(h.route_path('user_groups_update', user_group_id=c.user_group.users_group_id), id='edit_user_group', request=request)}
9 ${h.secure_form(h.route_path('user_groups_update', user_group_id=c.user_group.users_group_id), id='edit_user_group', request=request)}
10 <div class="form">
10 <div class="form">
11 <!-- fields -->
11 <!-- fields -->
12 <div class="fields">
12 <div class="fields">
13 <div class="field">
13 <div class="field">
14 <div class="label">
14 <div class="label">
15 <label for="users_group_name">${_('Group name')}:</label>
15 <label for="users_group_name">${_('Group name')}:</label>
16 </div>
16 </div>
17 <div class="input">
17 <div class="input">
18 ${h.text('users_group_name',class_='medium')}
18 ${h.text('users_group_name',class_='medium')}
19 </div>
19 </div>
20 </div>
20 </div>
21
21
22 <div class="field badged-field">
22 <div class="field badged-field">
23 <div class="label">
23 <div class="label">
24 <label for="user">${_('Owner')}:</label>
24 <label for="user">${_('Owner')}:</label>
25 </div>
25 </div>
26 <div class="input">
26 <div class="input">
27 <div class="badge-input-container">
27 <div class="badge-input-container">
28 <div class="user-badge">
28 <div class="user-badge">
29 ${base.gravatar_with_user(c.user_group.user.email, show_disabled=not c.user_group.user.active)}
29 ${base.gravatar_with_user(c.user_group.user.email, show_disabled=not c.user_group.user.active)}
30 </div>
30 </div>
31 <div class="badge-input-wrap">
31 <div class="badge-input-wrap">
32 ${h.text('user', class_="medium", autocomplete="off")}
32 ${h.text('user', class_="medium", autocomplete="off")}
33 </div>
33 </div>
34 </div>
34 </div>
35 <form:error name="user"/>
35 <form:error name="user"/>
36 <p class="help-block">${_('Change owner of this user group.')}</p>
36 <p class="help-block">${_('Change owner of this user group.')}</p>
37 </div>
37 </div>
38 </div>
38 </div>
39
39
40 <div class="field">
40 <div class="field">
41 <div class="label label-textarea">
41 <div class="label label-textarea">
42 <label for="user_group_description">${_('Description')}:</label>
42 <label for="user_group_description">${_('Description')}:</label>
43 </div>
43 </div>
44 <div class="textarea textarea-small editor">
44 <div class="textarea textarea-small editor">
45 ${h.textarea('user_group_description',cols=23,rows=5,class_="medium")}
45 ${h.textarea('user_group_description',cols=23,rows=5,class_="medium")}
46 <span class="help-block">${_('Short, optional description for this user group.')}</span>
46 <span class="help-block">${_('Short, optional description for this user group.')}</span>
47 </div>
47 </div>
48 </div>
48 </div>
49 <div class="field">
49 <div class="field">
50 <div class="label label-checkbox">
50 <div class="label label-checkbox">
51 <label for="users_group_active">${_('Active')}:</label>
51 <label for="users_group_active">${_('Active')}:</label>
52 </div>
52 </div>
53 <div class="checkboxes">
53 <div class="checkboxes">
54 ${h.checkbox('users_group_active',value=True)}
54 ${h.checkbox('users_group_active',value=True)}
55 </div>
55 </div>
56 </div>
56 </div>
57
57
58 <div class="field">
58 <div class="field">
59 <div class="label label-checkbox">
59 <div class="label label-checkbox">
60 <label for="users_group_active">${_('Add members')}:</label>
60 <label for="users_group_active">${_('Add members')}:</label>
61 </div>
61 </div>
62 <div class="input">
62 <div class="input">
63 ${h.text('user_group_add_members', placeholder="user/usergroup", class_="medium")}
63 ${h.text('user_group_add_members', placeholder="user/usergroup", class_="medium")}
64 </div>
64 </div>
65 </div>
65 </div>
66
66
67 <input type="hidden" name="__start__" value="user_group_members:sequence"/>
67 <input type="hidden" name="__start__" value="user_group_members:sequence"/>
68 <table id="group_members_placeholder" class="rctable group_members">
68 <table id="group_members_placeholder" class="rctable group_members">
69 <tr>
69 <tr>
70 <th>${_('Username')}</th>
70 <th>${_('Username')}</th>
71 <th>${_('Action')}</th>
71 <th>${_('Action')}</th>
72 </tr>
72 </tr>
73
73
74 % if c.group_members_obj:
74 % if c.group_members_obj:
75 % for user in c.group_members_obj:
75 % for user in c.group_members_obj:
76 <tr>
76 <tr>
77 <td id="member_user_${user.user_id}" class="td-author">
77 <td id="member_user_${user.user_id}" class="td-author">
78 <div class="group_member">
78 <div class="group_member">
79 ${base.gravatar(user.email, 16)}
79 ${base.gravatar(user.email, 16)}
80 <span class="username user">${h.link_to(h.person(user), h.url( 'edit_user',user_id=user.user_id))}</span>
80 <span class="username user">${h.link_to(h.person(user), h.route_path('user_edit',user_id=user.user_id))}</span>
81 <input type="hidden" name="__start__" value="member:mapping">
81 <input type="hidden" name="__start__" value="member:mapping">
82 <input type="hidden" name="member_user_id" value="${user.user_id}">
82 <input type="hidden" name="member_user_id" value="${user.user_id}">
83 <input type="hidden" name="type" value="existing" id="member_${user.user_id}">
83 <input type="hidden" name="type" value="existing" id="member_${user.user_id}">
84 <input type="hidden" name="__end__" value="member:mapping">
84 <input type="hidden" name="__end__" value="member:mapping">
85 </div>
85 </div>
86 </td>
86 </td>
87 <td class="">
87 <td class="">
88 <div class="usergroup_member_remove action_button" onclick="removeUserGroupMember(${user.user_id}, true)" style="visibility: visible;">
88 <div class="usergroup_member_remove action_button" onclick="removeUserGroupMember(${user.user_id}, true)" style="visibility: visible;">
89 <i class="icon-remove-sign"></i>
89 <i class="icon-remove-sign"></i>
90 </div>
90 </div>
91 </td>
91 </td>
92 </tr>
92 </tr>
93 % endfor
93 % endfor
94
94
95 % else:
95 % else:
96 <tr><td colspan="2">${_('No members yet')}</td></tr>
96 <tr><td colspan="2">${_('No members yet')}</td></tr>
97 % endif
97 % endif
98 </table>
98 </table>
99 <input type="hidden" name="__end__" value="user_group_members:sequence"/>
99 <input type="hidden" name="__end__" value="user_group_members:sequence"/>
100
100
101 <div class="buttons">
101 <div class="buttons">
102 ${h.submit('Save',_('Save'),class_="btn")}
102 ${h.submit('Save',_('Save'),class_="btn")}
103 </div>
103 </div>
104 </div>
104 </div>
105 </div>
105 </div>
106 ${h.end_form()}
106 ${h.end_form()}
107 </div>
107 </div>
108 </div>
108 </div>
109 <script>
109 <script>
110 $(document).ready(function(){
110 $(document).ready(function(){
111 $("#group_parent_id").select2({
111 $("#group_parent_id").select2({
112 'containerCssClass': "drop-menu",
112 'containerCssClass': "drop-menu",
113 'dropdownCssClass': "drop-menu-dropdown",
113 'dropdownCssClass': "drop-menu-dropdown",
114 'dropdownAutoWidth': true
114 'dropdownAutoWidth': true
115 });
115 });
116
116
117 removeUserGroupMember = function(userId){
117 removeUserGroupMember = function(userId){
118 $('#member_'+userId).val('remove');
118 $('#member_'+userId).val('remove');
119 $('#member_user_'+userId).addClass('to-delete');
119 $('#member_user_'+userId).addClass('to-delete');
120 };
120 };
121
121
122 $('#user_group_add_members').autocomplete({
122 $('#user_group_add_members').autocomplete({
123 serviceUrl: pyroutes.url('user_autocomplete_data'),
123 serviceUrl: pyroutes.url('user_autocomplete_data'),
124 minChars:2,
124 minChars:2,
125 maxHeight:400,
125 maxHeight:400,
126 width:300,
126 width:300,
127 deferRequestBy: 300, //miliseconds
127 deferRequestBy: 300, //miliseconds
128 showNoSuggestionNotice: true,
128 showNoSuggestionNotice: true,
129 params: { user_groups:true },
129 params: { user_groups:true },
130 formatResult: autocompleteFormatResult,
130 formatResult: autocompleteFormatResult,
131 lookupFilter: autocompleteFilterResult,
131 lookupFilter: autocompleteFilterResult,
132 onSelect: function(element, suggestion){
132 onSelect: function(element, suggestion){
133
133
134 function addMember(user, fromUserGroup) {
134 function addMember(user, fromUserGroup) {
135 var gravatar = user.icon_link;
135 var gravatar = user.icon_link;
136 var username = user.value_display;
136 var username = user.value_display;
137 var userLink = pyroutes.url('edit_user', {"user_id": user.id});
137 var userLink = pyroutes.url('user_edit', {"user_id": user.id});
138 var uid = user.id;
138 var uid = user.id;
139
139
140 if (fromUserGroup) {
140 if (fromUserGroup) {
141 username = username +" "+ _gettext('(from usergroup {0})'.format(fromUserGroup))
141 username = username +" "+ _gettext('(from usergroup {0})'.format(fromUserGroup))
142 }
142 }
143
143
144 var elem = $(
144 var elem = $(
145 ('<tr>'+
145 ('<tr>'+
146 '<td id="member_user_{6}" class="td-author td-author-new-entry">'+
146 '<td id="member_user_{6}" class="td-author td-author-new-entry">'+
147 '<div class="group_member">'+
147 '<div class="group_member">'+
148 '<img class="gravatar" src="{0}" height="16" width="16">'+
148 '<img class="gravatar" src="{0}" height="16" width="16">'+
149 '<span class="username user"><a href="{1}">{2}</a></span>'+
149 '<span class="username user"><a href="{1}">{2}</a></span>'+
150 '<input type="hidden" name="__start__" value="member:mapping">'+
150 '<input type="hidden" name="__start__" value="member:mapping">'+
151 '<input type="hidden" name="member_user_id" value="{3}">'+
151 '<input type="hidden" name="member_user_id" value="{3}">'+
152 '<input type="hidden" name="type" value="new" id="member_{4}">'+
152 '<input type="hidden" name="type" value="new" id="member_{4}">'+
153 '<input type="hidden" name="__end__" value="member:mapping">'+
153 '<input type="hidden" name="__end__" value="member:mapping">'+
154 '</div>'+
154 '</div>'+
155 '</td>'+
155 '</td>'+
156 '<td class="td-author-new-entry">'+
156 '<td class="td-author-new-entry">'+
157 '<div class="usergroup_member_remove action_button" onclick="removeUserGroupMember({5}, true)" style="visibility: visible;">'+
157 '<div class="usergroup_member_remove action_button" onclick="removeUserGroupMember({5}, true)" style="visibility: visible;">'+
158 '<i class="icon-remove-sign"></i>'+
158 '<i class="icon-remove-sign"></i>'+
159 '</div>'+
159 '</div>'+
160 '</td>'+
160 '</td>'+
161 '</tr>').format(gravatar, userLink, username,
161 '</tr>').format(gravatar, userLink, username,
162 uid, uid, uid, uid)
162 uid, uid, uid, uid)
163 );
163 );
164 $('#group_members_placeholder').append(elem)
164 $('#group_members_placeholder').append(elem)
165 }
165 }
166
166
167 if (suggestion.value_type == 'user_group') {
167 if (suggestion.value_type == 'user_group') {
168 $.getJSON(
168 $.getJSON(
169 pyroutes.url('user_group_members_data',
169 pyroutes.url('user_group_members_data',
170 {'user_group_id': suggestion.id}),
170 {'user_group_id': suggestion.id}),
171 function(data) {
171 function(data) {
172 $.each(data.members, function(idx, user) {
172 $.each(data.members, function(idx, user) {
173 addMember(user, suggestion.value)
173 addMember(user, suggestion.value)
174 });
174 });
175 }
175 }
176 );
176 );
177 } else if (suggestion.value_type == 'user') {
177 } else if (suggestion.value_type == 'user') {
178 addMember(suggestion, null);
178 addMember(suggestion, null);
179 }
179 }
180 }
180 }
181 });
181 });
182
182
183
183
184 UsersAutoComplete('user', '${c.rhodecode_user.user_id}');
184 UsersAutoComplete('user', '${c.rhodecode_user.user_id}');
185 })
185 })
186 </script>
186 </script>
@@ -1,147 +1,147 b''
1 ## -*- coding: utf-8 -*-
1 ## -*- coding: utf-8 -*-
2 <%inherit file="/base/base.mako"/>
2 <%inherit file="/base/base.mako"/>
3
3
4 <%def name="title()">
4 <%def name="title()">
5 ${_('Add user')}
5 ${_('Add user')}
6 %if c.rhodecode_name:
6 %if c.rhodecode_name:
7 &middot; ${h.branding(c.rhodecode_name)}
7 &middot; ${h.branding(c.rhodecode_name)}
8 %endif
8 %endif
9 </%def>
9 </%def>
10 <%def name="breadcrumbs_links()">
10 <%def name="breadcrumbs_links()">
11 ${h.link_to(_('Admin'),h.route_path('admin_home'))}
11 ${h.link_to(_('Admin'),h.route_path('admin_home'))}
12 &raquo;
12 &raquo;
13 ${h.link_to(_('Users'),h.route_path('users'))}
13 ${h.link_to(_('Users'),h.route_path('users'))}
14 &raquo;
14 &raquo;
15 ${_('Add User')}
15 ${_('Add User')}
16 </%def>
16 </%def>
17
17
18 <%def name="menu_bar_nav()">
18 <%def name="menu_bar_nav()">
19 ${self.menu_items(active='admin')}
19 ${self.menu_items(active='admin')}
20 </%def>
20 </%def>
21
21
22 <%def name="main()">
22 <%def name="main()">
23 <div class="box">
23 <div class="box">
24 <!-- box / title -->
24 <!-- box / title -->
25 <div class="title">
25 <div class="title">
26 ${self.breadcrumbs()}
26 ${self.breadcrumbs()}
27 </div>
27 </div>
28 <!-- end box / title -->
28 <!-- end box / title -->
29 ${h.secure_form(h.url('users'))}
29 ${h.secure_form(h.route_path('users_create'), request=request)}
30 <div class="form">
30 <div class="form">
31 <!-- fields -->
31 <!-- fields -->
32 <div class="fields">
32 <div class="fields">
33 <div class="field">
33 <div class="field">
34 <div class="label">
34 <div class="label">
35 <label for="username">${_('Username')}:</label>
35 <label for="username">${_('Username')}:</label>
36 </div>
36 </div>
37 <div class="input">
37 <div class="input">
38 ${h.text('username', class_='medium')}
38 ${h.text('username', class_='medium')}
39 </div>
39 </div>
40 </div>
40 </div>
41
41
42 <div class="field">
42 <div class="field">
43 <div class="label">
43 <div class="label">
44 <label for="password">${_('Password')}:</label>
44 <label for="password">${_('Password')}:</label>
45 </div>
45 </div>
46 <div class="input">
46 <div class="input">
47 ${h.password('password', class_='medium')}
47 ${h.password('password', class_='medium')}
48 </div>
48 </div>
49 </div>
49 </div>
50
50
51 <div class="field">
51 <div class="field">
52 <div class="label">
52 <div class="label">
53 <label for="password_confirmation">${_('Password confirmation')}:</label>
53 <label for="password_confirmation">${_('Password confirmation')}:</label>
54 </div>
54 </div>
55 <div class="input">
55 <div class="input">
56 ${h.password('password_confirmation',autocomplete="off", class_='medium')}
56 ${h.password('password_confirmation',autocomplete="off", class_='medium')}
57 <div class="info-block">
57 <div class="info-block">
58 <a id="generate_password" href="#">
58 <a id="generate_password" href="#">
59 <i class="icon-lock"></i> ${_('Generate password')}
59 <i class="icon-lock"></i> ${_('Generate password')}
60 </a>
60 </a>
61 <span id="generate_password_preview"></span>
61 <span id="generate_password_preview"></span>
62 </div>
62 </div>
63 </div>
63 </div>
64 </div>
64 </div>
65
65
66 <div class="field">
66 <div class="field">
67 <div class="label">
67 <div class="label">
68 <label for="firstname">${_('First Name')}:</label>
68 <label for="firstname">${_('First Name')}:</label>
69 </div>
69 </div>
70 <div class="input">
70 <div class="input">
71 ${h.text('firstname', class_='medium')}
71 ${h.text('firstname', class_='medium')}
72 </div>
72 </div>
73 </div>
73 </div>
74
74
75 <div class="field">
75 <div class="field">
76 <div class="label">
76 <div class="label">
77 <label for="lastname">${_('Last Name')}:</label>
77 <label for="lastname">${_('Last Name')}:</label>
78 </div>
78 </div>
79 <div class="input">
79 <div class="input">
80 ${h.text('lastname', class_='medium')}
80 ${h.text('lastname', class_='medium')}
81 </div>
81 </div>
82 </div>
82 </div>
83
83
84 <div class="field">
84 <div class="field">
85 <div class="label">
85 <div class="label">
86 <label for="email">${_('Email')}:</label>
86 <label for="email">${_('Email')}:</label>
87 </div>
87 </div>
88 <div class="input">
88 <div class="input">
89 ${h.text('email', class_='medium')}
89 ${h.text('email', class_='medium')}
90 ${h.hidden('extern_name', c.default_extern_type)}
90 ${h.hidden('extern_name', c.default_extern_type)}
91 ${h.hidden('extern_type', c.default_extern_type)}
91 ${h.hidden('extern_type', c.default_extern_type)}
92 </div>
92 </div>
93 </div>
93 </div>
94
94
95 <div class="field">
95 <div class="field">
96 <div class="label label-checkbox">
96 <div class="label label-checkbox">
97 <label for="active">${_('Active')}:</label>
97 <label for="active">${_('Active')}:</label>
98 </div>
98 </div>
99 <div class="checkboxes">
99 <div class="checkboxes">
100 ${h.checkbox('active',value=True,checked='checked')}
100 ${h.checkbox('active',value=True,checked='checked')}
101 </div>
101 </div>
102 </div>
102 </div>
103
103
104 <div class="field">
104 <div class="field">
105 <div class="label label-checkbox">
105 <div class="label label-checkbox">
106 <label for="password_change">${_('Password change')}:</label>
106 <label for="password_change">${_('Password change')}:</label>
107 </div>
107 </div>
108 <div class="checkboxes">
108 <div class="checkboxes">
109 ${h.checkbox('password_change',value=True)}
109 ${h.checkbox('password_change',value=True)}
110 <span class="help-block">${_('Force user to change his password on the next login')}</span>
110 <span class="help-block">${_('Force user to change his password on the next login')}</span>
111 </div>
111 </div>
112 </div>
112 </div>
113
113
114 <div class="field">
114 <div class="field">
115 <div class="label label-checkbox">
115 <div class="label label-checkbox">
116 <label for="create_repo_group">${_('Add personal repository group')}:</label>
116 <label for="create_repo_group">${_('Add personal repository group')}:</label>
117 </div>
117 </div>
118 <div class="checkboxes">
118 <div class="checkboxes">
119 ${h.checkbox('create_repo_group',value=True, checked=c.default_create_repo_group)}
119 ${h.checkbox('create_repo_group',value=True, checked=c.default_create_repo_group)}
120 <span class="help-block">
120 <span class="help-block">
121 ${_('New group will be created at: `/%(path)s`') % {'path': c.personal_repo_group_name}}<br/>
121 ${_('New group will be created at: `/%(path)s`') % {'path': c.personal_repo_group_name}}<br/>
122 ${_('User will be automatically set as this group owner.')}
122 ${_('User will be automatically set as this group owner.')}
123 </span>
123 </span>
124 </div>
124 </div>
125 </div>
125 </div>
126
126
127 <div class="buttons">
127 <div class="buttons">
128 ${h.submit('save',_('Save'),class_="btn")}
128 ${h.submit('save',_('Save'),class_="btn")}
129 </div>
129 </div>
130 </div>
130 </div>
131 </div>
131 </div>
132 ${h.end_form()}
132 ${h.end_form()}
133 </div>
133 </div>
134 <script>
134 <script>
135 $(document).ready(function(){
135 $(document).ready(function(){
136 $('#username').focus();
136 $('#username').focus();
137
137
138 $('#generate_password').on('click', function(e){
138 $('#generate_password').on('click', function(e){
139 var tmpl = "(${_('generated password:')} {0})";
139 var tmpl = "(${_('generated password:')} {0})";
140 var new_passwd = generatePassword(12);
140 var new_passwd = generatePassword(12);
141 $('#generate_password_preview').html(tmpl.format(new_passwd));
141 $('#generate_password_preview').html(tmpl.format(new_passwd));
142 $('#password').val(new_passwd);
142 $('#password').val(new_passwd);
143 $('#password_confirmation').val(new_passwd);
143 $('#password_confirmation').val(new_passwd);
144 })
144 })
145 })
145 })
146 </script>
146 </script>
147 </%def>
147 </%def>
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now