##// END OF EJS Templates
users: ported controllers from pylons into pyramid views.
marcink -
r2114:6e357177 default
parent child Browse files
Show More
@@ -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,4213 +1,4227 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 Database Models for RhodeCode Enterprise
22 Database Models for RhodeCode Enterprise
23 """
23 """
24
24
25 import re
25 import re
26 import os
26 import os
27 import time
27 import time
28 import hashlib
28 import hashlib
29 import logging
29 import logging
30 import datetime
30 import datetime
31 import warnings
31 import warnings
32 import ipaddress
32 import ipaddress
33 import functools
33 import functools
34 import traceback
34 import traceback
35 import collections
35 import collections
36
36
37
37
38 from sqlalchemy import *
38 from sqlalchemy import *
39 from sqlalchemy.ext.declarative import declared_attr
39 from sqlalchemy.ext.declarative import declared_attr
40 from sqlalchemy.ext.hybrid import hybrid_property
40 from sqlalchemy.ext.hybrid import hybrid_property
41 from sqlalchemy.orm import (
41 from sqlalchemy.orm import (
42 relationship, joinedload, class_mapper, validates, aliased)
42 relationship, joinedload, class_mapper, validates, aliased)
43 from sqlalchemy.sql.expression import true
43 from sqlalchemy.sql.expression import true
44 from sqlalchemy.sql.functions import coalesce, count # noqa
44 from sqlalchemy.sql.functions import coalesce, count # noqa
45 from sqlalchemy.exc import IntegrityError # noqa
45 from sqlalchemy.exc import IntegrityError # noqa
46 from sqlalchemy.dialects.mysql import LONGTEXT
46 from sqlalchemy.dialects.mysql import LONGTEXT
47 from beaker.cache import cache_region
47 from beaker.cache import cache_region
48 from zope.cachedescriptors.property import Lazy as LazyProperty
48 from zope.cachedescriptors.property import Lazy as LazyProperty
49
49
50 from pyramid.threadlocal import get_current_request
50 from pyramid.threadlocal import get_current_request
51
51
52 from rhodecode.translation import _
52 from rhodecode.translation import _
53 from rhodecode.lib.vcs import get_vcs_instance
53 from rhodecode.lib.vcs import get_vcs_instance
54 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
54 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
55 from rhodecode.lib.utils2 import (
55 from rhodecode.lib.utils2 import (
56 str2bool, safe_str, get_commit_safe, safe_unicode, md5_safe,
56 str2bool, safe_str, get_commit_safe, safe_unicode, md5_safe,
57 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
57 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
58 glob2re, StrictAttributeDict, cleaned_uri)
58 glob2re, StrictAttributeDict, cleaned_uri)
59 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType
59 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType
60 from rhodecode.lib.ext_json import json
60 from rhodecode.lib.ext_json import json
61 from rhodecode.lib.caching_query import FromCache
61 from rhodecode.lib.caching_query import FromCache
62 from rhodecode.lib.encrypt import AESCipher
62 from rhodecode.lib.encrypt import AESCipher
63
63
64 from rhodecode.model.meta import Base, Session
64 from rhodecode.model.meta import Base, Session
65
65
66 URL_SEP = '/'
66 URL_SEP = '/'
67 log = logging.getLogger(__name__)
67 log = logging.getLogger(__name__)
68
68
69 # =============================================================================
69 # =============================================================================
70 # BASE CLASSES
70 # BASE CLASSES
71 # =============================================================================
71 # =============================================================================
72
72
73 # this is propagated from .ini file rhodecode.encrypted_values.secret or
73 # this is propagated from .ini file rhodecode.encrypted_values.secret or
74 # beaker.session.secret if first is not set.
74 # beaker.session.secret if first is not set.
75 # and initialized at environment.py
75 # and initialized at environment.py
76 ENCRYPTION_KEY = None
76 ENCRYPTION_KEY = None
77
77
78 # used to sort permissions by types, '#' used here is not allowed to be in
78 # used to sort permissions by types, '#' used here is not allowed to be in
79 # usernames, and it's very early in sorted string.printable table.
79 # usernames, and it's very early in sorted string.printable table.
80 PERMISSION_TYPE_SORT = {
80 PERMISSION_TYPE_SORT = {
81 'admin': '####',
81 'admin': '####',
82 'write': '###',
82 'write': '###',
83 'read': '##',
83 'read': '##',
84 'none': '#',
84 'none': '#',
85 }
85 }
86
86
87
87
88 def display_user_sort(obj):
88 def display_user_sort(obj):
89 """
89 """
90 Sort function used to sort permissions in .permissions() function of
90 Sort function used to sort permissions in .permissions() function of
91 Repository, RepoGroup, UserGroup. Also it put the default user in front
91 Repository, RepoGroup, UserGroup. Also it put the default user in front
92 of all other resources
92 of all other resources
93 """
93 """
94
94
95 if obj.username == User.DEFAULT_USER:
95 if obj.username == User.DEFAULT_USER:
96 return '#####'
96 return '#####'
97 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
97 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
98 return prefix + obj.username
98 return prefix + obj.username
99
99
100
100
101 def display_user_group_sort(obj):
101 def display_user_group_sort(obj):
102 """
102 """
103 Sort function used to sort permissions in .permissions() function of
103 Sort function used to sort permissions in .permissions() function of
104 Repository, RepoGroup, UserGroup. Also it put the default user in front
104 Repository, RepoGroup, UserGroup. Also it put the default user in front
105 of all other resources
105 of all other resources
106 """
106 """
107
107
108 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
108 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
109 return prefix + obj.users_group_name
109 return prefix + obj.users_group_name
110
110
111
111
112 def _hash_key(k):
112 def _hash_key(k):
113 return md5_safe(k)
113 return md5_safe(k)
114
114
115
115
116 def in_filter_generator(qry, items, limit=500):
116 def in_filter_generator(qry, items, limit=500):
117 """
117 """
118 Splits IN() into multiple with OR
118 Splits IN() into multiple with OR
119 e.g.::
119 e.g.::
120 cnt = Repository.query().filter(
120 cnt = Repository.query().filter(
121 or_(
121 or_(
122 *in_filter_generator(Repository.repo_id, range(100000))
122 *in_filter_generator(Repository.repo_id, range(100000))
123 )).count()
123 )).count()
124 """
124 """
125 parts = []
125 parts = []
126 for chunk in xrange(0, len(items), limit):
126 for chunk in xrange(0, len(items), limit):
127 parts.append(
127 parts.append(
128 qry.in_(items[chunk: chunk + limit])
128 qry.in_(items[chunk: chunk + limit])
129 )
129 )
130
130
131 return parts
131 return parts
132
132
133
133
134 class EncryptedTextValue(TypeDecorator):
134 class EncryptedTextValue(TypeDecorator):
135 """
135 """
136 Special column for encrypted long text data, use like::
136 Special column for encrypted long text data, use like::
137
137
138 value = Column("encrypted_value", EncryptedValue(), nullable=False)
138 value = Column("encrypted_value", EncryptedValue(), nullable=False)
139
139
140 This column is intelligent so if value is in unencrypted form it return
140 This column is intelligent so if value is in unencrypted form it return
141 unencrypted form, but on save it always encrypts
141 unencrypted form, but on save it always encrypts
142 """
142 """
143 impl = Text
143 impl = Text
144
144
145 def process_bind_param(self, value, dialect):
145 def process_bind_param(self, value, dialect):
146 if not value:
146 if not value:
147 return value
147 return value
148 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
148 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
149 # protect against double encrypting if someone manually starts
149 # protect against double encrypting if someone manually starts
150 # doing
150 # doing
151 raise ValueError('value needs to be in unencrypted format, ie. '
151 raise ValueError('value needs to be in unencrypted format, ie. '
152 'not starting with enc$aes')
152 'not starting with enc$aes')
153 return 'enc$aes_hmac$%s' % AESCipher(
153 return 'enc$aes_hmac$%s' % AESCipher(
154 ENCRYPTION_KEY, hmac=True).encrypt(value)
154 ENCRYPTION_KEY, hmac=True).encrypt(value)
155
155
156 def process_result_value(self, value, dialect):
156 def process_result_value(self, value, dialect):
157 import rhodecode
157 import rhodecode
158
158
159 if not value:
159 if not value:
160 return value
160 return value
161
161
162 parts = value.split('$', 3)
162 parts = value.split('$', 3)
163 if not len(parts) == 3:
163 if not len(parts) == 3:
164 # probably not encrypted values
164 # probably not encrypted values
165 return value
165 return value
166 else:
166 else:
167 if parts[0] != 'enc':
167 if parts[0] != 'enc':
168 # parts ok but without our header ?
168 # parts ok but without our header ?
169 return value
169 return value
170 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
170 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
171 'rhodecode.encrypted_values.strict') or True)
171 'rhodecode.encrypted_values.strict') or True)
172 # at that stage we know it's our encryption
172 # at that stage we know it's our encryption
173 if parts[1] == 'aes':
173 if parts[1] == 'aes':
174 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
174 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
175 elif parts[1] == 'aes_hmac':
175 elif parts[1] == 'aes_hmac':
176 decrypted_data = AESCipher(
176 decrypted_data = AESCipher(
177 ENCRYPTION_KEY, hmac=True,
177 ENCRYPTION_KEY, hmac=True,
178 strict_verification=enc_strict_mode).decrypt(parts[2])
178 strict_verification=enc_strict_mode).decrypt(parts[2])
179 else:
179 else:
180 raise ValueError(
180 raise ValueError(
181 'Encryption type part is wrong, must be `aes` '
181 'Encryption type part is wrong, must be `aes` '
182 'or `aes_hmac`, got `%s` instead' % (parts[1]))
182 'or `aes_hmac`, got `%s` instead' % (parts[1]))
183 return decrypted_data
183 return decrypted_data
184
184
185
185
186 class BaseModel(object):
186 class BaseModel(object):
187 """
187 """
188 Base Model for all classes
188 Base Model for all classes
189 """
189 """
190
190
191 @classmethod
191 @classmethod
192 def _get_keys(cls):
192 def _get_keys(cls):
193 """return column names for this model """
193 """return column names for this model """
194 return class_mapper(cls).c.keys()
194 return class_mapper(cls).c.keys()
195
195
196 def get_dict(self):
196 def get_dict(self):
197 """
197 """
198 return dict with keys and values corresponding
198 return dict with keys and values corresponding
199 to this model data """
199 to this model data """
200
200
201 d = {}
201 d = {}
202 for k in self._get_keys():
202 for k in self._get_keys():
203 d[k] = getattr(self, k)
203 d[k] = getattr(self, k)
204
204
205 # also use __json__() if present to get additional fields
205 # also use __json__() if present to get additional fields
206 _json_attr = getattr(self, '__json__', None)
206 _json_attr = getattr(self, '__json__', None)
207 if _json_attr:
207 if _json_attr:
208 # update with attributes from __json__
208 # update with attributes from __json__
209 if callable(_json_attr):
209 if callable(_json_attr):
210 _json_attr = _json_attr()
210 _json_attr = _json_attr()
211 for k, val in _json_attr.iteritems():
211 for k, val in _json_attr.iteritems():
212 d[k] = val
212 d[k] = val
213 return d
213 return d
214
214
215 def get_appstruct(self):
215 def get_appstruct(self):
216 """return list with keys and values tuples corresponding
216 """return list with keys and values tuples corresponding
217 to this model data """
217 to this model data """
218
218
219 l = []
219 l = []
220 for k in self._get_keys():
220 for k in self._get_keys():
221 l.append((k, getattr(self, k),))
221 l.append((k, getattr(self, k),))
222 return l
222 return l
223
223
224 def populate_obj(self, populate_dict):
224 def populate_obj(self, populate_dict):
225 """populate model with data from given populate_dict"""
225 """populate model with data from given populate_dict"""
226
226
227 for k in self._get_keys():
227 for k in self._get_keys():
228 if k in populate_dict:
228 if k in populate_dict:
229 setattr(self, k, populate_dict[k])
229 setattr(self, k, populate_dict[k])
230
230
231 @classmethod
231 @classmethod
232 def query(cls):
232 def query(cls):
233 return Session().query(cls)
233 return Session().query(cls)
234
234
235 @classmethod
235 @classmethod
236 def get(cls, id_):
236 def get(cls, id_):
237 if id_:
237 if id_:
238 return cls.query().get(id_)
238 return cls.query().get(id_)
239
239
240 @classmethod
240 @classmethod
241 def get_or_404(cls, id_):
241 def get_or_404(cls, id_):
242 from pyramid.httpexceptions import HTTPNotFound
242 from pyramid.httpexceptions import HTTPNotFound
243
243
244 try:
244 try:
245 id_ = int(id_)
245 id_ = int(id_)
246 except (TypeError, ValueError):
246 except (TypeError, ValueError):
247 raise HTTPNotFound()
247 raise HTTPNotFound()
248
248
249 res = cls.query().get(id_)
249 res = cls.query().get(id_)
250 if not res:
250 if not res:
251 raise HTTPNotFound()
251 raise HTTPNotFound()
252 return res
252 return res
253
253
254 @classmethod
254 @classmethod
255 def getAll(cls):
255 def getAll(cls):
256 # deprecated and left for backward compatibility
256 # deprecated and left for backward compatibility
257 return cls.get_all()
257 return cls.get_all()
258
258
259 @classmethod
259 @classmethod
260 def get_all(cls):
260 def get_all(cls):
261 return cls.query().all()
261 return cls.query().all()
262
262
263 @classmethod
263 @classmethod
264 def delete(cls, id_):
264 def delete(cls, id_):
265 obj = cls.query().get(id_)
265 obj = cls.query().get(id_)
266 Session().delete(obj)
266 Session().delete(obj)
267
267
268 @classmethod
268 @classmethod
269 def identity_cache(cls, session, attr_name, value):
269 def identity_cache(cls, session, attr_name, value):
270 exist_in_session = []
270 exist_in_session = []
271 for (item_cls, pkey), instance in session.identity_map.items():
271 for (item_cls, pkey), instance in session.identity_map.items():
272 if cls == item_cls and getattr(instance, attr_name) == value:
272 if cls == item_cls and getattr(instance, attr_name) == value:
273 exist_in_session.append(instance)
273 exist_in_session.append(instance)
274 if exist_in_session:
274 if exist_in_session:
275 if len(exist_in_session) == 1:
275 if len(exist_in_session) == 1:
276 return exist_in_session[0]
276 return exist_in_session[0]
277 log.exception(
277 log.exception(
278 'multiple objects with attr %s and '
278 'multiple objects with attr %s and '
279 'value %s found with same name: %r',
279 'value %s found with same name: %r',
280 attr_name, value, exist_in_session)
280 attr_name, value, exist_in_session)
281
281
282 def __repr__(self):
282 def __repr__(self):
283 if hasattr(self, '__unicode__'):
283 if hasattr(self, '__unicode__'):
284 # python repr needs to return str
284 # python repr needs to return str
285 try:
285 try:
286 return safe_str(self.__unicode__())
286 return safe_str(self.__unicode__())
287 except UnicodeDecodeError:
287 except UnicodeDecodeError:
288 pass
288 pass
289 return '<DB:%s>' % (self.__class__.__name__)
289 return '<DB:%s>' % (self.__class__.__name__)
290
290
291
291
292 class RhodeCodeSetting(Base, BaseModel):
292 class RhodeCodeSetting(Base, BaseModel):
293 __tablename__ = 'rhodecode_settings'
293 __tablename__ = 'rhodecode_settings'
294 __table_args__ = (
294 __table_args__ = (
295 UniqueConstraint('app_settings_name'),
295 UniqueConstraint('app_settings_name'),
296 {'extend_existing': True, 'mysql_engine': 'InnoDB',
296 {'extend_existing': True, 'mysql_engine': 'InnoDB',
297 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
297 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
298 )
298 )
299
299
300 SETTINGS_TYPES = {
300 SETTINGS_TYPES = {
301 'str': safe_str,
301 'str': safe_str,
302 'int': safe_int,
302 'int': safe_int,
303 'unicode': safe_unicode,
303 'unicode': safe_unicode,
304 'bool': str2bool,
304 'bool': str2bool,
305 'list': functools.partial(aslist, sep=',')
305 'list': functools.partial(aslist, sep=',')
306 }
306 }
307 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
307 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
308 GLOBAL_CONF_KEY = 'app_settings'
308 GLOBAL_CONF_KEY = 'app_settings'
309
309
310 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
310 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
311 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
311 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
312 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
312 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
313 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
313 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
314
314
315 def __init__(self, key='', val='', type='unicode'):
315 def __init__(self, key='', val='', type='unicode'):
316 self.app_settings_name = key
316 self.app_settings_name = key
317 self.app_settings_type = type
317 self.app_settings_type = type
318 self.app_settings_value = val
318 self.app_settings_value = val
319
319
320 @validates('_app_settings_value')
320 @validates('_app_settings_value')
321 def validate_settings_value(self, key, val):
321 def validate_settings_value(self, key, val):
322 assert type(val) == unicode
322 assert type(val) == unicode
323 return val
323 return val
324
324
325 @hybrid_property
325 @hybrid_property
326 def app_settings_value(self):
326 def app_settings_value(self):
327 v = self._app_settings_value
327 v = self._app_settings_value
328 _type = self.app_settings_type
328 _type = self.app_settings_type
329 if _type:
329 if _type:
330 _type = self.app_settings_type.split('.')[0]
330 _type = self.app_settings_type.split('.')[0]
331 # decode the encrypted value
331 # decode the encrypted value
332 if 'encrypted' in self.app_settings_type:
332 if 'encrypted' in self.app_settings_type:
333 cipher = EncryptedTextValue()
333 cipher = EncryptedTextValue()
334 v = safe_unicode(cipher.process_result_value(v, None))
334 v = safe_unicode(cipher.process_result_value(v, None))
335
335
336 converter = self.SETTINGS_TYPES.get(_type) or \
336 converter = self.SETTINGS_TYPES.get(_type) or \
337 self.SETTINGS_TYPES['unicode']
337 self.SETTINGS_TYPES['unicode']
338 return converter(v)
338 return converter(v)
339
339
340 @app_settings_value.setter
340 @app_settings_value.setter
341 def app_settings_value(self, val):
341 def app_settings_value(self, val):
342 """
342 """
343 Setter that will always make sure we use unicode in app_settings_value
343 Setter that will always make sure we use unicode in app_settings_value
344
344
345 :param val:
345 :param val:
346 """
346 """
347 val = safe_unicode(val)
347 val = safe_unicode(val)
348 # encode the encrypted value
348 # encode the encrypted value
349 if 'encrypted' in self.app_settings_type:
349 if 'encrypted' in self.app_settings_type:
350 cipher = EncryptedTextValue()
350 cipher = EncryptedTextValue()
351 val = safe_unicode(cipher.process_bind_param(val, None))
351 val = safe_unicode(cipher.process_bind_param(val, None))
352 self._app_settings_value = val
352 self._app_settings_value = val
353
353
354 @hybrid_property
354 @hybrid_property
355 def app_settings_type(self):
355 def app_settings_type(self):
356 return self._app_settings_type
356 return self._app_settings_type
357
357
358 @app_settings_type.setter
358 @app_settings_type.setter
359 def app_settings_type(self, val):
359 def app_settings_type(self, val):
360 if val.split('.')[0] not in self.SETTINGS_TYPES:
360 if val.split('.')[0] not in self.SETTINGS_TYPES:
361 raise Exception('type must be one of %s got %s'
361 raise Exception('type must be one of %s got %s'
362 % (self.SETTINGS_TYPES.keys(), val))
362 % (self.SETTINGS_TYPES.keys(), val))
363 self._app_settings_type = val
363 self._app_settings_type = val
364
364
365 def __unicode__(self):
365 def __unicode__(self):
366 return u"<%s('%s:%s[%s]')>" % (
366 return u"<%s('%s:%s[%s]')>" % (
367 self.__class__.__name__,
367 self.__class__.__name__,
368 self.app_settings_name, self.app_settings_value,
368 self.app_settings_name, self.app_settings_value,
369 self.app_settings_type
369 self.app_settings_type
370 )
370 )
371
371
372
372
373 class RhodeCodeUi(Base, BaseModel):
373 class RhodeCodeUi(Base, BaseModel):
374 __tablename__ = 'rhodecode_ui'
374 __tablename__ = 'rhodecode_ui'
375 __table_args__ = (
375 __table_args__ = (
376 UniqueConstraint('ui_key'),
376 UniqueConstraint('ui_key'),
377 {'extend_existing': True, 'mysql_engine': 'InnoDB',
377 {'extend_existing': True, 'mysql_engine': 'InnoDB',
378 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
378 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
379 )
379 )
380
380
381 HOOK_REPO_SIZE = 'changegroup.repo_size'
381 HOOK_REPO_SIZE = 'changegroup.repo_size'
382 # HG
382 # HG
383 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
383 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
384 HOOK_PULL = 'outgoing.pull_logger'
384 HOOK_PULL = 'outgoing.pull_logger'
385 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
385 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
386 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
386 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
387 HOOK_PUSH = 'changegroup.push_logger'
387 HOOK_PUSH = 'changegroup.push_logger'
388 HOOK_PUSH_KEY = 'pushkey.key_push'
388 HOOK_PUSH_KEY = 'pushkey.key_push'
389
389
390 # TODO: johbo: Unify way how hooks are configured for git and hg,
390 # TODO: johbo: Unify way how hooks are configured for git and hg,
391 # git part is currently hardcoded.
391 # git part is currently hardcoded.
392
392
393 # SVN PATTERNS
393 # SVN PATTERNS
394 SVN_BRANCH_ID = 'vcs_svn_branch'
394 SVN_BRANCH_ID = 'vcs_svn_branch'
395 SVN_TAG_ID = 'vcs_svn_tag'
395 SVN_TAG_ID = 'vcs_svn_tag'
396
396
397 ui_id = Column(
397 ui_id = Column(
398 "ui_id", Integer(), nullable=False, unique=True, default=None,
398 "ui_id", Integer(), nullable=False, unique=True, default=None,
399 primary_key=True)
399 primary_key=True)
400 ui_section = Column(
400 ui_section = Column(
401 "ui_section", String(255), nullable=True, unique=None, default=None)
401 "ui_section", String(255), nullable=True, unique=None, default=None)
402 ui_key = Column(
402 ui_key = Column(
403 "ui_key", String(255), nullable=True, unique=None, default=None)
403 "ui_key", String(255), nullable=True, unique=None, default=None)
404 ui_value = Column(
404 ui_value = Column(
405 "ui_value", String(255), nullable=True, unique=None, default=None)
405 "ui_value", String(255), nullable=True, unique=None, default=None)
406 ui_active = Column(
406 ui_active = Column(
407 "ui_active", Boolean(), nullable=True, unique=None, default=True)
407 "ui_active", Boolean(), nullable=True, unique=None, default=True)
408
408
409 def __repr__(self):
409 def __repr__(self):
410 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
410 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
411 self.ui_key, self.ui_value)
411 self.ui_key, self.ui_value)
412
412
413
413
414 class RepoRhodeCodeSetting(Base, BaseModel):
414 class RepoRhodeCodeSetting(Base, BaseModel):
415 __tablename__ = 'repo_rhodecode_settings'
415 __tablename__ = 'repo_rhodecode_settings'
416 __table_args__ = (
416 __table_args__ = (
417 UniqueConstraint(
417 UniqueConstraint(
418 'app_settings_name', 'repository_id',
418 'app_settings_name', 'repository_id',
419 name='uq_repo_rhodecode_setting_name_repo_id'),
419 name='uq_repo_rhodecode_setting_name_repo_id'),
420 {'extend_existing': True, 'mysql_engine': 'InnoDB',
420 {'extend_existing': True, 'mysql_engine': 'InnoDB',
421 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
421 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
422 )
422 )
423
423
424 repository_id = Column(
424 repository_id = Column(
425 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
425 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
426 nullable=False)
426 nullable=False)
427 app_settings_id = Column(
427 app_settings_id = Column(
428 "app_settings_id", Integer(), nullable=False, unique=True,
428 "app_settings_id", Integer(), nullable=False, unique=True,
429 default=None, primary_key=True)
429 default=None, primary_key=True)
430 app_settings_name = Column(
430 app_settings_name = Column(
431 "app_settings_name", String(255), nullable=True, unique=None,
431 "app_settings_name", String(255), nullable=True, unique=None,
432 default=None)
432 default=None)
433 _app_settings_value = Column(
433 _app_settings_value = Column(
434 "app_settings_value", String(4096), nullable=True, unique=None,
434 "app_settings_value", String(4096), nullable=True, unique=None,
435 default=None)
435 default=None)
436 _app_settings_type = Column(
436 _app_settings_type = Column(
437 "app_settings_type", String(255), nullable=True, unique=None,
437 "app_settings_type", String(255), nullable=True, unique=None,
438 default=None)
438 default=None)
439
439
440 repository = relationship('Repository')
440 repository = relationship('Repository')
441
441
442 def __init__(self, repository_id, key='', val='', type='unicode'):
442 def __init__(self, repository_id, key='', val='', type='unicode'):
443 self.repository_id = repository_id
443 self.repository_id = repository_id
444 self.app_settings_name = key
444 self.app_settings_name = key
445 self.app_settings_type = type
445 self.app_settings_type = type
446 self.app_settings_value = val
446 self.app_settings_value = val
447
447
448 @validates('_app_settings_value')
448 @validates('_app_settings_value')
449 def validate_settings_value(self, key, val):
449 def validate_settings_value(self, key, val):
450 assert type(val) == unicode
450 assert type(val) == unicode
451 return val
451 return val
452
452
453 @hybrid_property
453 @hybrid_property
454 def app_settings_value(self):
454 def app_settings_value(self):
455 v = self._app_settings_value
455 v = self._app_settings_value
456 type_ = self.app_settings_type
456 type_ = self.app_settings_type
457 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
457 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
458 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
458 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
459 return converter(v)
459 return converter(v)
460
460
461 @app_settings_value.setter
461 @app_settings_value.setter
462 def app_settings_value(self, val):
462 def app_settings_value(self, val):
463 """
463 """
464 Setter that will always make sure we use unicode in app_settings_value
464 Setter that will always make sure we use unicode in app_settings_value
465
465
466 :param val:
466 :param val:
467 """
467 """
468 self._app_settings_value = safe_unicode(val)
468 self._app_settings_value = safe_unicode(val)
469
469
470 @hybrid_property
470 @hybrid_property
471 def app_settings_type(self):
471 def app_settings_type(self):
472 return self._app_settings_type
472 return self._app_settings_type
473
473
474 @app_settings_type.setter
474 @app_settings_type.setter
475 def app_settings_type(self, val):
475 def app_settings_type(self, val):
476 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
476 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
477 if val not in SETTINGS_TYPES:
477 if val not in SETTINGS_TYPES:
478 raise Exception('type must be one of %s got %s'
478 raise Exception('type must be one of %s got %s'
479 % (SETTINGS_TYPES.keys(), val))
479 % (SETTINGS_TYPES.keys(), val))
480 self._app_settings_type = val
480 self._app_settings_type = val
481
481
482 def __unicode__(self):
482 def __unicode__(self):
483 return u"<%s('%s:%s:%s[%s]')>" % (
483 return u"<%s('%s:%s:%s[%s]')>" % (
484 self.__class__.__name__, self.repository.repo_name,
484 self.__class__.__name__, self.repository.repo_name,
485 self.app_settings_name, self.app_settings_value,
485 self.app_settings_name, self.app_settings_value,
486 self.app_settings_type
486 self.app_settings_type
487 )
487 )
488
488
489
489
490 class RepoRhodeCodeUi(Base, BaseModel):
490 class RepoRhodeCodeUi(Base, BaseModel):
491 __tablename__ = 'repo_rhodecode_ui'
491 __tablename__ = 'repo_rhodecode_ui'
492 __table_args__ = (
492 __table_args__ = (
493 UniqueConstraint(
493 UniqueConstraint(
494 'repository_id', 'ui_section', 'ui_key',
494 'repository_id', 'ui_section', 'ui_key',
495 name='uq_repo_rhodecode_ui_repository_id_section_key'),
495 name='uq_repo_rhodecode_ui_repository_id_section_key'),
496 {'extend_existing': True, 'mysql_engine': 'InnoDB',
496 {'extend_existing': True, 'mysql_engine': 'InnoDB',
497 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
497 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
498 )
498 )
499
499
500 repository_id = Column(
500 repository_id = Column(
501 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
501 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
502 nullable=False)
502 nullable=False)
503 ui_id = Column(
503 ui_id = Column(
504 "ui_id", Integer(), nullable=False, unique=True, default=None,
504 "ui_id", Integer(), nullable=False, unique=True, default=None,
505 primary_key=True)
505 primary_key=True)
506 ui_section = Column(
506 ui_section = Column(
507 "ui_section", String(255), nullable=True, unique=None, default=None)
507 "ui_section", String(255), nullable=True, unique=None, default=None)
508 ui_key = Column(
508 ui_key = Column(
509 "ui_key", String(255), nullable=True, unique=None, default=None)
509 "ui_key", String(255), nullable=True, unique=None, default=None)
510 ui_value = Column(
510 ui_value = Column(
511 "ui_value", String(255), nullable=True, unique=None, default=None)
511 "ui_value", String(255), nullable=True, unique=None, default=None)
512 ui_active = Column(
512 ui_active = Column(
513 "ui_active", Boolean(), nullable=True, unique=None, default=True)
513 "ui_active", Boolean(), nullable=True, unique=None, default=True)
514
514
515 repository = relationship('Repository')
515 repository = relationship('Repository')
516
516
517 def __repr__(self):
517 def __repr__(self):
518 return '<%s[%s:%s]%s=>%s]>' % (
518 return '<%s[%s:%s]%s=>%s]>' % (
519 self.__class__.__name__, self.repository.repo_name,
519 self.__class__.__name__, self.repository.repo_name,
520 self.ui_section, self.ui_key, self.ui_value)
520 self.ui_section, self.ui_key, self.ui_value)
521
521
522
522
523 class User(Base, BaseModel):
523 class User(Base, BaseModel):
524 __tablename__ = 'users'
524 __tablename__ = 'users'
525 __table_args__ = (
525 __table_args__ = (
526 UniqueConstraint('username'), UniqueConstraint('email'),
526 UniqueConstraint('username'), UniqueConstraint('email'),
527 Index('u_username_idx', 'username'),
527 Index('u_username_idx', 'username'),
528 Index('u_email_idx', 'email'),
528 Index('u_email_idx', 'email'),
529 {'extend_existing': True, 'mysql_engine': 'InnoDB',
529 {'extend_existing': True, 'mysql_engine': 'InnoDB',
530 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
530 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
531 )
531 )
532 DEFAULT_USER = 'default'
532 DEFAULT_USER = 'default'
533 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
533 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
534 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
534 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
535
535
536 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
536 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
537 username = Column("username", String(255), nullable=True, unique=None, default=None)
537 username = Column("username", String(255), nullable=True, unique=None, default=None)
538 password = Column("password", String(255), nullable=True, unique=None, default=None)
538 password = Column("password", String(255), nullable=True, unique=None, default=None)
539 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
539 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
540 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
540 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
541 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
541 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
542 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
542 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
543 _email = Column("email", String(255), nullable=True, unique=None, default=None)
543 _email = Column("email", String(255), nullable=True, unique=None, default=None)
544 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
544 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
545 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
545 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
546
546
547 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
547 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
548 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
548 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
549 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
549 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
550 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
550 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
551 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
551 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
552 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
552 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
553
553
554 user_log = relationship('UserLog')
554 user_log = relationship('UserLog')
555 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
555 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
556
556
557 repositories = relationship('Repository')
557 repositories = relationship('Repository')
558 repository_groups = relationship('RepoGroup')
558 repository_groups = relationship('RepoGroup')
559 user_groups = relationship('UserGroup')
559 user_groups = relationship('UserGroup')
560
560
561 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
561 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
562 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
562 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
563
563
564 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
564 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
565 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
565 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
566 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
566 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
567
567
568 group_member = relationship('UserGroupMember', cascade='all')
568 group_member = relationship('UserGroupMember', cascade='all')
569
569
570 notifications = relationship('UserNotification', cascade='all')
570 notifications = relationship('UserNotification', cascade='all')
571 # notifications assigned to this user
571 # notifications assigned to this user
572 user_created_notifications = relationship('Notification', cascade='all')
572 user_created_notifications = relationship('Notification', cascade='all')
573 # comments created by this user
573 # comments created by this user
574 user_comments = relationship('ChangesetComment', cascade='all')
574 user_comments = relationship('ChangesetComment', cascade='all')
575 # user profile extra info
575 # user profile extra info
576 user_emails = relationship('UserEmailMap', cascade='all')
576 user_emails = relationship('UserEmailMap', cascade='all')
577 user_ip_map = relationship('UserIpMap', cascade='all')
577 user_ip_map = relationship('UserIpMap', cascade='all')
578 user_auth_tokens = relationship('UserApiKeys', cascade='all')
578 user_auth_tokens = relationship('UserApiKeys', cascade='all')
579 user_ssh_keys = relationship('UserSshKeys', cascade='all')
579 user_ssh_keys = relationship('UserSshKeys', cascade='all')
580
580
581 # gists
581 # gists
582 user_gists = relationship('Gist', cascade='all')
582 user_gists = relationship('Gist', cascade='all')
583 # user pull requests
583 # user pull requests
584 user_pull_requests = relationship('PullRequest', cascade='all')
584 user_pull_requests = relationship('PullRequest', cascade='all')
585 # external identities
585 # external identities
586 extenal_identities = relationship(
586 extenal_identities = relationship(
587 'ExternalIdentity',
587 'ExternalIdentity',
588 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
588 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
589 cascade='all')
589 cascade='all')
590 # review rules
590 # review rules
591 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
591 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
592
592
593 def __unicode__(self):
593 def __unicode__(self):
594 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
594 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
595 self.user_id, self.username)
595 self.user_id, self.username)
596
596
597 @hybrid_property
597 @hybrid_property
598 def email(self):
598 def email(self):
599 return self._email
599 return self._email
600
600
601 @email.setter
601 @email.setter
602 def email(self, val):
602 def email(self, val):
603 self._email = val.lower() if val else None
603 self._email = val.lower() if val else None
604
604
605 @hybrid_property
605 @hybrid_property
606 def first_name(self):
606 def first_name(self):
607 from rhodecode.lib import helpers as h
607 from rhodecode.lib import helpers as h
608 if self.name:
608 if self.name:
609 return h.escape(self.name)
609 return h.escape(self.name)
610 return self.name
610 return self.name
611
611
612 @hybrid_property
612 @hybrid_property
613 def last_name(self):
613 def last_name(self):
614 from rhodecode.lib import helpers as h
614 from rhodecode.lib import helpers as h
615 if self.lastname:
615 if self.lastname:
616 return h.escape(self.lastname)
616 return h.escape(self.lastname)
617 return self.lastname
617 return self.lastname
618
618
619 @hybrid_property
619 @hybrid_property
620 def api_key(self):
620 def api_key(self):
621 """
621 """
622 Fetch if exist an auth-token with role ALL connected to this user
622 Fetch if exist an auth-token with role ALL connected to this user
623 """
623 """
624 user_auth_token = UserApiKeys.query()\
624 user_auth_token = UserApiKeys.query()\
625 .filter(UserApiKeys.user_id == self.user_id)\
625 .filter(UserApiKeys.user_id == self.user_id)\
626 .filter(or_(UserApiKeys.expires == -1,
626 .filter(or_(UserApiKeys.expires == -1,
627 UserApiKeys.expires >= time.time()))\
627 UserApiKeys.expires >= time.time()))\
628 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
628 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
629 if user_auth_token:
629 if user_auth_token:
630 user_auth_token = user_auth_token.api_key
630 user_auth_token = user_auth_token.api_key
631
631
632 return user_auth_token
632 return user_auth_token
633
633
634 @api_key.setter
634 @api_key.setter
635 def api_key(self, val):
635 def api_key(self, val):
636 # don't allow to set API key this is deprecated for now
636 # don't allow to set API key this is deprecated for now
637 self._api_key = None
637 self._api_key = None
638
638
639 @property
639 @property
640 def reviewer_pull_requests(self):
640 def reviewer_pull_requests(self):
641 return PullRequestReviewers.query() \
641 return PullRequestReviewers.query() \
642 .options(joinedload(PullRequestReviewers.pull_request)) \
642 .options(joinedload(PullRequestReviewers.pull_request)) \
643 .filter(PullRequestReviewers.user_id == self.user_id) \
643 .filter(PullRequestReviewers.user_id == self.user_id) \
644 .all()
644 .all()
645
645
646 @property
646 @property
647 def firstname(self):
647 def firstname(self):
648 # alias for future
648 # alias for future
649 return self.name
649 return self.name
650
650
651 @property
651 @property
652 def emails(self):
652 def emails(self):
653 other = UserEmailMap.query()\
653 other = UserEmailMap.query()\
654 .filter(UserEmailMap.user == self) \
654 .filter(UserEmailMap.user == self) \
655 .order_by(UserEmailMap.email_id.asc()) \
655 .order_by(UserEmailMap.email_id.asc()) \
656 .all()
656 .all()
657 return [self.email] + [x.email for x in other]
657 return [self.email] + [x.email for x in other]
658
658
659 @property
659 @property
660 def auth_tokens(self):
660 def auth_tokens(self):
661 auth_tokens = self.get_auth_tokens()
661 auth_tokens = self.get_auth_tokens()
662 return [x.api_key for x in auth_tokens]
662 return [x.api_key for x in auth_tokens]
663
663
664 def get_auth_tokens(self):
664 def get_auth_tokens(self):
665 return UserApiKeys.query()\
665 return UserApiKeys.query()\
666 .filter(UserApiKeys.user == self)\
666 .filter(UserApiKeys.user == self)\
667 .order_by(UserApiKeys.user_api_key_id.asc())\
667 .order_by(UserApiKeys.user_api_key_id.asc())\
668 .all()
668 .all()
669
669
670 @property
670 @property
671 def feed_token(self):
671 def feed_token(self):
672 return self.get_feed_token()
672 return self.get_feed_token()
673
673
674 def get_feed_token(self):
674 def get_feed_token(self):
675 feed_tokens = UserApiKeys.query()\
675 feed_tokens = UserApiKeys.query()\
676 .filter(UserApiKeys.user == self)\
676 .filter(UserApiKeys.user == self)\
677 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)\
677 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)\
678 .all()
678 .all()
679 if feed_tokens:
679 if feed_tokens:
680 return feed_tokens[0].api_key
680 return feed_tokens[0].api_key
681 return 'NO_FEED_TOKEN_AVAILABLE'
681 return 'NO_FEED_TOKEN_AVAILABLE'
682
682
683 @classmethod
683 @classmethod
684 def get(cls, user_id, cache=False):
685 if not user_id:
686 return
687
688 user = cls.query()
689 if cache:
690 user = user.options(
691 FromCache("sql_cache_short", "get_users_%s" % user_id))
692 return user.get(user_id)
693
694 @classmethod
684 def extra_valid_auth_tokens(cls, user, role=None):
695 def extra_valid_auth_tokens(cls, user, role=None):
685 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
696 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
686 .filter(or_(UserApiKeys.expires == -1,
697 .filter(or_(UserApiKeys.expires == -1,
687 UserApiKeys.expires >= time.time()))
698 UserApiKeys.expires >= time.time()))
688 if role:
699 if role:
689 tokens = tokens.filter(or_(UserApiKeys.role == role,
700 tokens = tokens.filter(or_(UserApiKeys.role == role,
690 UserApiKeys.role == UserApiKeys.ROLE_ALL))
701 UserApiKeys.role == UserApiKeys.ROLE_ALL))
691 return tokens.all()
702 return tokens.all()
692
703
693 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
704 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
694 from rhodecode.lib import auth
705 from rhodecode.lib import auth
695
706
696 log.debug('Trying to authenticate user: %s via auth-token, '
707 log.debug('Trying to authenticate user: %s via auth-token, '
697 'and roles: %s', self, roles)
708 'and roles: %s', self, roles)
698
709
699 if not auth_token:
710 if not auth_token:
700 return False
711 return False
701
712
702 crypto_backend = auth.crypto_backend()
713 crypto_backend = auth.crypto_backend()
703
714
704 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
715 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
705 tokens_q = UserApiKeys.query()\
716 tokens_q = UserApiKeys.query()\
706 .filter(UserApiKeys.user_id == self.user_id)\
717 .filter(UserApiKeys.user_id == self.user_id)\
707 .filter(or_(UserApiKeys.expires == -1,
718 .filter(or_(UserApiKeys.expires == -1,
708 UserApiKeys.expires >= time.time()))
719 UserApiKeys.expires >= time.time()))
709
720
710 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
721 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
711
722
712 plain_tokens = []
723 plain_tokens = []
713 hash_tokens = []
724 hash_tokens = []
714
725
715 for token in tokens_q.all():
726 for token in tokens_q.all():
716 # verify scope first
727 # verify scope first
717 if token.repo_id:
728 if token.repo_id:
718 # token has a scope, we need to verify it
729 # token has a scope, we need to verify it
719 if scope_repo_id != token.repo_id:
730 if scope_repo_id != token.repo_id:
720 log.debug(
731 log.debug(
721 'Scope mismatch: token has a set repo scope: %s, '
732 'Scope mismatch: token has a set repo scope: %s, '
722 'and calling scope is:%s, skipping further checks',
733 'and calling scope is:%s, skipping further checks',
723 token.repo, scope_repo_id)
734 token.repo, scope_repo_id)
724 # token has a scope, and it doesn't match, skip token
735 # token has a scope, and it doesn't match, skip token
725 continue
736 continue
726
737
727 if token.api_key.startswith(crypto_backend.ENC_PREF):
738 if token.api_key.startswith(crypto_backend.ENC_PREF):
728 hash_tokens.append(token.api_key)
739 hash_tokens.append(token.api_key)
729 else:
740 else:
730 plain_tokens.append(token.api_key)
741 plain_tokens.append(token.api_key)
731
742
732 is_plain_match = auth_token in plain_tokens
743 is_plain_match = auth_token in plain_tokens
733 if is_plain_match:
744 if is_plain_match:
734 return True
745 return True
735
746
736 for hashed in hash_tokens:
747 for hashed in hash_tokens:
737 # TODO(marcink): this is expensive to calculate, but most secure
748 # TODO(marcink): this is expensive to calculate, but most secure
738 match = crypto_backend.hash_check(auth_token, hashed)
749 match = crypto_backend.hash_check(auth_token, hashed)
739 if match:
750 if match:
740 return True
751 return True
741
752
742 return False
753 return False
743
754
744 @property
755 @property
745 def ip_addresses(self):
756 def ip_addresses(self):
746 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
757 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
747 return [x.ip_addr for x in ret]
758 return [x.ip_addr for x in ret]
748
759
749 @property
760 @property
750 def username_and_name(self):
761 def username_and_name(self):
751 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
762 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
752
763
753 @property
764 @property
754 def username_or_name_or_email(self):
765 def username_or_name_or_email(self):
755 full_name = self.full_name if self.full_name is not ' ' else None
766 full_name = self.full_name if self.full_name is not ' ' else None
756 return self.username or full_name or self.email
767 return self.username or full_name or self.email
757
768
758 @property
769 @property
759 def full_name(self):
770 def full_name(self):
760 return '%s %s' % (self.first_name, self.last_name)
771 return '%s %s' % (self.first_name, self.last_name)
761
772
762 @property
773 @property
763 def full_name_or_username(self):
774 def full_name_or_username(self):
764 return ('%s %s' % (self.first_name, self.last_name)
775 return ('%s %s' % (self.first_name, self.last_name)
765 if (self.first_name and self.last_name) else self.username)
776 if (self.first_name and self.last_name) else self.username)
766
777
767 @property
778 @property
768 def full_contact(self):
779 def full_contact(self):
769 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
780 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
770
781
771 @property
782 @property
772 def short_contact(self):
783 def short_contact(self):
773 return '%s %s' % (self.first_name, self.last_name)
784 return '%s %s' % (self.first_name, self.last_name)
774
785
775 @property
786 @property
776 def is_admin(self):
787 def is_admin(self):
777 return self.admin
788 return self.admin
778
789
779 def AuthUser(self, **kwargs):
790 def AuthUser(self, **kwargs):
780 """
791 """
781 Returns instance of AuthUser for this user
792 Returns instance of AuthUser for this user
782 """
793 """
783 from rhodecode.lib.auth import AuthUser
794 from rhodecode.lib.auth import AuthUser
784 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
795 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
785
796
786 @hybrid_property
797 @hybrid_property
787 def user_data(self):
798 def user_data(self):
788 if not self._user_data:
799 if not self._user_data:
789 return {}
800 return {}
790
801
791 try:
802 try:
792 return json.loads(self._user_data)
803 return json.loads(self._user_data)
793 except TypeError:
804 except TypeError:
794 return {}
805 return {}
795
806
796 @user_data.setter
807 @user_data.setter
797 def user_data(self, val):
808 def user_data(self, val):
798 if not isinstance(val, dict):
809 if not isinstance(val, dict):
799 raise Exception('user_data must be dict, got %s' % type(val))
810 raise Exception('user_data must be dict, got %s' % type(val))
800 try:
811 try:
801 self._user_data = json.dumps(val)
812 self._user_data = json.dumps(val)
802 except Exception:
813 except Exception:
803 log.error(traceback.format_exc())
814 log.error(traceback.format_exc())
804
815
805 @classmethod
816 @classmethod
806 def get_by_username(cls, username, case_insensitive=False,
817 def get_by_username(cls, username, case_insensitive=False,
807 cache=False, identity_cache=False):
818 cache=False, identity_cache=False):
808 session = Session()
819 session = Session()
809
820
810 if case_insensitive:
821 if case_insensitive:
811 q = cls.query().filter(
822 q = cls.query().filter(
812 func.lower(cls.username) == func.lower(username))
823 func.lower(cls.username) == func.lower(username))
813 else:
824 else:
814 q = cls.query().filter(cls.username == username)
825 q = cls.query().filter(cls.username == username)
815
826
816 if cache:
827 if cache:
817 if identity_cache:
828 if identity_cache:
818 val = cls.identity_cache(session, 'username', username)
829 val = cls.identity_cache(session, 'username', username)
819 if val:
830 if val:
820 return val
831 return val
821 else:
832 else:
822 cache_key = "get_user_by_name_%s" % _hash_key(username)
833 cache_key = "get_user_by_name_%s" % _hash_key(username)
823 q = q.options(
834 q = q.options(
824 FromCache("sql_cache_short", cache_key))
835 FromCache("sql_cache_short", cache_key))
825
836
826 return q.scalar()
837 return q.scalar()
827
838
828 @classmethod
839 @classmethod
829 def get_by_auth_token(cls, auth_token, cache=False):
840 def get_by_auth_token(cls, auth_token, cache=False):
830 q = UserApiKeys.query()\
841 q = UserApiKeys.query()\
831 .filter(UserApiKeys.api_key == auth_token)\
842 .filter(UserApiKeys.api_key == auth_token)\
832 .filter(or_(UserApiKeys.expires == -1,
843 .filter(or_(UserApiKeys.expires == -1,
833 UserApiKeys.expires >= time.time()))
844 UserApiKeys.expires >= time.time()))
834 if cache:
845 if cache:
835 q = q.options(
846 q = q.options(
836 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
847 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
837
848
838 match = q.first()
849 match = q.first()
839 if match:
850 if match:
840 return match.user
851 return match.user
841
852
842 @classmethod
853 @classmethod
843 def get_by_email(cls, email, case_insensitive=False, cache=False):
854 def get_by_email(cls, email, case_insensitive=False, cache=False):
844
855
845 if case_insensitive:
856 if case_insensitive:
846 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
857 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
847
858
848 else:
859 else:
849 q = cls.query().filter(cls.email == email)
860 q = cls.query().filter(cls.email == email)
850
861
851 email_key = _hash_key(email)
862 email_key = _hash_key(email)
852 if cache:
863 if cache:
853 q = q.options(
864 q = q.options(
854 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
865 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
855
866
856 ret = q.scalar()
867 ret = q.scalar()
857 if ret is None:
868 if ret is None:
858 q = UserEmailMap.query()
869 q = UserEmailMap.query()
859 # try fetching in alternate email map
870 # try fetching in alternate email map
860 if case_insensitive:
871 if case_insensitive:
861 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
872 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
862 else:
873 else:
863 q = q.filter(UserEmailMap.email == email)
874 q = q.filter(UserEmailMap.email == email)
864 q = q.options(joinedload(UserEmailMap.user))
875 q = q.options(joinedload(UserEmailMap.user))
865 if cache:
876 if cache:
866 q = q.options(
877 q = q.options(
867 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
878 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
868 ret = getattr(q.scalar(), 'user', None)
879 ret = getattr(q.scalar(), 'user', None)
869
880
870 return ret
881 return ret
871
882
872 @classmethod
883 @classmethod
873 def get_from_cs_author(cls, author):
884 def get_from_cs_author(cls, author):
874 """
885 """
875 Tries to get User objects out of commit author string
886 Tries to get User objects out of commit author string
876
887
877 :param author:
888 :param author:
878 """
889 """
879 from rhodecode.lib.helpers import email, author_name
890 from rhodecode.lib.helpers import email, author_name
880 # Valid email in the attribute passed, see if they're in the system
891 # Valid email in the attribute passed, see if they're in the system
881 _email = email(author)
892 _email = email(author)
882 if _email:
893 if _email:
883 user = cls.get_by_email(_email, case_insensitive=True)
894 user = cls.get_by_email(_email, case_insensitive=True)
884 if user:
895 if user:
885 return user
896 return user
886 # Maybe we can match by username?
897 # Maybe we can match by username?
887 _author = author_name(author)
898 _author = author_name(author)
888 user = cls.get_by_username(_author, case_insensitive=True)
899 user = cls.get_by_username(_author, case_insensitive=True)
889 if user:
900 if user:
890 return user
901 return user
891
902
892 def update_userdata(self, **kwargs):
903 def update_userdata(self, **kwargs):
893 usr = self
904 usr = self
894 old = usr.user_data
905 old = usr.user_data
895 old.update(**kwargs)
906 old.update(**kwargs)
896 usr.user_data = old
907 usr.user_data = old
897 Session().add(usr)
908 Session().add(usr)
898 log.debug('updated userdata with ', kwargs)
909 log.debug('updated userdata with ', kwargs)
899
910
900 def update_lastlogin(self):
911 def update_lastlogin(self):
901 """Update user lastlogin"""
912 """Update user lastlogin"""
902 self.last_login = datetime.datetime.now()
913 self.last_login = datetime.datetime.now()
903 Session().add(self)
914 Session().add(self)
904 log.debug('updated user %s lastlogin', self.username)
915 log.debug('updated user %s lastlogin', self.username)
905
916
906 def update_lastactivity(self):
917 def update_lastactivity(self):
907 """Update user lastactivity"""
918 """Update user lastactivity"""
908 self.last_activity = datetime.datetime.now()
919 self.last_activity = datetime.datetime.now()
909 Session().add(self)
920 Session().add(self)
910 log.debug('updated user %s lastactivity', self.username)
921 log.debug('updated user %s lastactivity', self.username)
911
922
912 def update_password(self, new_password):
923 def update_password(self, new_password):
913 from rhodecode.lib.auth import get_crypt_password
924 from rhodecode.lib.auth import get_crypt_password
914
925
915 self.password = get_crypt_password(new_password)
926 self.password = get_crypt_password(new_password)
916 Session().add(self)
927 Session().add(self)
917
928
918 @classmethod
929 @classmethod
919 def get_first_super_admin(cls):
930 def get_first_super_admin(cls):
920 user = User.query().filter(User.admin == true()).first()
931 user = User.query().filter(User.admin == true()).first()
921 if user is None:
932 if user is None:
922 raise Exception('FATAL: Missing administrative account!')
933 raise Exception('FATAL: Missing administrative account!')
923 return user
934 return user
924
935
925 @classmethod
936 @classmethod
926 def get_all_super_admins(cls):
937 def get_all_super_admins(cls):
927 """
938 """
928 Returns all admin accounts sorted by username
939 Returns all admin accounts sorted by username
929 """
940 """
930 return User.query().filter(User.admin == true())\
941 return User.query().filter(User.admin == true())\
931 .order_by(User.username.asc()).all()
942 .order_by(User.username.asc()).all()
932
943
933 @classmethod
944 @classmethod
934 def get_default_user(cls, cache=False, refresh=False):
945 def get_default_user(cls, cache=False, refresh=False):
935 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
946 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
936 if user is None:
947 if user is None:
937 raise Exception('FATAL: Missing default account!')
948 raise Exception('FATAL: Missing default account!')
938 if refresh:
949 if refresh:
939 # The default user might be based on outdated state which
950 # The default user might be based on outdated state which
940 # has been loaded from the cache.
951 # has been loaded from the cache.
941 # A call to refresh() ensures that the
952 # A call to refresh() ensures that the
942 # latest state from the database is used.
953 # latest state from the database is used.
943 Session().refresh(user)
954 Session().refresh(user)
944 return user
955 return user
945
956
946 def _get_default_perms(self, user, suffix=''):
957 def _get_default_perms(self, user, suffix=''):
947 from rhodecode.model.permission import PermissionModel
958 from rhodecode.model.permission import PermissionModel
948 return PermissionModel().get_default_perms(user.user_perms, suffix)
959 return PermissionModel().get_default_perms(user.user_perms, suffix)
949
960
950 def get_default_perms(self, suffix=''):
961 def get_default_perms(self, suffix=''):
951 return self._get_default_perms(self, suffix)
962 return self._get_default_perms(self, suffix)
952
963
953 def get_api_data(self, include_secrets=False, details='full'):
964 def get_api_data(self, include_secrets=False, details='full'):
954 """
965 """
955 Common function for generating user related data for API
966 Common function for generating user related data for API
956
967
957 :param include_secrets: By default secrets in the API data will be replaced
968 :param include_secrets: By default secrets in the API data will be replaced
958 by a placeholder value to prevent exposing this data by accident. In case
969 by a placeholder value to prevent exposing this data by accident. In case
959 this data shall be exposed, set this flag to ``True``.
970 this data shall be exposed, set this flag to ``True``.
960
971
961 :param details: details can be 'basic|full' basic gives only a subset of
972 :param details: details can be 'basic|full' basic gives only a subset of
962 the available user information that includes user_id, name and emails.
973 the available user information that includes user_id, name and emails.
963 """
974 """
964 user = self
975 user = self
965 user_data = self.user_data
976 user_data = self.user_data
966 data = {
977 data = {
967 'user_id': user.user_id,
978 'user_id': user.user_id,
968 'username': user.username,
979 'username': user.username,
969 'firstname': user.name,
980 'firstname': user.name,
970 'lastname': user.lastname,
981 'lastname': user.lastname,
971 'email': user.email,
982 'email': user.email,
972 'emails': user.emails,
983 'emails': user.emails,
973 }
984 }
974 if details == 'basic':
985 if details == 'basic':
975 return data
986 return data
976
987
977 auth_token_length = 40
988 auth_token_length = 40
978 auth_token_replacement = '*' * auth_token_length
989 auth_token_replacement = '*' * auth_token_length
979
990
980 extras = {
991 extras = {
981 'auth_tokens': [auth_token_replacement],
992 'auth_tokens': [auth_token_replacement],
982 'active': user.active,
993 'active': user.active,
983 'admin': user.admin,
994 'admin': user.admin,
984 'extern_type': user.extern_type,
995 'extern_type': user.extern_type,
985 'extern_name': user.extern_name,
996 'extern_name': user.extern_name,
986 'last_login': user.last_login,
997 'last_login': user.last_login,
987 'last_activity': user.last_activity,
998 'last_activity': user.last_activity,
988 'ip_addresses': user.ip_addresses,
999 'ip_addresses': user.ip_addresses,
989 'language': user_data.get('language')
1000 'language': user_data.get('language')
990 }
1001 }
991 data.update(extras)
1002 data.update(extras)
992
1003
993 if include_secrets:
1004 if include_secrets:
994 data['auth_tokens'] = user.auth_tokens
1005 data['auth_tokens'] = user.auth_tokens
995 return data
1006 return data
996
1007
997 def __json__(self):
1008 def __json__(self):
998 data = {
1009 data = {
999 'full_name': self.full_name,
1010 'full_name': self.full_name,
1000 'full_name_or_username': self.full_name_or_username,
1011 'full_name_or_username': self.full_name_or_username,
1001 'short_contact': self.short_contact,
1012 'short_contact': self.short_contact,
1002 'full_contact': self.full_contact,
1013 'full_contact': self.full_contact,
1003 }
1014 }
1004 data.update(self.get_api_data())
1015 data.update(self.get_api_data())
1005 return data
1016 return data
1006
1017
1007
1018
1008 class UserApiKeys(Base, BaseModel):
1019 class UserApiKeys(Base, BaseModel):
1009 __tablename__ = 'user_api_keys'
1020 __tablename__ = 'user_api_keys'
1010 __table_args__ = (
1021 __table_args__ = (
1011 Index('uak_api_key_idx', 'api_key', unique=True),
1022 Index('uak_api_key_idx', 'api_key', unique=True),
1012 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1023 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1013 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1024 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1014 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1025 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1015 )
1026 )
1016 __mapper_args__ = {}
1027 __mapper_args__ = {}
1017
1028
1018 # ApiKey role
1029 # ApiKey role
1019 ROLE_ALL = 'token_role_all'
1030 ROLE_ALL = 'token_role_all'
1020 ROLE_HTTP = 'token_role_http'
1031 ROLE_HTTP = 'token_role_http'
1021 ROLE_VCS = 'token_role_vcs'
1032 ROLE_VCS = 'token_role_vcs'
1022 ROLE_API = 'token_role_api'
1033 ROLE_API = 'token_role_api'
1023 ROLE_FEED = 'token_role_feed'
1034 ROLE_FEED = 'token_role_feed'
1024 ROLE_PASSWORD_RESET = 'token_password_reset'
1035 ROLE_PASSWORD_RESET = 'token_password_reset'
1025
1036
1026 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
1037 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
1027
1038
1028 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1039 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1029 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1040 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1030 api_key = Column("api_key", String(255), nullable=False, unique=True)
1041 api_key = Column("api_key", String(255), nullable=False, unique=True)
1031 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1042 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1032 expires = Column('expires', Float(53), nullable=False)
1043 expires = Column('expires', Float(53), nullable=False)
1033 role = Column('role', String(255), nullable=True)
1044 role = Column('role', String(255), nullable=True)
1034 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1045 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1035
1046
1036 # scope columns
1047 # scope columns
1037 repo_id = Column(
1048 repo_id = Column(
1038 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1049 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1039 nullable=True, unique=None, default=None)
1050 nullable=True, unique=None, default=None)
1040 repo = relationship('Repository', lazy='joined')
1051 repo = relationship('Repository', lazy='joined')
1041
1052
1042 repo_group_id = Column(
1053 repo_group_id = Column(
1043 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1054 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1044 nullable=True, unique=None, default=None)
1055 nullable=True, unique=None, default=None)
1045 repo_group = relationship('RepoGroup', lazy='joined')
1056 repo_group = relationship('RepoGroup', lazy='joined')
1046
1057
1047 user = relationship('User', lazy='joined')
1058 user = relationship('User', lazy='joined')
1048
1059
1049 def __unicode__(self):
1060 def __unicode__(self):
1050 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1061 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1051
1062
1052 def __json__(self):
1063 def __json__(self):
1053 data = {
1064 data = {
1054 'auth_token': self.api_key,
1065 'auth_token': self.api_key,
1055 'role': self.role,
1066 'role': self.role,
1056 'scope': self.scope_humanized,
1067 'scope': self.scope_humanized,
1057 'expired': self.expired
1068 'expired': self.expired
1058 }
1069 }
1059 return data
1070 return data
1060
1071
1061 def get_api_data(self, include_secrets=False):
1072 def get_api_data(self, include_secrets=False):
1062 data = self.__json__()
1073 data = self.__json__()
1063 if include_secrets:
1074 if include_secrets:
1064 return data
1075 return data
1065 else:
1076 else:
1066 data['auth_token'] = self.token_obfuscated
1077 data['auth_token'] = self.token_obfuscated
1067 return data
1078 return data
1068
1079
1069 @hybrid_property
1080 @hybrid_property
1070 def description_safe(self):
1081 def description_safe(self):
1071 from rhodecode.lib import helpers as h
1082 from rhodecode.lib import helpers as h
1072 return h.escape(self.description)
1083 return h.escape(self.description)
1073
1084
1074 @property
1085 @property
1075 def expired(self):
1086 def expired(self):
1076 if self.expires == -1:
1087 if self.expires == -1:
1077 return False
1088 return False
1078 return time.time() > self.expires
1089 return time.time() > self.expires
1079
1090
1080 @classmethod
1091 @classmethod
1081 def _get_role_name(cls, role):
1092 def _get_role_name(cls, role):
1082 return {
1093 return {
1083 cls.ROLE_ALL: _('all'),
1094 cls.ROLE_ALL: _('all'),
1084 cls.ROLE_HTTP: _('http/web interface'),
1095 cls.ROLE_HTTP: _('http/web interface'),
1085 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1096 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1086 cls.ROLE_API: _('api calls'),
1097 cls.ROLE_API: _('api calls'),
1087 cls.ROLE_FEED: _('feed access'),
1098 cls.ROLE_FEED: _('feed access'),
1088 }.get(role, role)
1099 }.get(role, role)
1089
1100
1090 @property
1101 @property
1091 def role_humanized(self):
1102 def role_humanized(self):
1092 return self._get_role_name(self.role)
1103 return self._get_role_name(self.role)
1093
1104
1094 def _get_scope(self):
1105 def _get_scope(self):
1095 if self.repo:
1106 if self.repo:
1096 return repr(self.repo)
1107 return repr(self.repo)
1097 if self.repo_group:
1108 if self.repo_group:
1098 return repr(self.repo_group) + ' (recursive)'
1109 return repr(self.repo_group) + ' (recursive)'
1099 return 'global'
1110 return 'global'
1100
1111
1101 @property
1112 @property
1102 def scope_humanized(self):
1113 def scope_humanized(self):
1103 return self._get_scope()
1114 return self._get_scope()
1104
1115
1105 @property
1116 @property
1106 def token_obfuscated(self):
1117 def token_obfuscated(self):
1107 if self.api_key:
1118 if self.api_key:
1108 return self.api_key[:4] + "****"
1119 return self.api_key[:4] + "****"
1109
1120
1110
1121
1111 class UserEmailMap(Base, BaseModel):
1122 class UserEmailMap(Base, BaseModel):
1112 __tablename__ = 'user_email_map'
1123 __tablename__ = 'user_email_map'
1113 __table_args__ = (
1124 __table_args__ = (
1114 Index('uem_email_idx', 'email'),
1125 Index('uem_email_idx', 'email'),
1115 UniqueConstraint('email'),
1126 UniqueConstraint('email'),
1116 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1127 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1117 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1128 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1118 )
1129 )
1119 __mapper_args__ = {}
1130 __mapper_args__ = {}
1120
1131
1121 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1132 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1122 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1133 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1123 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1134 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1124 user = relationship('User', lazy='joined')
1135 user = relationship('User', lazy='joined')
1125
1136
1126 @validates('_email')
1137 @validates('_email')
1127 def validate_email(self, key, email):
1138 def validate_email(self, key, email):
1128 # check if this email is not main one
1139 # check if this email is not main one
1129 main_email = Session().query(User).filter(User.email == email).scalar()
1140 main_email = Session().query(User).filter(User.email == email).scalar()
1130 if main_email is not None:
1141 if main_email is not None:
1131 raise AttributeError('email %s is present is user table' % email)
1142 raise AttributeError('email %s is present is user table' % email)
1132 return email
1143 return email
1133
1144
1134 @hybrid_property
1145 @hybrid_property
1135 def email(self):
1146 def email(self):
1136 return self._email
1147 return self._email
1137
1148
1138 @email.setter
1149 @email.setter
1139 def email(self, val):
1150 def email(self, val):
1140 self._email = val.lower() if val else None
1151 self._email = val.lower() if val else None
1141
1152
1142
1153
1143 class UserIpMap(Base, BaseModel):
1154 class UserIpMap(Base, BaseModel):
1144 __tablename__ = 'user_ip_map'
1155 __tablename__ = 'user_ip_map'
1145 __table_args__ = (
1156 __table_args__ = (
1146 UniqueConstraint('user_id', 'ip_addr'),
1157 UniqueConstraint('user_id', 'ip_addr'),
1147 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1158 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1148 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1159 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1149 )
1160 )
1150 __mapper_args__ = {}
1161 __mapper_args__ = {}
1151
1162
1152 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1163 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1153 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1164 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1154 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1165 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1155 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1166 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1156 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1167 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1157 user = relationship('User', lazy='joined')
1168 user = relationship('User', lazy='joined')
1158
1169
1159 @hybrid_property
1170 @hybrid_property
1160 def description_safe(self):
1171 def description_safe(self):
1161 from rhodecode.lib import helpers as h
1172 from rhodecode.lib import helpers as h
1162 return h.escape(self.description)
1173 return h.escape(self.description)
1163
1174
1164 @classmethod
1175 @classmethod
1165 def _get_ip_range(cls, ip_addr):
1176 def _get_ip_range(cls, ip_addr):
1166 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1177 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1167 return [str(net.network_address), str(net.broadcast_address)]
1178 return [str(net.network_address), str(net.broadcast_address)]
1168
1179
1169 def __json__(self):
1180 def __json__(self):
1170 return {
1181 return {
1171 'ip_addr': self.ip_addr,
1182 'ip_addr': self.ip_addr,
1172 'ip_range': self._get_ip_range(self.ip_addr),
1183 'ip_range': self._get_ip_range(self.ip_addr),
1173 }
1184 }
1174
1185
1175 def __unicode__(self):
1186 def __unicode__(self):
1176 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1187 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1177 self.user_id, self.ip_addr)
1188 self.user_id, self.ip_addr)
1178
1189
1179
1190
1180 class UserSshKeys(Base, BaseModel):
1191 class UserSshKeys(Base, BaseModel):
1181 __tablename__ = 'user_ssh_keys'
1192 __tablename__ = 'user_ssh_keys'
1182 __table_args__ = (
1193 __table_args__ = (
1183 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1194 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1184
1195
1185 UniqueConstraint('ssh_key_fingerprint'),
1196 UniqueConstraint('ssh_key_fingerprint'),
1186
1197
1187 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1198 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1188 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1199 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1189 )
1200 )
1190 __mapper_args__ = {}
1201 __mapper_args__ = {}
1191
1202
1192 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1203 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1193 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1204 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1194 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(1024), nullable=False, unique=None, default=None)
1205 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(1024), nullable=False, unique=None, default=None)
1195
1206
1196 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1207 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1197
1208
1198 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1209 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1199 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1210 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1200 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1211 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1201
1212
1202 user = relationship('User', lazy='joined')
1213 user = relationship('User', lazy='joined')
1203
1214
1204 def __json__(self):
1215 def __json__(self):
1205 data = {
1216 data = {
1206 'ssh_fingerprint': self.ssh_key_fingerprint,
1217 'ssh_fingerprint': self.ssh_key_fingerprint,
1207 'description': self.description,
1218 'description': self.description,
1208 'created_on': self.created_on
1219 'created_on': self.created_on
1209 }
1220 }
1210 return data
1221 return data
1211
1222
1212 def get_api_data(self):
1223 def get_api_data(self):
1213 data = self.__json__()
1224 data = self.__json__()
1214 return data
1225 return data
1215
1226
1216
1227
1217 class UserLog(Base, BaseModel):
1228 class UserLog(Base, BaseModel):
1218 __tablename__ = 'user_logs'
1229 __tablename__ = 'user_logs'
1219 __table_args__ = (
1230 __table_args__ = (
1220 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1231 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1221 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1232 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1222 )
1233 )
1223 VERSION_1 = 'v1'
1234 VERSION_1 = 'v1'
1224 VERSION_2 = 'v2'
1235 VERSION_2 = 'v2'
1225 VERSIONS = [VERSION_1, VERSION_2]
1236 VERSIONS = [VERSION_1, VERSION_2]
1226
1237
1227 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1238 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1228 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1239 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1229 username = Column("username", String(255), nullable=True, unique=None, default=None)
1240 username = Column("username", String(255), nullable=True, unique=None, default=None)
1230 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1241 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1231 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1242 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1232 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1243 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1233 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1244 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1234 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1245 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1235
1246
1236 version = Column("version", String(255), nullable=True, default=VERSION_1)
1247 version = Column("version", String(255), nullable=True, default=VERSION_1)
1237 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1248 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1238 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1249 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1239
1250
1240 def __unicode__(self):
1251 def __unicode__(self):
1241 return u"<%s('id:%s:%s')>" % (
1252 return u"<%s('id:%s:%s')>" % (
1242 self.__class__.__name__, self.repository_name, self.action)
1253 self.__class__.__name__, self.repository_name, self.action)
1243
1254
1244 def __json__(self):
1255 def __json__(self):
1245 return {
1256 return {
1246 'user_id': self.user_id,
1257 'user_id': self.user_id,
1247 'username': self.username,
1258 'username': self.username,
1248 'repository_id': self.repository_id,
1259 'repository_id': self.repository_id,
1249 'repository_name': self.repository_name,
1260 'repository_name': self.repository_name,
1250 'user_ip': self.user_ip,
1261 'user_ip': self.user_ip,
1251 'action_date': self.action_date,
1262 'action_date': self.action_date,
1252 'action': self.action,
1263 'action': self.action,
1253 }
1264 }
1254
1265
1255 @hybrid_property
1266 @hybrid_property
1256 def entry_id(self):
1267 def entry_id(self):
1257 return self.user_log_id
1268 return self.user_log_id
1258
1269
1259 @property
1270 @property
1260 def action_as_day(self):
1271 def action_as_day(self):
1261 return datetime.date(*self.action_date.timetuple()[:3])
1272 return datetime.date(*self.action_date.timetuple()[:3])
1262
1273
1263 user = relationship('User')
1274 user = relationship('User')
1264 repository = relationship('Repository', cascade='')
1275 repository = relationship('Repository', cascade='')
1265
1276
1266
1277
1267 class UserGroup(Base, BaseModel):
1278 class UserGroup(Base, BaseModel):
1268 __tablename__ = 'users_groups'
1279 __tablename__ = 'users_groups'
1269 __table_args__ = (
1280 __table_args__ = (
1270 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1281 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1271 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1282 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1272 )
1283 )
1273
1284
1274 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1285 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1275 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1286 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1276 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1287 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1277 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1288 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1278 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1289 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1279 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1290 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1280 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1291 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1281 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1292 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1282
1293
1283 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1294 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1284 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1295 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1285 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1296 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1286 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1297 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1287 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1298 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1288 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1299 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1289
1300
1290 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1301 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1291 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1302 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1292
1303
1293 @classmethod
1304 @classmethod
1294 def _load_group_data(cls, column):
1305 def _load_group_data(cls, column):
1295 if not column:
1306 if not column:
1296 return {}
1307 return {}
1297
1308
1298 try:
1309 try:
1299 return json.loads(column) or {}
1310 return json.loads(column) or {}
1300 except TypeError:
1311 except TypeError:
1301 return {}
1312 return {}
1302
1313
1303 @hybrid_property
1314 @hybrid_property
1304 def description_safe(self):
1315 def description_safe(self):
1305 from rhodecode.lib import helpers as h
1316 from rhodecode.lib import helpers as h
1306 return h.escape(self.description)
1317 return h.escape(self.description)
1307
1318
1308 @hybrid_property
1319 @hybrid_property
1309 def group_data(self):
1320 def group_data(self):
1310 return self._load_group_data(self._group_data)
1321 return self._load_group_data(self._group_data)
1311
1322
1312 @group_data.expression
1323 @group_data.expression
1313 def group_data(self, **kwargs):
1324 def group_data(self, **kwargs):
1314 return self._group_data
1325 return self._group_data
1315
1326
1316 @group_data.setter
1327 @group_data.setter
1317 def group_data(self, val):
1328 def group_data(self, val):
1318 try:
1329 try:
1319 self._group_data = json.dumps(val)
1330 self._group_data = json.dumps(val)
1320 except Exception:
1331 except Exception:
1321 log.error(traceback.format_exc())
1332 log.error(traceback.format_exc())
1322
1333
1323 def __unicode__(self):
1334 def __unicode__(self):
1324 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1335 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1325 self.users_group_id,
1336 self.users_group_id,
1326 self.users_group_name)
1337 self.users_group_name)
1327
1338
1328 @classmethod
1339 @classmethod
1329 def get_by_group_name(cls, group_name, cache=False,
1340 def get_by_group_name(cls, group_name, cache=False,
1330 case_insensitive=False):
1341 case_insensitive=False):
1331 if case_insensitive:
1342 if case_insensitive:
1332 q = cls.query().filter(func.lower(cls.users_group_name) ==
1343 q = cls.query().filter(func.lower(cls.users_group_name) ==
1333 func.lower(group_name))
1344 func.lower(group_name))
1334
1345
1335 else:
1346 else:
1336 q = cls.query().filter(cls.users_group_name == group_name)
1347 q = cls.query().filter(cls.users_group_name == group_name)
1337 if cache:
1348 if cache:
1338 q = q.options(
1349 q = q.options(
1339 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1350 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1340 return q.scalar()
1351 return q.scalar()
1341
1352
1342 @classmethod
1353 @classmethod
1343 def get(cls, user_group_id, cache=False):
1354 def get(cls, user_group_id, cache=False):
1355 if not user_group_id:
1356 return
1357
1344 user_group = cls.query()
1358 user_group = cls.query()
1345 if cache:
1359 if cache:
1346 user_group = user_group.options(
1360 user_group = user_group.options(
1347 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1361 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1348 return user_group.get(user_group_id)
1362 return user_group.get(user_group_id)
1349
1363
1350 def permissions(self, with_admins=True, with_owner=True):
1364 def permissions(self, with_admins=True, with_owner=True):
1351 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1365 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1352 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1366 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1353 joinedload(UserUserGroupToPerm.user),
1367 joinedload(UserUserGroupToPerm.user),
1354 joinedload(UserUserGroupToPerm.permission),)
1368 joinedload(UserUserGroupToPerm.permission),)
1355
1369
1356 # get owners and admins and permissions. We do a trick of re-writing
1370 # get owners and admins and permissions. We do a trick of re-writing
1357 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1371 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1358 # has a global reference and changing one object propagates to all
1372 # has a global reference and changing one object propagates to all
1359 # others. This means if admin is also an owner admin_row that change
1373 # others. This means if admin is also an owner admin_row that change
1360 # would propagate to both objects
1374 # would propagate to both objects
1361 perm_rows = []
1375 perm_rows = []
1362 for _usr in q.all():
1376 for _usr in q.all():
1363 usr = AttributeDict(_usr.user.get_dict())
1377 usr = AttributeDict(_usr.user.get_dict())
1364 usr.permission = _usr.permission.permission_name
1378 usr.permission = _usr.permission.permission_name
1365 perm_rows.append(usr)
1379 perm_rows.append(usr)
1366
1380
1367 # filter the perm rows by 'default' first and then sort them by
1381 # filter the perm rows by 'default' first and then sort them by
1368 # admin,write,read,none permissions sorted again alphabetically in
1382 # admin,write,read,none permissions sorted again alphabetically in
1369 # each group
1383 # each group
1370 perm_rows = sorted(perm_rows, key=display_user_sort)
1384 perm_rows = sorted(perm_rows, key=display_user_sort)
1371
1385
1372 _admin_perm = 'usergroup.admin'
1386 _admin_perm = 'usergroup.admin'
1373 owner_row = []
1387 owner_row = []
1374 if with_owner:
1388 if with_owner:
1375 usr = AttributeDict(self.user.get_dict())
1389 usr = AttributeDict(self.user.get_dict())
1376 usr.owner_row = True
1390 usr.owner_row = True
1377 usr.permission = _admin_perm
1391 usr.permission = _admin_perm
1378 owner_row.append(usr)
1392 owner_row.append(usr)
1379
1393
1380 super_admin_rows = []
1394 super_admin_rows = []
1381 if with_admins:
1395 if with_admins:
1382 for usr in User.get_all_super_admins():
1396 for usr in User.get_all_super_admins():
1383 # if this admin is also owner, don't double the record
1397 # if this admin is also owner, don't double the record
1384 if usr.user_id == owner_row[0].user_id:
1398 if usr.user_id == owner_row[0].user_id:
1385 owner_row[0].admin_row = True
1399 owner_row[0].admin_row = True
1386 else:
1400 else:
1387 usr = AttributeDict(usr.get_dict())
1401 usr = AttributeDict(usr.get_dict())
1388 usr.admin_row = True
1402 usr.admin_row = True
1389 usr.permission = _admin_perm
1403 usr.permission = _admin_perm
1390 super_admin_rows.append(usr)
1404 super_admin_rows.append(usr)
1391
1405
1392 return super_admin_rows + owner_row + perm_rows
1406 return super_admin_rows + owner_row + perm_rows
1393
1407
1394 def permission_user_groups(self):
1408 def permission_user_groups(self):
1395 q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self)
1409 q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self)
1396 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1410 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1397 joinedload(UserGroupUserGroupToPerm.target_user_group),
1411 joinedload(UserGroupUserGroupToPerm.target_user_group),
1398 joinedload(UserGroupUserGroupToPerm.permission),)
1412 joinedload(UserGroupUserGroupToPerm.permission),)
1399
1413
1400 perm_rows = []
1414 perm_rows = []
1401 for _user_group in q.all():
1415 for _user_group in q.all():
1402 usr = AttributeDict(_user_group.user_group.get_dict())
1416 usr = AttributeDict(_user_group.user_group.get_dict())
1403 usr.permission = _user_group.permission.permission_name
1417 usr.permission = _user_group.permission.permission_name
1404 perm_rows.append(usr)
1418 perm_rows.append(usr)
1405
1419
1406 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1420 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1407 return perm_rows
1421 return perm_rows
1408
1422
1409 def _get_default_perms(self, user_group, suffix=''):
1423 def _get_default_perms(self, user_group, suffix=''):
1410 from rhodecode.model.permission import PermissionModel
1424 from rhodecode.model.permission import PermissionModel
1411 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1425 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1412
1426
1413 def get_default_perms(self, suffix=''):
1427 def get_default_perms(self, suffix=''):
1414 return self._get_default_perms(self, suffix)
1428 return self._get_default_perms(self, suffix)
1415
1429
1416 def get_api_data(self, with_group_members=True, include_secrets=False):
1430 def get_api_data(self, with_group_members=True, include_secrets=False):
1417 """
1431 """
1418 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1432 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1419 basically forwarded.
1433 basically forwarded.
1420
1434
1421 """
1435 """
1422 user_group = self
1436 user_group = self
1423 data = {
1437 data = {
1424 'users_group_id': user_group.users_group_id,
1438 'users_group_id': user_group.users_group_id,
1425 'group_name': user_group.users_group_name,
1439 'group_name': user_group.users_group_name,
1426 'group_description': user_group.user_group_description,
1440 'group_description': user_group.user_group_description,
1427 'active': user_group.users_group_active,
1441 'active': user_group.users_group_active,
1428 'owner': user_group.user.username,
1442 'owner': user_group.user.username,
1429 'owner_email': user_group.user.email,
1443 'owner_email': user_group.user.email,
1430 }
1444 }
1431
1445
1432 if with_group_members:
1446 if with_group_members:
1433 users = []
1447 users = []
1434 for user in user_group.members:
1448 for user in user_group.members:
1435 user = user.user
1449 user = user.user
1436 users.append(user.get_api_data(include_secrets=include_secrets))
1450 users.append(user.get_api_data(include_secrets=include_secrets))
1437 data['users'] = users
1451 data['users'] = users
1438
1452
1439 return data
1453 return data
1440
1454
1441
1455
1442 class UserGroupMember(Base, BaseModel):
1456 class UserGroupMember(Base, BaseModel):
1443 __tablename__ = 'users_groups_members'
1457 __tablename__ = 'users_groups_members'
1444 __table_args__ = (
1458 __table_args__ = (
1445 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1459 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1446 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1460 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1447 )
1461 )
1448
1462
1449 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1463 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1450 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1464 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1451 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1465 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1452
1466
1453 user = relationship('User', lazy='joined')
1467 user = relationship('User', lazy='joined')
1454 users_group = relationship('UserGroup')
1468 users_group = relationship('UserGroup')
1455
1469
1456 def __init__(self, gr_id='', u_id=''):
1470 def __init__(self, gr_id='', u_id=''):
1457 self.users_group_id = gr_id
1471 self.users_group_id = gr_id
1458 self.user_id = u_id
1472 self.user_id = u_id
1459
1473
1460
1474
1461 class RepositoryField(Base, BaseModel):
1475 class RepositoryField(Base, BaseModel):
1462 __tablename__ = 'repositories_fields'
1476 __tablename__ = 'repositories_fields'
1463 __table_args__ = (
1477 __table_args__ = (
1464 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1478 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1465 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1479 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1466 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1480 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1467 )
1481 )
1468 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1482 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1469
1483
1470 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1484 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1471 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1485 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1472 field_key = Column("field_key", String(250))
1486 field_key = Column("field_key", String(250))
1473 field_label = Column("field_label", String(1024), nullable=False)
1487 field_label = Column("field_label", String(1024), nullable=False)
1474 field_value = Column("field_value", String(10000), nullable=False)
1488 field_value = Column("field_value", String(10000), nullable=False)
1475 field_desc = Column("field_desc", String(1024), nullable=False)
1489 field_desc = Column("field_desc", String(1024), nullable=False)
1476 field_type = Column("field_type", String(255), nullable=False, unique=None)
1490 field_type = Column("field_type", String(255), nullable=False, unique=None)
1477 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1491 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1478
1492
1479 repository = relationship('Repository')
1493 repository = relationship('Repository')
1480
1494
1481 @property
1495 @property
1482 def field_key_prefixed(self):
1496 def field_key_prefixed(self):
1483 return 'ex_%s' % self.field_key
1497 return 'ex_%s' % self.field_key
1484
1498
1485 @classmethod
1499 @classmethod
1486 def un_prefix_key(cls, key):
1500 def un_prefix_key(cls, key):
1487 if key.startswith(cls.PREFIX):
1501 if key.startswith(cls.PREFIX):
1488 return key[len(cls.PREFIX):]
1502 return key[len(cls.PREFIX):]
1489 return key
1503 return key
1490
1504
1491 @classmethod
1505 @classmethod
1492 def get_by_key_name(cls, key, repo):
1506 def get_by_key_name(cls, key, repo):
1493 row = cls.query()\
1507 row = cls.query()\
1494 .filter(cls.repository == repo)\
1508 .filter(cls.repository == repo)\
1495 .filter(cls.field_key == key).scalar()
1509 .filter(cls.field_key == key).scalar()
1496 return row
1510 return row
1497
1511
1498
1512
1499 class Repository(Base, BaseModel):
1513 class Repository(Base, BaseModel):
1500 __tablename__ = 'repositories'
1514 __tablename__ = 'repositories'
1501 __table_args__ = (
1515 __table_args__ = (
1502 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1516 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1503 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1517 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1504 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1518 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1505 )
1519 )
1506 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1520 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1507 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1521 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1508
1522
1509 STATE_CREATED = 'repo_state_created'
1523 STATE_CREATED = 'repo_state_created'
1510 STATE_PENDING = 'repo_state_pending'
1524 STATE_PENDING = 'repo_state_pending'
1511 STATE_ERROR = 'repo_state_error'
1525 STATE_ERROR = 'repo_state_error'
1512
1526
1513 LOCK_AUTOMATIC = 'lock_auto'
1527 LOCK_AUTOMATIC = 'lock_auto'
1514 LOCK_API = 'lock_api'
1528 LOCK_API = 'lock_api'
1515 LOCK_WEB = 'lock_web'
1529 LOCK_WEB = 'lock_web'
1516 LOCK_PULL = 'lock_pull'
1530 LOCK_PULL = 'lock_pull'
1517
1531
1518 NAME_SEP = URL_SEP
1532 NAME_SEP = URL_SEP
1519
1533
1520 repo_id = Column(
1534 repo_id = Column(
1521 "repo_id", Integer(), nullable=False, unique=True, default=None,
1535 "repo_id", Integer(), nullable=False, unique=True, default=None,
1522 primary_key=True)
1536 primary_key=True)
1523 _repo_name = Column(
1537 _repo_name = Column(
1524 "repo_name", Text(), nullable=False, default=None)
1538 "repo_name", Text(), nullable=False, default=None)
1525 _repo_name_hash = Column(
1539 _repo_name_hash = Column(
1526 "repo_name_hash", String(255), nullable=False, unique=True)
1540 "repo_name_hash", String(255), nullable=False, unique=True)
1527 repo_state = Column("repo_state", String(255), nullable=True)
1541 repo_state = Column("repo_state", String(255), nullable=True)
1528
1542
1529 clone_uri = Column(
1543 clone_uri = Column(
1530 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1544 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1531 default=None)
1545 default=None)
1532 repo_type = Column(
1546 repo_type = Column(
1533 "repo_type", String(255), nullable=False, unique=False, default=None)
1547 "repo_type", String(255), nullable=False, unique=False, default=None)
1534 user_id = Column(
1548 user_id = Column(
1535 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1549 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1536 unique=False, default=None)
1550 unique=False, default=None)
1537 private = Column(
1551 private = Column(
1538 "private", Boolean(), nullable=True, unique=None, default=None)
1552 "private", Boolean(), nullable=True, unique=None, default=None)
1539 enable_statistics = Column(
1553 enable_statistics = Column(
1540 "statistics", Boolean(), nullable=True, unique=None, default=True)
1554 "statistics", Boolean(), nullable=True, unique=None, default=True)
1541 enable_downloads = Column(
1555 enable_downloads = Column(
1542 "downloads", Boolean(), nullable=True, unique=None, default=True)
1556 "downloads", Boolean(), nullable=True, unique=None, default=True)
1543 description = Column(
1557 description = Column(
1544 "description", String(10000), nullable=True, unique=None, default=None)
1558 "description", String(10000), nullable=True, unique=None, default=None)
1545 created_on = Column(
1559 created_on = Column(
1546 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1560 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1547 default=datetime.datetime.now)
1561 default=datetime.datetime.now)
1548 updated_on = Column(
1562 updated_on = Column(
1549 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1563 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1550 default=datetime.datetime.now)
1564 default=datetime.datetime.now)
1551 _landing_revision = Column(
1565 _landing_revision = Column(
1552 "landing_revision", String(255), nullable=False, unique=False,
1566 "landing_revision", String(255), nullable=False, unique=False,
1553 default=None)
1567 default=None)
1554 enable_locking = Column(
1568 enable_locking = Column(
1555 "enable_locking", Boolean(), nullable=False, unique=None,
1569 "enable_locking", Boolean(), nullable=False, unique=None,
1556 default=False)
1570 default=False)
1557 _locked = Column(
1571 _locked = Column(
1558 "locked", String(255), nullable=True, unique=False, default=None)
1572 "locked", String(255), nullable=True, unique=False, default=None)
1559 _changeset_cache = Column(
1573 _changeset_cache = Column(
1560 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1574 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1561
1575
1562 fork_id = Column(
1576 fork_id = Column(
1563 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1577 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1564 nullable=True, unique=False, default=None)
1578 nullable=True, unique=False, default=None)
1565 group_id = Column(
1579 group_id = Column(
1566 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1580 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1567 unique=False, default=None)
1581 unique=False, default=None)
1568
1582
1569 user = relationship('User', lazy='joined')
1583 user = relationship('User', lazy='joined')
1570 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1584 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1571 group = relationship('RepoGroup', lazy='joined')
1585 group = relationship('RepoGroup', lazy='joined')
1572 repo_to_perm = relationship(
1586 repo_to_perm = relationship(
1573 'UserRepoToPerm', cascade='all',
1587 'UserRepoToPerm', cascade='all',
1574 order_by='UserRepoToPerm.repo_to_perm_id')
1588 order_by='UserRepoToPerm.repo_to_perm_id')
1575 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1589 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1576 stats = relationship('Statistics', cascade='all', uselist=False)
1590 stats = relationship('Statistics', cascade='all', uselist=False)
1577
1591
1578 followers = relationship(
1592 followers = relationship(
1579 'UserFollowing',
1593 'UserFollowing',
1580 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1594 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1581 cascade='all')
1595 cascade='all')
1582 extra_fields = relationship(
1596 extra_fields = relationship(
1583 'RepositoryField', cascade="all, delete, delete-orphan")
1597 'RepositoryField', cascade="all, delete, delete-orphan")
1584 logs = relationship('UserLog')
1598 logs = relationship('UserLog')
1585 comments = relationship(
1599 comments = relationship(
1586 'ChangesetComment', cascade="all, delete, delete-orphan")
1600 'ChangesetComment', cascade="all, delete, delete-orphan")
1587 pull_requests_source = relationship(
1601 pull_requests_source = relationship(
1588 'PullRequest',
1602 'PullRequest',
1589 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1603 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1590 cascade="all, delete, delete-orphan")
1604 cascade="all, delete, delete-orphan")
1591 pull_requests_target = relationship(
1605 pull_requests_target = relationship(
1592 'PullRequest',
1606 'PullRequest',
1593 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1607 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1594 cascade="all, delete, delete-orphan")
1608 cascade="all, delete, delete-orphan")
1595 ui = relationship('RepoRhodeCodeUi', cascade="all")
1609 ui = relationship('RepoRhodeCodeUi', cascade="all")
1596 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1610 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1597 integrations = relationship('Integration',
1611 integrations = relationship('Integration',
1598 cascade="all, delete, delete-orphan")
1612 cascade="all, delete, delete-orphan")
1599
1613
1600 def __unicode__(self):
1614 def __unicode__(self):
1601 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1615 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1602 safe_unicode(self.repo_name))
1616 safe_unicode(self.repo_name))
1603
1617
1604 @hybrid_property
1618 @hybrid_property
1605 def description_safe(self):
1619 def description_safe(self):
1606 from rhodecode.lib import helpers as h
1620 from rhodecode.lib import helpers as h
1607 return h.escape(self.description)
1621 return h.escape(self.description)
1608
1622
1609 @hybrid_property
1623 @hybrid_property
1610 def landing_rev(self):
1624 def landing_rev(self):
1611 # always should return [rev_type, rev]
1625 # always should return [rev_type, rev]
1612 if self._landing_revision:
1626 if self._landing_revision:
1613 _rev_info = self._landing_revision.split(':')
1627 _rev_info = self._landing_revision.split(':')
1614 if len(_rev_info) < 2:
1628 if len(_rev_info) < 2:
1615 _rev_info.insert(0, 'rev')
1629 _rev_info.insert(0, 'rev')
1616 return [_rev_info[0], _rev_info[1]]
1630 return [_rev_info[0], _rev_info[1]]
1617 return [None, None]
1631 return [None, None]
1618
1632
1619 @landing_rev.setter
1633 @landing_rev.setter
1620 def landing_rev(self, val):
1634 def landing_rev(self, val):
1621 if ':' not in val:
1635 if ':' not in val:
1622 raise ValueError('value must be delimited with `:` and consist '
1636 raise ValueError('value must be delimited with `:` and consist '
1623 'of <rev_type>:<rev>, got %s instead' % val)
1637 'of <rev_type>:<rev>, got %s instead' % val)
1624 self._landing_revision = val
1638 self._landing_revision = val
1625
1639
1626 @hybrid_property
1640 @hybrid_property
1627 def locked(self):
1641 def locked(self):
1628 if self._locked:
1642 if self._locked:
1629 user_id, timelocked, reason = self._locked.split(':')
1643 user_id, timelocked, reason = self._locked.split(':')
1630 lock_values = int(user_id), timelocked, reason
1644 lock_values = int(user_id), timelocked, reason
1631 else:
1645 else:
1632 lock_values = [None, None, None]
1646 lock_values = [None, None, None]
1633 return lock_values
1647 return lock_values
1634
1648
1635 @locked.setter
1649 @locked.setter
1636 def locked(self, val):
1650 def locked(self, val):
1637 if val and isinstance(val, (list, tuple)):
1651 if val and isinstance(val, (list, tuple)):
1638 self._locked = ':'.join(map(str, val))
1652 self._locked = ':'.join(map(str, val))
1639 else:
1653 else:
1640 self._locked = None
1654 self._locked = None
1641
1655
1642 @hybrid_property
1656 @hybrid_property
1643 def changeset_cache(self):
1657 def changeset_cache(self):
1644 from rhodecode.lib.vcs.backends.base import EmptyCommit
1658 from rhodecode.lib.vcs.backends.base import EmptyCommit
1645 dummy = EmptyCommit().__json__()
1659 dummy = EmptyCommit().__json__()
1646 if not self._changeset_cache:
1660 if not self._changeset_cache:
1647 return dummy
1661 return dummy
1648 try:
1662 try:
1649 return json.loads(self._changeset_cache)
1663 return json.loads(self._changeset_cache)
1650 except TypeError:
1664 except TypeError:
1651 return dummy
1665 return dummy
1652 except Exception:
1666 except Exception:
1653 log.error(traceback.format_exc())
1667 log.error(traceback.format_exc())
1654 return dummy
1668 return dummy
1655
1669
1656 @changeset_cache.setter
1670 @changeset_cache.setter
1657 def changeset_cache(self, val):
1671 def changeset_cache(self, val):
1658 try:
1672 try:
1659 self._changeset_cache = json.dumps(val)
1673 self._changeset_cache = json.dumps(val)
1660 except Exception:
1674 except Exception:
1661 log.error(traceback.format_exc())
1675 log.error(traceback.format_exc())
1662
1676
1663 @hybrid_property
1677 @hybrid_property
1664 def repo_name(self):
1678 def repo_name(self):
1665 return self._repo_name
1679 return self._repo_name
1666
1680
1667 @repo_name.setter
1681 @repo_name.setter
1668 def repo_name(self, value):
1682 def repo_name(self, value):
1669 self._repo_name = value
1683 self._repo_name = value
1670 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1684 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1671
1685
1672 @classmethod
1686 @classmethod
1673 def normalize_repo_name(cls, repo_name):
1687 def normalize_repo_name(cls, repo_name):
1674 """
1688 """
1675 Normalizes os specific repo_name to the format internally stored inside
1689 Normalizes os specific repo_name to the format internally stored inside
1676 database using URL_SEP
1690 database using URL_SEP
1677
1691
1678 :param cls:
1692 :param cls:
1679 :param repo_name:
1693 :param repo_name:
1680 """
1694 """
1681 return cls.NAME_SEP.join(repo_name.split(os.sep))
1695 return cls.NAME_SEP.join(repo_name.split(os.sep))
1682
1696
1683 @classmethod
1697 @classmethod
1684 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1698 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1685 session = Session()
1699 session = Session()
1686 q = session.query(cls).filter(cls.repo_name == repo_name)
1700 q = session.query(cls).filter(cls.repo_name == repo_name)
1687
1701
1688 if cache:
1702 if cache:
1689 if identity_cache:
1703 if identity_cache:
1690 val = cls.identity_cache(session, 'repo_name', repo_name)
1704 val = cls.identity_cache(session, 'repo_name', repo_name)
1691 if val:
1705 if val:
1692 return val
1706 return val
1693 else:
1707 else:
1694 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1708 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1695 q = q.options(
1709 q = q.options(
1696 FromCache("sql_cache_short", cache_key))
1710 FromCache("sql_cache_short", cache_key))
1697
1711
1698 return q.scalar()
1712 return q.scalar()
1699
1713
1700 @classmethod
1714 @classmethod
1701 def get_by_full_path(cls, repo_full_path):
1715 def get_by_full_path(cls, repo_full_path):
1702 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1716 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1703 repo_name = cls.normalize_repo_name(repo_name)
1717 repo_name = cls.normalize_repo_name(repo_name)
1704 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1718 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1705
1719
1706 @classmethod
1720 @classmethod
1707 def get_repo_forks(cls, repo_id):
1721 def get_repo_forks(cls, repo_id):
1708 return cls.query().filter(Repository.fork_id == repo_id)
1722 return cls.query().filter(Repository.fork_id == repo_id)
1709
1723
1710 @classmethod
1724 @classmethod
1711 def base_path(cls):
1725 def base_path(cls):
1712 """
1726 """
1713 Returns base path when all repos are stored
1727 Returns base path when all repos are stored
1714
1728
1715 :param cls:
1729 :param cls:
1716 """
1730 """
1717 q = Session().query(RhodeCodeUi)\
1731 q = Session().query(RhodeCodeUi)\
1718 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1732 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1719 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1733 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1720 return q.one().ui_value
1734 return q.one().ui_value
1721
1735
1722 @classmethod
1736 @classmethod
1723 def is_valid(cls, repo_name):
1737 def is_valid(cls, repo_name):
1724 """
1738 """
1725 returns True if given repo name is a valid filesystem repository
1739 returns True if given repo name is a valid filesystem repository
1726
1740
1727 :param cls:
1741 :param cls:
1728 :param repo_name:
1742 :param repo_name:
1729 """
1743 """
1730 from rhodecode.lib.utils import is_valid_repo
1744 from rhodecode.lib.utils import is_valid_repo
1731
1745
1732 return is_valid_repo(repo_name, cls.base_path())
1746 return is_valid_repo(repo_name, cls.base_path())
1733
1747
1734 @classmethod
1748 @classmethod
1735 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1749 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1736 case_insensitive=True):
1750 case_insensitive=True):
1737 q = Repository.query()
1751 q = Repository.query()
1738
1752
1739 if not isinstance(user_id, Optional):
1753 if not isinstance(user_id, Optional):
1740 q = q.filter(Repository.user_id == user_id)
1754 q = q.filter(Repository.user_id == user_id)
1741
1755
1742 if not isinstance(group_id, Optional):
1756 if not isinstance(group_id, Optional):
1743 q = q.filter(Repository.group_id == group_id)
1757 q = q.filter(Repository.group_id == group_id)
1744
1758
1745 if case_insensitive:
1759 if case_insensitive:
1746 q = q.order_by(func.lower(Repository.repo_name))
1760 q = q.order_by(func.lower(Repository.repo_name))
1747 else:
1761 else:
1748 q = q.order_by(Repository.repo_name)
1762 q = q.order_by(Repository.repo_name)
1749 return q.all()
1763 return q.all()
1750
1764
1751 @property
1765 @property
1752 def forks(self):
1766 def forks(self):
1753 """
1767 """
1754 Return forks of this repo
1768 Return forks of this repo
1755 """
1769 """
1756 return Repository.get_repo_forks(self.repo_id)
1770 return Repository.get_repo_forks(self.repo_id)
1757
1771
1758 @property
1772 @property
1759 def parent(self):
1773 def parent(self):
1760 """
1774 """
1761 Returns fork parent
1775 Returns fork parent
1762 """
1776 """
1763 return self.fork
1777 return self.fork
1764
1778
1765 @property
1779 @property
1766 def just_name(self):
1780 def just_name(self):
1767 return self.repo_name.split(self.NAME_SEP)[-1]
1781 return self.repo_name.split(self.NAME_SEP)[-1]
1768
1782
1769 @property
1783 @property
1770 def groups_with_parents(self):
1784 def groups_with_parents(self):
1771 groups = []
1785 groups = []
1772 if self.group is None:
1786 if self.group is None:
1773 return groups
1787 return groups
1774
1788
1775 cur_gr = self.group
1789 cur_gr = self.group
1776 groups.insert(0, cur_gr)
1790 groups.insert(0, cur_gr)
1777 while 1:
1791 while 1:
1778 gr = getattr(cur_gr, 'parent_group', None)
1792 gr = getattr(cur_gr, 'parent_group', None)
1779 cur_gr = cur_gr.parent_group
1793 cur_gr = cur_gr.parent_group
1780 if gr is None:
1794 if gr is None:
1781 break
1795 break
1782 groups.insert(0, gr)
1796 groups.insert(0, gr)
1783
1797
1784 return groups
1798 return groups
1785
1799
1786 @property
1800 @property
1787 def groups_and_repo(self):
1801 def groups_and_repo(self):
1788 return self.groups_with_parents, self
1802 return self.groups_with_parents, self
1789
1803
1790 @LazyProperty
1804 @LazyProperty
1791 def repo_path(self):
1805 def repo_path(self):
1792 """
1806 """
1793 Returns base full path for that repository means where it actually
1807 Returns base full path for that repository means where it actually
1794 exists on a filesystem
1808 exists on a filesystem
1795 """
1809 """
1796 q = Session().query(RhodeCodeUi).filter(
1810 q = Session().query(RhodeCodeUi).filter(
1797 RhodeCodeUi.ui_key == self.NAME_SEP)
1811 RhodeCodeUi.ui_key == self.NAME_SEP)
1798 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1812 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1799 return q.one().ui_value
1813 return q.one().ui_value
1800
1814
1801 @property
1815 @property
1802 def repo_full_path(self):
1816 def repo_full_path(self):
1803 p = [self.repo_path]
1817 p = [self.repo_path]
1804 # we need to split the name by / since this is how we store the
1818 # we need to split the name by / since this is how we store the
1805 # names in the database, but that eventually needs to be converted
1819 # names in the database, but that eventually needs to be converted
1806 # into a valid system path
1820 # into a valid system path
1807 p += self.repo_name.split(self.NAME_SEP)
1821 p += self.repo_name.split(self.NAME_SEP)
1808 return os.path.join(*map(safe_unicode, p))
1822 return os.path.join(*map(safe_unicode, p))
1809
1823
1810 @property
1824 @property
1811 def cache_keys(self):
1825 def cache_keys(self):
1812 """
1826 """
1813 Returns associated cache keys for that repo
1827 Returns associated cache keys for that repo
1814 """
1828 """
1815 return CacheKey.query()\
1829 return CacheKey.query()\
1816 .filter(CacheKey.cache_args == self.repo_name)\
1830 .filter(CacheKey.cache_args == self.repo_name)\
1817 .order_by(CacheKey.cache_key)\
1831 .order_by(CacheKey.cache_key)\
1818 .all()
1832 .all()
1819
1833
1820 def get_new_name(self, repo_name):
1834 def get_new_name(self, repo_name):
1821 """
1835 """
1822 returns new full repository name based on assigned group and new new
1836 returns new full repository name based on assigned group and new new
1823
1837
1824 :param group_name:
1838 :param group_name:
1825 """
1839 """
1826 path_prefix = self.group.full_path_splitted if self.group else []
1840 path_prefix = self.group.full_path_splitted if self.group else []
1827 return self.NAME_SEP.join(path_prefix + [repo_name])
1841 return self.NAME_SEP.join(path_prefix + [repo_name])
1828
1842
1829 @property
1843 @property
1830 def _config(self):
1844 def _config(self):
1831 """
1845 """
1832 Returns db based config object.
1846 Returns db based config object.
1833 """
1847 """
1834 from rhodecode.lib.utils import make_db_config
1848 from rhodecode.lib.utils import make_db_config
1835 return make_db_config(clear_session=False, repo=self)
1849 return make_db_config(clear_session=False, repo=self)
1836
1850
1837 def permissions(self, with_admins=True, with_owner=True):
1851 def permissions(self, with_admins=True, with_owner=True):
1838 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1852 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1839 q = q.options(joinedload(UserRepoToPerm.repository),
1853 q = q.options(joinedload(UserRepoToPerm.repository),
1840 joinedload(UserRepoToPerm.user),
1854 joinedload(UserRepoToPerm.user),
1841 joinedload(UserRepoToPerm.permission),)
1855 joinedload(UserRepoToPerm.permission),)
1842
1856
1843 # get owners and admins and permissions. We do a trick of re-writing
1857 # get owners and admins and permissions. We do a trick of re-writing
1844 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1858 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1845 # has a global reference and changing one object propagates to all
1859 # has a global reference and changing one object propagates to all
1846 # others. This means if admin is also an owner admin_row that change
1860 # others. This means if admin is also an owner admin_row that change
1847 # would propagate to both objects
1861 # would propagate to both objects
1848 perm_rows = []
1862 perm_rows = []
1849 for _usr in q.all():
1863 for _usr in q.all():
1850 usr = AttributeDict(_usr.user.get_dict())
1864 usr = AttributeDict(_usr.user.get_dict())
1851 usr.permission = _usr.permission.permission_name
1865 usr.permission = _usr.permission.permission_name
1852 perm_rows.append(usr)
1866 perm_rows.append(usr)
1853
1867
1854 # filter the perm rows by 'default' first and then sort them by
1868 # filter the perm rows by 'default' first and then sort them by
1855 # admin,write,read,none permissions sorted again alphabetically in
1869 # admin,write,read,none permissions sorted again alphabetically in
1856 # each group
1870 # each group
1857 perm_rows = sorted(perm_rows, key=display_user_sort)
1871 perm_rows = sorted(perm_rows, key=display_user_sort)
1858
1872
1859 _admin_perm = 'repository.admin'
1873 _admin_perm = 'repository.admin'
1860 owner_row = []
1874 owner_row = []
1861 if with_owner:
1875 if with_owner:
1862 usr = AttributeDict(self.user.get_dict())
1876 usr = AttributeDict(self.user.get_dict())
1863 usr.owner_row = True
1877 usr.owner_row = True
1864 usr.permission = _admin_perm
1878 usr.permission = _admin_perm
1865 owner_row.append(usr)
1879 owner_row.append(usr)
1866
1880
1867 super_admin_rows = []
1881 super_admin_rows = []
1868 if with_admins:
1882 if with_admins:
1869 for usr in User.get_all_super_admins():
1883 for usr in User.get_all_super_admins():
1870 # if this admin is also owner, don't double the record
1884 # if this admin is also owner, don't double the record
1871 if usr.user_id == owner_row[0].user_id:
1885 if usr.user_id == owner_row[0].user_id:
1872 owner_row[0].admin_row = True
1886 owner_row[0].admin_row = True
1873 else:
1887 else:
1874 usr = AttributeDict(usr.get_dict())
1888 usr = AttributeDict(usr.get_dict())
1875 usr.admin_row = True
1889 usr.admin_row = True
1876 usr.permission = _admin_perm
1890 usr.permission = _admin_perm
1877 super_admin_rows.append(usr)
1891 super_admin_rows.append(usr)
1878
1892
1879 return super_admin_rows + owner_row + perm_rows
1893 return super_admin_rows + owner_row + perm_rows
1880
1894
1881 def permission_user_groups(self):
1895 def permission_user_groups(self):
1882 q = UserGroupRepoToPerm.query().filter(
1896 q = UserGroupRepoToPerm.query().filter(
1883 UserGroupRepoToPerm.repository == self)
1897 UserGroupRepoToPerm.repository == self)
1884 q = q.options(joinedload(UserGroupRepoToPerm.repository),
1898 q = q.options(joinedload(UserGroupRepoToPerm.repository),
1885 joinedload(UserGroupRepoToPerm.users_group),
1899 joinedload(UserGroupRepoToPerm.users_group),
1886 joinedload(UserGroupRepoToPerm.permission),)
1900 joinedload(UserGroupRepoToPerm.permission),)
1887
1901
1888 perm_rows = []
1902 perm_rows = []
1889 for _user_group in q.all():
1903 for _user_group in q.all():
1890 usr = AttributeDict(_user_group.users_group.get_dict())
1904 usr = AttributeDict(_user_group.users_group.get_dict())
1891 usr.permission = _user_group.permission.permission_name
1905 usr.permission = _user_group.permission.permission_name
1892 perm_rows.append(usr)
1906 perm_rows.append(usr)
1893
1907
1894 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1908 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1895 return perm_rows
1909 return perm_rows
1896
1910
1897 def get_api_data(self, include_secrets=False):
1911 def get_api_data(self, include_secrets=False):
1898 """
1912 """
1899 Common function for generating repo api data
1913 Common function for generating repo api data
1900
1914
1901 :param include_secrets: See :meth:`User.get_api_data`.
1915 :param include_secrets: See :meth:`User.get_api_data`.
1902
1916
1903 """
1917 """
1904 # TODO: mikhail: Here there is an anti-pattern, we probably need to
1918 # TODO: mikhail: Here there is an anti-pattern, we probably need to
1905 # move this methods on models level.
1919 # move this methods on models level.
1906 from rhodecode.model.settings import SettingsModel
1920 from rhodecode.model.settings import SettingsModel
1907 from rhodecode.model.repo import RepoModel
1921 from rhodecode.model.repo import RepoModel
1908
1922
1909 repo = self
1923 repo = self
1910 _user_id, _time, _reason = self.locked
1924 _user_id, _time, _reason = self.locked
1911
1925
1912 data = {
1926 data = {
1913 'repo_id': repo.repo_id,
1927 'repo_id': repo.repo_id,
1914 'repo_name': repo.repo_name,
1928 'repo_name': repo.repo_name,
1915 'repo_type': repo.repo_type,
1929 'repo_type': repo.repo_type,
1916 'clone_uri': repo.clone_uri or '',
1930 'clone_uri': repo.clone_uri or '',
1917 'url': RepoModel().get_url(self),
1931 'url': RepoModel().get_url(self),
1918 'private': repo.private,
1932 'private': repo.private,
1919 'created_on': repo.created_on,
1933 'created_on': repo.created_on,
1920 'description': repo.description_safe,
1934 'description': repo.description_safe,
1921 'landing_rev': repo.landing_rev,
1935 'landing_rev': repo.landing_rev,
1922 'owner': repo.user.username,
1936 'owner': repo.user.username,
1923 'fork_of': repo.fork.repo_name if repo.fork else None,
1937 'fork_of': repo.fork.repo_name if repo.fork else None,
1924 'fork_of_id': repo.fork.repo_id if repo.fork else None,
1938 'fork_of_id': repo.fork.repo_id if repo.fork else None,
1925 'enable_statistics': repo.enable_statistics,
1939 'enable_statistics': repo.enable_statistics,
1926 'enable_locking': repo.enable_locking,
1940 'enable_locking': repo.enable_locking,
1927 'enable_downloads': repo.enable_downloads,
1941 'enable_downloads': repo.enable_downloads,
1928 'last_changeset': repo.changeset_cache,
1942 'last_changeset': repo.changeset_cache,
1929 'locked_by': User.get(_user_id).get_api_data(
1943 'locked_by': User.get(_user_id).get_api_data(
1930 include_secrets=include_secrets) if _user_id else None,
1944 include_secrets=include_secrets) if _user_id else None,
1931 'locked_date': time_to_datetime(_time) if _time else None,
1945 'locked_date': time_to_datetime(_time) if _time else None,
1932 'lock_reason': _reason if _reason else None,
1946 'lock_reason': _reason if _reason else None,
1933 }
1947 }
1934
1948
1935 # TODO: mikhail: should be per-repo settings here
1949 # TODO: mikhail: should be per-repo settings here
1936 rc_config = SettingsModel().get_all_settings()
1950 rc_config = SettingsModel().get_all_settings()
1937 repository_fields = str2bool(
1951 repository_fields = str2bool(
1938 rc_config.get('rhodecode_repository_fields'))
1952 rc_config.get('rhodecode_repository_fields'))
1939 if repository_fields:
1953 if repository_fields:
1940 for f in self.extra_fields:
1954 for f in self.extra_fields:
1941 data[f.field_key_prefixed] = f.field_value
1955 data[f.field_key_prefixed] = f.field_value
1942
1956
1943 return data
1957 return data
1944
1958
1945 @classmethod
1959 @classmethod
1946 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
1960 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
1947 if not lock_time:
1961 if not lock_time:
1948 lock_time = time.time()
1962 lock_time = time.time()
1949 if not lock_reason:
1963 if not lock_reason:
1950 lock_reason = cls.LOCK_AUTOMATIC
1964 lock_reason = cls.LOCK_AUTOMATIC
1951 repo.locked = [user_id, lock_time, lock_reason]
1965 repo.locked = [user_id, lock_time, lock_reason]
1952 Session().add(repo)
1966 Session().add(repo)
1953 Session().commit()
1967 Session().commit()
1954
1968
1955 @classmethod
1969 @classmethod
1956 def unlock(cls, repo):
1970 def unlock(cls, repo):
1957 repo.locked = None
1971 repo.locked = None
1958 Session().add(repo)
1972 Session().add(repo)
1959 Session().commit()
1973 Session().commit()
1960
1974
1961 @classmethod
1975 @classmethod
1962 def getlock(cls, repo):
1976 def getlock(cls, repo):
1963 return repo.locked
1977 return repo.locked
1964
1978
1965 def is_user_lock(self, user_id):
1979 def is_user_lock(self, user_id):
1966 if self.lock[0]:
1980 if self.lock[0]:
1967 lock_user_id = safe_int(self.lock[0])
1981 lock_user_id = safe_int(self.lock[0])
1968 user_id = safe_int(user_id)
1982 user_id = safe_int(user_id)
1969 # both are ints, and they are equal
1983 # both are ints, and they are equal
1970 return all([lock_user_id, user_id]) and lock_user_id == user_id
1984 return all([lock_user_id, user_id]) and lock_user_id == user_id
1971
1985
1972 return False
1986 return False
1973
1987
1974 def get_locking_state(self, action, user_id, only_when_enabled=True):
1988 def get_locking_state(self, action, user_id, only_when_enabled=True):
1975 """
1989 """
1976 Checks locking on this repository, if locking is enabled and lock is
1990 Checks locking on this repository, if locking is enabled and lock is
1977 present returns a tuple of make_lock, locked, locked_by.
1991 present returns a tuple of make_lock, locked, locked_by.
1978 make_lock can have 3 states None (do nothing) True, make lock
1992 make_lock can have 3 states None (do nothing) True, make lock
1979 False release lock, This value is later propagated to hooks, which
1993 False release lock, This value is later propagated to hooks, which
1980 do the locking. Think about this as signals passed to hooks what to do.
1994 do the locking. Think about this as signals passed to hooks what to do.
1981
1995
1982 """
1996 """
1983 # TODO: johbo: This is part of the business logic and should be moved
1997 # TODO: johbo: This is part of the business logic and should be moved
1984 # into the RepositoryModel.
1998 # into the RepositoryModel.
1985
1999
1986 if action not in ('push', 'pull'):
2000 if action not in ('push', 'pull'):
1987 raise ValueError("Invalid action value: %s" % repr(action))
2001 raise ValueError("Invalid action value: %s" % repr(action))
1988
2002
1989 # defines if locked error should be thrown to user
2003 # defines if locked error should be thrown to user
1990 currently_locked = False
2004 currently_locked = False
1991 # defines if new lock should be made, tri-state
2005 # defines if new lock should be made, tri-state
1992 make_lock = None
2006 make_lock = None
1993 repo = self
2007 repo = self
1994 user = User.get(user_id)
2008 user = User.get(user_id)
1995
2009
1996 lock_info = repo.locked
2010 lock_info = repo.locked
1997
2011
1998 if repo and (repo.enable_locking or not only_when_enabled):
2012 if repo and (repo.enable_locking or not only_when_enabled):
1999 if action == 'push':
2013 if action == 'push':
2000 # check if it's already locked !, if it is compare users
2014 # check if it's already locked !, if it is compare users
2001 locked_by_user_id = lock_info[0]
2015 locked_by_user_id = lock_info[0]
2002 if user.user_id == locked_by_user_id:
2016 if user.user_id == locked_by_user_id:
2003 log.debug(
2017 log.debug(
2004 'Got `push` action from user %s, now unlocking', user)
2018 'Got `push` action from user %s, now unlocking', user)
2005 # unlock if we have push from user who locked
2019 # unlock if we have push from user who locked
2006 make_lock = False
2020 make_lock = False
2007 else:
2021 else:
2008 # we're not the same user who locked, ban with
2022 # we're not the same user who locked, ban with
2009 # code defined in settings (default is 423 HTTP Locked) !
2023 # code defined in settings (default is 423 HTTP Locked) !
2010 log.debug('Repo %s is currently locked by %s', repo, user)
2024 log.debug('Repo %s is currently locked by %s', repo, user)
2011 currently_locked = True
2025 currently_locked = True
2012 elif action == 'pull':
2026 elif action == 'pull':
2013 # [0] user [1] date
2027 # [0] user [1] date
2014 if lock_info[0] and lock_info[1]:
2028 if lock_info[0] and lock_info[1]:
2015 log.debug('Repo %s is currently locked by %s', repo, user)
2029 log.debug('Repo %s is currently locked by %s', repo, user)
2016 currently_locked = True
2030 currently_locked = True
2017 else:
2031 else:
2018 log.debug('Setting lock on repo %s by %s', repo, user)
2032 log.debug('Setting lock on repo %s by %s', repo, user)
2019 make_lock = True
2033 make_lock = True
2020
2034
2021 else:
2035 else:
2022 log.debug('Repository %s do not have locking enabled', repo)
2036 log.debug('Repository %s do not have locking enabled', repo)
2023
2037
2024 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2038 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2025 make_lock, currently_locked, lock_info)
2039 make_lock, currently_locked, lock_info)
2026
2040
2027 from rhodecode.lib.auth import HasRepoPermissionAny
2041 from rhodecode.lib.auth import HasRepoPermissionAny
2028 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2042 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2029 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2043 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2030 # if we don't have at least write permission we cannot make a lock
2044 # if we don't have at least write permission we cannot make a lock
2031 log.debug('lock state reset back to FALSE due to lack '
2045 log.debug('lock state reset back to FALSE due to lack '
2032 'of at least read permission')
2046 'of at least read permission')
2033 make_lock = False
2047 make_lock = False
2034
2048
2035 return make_lock, currently_locked, lock_info
2049 return make_lock, currently_locked, lock_info
2036
2050
2037 @property
2051 @property
2038 def last_db_change(self):
2052 def last_db_change(self):
2039 return self.updated_on
2053 return self.updated_on
2040
2054
2041 @property
2055 @property
2042 def clone_uri_hidden(self):
2056 def clone_uri_hidden(self):
2043 clone_uri = self.clone_uri
2057 clone_uri = self.clone_uri
2044 if clone_uri:
2058 if clone_uri:
2045 import urlobject
2059 import urlobject
2046 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2060 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2047 if url_obj.password:
2061 if url_obj.password:
2048 clone_uri = url_obj.with_password('*****')
2062 clone_uri = url_obj.with_password('*****')
2049 return clone_uri
2063 return clone_uri
2050
2064
2051 def clone_url(self, **override):
2065 def clone_url(self, **override):
2052 from rhodecode.model.settings import SettingsModel
2066 from rhodecode.model.settings import SettingsModel
2053
2067
2054 uri_tmpl = None
2068 uri_tmpl = None
2055 if 'with_id' in override:
2069 if 'with_id' in override:
2056 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2070 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2057 del override['with_id']
2071 del override['with_id']
2058
2072
2059 if 'uri_tmpl' in override:
2073 if 'uri_tmpl' in override:
2060 uri_tmpl = override['uri_tmpl']
2074 uri_tmpl = override['uri_tmpl']
2061 del override['uri_tmpl']
2075 del override['uri_tmpl']
2062
2076
2063 # we didn't override our tmpl from **overrides
2077 # we didn't override our tmpl from **overrides
2064 if not uri_tmpl:
2078 if not uri_tmpl:
2065 rc_config = SettingsModel().get_all_settings(cache=True)
2079 rc_config = SettingsModel().get_all_settings(cache=True)
2066 uri_tmpl = rc_config.get(
2080 uri_tmpl = rc_config.get(
2067 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2081 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2068
2082
2069 request = get_current_request()
2083 request = get_current_request()
2070 return get_clone_url(request=request,
2084 return get_clone_url(request=request,
2071 uri_tmpl=uri_tmpl,
2085 uri_tmpl=uri_tmpl,
2072 repo_name=self.repo_name,
2086 repo_name=self.repo_name,
2073 repo_id=self.repo_id, **override)
2087 repo_id=self.repo_id, **override)
2074
2088
2075 def set_state(self, state):
2089 def set_state(self, state):
2076 self.repo_state = state
2090 self.repo_state = state
2077 Session().add(self)
2091 Session().add(self)
2078 #==========================================================================
2092 #==========================================================================
2079 # SCM PROPERTIES
2093 # SCM PROPERTIES
2080 #==========================================================================
2094 #==========================================================================
2081
2095
2082 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2096 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2083 return get_commit_safe(
2097 return get_commit_safe(
2084 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2098 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2085
2099
2086 def get_changeset(self, rev=None, pre_load=None):
2100 def get_changeset(self, rev=None, pre_load=None):
2087 warnings.warn("Use get_commit", DeprecationWarning)
2101 warnings.warn("Use get_commit", DeprecationWarning)
2088 commit_id = None
2102 commit_id = None
2089 commit_idx = None
2103 commit_idx = None
2090 if isinstance(rev, basestring):
2104 if isinstance(rev, basestring):
2091 commit_id = rev
2105 commit_id = rev
2092 else:
2106 else:
2093 commit_idx = rev
2107 commit_idx = rev
2094 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2108 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2095 pre_load=pre_load)
2109 pre_load=pre_load)
2096
2110
2097 def get_landing_commit(self):
2111 def get_landing_commit(self):
2098 """
2112 """
2099 Returns landing commit, or if that doesn't exist returns the tip
2113 Returns landing commit, or if that doesn't exist returns the tip
2100 """
2114 """
2101 _rev_type, _rev = self.landing_rev
2115 _rev_type, _rev = self.landing_rev
2102 commit = self.get_commit(_rev)
2116 commit = self.get_commit(_rev)
2103 if isinstance(commit, EmptyCommit):
2117 if isinstance(commit, EmptyCommit):
2104 return self.get_commit()
2118 return self.get_commit()
2105 return commit
2119 return commit
2106
2120
2107 def update_commit_cache(self, cs_cache=None, config=None):
2121 def update_commit_cache(self, cs_cache=None, config=None):
2108 """
2122 """
2109 Update cache of last changeset for repository, keys should be::
2123 Update cache of last changeset for repository, keys should be::
2110
2124
2111 short_id
2125 short_id
2112 raw_id
2126 raw_id
2113 revision
2127 revision
2114 parents
2128 parents
2115 message
2129 message
2116 date
2130 date
2117 author
2131 author
2118
2132
2119 :param cs_cache:
2133 :param cs_cache:
2120 """
2134 """
2121 from rhodecode.lib.vcs.backends.base import BaseChangeset
2135 from rhodecode.lib.vcs.backends.base import BaseChangeset
2122 if cs_cache is None:
2136 if cs_cache is None:
2123 # use no-cache version here
2137 # use no-cache version here
2124 scm_repo = self.scm_instance(cache=False, config=config)
2138 scm_repo = self.scm_instance(cache=False, config=config)
2125 if scm_repo:
2139 if scm_repo:
2126 cs_cache = scm_repo.get_commit(
2140 cs_cache = scm_repo.get_commit(
2127 pre_load=["author", "date", "message", "parents"])
2141 pre_load=["author", "date", "message", "parents"])
2128 else:
2142 else:
2129 cs_cache = EmptyCommit()
2143 cs_cache = EmptyCommit()
2130
2144
2131 if isinstance(cs_cache, BaseChangeset):
2145 if isinstance(cs_cache, BaseChangeset):
2132 cs_cache = cs_cache.__json__()
2146 cs_cache = cs_cache.__json__()
2133
2147
2134 def is_outdated(new_cs_cache):
2148 def is_outdated(new_cs_cache):
2135 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2149 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2136 new_cs_cache['revision'] != self.changeset_cache['revision']):
2150 new_cs_cache['revision'] != self.changeset_cache['revision']):
2137 return True
2151 return True
2138 return False
2152 return False
2139
2153
2140 # check if we have maybe already latest cached revision
2154 # check if we have maybe already latest cached revision
2141 if is_outdated(cs_cache) or not self.changeset_cache:
2155 if is_outdated(cs_cache) or not self.changeset_cache:
2142 _default = datetime.datetime.fromtimestamp(0)
2156 _default = datetime.datetime.fromtimestamp(0)
2143 last_change = cs_cache.get('date') or _default
2157 last_change = cs_cache.get('date') or _default
2144 log.debug('updated repo %s with new cs cache %s',
2158 log.debug('updated repo %s with new cs cache %s',
2145 self.repo_name, cs_cache)
2159 self.repo_name, cs_cache)
2146 self.updated_on = last_change
2160 self.updated_on = last_change
2147 self.changeset_cache = cs_cache
2161 self.changeset_cache = cs_cache
2148 Session().add(self)
2162 Session().add(self)
2149 Session().commit()
2163 Session().commit()
2150 else:
2164 else:
2151 log.debug('Skipping update_commit_cache for repo:`%s` '
2165 log.debug('Skipping update_commit_cache for repo:`%s` '
2152 'commit already with latest changes', self.repo_name)
2166 'commit already with latest changes', self.repo_name)
2153
2167
2154 @property
2168 @property
2155 def tip(self):
2169 def tip(self):
2156 return self.get_commit('tip')
2170 return self.get_commit('tip')
2157
2171
2158 @property
2172 @property
2159 def author(self):
2173 def author(self):
2160 return self.tip.author
2174 return self.tip.author
2161
2175
2162 @property
2176 @property
2163 def last_change(self):
2177 def last_change(self):
2164 return self.scm_instance().last_change
2178 return self.scm_instance().last_change
2165
2179
2166 def get_comments(self, revisions=None):
2180 def get_comments(self, revisions=None):
2167 """
2181 """
2168 Returns comments for this repository grouped by revisions
2182 Returns comments for this repository grouped by revisions
2169
2183
2170 :param revisions: filter query by revisions only
2184 :param revisions: filter query by revisions only
2171 """
2185 """
2172 cmts = ChangesetComment.query()\
2186 cmts = ChangesetComment.query()\
2173 .filter(ChangesetComment.repo == self)
2187 .filter(ChangesetComment.repo == self)
2174 if revisions:
2188 if revisions:
2175 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2189 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2176 grouped = collections.defaultdict(list)
2190 grouped = collections.defaultdict(list)
2177 for cmt in cmts.all():
2191 for cmt in cmts.all():
2178 grouped[cmt.revision].append(cmt)
2192 grouped[cmt.revision].append(cmt)
2179 return grouped
2193 return grouped
2180
2194
2181 def statuses(self, revisions=None):
2195 def statuses(self, revisions=None):
2182 """
2196 """
2183 Returns statuses for this repository
2197 Returns statuses for this repository
2184
2198
2185 :param revisions: list of revisions to get statuses for
2199 :param revisions: list of revisions to get statuses for
2186 """
2200 """
2187 statuses = ChangesetStatus.query()\
2201 statuses = ChangesetStatus.query()\
2188 .filter(ChangesetStatus.repo == self)\
2202 .filter(ChangesetStatus.repo == self)\
2189 .filter(ChangesetStatus.version == 0)
2203 .filter(ChangesetStatus.version == 0)
2190
2204
2191 if revisions:
2205 if revisions:
2192 # Try doing the filtering in chunks to avoid hitting limits
2206 # Try doing the filtering in chunks to avoid hitting limits
2193 size = 500
2207 size = 500
2194 status_results = []
2208 status_results = []
2195 for chunk in xrange(0, len(revisions), size):
2209 for chunk in xrange(0, len(revisions), size):
2196 status_results += statuses.filter(
2210 status_results += statuses.filter(
2197 ChangesetStatus.revision.in_(
2211 ChangesetStatus.revision.in_(
2198 revisions[chunk: chunk+size])
2212 revisions[chunk: chunk+size])
2199 ).all()
2213 ).all()
2200 else:
2214 else:
2201 status_results = statuses.all()
2215 status_results = statuses.all()
2202
2216
2203 grouped = {}
2217 grouped = {}
2204
2218
2205 # maybe we have open new pullrequest without a status?
2219 # maybe we have open new pullrequest without a status?
2206 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2220 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2207 status_lbl = ChangesetStatus.get_status_lbl(stat)
2221 status_lbl = ChangesetStatus.get_status_lbl(stat)
2208 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2222 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2209 for rev in pr.revisions:
2223 for rev in pr.revisions:
2210 pr_id = pr.pull_request_id
2224 pr_id = pr.pull_request_id
2211 pr_repo = pr.target_repo.repo_name
2225 pr_repo = pr.target_repo.repo_name
2212 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2226 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2213
2227
2214 for stat in status_results:
2228 for stat in status_results:
2215 pr_id = pr_repo = None
2229 pr_id = pr_repo = None
2216 if stat.pull_request:
2230 if stat.pull_request:
2217 pr_id = stat.pull_request.pull_request_id
2231 pr_id = stat.pull_request.pull_request_id
2218 pr_repo = stat.pull_request.target_repo.repo_name
2232 pr_repo = stat.pull_request.target_repo.repo_name
2219 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2233 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2220 pr_id, pr_repo]
2234 pr_id, pr_repo]
2221 return grouped
2235 return grouped
2222
2236
2223 # ==========================================================================
2237 # ==========================================================================
2224 # SCM CACHE INSTANCE
2238 # SCM CACHE INSTANCE
2225 # ==========================================================================
2239 # ==========================================================================
2226
2240
2227 def scm_instance(self, **kwargs):
2241 def scm_instance(self, **kwargs):
2228 import rhodecode
2242 import rhodecode
2229
2243
2230 # Passing a config will not hit the cache currently only used
2244 # Passing a config will not hit the cache currently only used
2231 # for repo2dbmapper
2245 # for repo2dbmapper
2232 config = kwargs.pop('config', None)
2246 config = kwargs.pop('config', None)
2233 cache = kwargs.pop('cache', None)
2247 cache = kwargs.pop('cache', None)
2234 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2248 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2235 # if cache is NOT defined use default global, else we have a full
2249 # if cache is NOT defined use default global, else we have a full
2236 # control over cache behaviour
2250 # control over cache behaviour
2237 if cache is None and full_cache and not config:
2251 if cache is None and full_cache and not config:
2238 return self._get_instance_cached()
2252 return self._get_instance_cached()
2239 return self._get_instance(cache=bool(cache), config=config)
2253 return self._get_instance(cache=bool(cache), config=config)
2240
2254
2241 def _get_instance_cached(self):
2255 def _get_instance_cached(self):
2242 @cache_region('long_term')
2256 @cache_region('long_term')
2243 def _get_repo(cache_key):
2257 def _get_repo(cache_key):
2244 return self._get_instance()
2258 return self._get_instance()
2245
2259
2246 invalidator_context = CacheKey.repo_context_cache(
2260 invalidator_context = CacheKey.repo_context_cache(
2247 _get_repo, self.repo_name, None, thread_scoped=True)
2261 _get_repo, self.repo_name, None, thread_scoped=True)
2248
2262
2249 with invalidator_context as context:
2263 with invalidator_context as context:
2250 context.invalidate()
2264 context.invalidate()
2251 repo = context.compute()
2265 repo = context.compute()
2252
2266
2253 return repo
2267 return repo
2254
2268
2255 def _get_instance(self, cache=True, config=None):
2269 def _get_instance(self, cache=True, config=None):
2256 config = config or self._config
2270 config = config or self._config
2257 custom_wire = {
2271 custom_wire = {
2258 'cache': cache # controls the vcs.remote cache
2272 'cache': cache # controls the vcs.remote cache
2259 }
2273 }
2260 repo = get_vcs_instance(
2274 repo = get_vcs_instance(
2261 repo_path=safe_str(self.repo_full_path),
2275 repo_path=safe_str(self.repo_full_path),
2262 config=config,
2276 config=config,
2263 with_wire=custom_wire,
2277 with_wire=custom_wire,
2264 create=False,
2278 create=False,
2265 _vcs_alias=self.repo_type)
2279 _vcs_alias=self.repo_type)
2266
2280
2267 return repo
2281 return repo
2268
2282
2269 def __json__(self):
2283 def __json__(self):
2270 return {'landing_rev': self.landing_rev}
2284 return {'landing_rev': self.landing_rev}
2271
2285
2272 def get_dict(self):
2286 def get_dict(self):
2273
2287
2274 # Since we transformed `repo_name` to a hybrid property, we need to
2288 # Since we transformed `repo_name` to a hybrid property, we need to
2275 # keep compatibility with the code which uses `repo_name` field.
2289 # keep compatibility with the code which uses `repo_name` field.
2276
2290
2277 result = super(Repository, self).get_dict()
2291 result = super(Repository, self).get_dict()
2278 result['repo_name'] = result.pop('_repo_name', None)
2292 result['repo_name'] = result.pop('_repo_name', None)
2279 return result
2293 return result
2280
2294
2281
2295
2282 class RepoGroup(Base, BaseModel):
2296 class RepoGroup(Base, BaseModel):
2283 __tablename__ = 'groups'
2297 __tablename__ = 'groups'
2284 __table_args__ = (
2298 __table_args__ = (
2285 UniqueConstraint('group_name', 'group_parent_id'),
2299 UniqueConstraint('group_name', 'group_parent_id'),
2286 CheckConstraint('group_id != group_parent_id'),
2300 CheckConstraint('group_id != group_parent_id'),
2287 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2301 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2288 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2302 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2289 )
2303 )
2290 __mapper_args__ = {'order_by': 'group_name'}
2304 __mapper_args__ = {'order_by': 'group_name'}
2291
2305
2292 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2306 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2293
2307
2294 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2308 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2295 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2309 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2296 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2310 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2297 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2311 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2298 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2312 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2299 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2313 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2300 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2314 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2301 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2315 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2302 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2316 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2303
2317
2304 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2318 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2305 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2319 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2306 parent_group = relationship('RepoGroup', remote_side=group_id)
2320 parent_group = relationship('RepoGroup', remote_side=group_id)
2307 user = relationship('User')
2321 user = relationship('User')
2308 integrations = relationship('Integration',
2322 integrations = relationship('Integration',
2309 cascade="all, delete, delete-orphan")
2323 cascade="all, delete, delete-orphan")
2310
2324
2311 def __init__(self, group_name='', parent_group=None):
2325 def __init__(self, group_name='', parent_group=None):
2312 self.group_name = group_name
2326 self.group_name = group_name
2313 self.parent_group = parent_group
2327 self.parent_group = parent_group
2314
2328
2315 def __unicode__(self):
2329 def __unicode__(self):
2316 return u"<%s('id:%s:%s')>" % (
2330 return u"<%s('id:%s:%s')>" % (
2317 self.__class__.__name__, self.group_id, self.group_name)
2331 self.__class__.__name__, self.group_id, self.group_name)
2318
2332
2319 @hybrid_property
2333 @hybrid_property
2320 def description_safe(self):
2334 def description_safe(self):
2321 from rhodecode.lib import helpers as h
2335 from rhodecode.lib import helpers as h
2322 return h.escape(self.group_description)
2336 return h.escape(self.group_description)
2323
2337
2324 @classmethod
2338 @classmethod
2325 def _generate_choice(cls, repo_group):
2339 def _generate_choice(cls, repo_group):
2326 from webhelpers.html import literal as _literal
2340 from webhelpers.html import literal as _literal
2327 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2341 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2328 return repo_group.group_id, _name(repo_group.full_path_splitted)
2342 return repo_group.group_id, _name(repo_group.full_path_splitted)
2329
2343
2330 @classmethod
2344 @classmethod
2331 def groups_choices(cls, groups=None, show_empty_group=True):
2345 def groups_choices(cls, groups=None, show_empty_group=True):
2332 if not groups:
2346 if not groups:
2333 groups = cls.query().all()
2347 groups = cls.query().all()
2334
2348
2335 repo_groups = []
2349 repo_groups = []
2336 if show_empty_group:
2350 if show_empty_group:
2337 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2351 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2338
2352
2339 repo_groups.extend([cls._generate_choice(x) for x in groups])
2353 repo_groups.extend([cls._generate_choice(x) for x in groups])
2340
2354
2341 repo_groups = sorted(
2355 repo_groups = sorted(
2342 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2356 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2343 return repo_groups
2357 return repo_groups
2344
2358
2345 @classmethod
2359 @classmethod
2346 def url_sep(cls):
2360 def url_sep(cls):
2347 return URL_SEP
2361 return URL_SEP
2348
2362
2349 @classmethod
2363 @classmethod
2350 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2364 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2351 if case_insensitive:
2365 if case_insensitive:
2352 gr = cls.query().filter(func.lower(cls.group_name)
2366 gr = cls.query().filter(func.lower(cls.group_name)
2353 == func.lower(group_name))
2367 == func.lower(group_name))
2354 else:
2368 else:
2355 gr = cls.query().filter(cls.group_name == group_name)
2369 gr = cls.query().filter(cls.group_name == group_name)
2356 if cache:
2370 if cache:
2357 name_key = _hash_key(group_name)
2371 name_key = _hash_key(group_name)
2358 gr = gr.options(
2372 gr = gr.options(
2359 FromCache("sql_cache_short", "get_group_%s" % name_key))
2373 FromCache("sql_cache_short", "get_group_%s" % name_key))
2360 return gr.scalar()
2374 return gr.scalar()
2361
2375
2362 @classmethod
2376 @classmethod
2363 def get_user_personal_repo_group(cls, user_id):
2377 def get_user_personal_repo_group(cls, user_id):
2364 user = User.get(user_id)
2378 user = User.get(user_id)
2365 if user.username == User.DEFAULT_USER:
2379 if user.username == User.DEFAULT_USER:
2366 return None
2380 return None
2367
2381
2368 return cls.query()\
2382 return cls.query()\
2369 .filter(cls.personal == true()) \
2383 .filter(cls.personal == true()) \
2370 .filter(cls.user == user).scalar()
2384 .filter(cls.user == user).scalar()
2371
2385
2372 @classmethod
2386 @classmethod
2373 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2387 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2374 case_insensitive=True):
2388 case_insensitive=True):
2375 q = RepoGroup.query()
2389 q = RepoGroup.query()
2376
2390
2377 if not isinstance(user_id, Optional):
2391 if not isinstance(user_id, Optional):
2378 q = q.filter(RepoGroup.user_id == user_id)
2392 q = q.filter(RepoGroup.user_id == user_id)
2379
2393
2380 if not isinstance(group_id, Optional):
2394 if not isinstance(group_id, Optional):
2381 q = q.filter(RepoGroup.group_parent_id == group_id)
2395 q = q.filter(RepoGroup.group_parent_id == group_id)
2382
2396
2383 if case_insensitive:
2397 if case_insensitive:
2384 q = q.order_by(func.lower(RepoGroup.group_name))
2398 q = q.order_by(func.lower(RepoGroup.group_name))
2385 else:
2399 else:
2386 q = q.order_by(RepoGroup.group_name)
2400 q = q.order_by(RepoGroup.group_name)
2387 return q.all()
2401 return q.all()
2388
2402
2389 @property
2403 @property
2390 def parents(self):
2404 def parents(self):
2391 parents_recursion_limit = 10
2405 parents_recursion_limit = 10
2392 groups = []
2406 groups = []
2393 if self.parent_group is None:
2407 if self.parent_group is None:
2394 return groups
2408 return groups
2395 cur_gr = self.parent_group
2409 cur_gr = self.parent_group
2396 groups.insert(0, cur_gr)
2410 groups.insert(0, cur_gr)
2397 cnt = 0
2411 cnt = 0
2398 while 1:
2412 while 1:
2399 cnt += 1
2413 cnt += 1
2400 gr = getattr(cur_gr, 'parent_group', None)
2414 gr = getattr(cur_gr, 'parent_group', None)
2401 cur_gr = cur_gr.parent_group
2415 cur_gr = cur_gr.parent_group
2402 if gr is None:
2416 if gr is None:
2403 break
2417 break
2404 if cnt == parents_recursion_limit:
2418 if cnt == parents_recursion_limit:
2405 # this will prevent accidental infinit loops
2419 # this will prevent accidental infinit loops
2406 log.error(('more than %s parents found for group %s, stopping '
2420 log.error(('more than %s parents found for group %s, stopping '
2407 'recursive parent fetching' % (parents_recursion_limit, self)))
2421 'recursive parent fetching' % (parents_recursion_limit, self)))
2408 break
2422 break
2409
2423
2410 groups.insert(0, gr)
2424 groups.insert(0, gr)
2411 return groups
2425 return groups
2412
2426
2413 @property
2427 @property
2414 def last_db_change(self):
2428 def last_db_change(self):
2415 return self.updated_on
2429 return self.updated_on
2416
2430
2417 @property
2431 @property
2418 def children(self):
2432 def children(self):
2419 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2433 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2420
2434
2421 @property
2435 @property
2422 def name(self):
2436 def name(self):
2423 return self.group_name.split(RepoGroup.url_sep())[-1]
2437 return self.group_name.split(RepoGroup.url_sep())[-1]
2424
2438
2425 @property
2439 @property
2426 def full_path(self):
2440 def full_path(self):
2427 return self.group_name
2441 return self.group_name
2428
2442
2429 @property
2443 @property
2430 def full_path_splitted(self):
2444 def full_path_splitted(self):
2431 return self.group_name.split(RepoGroup.url_sep())
2445 return self.group_name.split(RepoGroup.url_sep())
2432
2446
2433 @property
2447 @property
2434 def repositories(self):
2448 def repositories(self):
2435 return Repository.query()\
2449 return Repository.query()\
2436 .filter(Repository.group == self)\
2450 .filter(Repository.group == self)\
2437 .order_by(Repository.repo_name)
2451 .order_by(Repository.repo_name)
2438
2452
2439 @property
2453 @property
2440 def repositories_recursive_count(self):
2454 def repositories_recursive_count(self):
2441 cnt = self.repositories.count()
2455 cnt = self.repositories.count()
2442
2456
2443 def children_count(group):
2457 def children_count(group):
2444 cnt = 0
2458 cnt = 0
2445 for child in group.children:
2459 for child in group.children:
2446 cnt += child.repositories.count()
2460 cnt += child.repositories.count()
2447 cnt += children_count(child)
2461 cnt += children_count(child)
2448 return cnt
2462 return cnt
2449
2463
2450 return cnt + children_count(self)
2464 return cnt + children_count(self)
2451
2465
2452 def _recursive_objects(self, include_repos=True):
2466 def _recursive_objects(self, include_repos=True):
2453 all_ = []
2467 all_ = []
2454
2468
2455 def _get_members(root_gr):
2469 def _get_members(root_gr):
2456 if include_repos:
2470 if include_repos:
2457 for r in root_gr.repositories:
2471 for r in root_gr.repositories:
2458 all_.append(r)
2472 all_.append(r)
2459 childs = root_gr.children.all()
2473 childs = root_gr.children.all()
2460 if childs:
2474 if childs:
2461 for gr in childs:
2475 for gr in childs:
2462 all_.append(gr)
2476 all_.append(gr)
2463 _get_members(gr)
2477 _get_members(gr)
2464
2478
2465 _get_members(self)
2479 _get_members(self)
2466 return [self] + all_
2480 return [self] + all_
2467
2481
2468 def recursive_groups_and_repos(self):
2482 def recursive_groups_and_repos(self):
2469 """
2483 """
2470 Recursive return all groups, with repositories in those groups
2484 Recursive return all groups, with repositories in those groups
2471 """
2485 """
2472 return self._recursive_objects()
2486 return self._recursive_objects()
2473
2487
2474 def recursive_groups(self):
2488 def recursive_groups(self):
2475 """
2489 """
2476 Returns all children groups for this group including children of children
2490 Returns all children groups for this group including children of children
2477 """
2491 """
2478 return self._recursive_objects(include_repos=False)
2492 return self._recursive_objects(include_repos=False)
2479
2493
2480 def get_new_name(self, group_name):
2494 def get_new_name(self, group_name):
2481 """
2495 """
2482 returns new full group name based on parent and new name
2496 returns new full group name based on parent and new name
2483
2497
2484 :param group_name:
2498 :param group_name:
2485 """
2499 """
2486 path_prefix = (self.parent_group.full_path_splitted if
2500 path_prefix = (self.parent_group.full_path_splitted if
2487 self.parent_group else [])
2501 self.parent_group else [])
2488 return RepoGroup.url_sep().join(path_prefix + [group_name])
2502 return RepoGroup.url_sep().join(path_prefix + [group_name])
2489
2503
2490 def permissions(self, with_admins=True, with_owner=True):
2504 def permissions(self, with_admins=True, with_owner=True):
2491 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2505 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2492 q = q.options(joinedload(UserRepoGroupToPerm.group),
2506 q = q.options(joinedload(UserRepoGroupToPerm.group),
2493 joinedload(UserRepoGroupToPerm.user),
2507 joinedload(UserRepoGroupToPerm.user),
2494 joinedload(UserRepoGroupToPerm.permission),)
2508 joinedload(UserRepoGroupToPerm.permission),)
2495
2509
2496 # get owners and admins and permissions. We do a trick of re-writing
2510 # get owners and admins and permissions. We do a trick of re-writing
2497 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2511 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2498 # has a global reference and changing one object propagates to all
2512 # has a global reference and changing one object propagates to all
2499 # others. This means if admin is also an owner admin_row that change
2513 # others. This means if admin is also an owner admin_row that change
2500 # would propagate to both objects
2514 # would propagate to both objects
2501 perm_rows = []
2515 perm_rows = []
2502 for _usr in q.all():
2516 for _usr in q.all():
2503 usr = AttributeDict(_usr.user.get_dict())
2517 usr = AttributeDict(_usr.user.get_dict())
2504 usr.permission = _usr.permission.permission_name
2518 usr.permission = _usr.permission.permission_name
2505 perm_rows.append(usr)
2519 perm_rows.append(usr)
2506
2520
2507 # filter the perm rows by 'default' first and then sort them by
2521 # filter the perm rows by 'default' first and then sort them by
2508 # admin,write,read,none permissions sorted again alphabetically in
2522 # admin,write,read,none permissions sorted again alphabetically in
2509 # each group
2523 # each group
2510 perm_rows = sorted(perm_rows, key=display_user_sort)
2524 perm_rows = sorted(perm_rows, key=display_user_sort)
2511
2525
2512 _admin_perm = 'group.admin'
2526 _admin_perm = 'group.admin'
2513 owner_row = []
2527 owner_row = []
2514 if with_owner:
2528 if with_owner:
2515 usr = AttributeDict(self.user.get_dict())
2529 usr = AttributeDict(self.user.get_dict())
2516 usr.owner_row = True
2530 usr.owner_row = True
2517 usr.permission = _admin_perm
2531 usr.permission = _admin_perm
2518 owner_row.append(usr)
2532 owner_row.append(usr)
2519
2533
2520 super_admin_rows = []
2534 super_admin_rows = []
2521 if with_admins:
2535 if with_admins:
2522 for usr in User.get_all_super_admins():
2536 for usr in User.get_all_super_admins():
2523 # if this admin is also owner, don't double the record
2537 # if this admin is also owner, don't double the record
2524 if usr.user_id == owner_row[0].user_id:
2538 if usr.user_id == owner_row[0].user_id:
2525 owner_row[0].admin_row = True
2539 owner_row[0].admin_row = True
2526 else:
2540 else:
2527 usr = AttributeDict(usr.get_dict())
2541 usr = AttributeDict(usr.get_dict())
2528 usr.admin_row = True
2542 usr.admin_row = True
2529 usr.permission = _admin_perm
2543 usr.permission = _admin_perm
2530 super_admin_rows.append(usr)
2544 super_admin_rows.append(usr)
2531
2545
2532 return super_admin_rows + owner_row + perm_rows
2546 return super_admin_rows + owner_row + perm_rows
2533
2547
2534 def permission_user_groups(self):
2548 def permission_user_groups(self):
2535 q = UserGroupRepoGroupToPerm.query().filter(UserGroupRepoGroupToPerm.group == self)
2549 q = UserGroupRepoGroupToPerm.query().filter(UserGroupRepoGroupToPerm.group == self)
2536 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2550 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2537 joinedload(UserGroupRepoGroupToPerm.users_group),
2551 joinedload(UserGroupRepoGroupToPerm.users_group),
2538 joinedload(UserGroupRepoGroupToPerm.permission),)
2552 joinedload(UserGroupRepoGroupToPerm.permission),)
2539
2553
2540 perm_rows = []
2554 perm_rows = []
2541 for _user_group in q.all():
2555 for _user_group in q.all():
2542 usr = AttributeDict(_user_group.users_group.get_dict())
2556 usr = AttributeDict(_user_group.users_group.get_dict())
2543 usr.permission = _user_group.permission.permission_name
2557 usr.permission = _user_group.permission.permission_name
2544 perm_rows.append(usr)
2558 perm_rows.append(usr)
2545
2559
2546 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2560 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2547 return perm_rows
2561 return perm_rows
2548
2562
2549 def get_api_data(self):
2563 def get_api_data(self):
2550 """
2564 """
2551 Common function for generating api data
2565 Common function for generating api data
2552
2566
2553 """
2567 """
2554 group = self
2568 group = self
2555 data = {
2569 data = {
2556 'group_id': group.group_id,
2570 'group_id': group.group_id,
2557 'group_name': group.group_name,
2571 'group_name': group.group_name,
2558 'group_description': group.description_safe,
2572 'group_description': group.description_safe,
2559 'parent_group': group.parent_group.group_name if group.parent_group else None,
2573 'parent_group': group.parent_group.group_name if group.parent_group else None,
2560 'repositories': [x.repo_name for x in group.repositories],
2574 'repositories': [x.repo_name for x in group.repositories],
2561 'owner': group.user.username,
2575 'owner': group.user.username,
2562 }
2576 }
2563 return data
2577 return data
2564
2578
2565
2579
2566 class Permission(Base, BaseModel):
2580 class Permission(Base, BaseModel):
2567 __tablename__ = 'permissions'
2581 __tablename__ = 'permissions'
2568 __table_args__ = (
2582 __table_args__ = (
2569 Index('p_perm_name_idx', 'permission_name'),
2583 Index('p_perm_name_idx', 'permission_name'),
2570 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2584 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2571 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2585 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2572 )
2586 )
2573 PERMS = [
2587 PERMS = [
2574 ('hg.admin', _('RhodeCode Super Administrator')),
2588 ('hg.admin', _('RhodeCode Super Administrator')),
2575
2589
2576 ('repository.none', _('Repository no access')),
2590 ('repository.none', _('Repository no access')),
2577 ('repository.read', _('Repository read access')),
2591 ('repository.read', _('Repository read access')),
2578 ('repository.write', _('Repository write access')),
2592 ('repository.write', _('Repository write access')),
2579 ('repository.admin', _('Repository admin access')),
2593 ('repository.admin', _('Repository admin access')),
2580
2594
2581 ('group.none', _('Repository group no access')),
2595 ('group.none', _('Repository group no access')),
2582 ('group.read', _('Repository group read access')),
2596 ('group.read', _('Repository group read access')),
2583 ('group.write', _('Repository group write access')),
2597 ('group.write', _('Repository group write access')),
2584 ('group.admin', _('Repository group admin access')),
2598 ('group.admin', _('Repository group admin access')),
2585
2599
2586 ('usergroup.none', _('User group no access')),
2600 ('usergroup.none', _('User group no access')),
2587 ('usergroup.read', _('User group read access')),
2601 ('usergroup.read', _('User group read access')),
2588 ('usergroup.write', _('User group write access')),
2602 ('usergroup.write', _('User group write access')),
2589 ('usergroup.admin', _('User group admin access')),
2603 ('usergroup.admin', _('User group admin access')),
2590
2604
2591 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2605 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2592 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2606 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2593
2607
2594 ('hg.usergroup.create.false', _('User Group creation disabled')),
2608 ('hg.usergroup.create.false', _('User Group creation disabled')),
2595 ('hg.usergroup.create.true', _('User Group creation enabled')),
2609 ('hg.usergroup.create.true', _('User Group creation enabled')),
2596
2610
2597 ('hg.create.none', _('Repository creation disabled')),
2611 ('hg.create.none', _('Repository creation disabled')),
2598 ('hg.create.repository', _('Repository creation enabled')),
2612 ('hg.create.repository', _('Repository creation enabled')),
2599 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2613 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2600 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2614 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2601
2615
2602 ('hg.fork.none', _('Repository forking disabled')),
2616 ('hg.fork.none', _('Repository forking disabled')),
2603 ('hg.fork.repository', _('Repository forking enabled')),
2617 ('hg.fork.repository', _('Repository forking enabled')),
2604
2618
2605 ('hg.register.none', _('Registration disabled')),
2619 ('hg.register.none', _('Registration disabled')),
2606 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2620 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2607 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2621 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2608
2622
2609 ('hg.password_reset.enabled', _('Password reset enabled')),
2623 ('hg.password_reset.enabled', _('Password reset enabled')),
2610 ('hg.password_reset.hidden', _('Password reset hidden')),
2624 ('hg.password_reset.hidden', _('Password reset hidden')),
2611 ('hg.password_reset.disabled', _('Password reset disabled')),
2625 ('hg.password_reset.disabled', _('Password reset disabled')),
2612
2626
2613 ('hg.extern_activate.manual', _('Manual activation of external account')),
2627 ('hg.extern_activate.manual', _('Manual activation of external account')),
2614 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2628 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2615
2629
2616 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2630 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2617 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2631 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2618 ]
2632 ]
2619
2633
2620 # definition of system default permissions for DEFAULT user
2634 # definition of system default permissions for DEFAULT user
2621 DEFAULT_USER_PERMISSIONS = [
2635 DEFAULT_USER_PERMISSIONS = [
2622 'repository.read',
2636 'repository.read',
2623 'group.read',
2637 'group.read',
2624 'usergroup.read',
2638 'usergroup.read',
2625 'hg.create.repository',
2639 'hg.create.repository',
2626 'hg.repogroup.create.false',
2640 'hg.repogroup.create.false',
2627 'hg.usergroup.create.false',
2641 'hg.usergroup.create.false',
2628 'hg.create.write_on_repogroup.true',
2642 'hg.create.write_on_repogroup.true',
2629 'hg.fork.repository',
2643 'hg.fork.repository',
2630 'hg.register.manual_activate',
2644 'hg.register.manual_activate',
2631 'hg.password_reset.enabled',
2645 'hg.password_reset.enabled',
2632 'hg.extern_activate.auto',
2646 'hg.extern_activate.auto',
2633 'hg.inherit_default_perms.true',
2647 'hg.inherit_default_perms.true',
2634 ]
2648 ]
2635
2649
2636 # defines which permissions are more important higher the more important
2650 # defines which permissions are more important higher the more important
2637 # Weight defines which permissions are more important.
2651 # Weight defines which permissions are more important.
2638 # The higher number the more important.
2652 # The higher number the more important.
2639 PERM_WEIGHTS = {
2653 PERM_WEIGHTS = {
2640 'repository.none': 0,
2654 'repository.none': 0,
2641 'repository.read': 1,
2655 'repository.read': 1,
2642 'repository.write': 3,
2656 'repository.write': 3,
2643 'repository.admin': 4,
2657 'repository.admin': 4,
2644
2658
2645 'group.none': 0,
2659 'group.none': 0,
2646 'group.read': 1,
2660 'group.read': 1,
2647 'group.write': 3,
2661 'group.write': 3,
2648 'group.admin': 4,
2662 'group.admin': 4,
2649
2663
2650 'usergroup.none': 0,
2664 'usergroup.none': 0,
2651 'usergroup.read': 1,
2665 'usergroup.read': 1,
2652 'usergroup.write': 3,
2666 'usergroup.write': 3,
2653 'usergroup.admin': 4,
2667 'usergroup.admin': 4,
2654
2668
2655 'hg.repogroup.create.false': 0,
2669 'hg.repogroup.create.false': 0,
2656 'hg.repogroup.create.true': 1,
2670 'hg.repogroup.create.true': 1,
2657
2671
2658 'hg.usergroup.create.false': 0,
2672 'hg.usergroup.create.false': 0,
2659 'hg.usergroup.create.true': 1,
2673 'hg.usergroup.create.true': 1,
2660
2674
2661 'hg.fork.none': 0,
2675 'hg.fork.none': 0,
2662 'hg.fork.repository': 1,
2676 'hg.fork.repository': 1,
2663 'hg.create.none': 0,
2677 'hg.create.none': 0,
2664 'hg.create.repository': 1
2678 'hg.create.repository': 1
2665 }
2679 }
2666
2680
2667 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2681 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2668 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2682 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2669 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2683 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2670
2684
2671 def __unicode__(self):
2685 def __unicode__(self):
2672 return u"<%s('%s:%s')>" % (
2686 return u"<%s('%s:%s')>" % (
2673 self.__class__.__name__, self.permission_id, self.permission_name
2687 self.__class__.__name__, self.permission_id, self.permission_name
2674 )
2688 )
2675
2689
2676 @classmethod
2690 @classmethod
2677 def get_by_key(cls, key):
2691 def get_by_key(cls, key):
2678 return cls.query().filter(cls.permission_name == key).scalar()
2692 return cls.query().filter(cls.permission_name == key).scalar()
2679
2693
2680 @classmethod
2694 @classmethod
2681 def get_default_repo_perms(cls, user_id, repo_id=None):
2695 def get_default_repo_perms(cls, user_id, repo_id=None):
2682 q = Session().query(UserRepoToPerm, Repository, Permission)\
2696 q = Session().query(UserRepoToPerm, Repository, Permission)\
2683 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2697 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2684 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2698 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2685 .filter(UserRepoToPerm.user_id == user_id)
2699 .filter(UserRepoToPerm.user_id == user_id)
2686 if repo_id:
2700 if repo_id:
2687 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2701 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2688 return q.all()
2702 return q.all()
2689
2703
2690 @classmethod
2704 @classmethod
2691 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2705 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2692 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2706 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2693 .join(
2707 .join(
2694 Permission,
2708 Permission,
2695 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2709 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2696 .join(
2710 .join(
2697 Repository,
2711 Repository,
2698 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2712 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2699 .join(
2713 .join(
2700 UserGroup,
2714 UserGroup,
2701 UserGroupRepoToPerm.users_group_id ==
2715 UserGroupRepoToPerm.users_group_id ==
2702 UserGroup.users_group_id)\
2716 UserGroup.users_group_id)\
2703 .join(
2717 .join(
2704 UserGroupMember,
2718 UserGroupMember,
2705 UserGroupRepoToPerm.users_group_id ==
2719 UserGroupRepoToPerm.users_group_id ==
2706 UserGroupMember.users_group_id)\
2720 UserGroupMember.users_group_id)\
2707 .filter(
2721 .filter(
2708 UserGroupMember.user_id == user_id,
2722 UserGroupMember.user_id == user_id,
2709 UserGroup.users_group_active == true())
2723 UserGroup.users_group_active == true())
2710 if repo_id:
2724 if repo_id:
2711 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2725 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2712 return q.all()
2726 return q.all()
2713
2727
2714 @classmethod
2728 @classmethod
2715 def get_default_group_perms(cls, user_id, repo_group_id=None):
2729 def get_default_group_perms(cls, user_id, repo_group_id=None):
2716 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2730 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2717 .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\
2731 .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\
2718 .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
2732 .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
2719 .filter(UserRepoGroupToPerm.user_id == user_id)
2733 .filter(UserRepoGroupToPerm.user_id == user_id)
2720 if repo_group_id:
2734 if repo_group_id:
2721 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2735 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2722 return q.all()
2736 return q.all()
2723
2737
2724 @classmethod
2738 @classmethod
2725 def get_default_group_perms_from_user_group(
2739 def get_default_group_perms_from_user_group(
2726 cls, user_id, repo_group_id=None):
2740 cls, user_id, repo_group_id=None):
2727 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2741 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2728 .join(
2742 .join(
2729 Permission,
2743 Permission,
2730 UserGroupRepoGroupToPerm.permission_id ==
2744 UserGroupRepoGroupToPerm.permission_id ==
2731 Permission.permission_id)\
2745 Permission.permission_id)\
2732 .join(
2746 .join(
2733 RepoGroup,
2747 RepoGroup,
2734 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2748 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2735 .join(
2749 .join(
2736 UserGroup,
2750 UserGroup,
2737 UserGroupRepoGroupToPerm.users_group_id ==
2751 UserGroupRepoGroupToPerm.users_group_id ==
2738 UserGroup.users_group_id)\
2752 UserGroup.users_group_id)\
2739 .join(
2753 .join(
2740 UserGroupMember,
2754 UserGroupMember,
2741 UserGroupRepoGroupToPerm.users_group_id ==
2755 UserGroupRepoGroupToPerm.users_group_id ==
2742 UserGroupMember.users_group_id)\
2756 UserGroupMember.users_group_id)\
2743 .filter(
2757 .filter(
2744 UserGroupMember.user_id == user_id,
2758 UserGroupMember.user_id == user_id,
2745 UserGroup.users_group_active == true())
2759 UserGroup.users_group_active == true())
2746 if repo_group_id:
2760 if repo_group_id:
2747 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
2761 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
2748 return q.all()
2762 return q.all()
2749
2763
2750 @classmethod
2764 @classmethod
2751 def get_default_user_group_perms(cls, user_id, user_group_id=None):
2765 def get_default_user_group_perms(cls, user_id, user_group_id=None):
2752 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
2766 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
2753 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
2767 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
2754 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
2768 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
2755 .filter(UserUserGroupToPerm.user_id == user_id)
2769 .filter(UserUserGroupToPerm.user_id == user_id)
2756 if user_group_id:
2770 if user_group_id:
2757 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
2771 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
2758 return q.all()
2772 return q.all()
2759
2773
2760 @classmethod
2774 @classmethod
2761 def get_default_user_group_perms_from_user_group(
2775 def get_default_user_group_perms_from_user_group(
2762 cls, user_id, user_group_id=None):
2776 cls, user_id, user_group_id=None):
2763 TargetUserGroup = aliased(UserGroup, name='target_user_group')
2777 TargetUserGroup = aliased(UserGroup, name='target_user_group')
2764 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
2778 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
2765 .join(
2779 .join(
2766 Permission,
2780 Permission,
2767 UserGroupUserGroupToPerm.permission_id ==
2781 UserGroupUserGroupToPerm.permission_id ==
2768 Permission.permission_id)\
2782 Permission.permission_id)\
2769 .join(
2783 .join(
2770 TargetUserGroup,
2784 TargetUserGroup,
2771 UserGroupUserGroupToPerm.target_user_group_id ==
2785 UserGroupUserGroupToPerm.target_user_group_id ==
2772 TargetUserGroup.users_group_id)\
2786 TargetUserGroup.users_group_id)\
2773 .join(
2787 .join(
2774 UserGroup,
2788 UserGroup,
2775 UserGroupUserGroupToPerm.user_group_id ==
2789 UserGroupUserGroupToPerm.user_group_id ==
2776 UserGroup.users_group_id)\
2790 UserGroup.users_group_id)\
2777 .join(
2791 .join(
2778 UserGroupMember,
2792 UserGroupMember,
2779 UserGroupUserGroupToPerm.user_group_id ==
2793 UserGroupUserGroupToPerm.user_group_id ==
2780 UserGroupMember.users_group_id)\
2794 UserGroupMember.users_group_id)\
2781 .filter(
2795 .filter(
2782 UserGroupMember.user_id == user_id,
2796 UserGroupMember.user_id == user_id,
2783 UserGroup.users_group_active == true())
2797 UserGroup.users_group_active == true())
2784 if user_group_id:
2798 if user_group_id:
2785 q = q.filter(
2799 q = q.filter(
2786 UserGroupUserGroupToPerm.user_group_id == user_group_id)
2800 UserGroupUserGroupToPerm.user_group_id == user_group_id)
2787
2801
2788 return q.all()
2802 return q.all()
2789
2803
2790
2804
2791 class UserRepoToPerm(Base, BaseModel):
2805 class UserRepoToPerm(Base, BaseModel):
2792 __tablename__ = 'repo_to_perm'
2806 __tablename__ = 'repo_to_perm'
2793 __table_args__ = (
2807 __table_args__ = (
2794 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
2808 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
2795 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2809 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2796 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2810 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2797 )
2811 )
2798 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2812 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2799 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2813 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2800 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2814 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2801 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2815 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2802
2816
2803 user = relationship('User')
2817 user = relationship('User')
2804 repository = relationship('Repository')
2818 repository = relationship('Repository')
2805 permission = relationship('Permission')
2819 permission = relationship('Permission')
2806
2820
2807 @classmethod
2821 @classmethod
2808 def create(cls, user, repository, permission):
2822 def create(cls, user, repository, permission):
2809 n = cls()
2823 n = cls()
2810 n.user = user
2824 n.user = user
2811 n.repository = repository
2825 n.repository = repository
2812 n.permission = permission
2826 n.permission = permission
2813 Session().add(n)
2827 Session().add(n)
2814 return n
2828 return n
2815
2829
2816 def __unicode__(self):
2830 def __unicode__(self):
2817 return u'<%s => %s >' % (self.user, self.repository)
2831 return u'<%s => %s >' % (self.user, self.repository)
2818
2832
2819
2833
2820 class UserUserGroupToPerm(Base, BaseModel):
2834 class UserUserGroupToPerm(Base, BaseModel):
2821 __tablename__ = 'user_user_group_to_perm'
2835 __tablename__ = 'user_user_group_to_perm'
2822 __table_args__ = (
2836 __table_args__ = (
2823 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
2837 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
2824 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2838 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2825 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2839 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2826 )
2840 )
2827 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2841 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2828 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2842 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2829 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2843 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2830 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2844 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2831
2845
2832 user = relationship('User')
2846 user = relationship('User')
2833 user_group = relationship('UserGroup')
2847 user_group = relationship('UserGroup')
2834 permission = relationship('Permission')
2848 permission = relationship('Permission')
2835
2849
2836 @classmethod
2850 @classmethod
2837 def create(cls, user, user_group, permission):
2851 def create(cls, user, user_group, permission):
2838 n = cls()
2852 n = cls()
2839 n.user = user
2853 n.user = user
2840 n.user_group = user_group
2854 n.user_group = user_group
2841 n.permission = permission
2855 n.permission = permission
2842 Session().add(n)
2856 Session().add(n)
2843 return n
2857 return n
2844
2858
2845 def __unicode__(self):
2859 def __unicode__(self):
2846 return u'<%s => %s >' % (self.user, self.user_group)
2860 return u'<%s => %s >' % (self.user, self.user_group)
2847
2861
2848
2862
2849 class UserToPerm(Base, BaseModel):
2863 class UserToPerm(Base, BaseModel):
2850 __tablename__ = 'user_to_perm'
2864 __tablename__ = 'user_to_perm'
2851 __table_args__ = (
2865 __table_args__ = (
2852 UniqueConstraint('user_id', 'permission_id'),
2866 UniqueConstraint('user_id', 'permission_id'),
2853 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2867 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2854 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2868 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2855 )
2869 )
2856 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2870 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2857 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2871 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2858 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2872 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2859
2873
2860 user = relationship('User')
2874 user = relationship('User')
2861 permission = relationship('Permission', lazy='joined')
2875 permission = relationship('Permission', lazy='joined')
2862
2876
2863 def __unicode__(self):
2877 def __unicode__(self):
2864 return u'<%s => %s >' % (self.user, self.permission)
2878 return u'<%s => %s >' % (self.user, self.permission)
2865
2879
2866
2880
2867 class UserGroupRepoToPerm(Base, BaseModel):
2881 class UserGroupRepoToPerm(Base, BaseModel):
2868 __tablename__ = 'users_group_repo_to_perm'
2882 __tablename__ = 'users_group_repo_to_perm'
2869 __table_args__ = (
2883 __table_args__ = (
2870 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
2884 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
2871 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2885 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2872 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2886 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2873 )
2887 )
2874 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2888 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2875 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2889 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2876 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2890 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2877 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2891 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2878
2892
2879 users_group = relationship('UserGroup')
2893 users_group = relationship('UserGroup')
2880 permission = relationship('Permission')
2894 permission = relationship('Permission')
2881 repository = relationship('Repository')
2895 repository = relationship('Repository')
2882
2896
2883 @classmethod
2897 @classmethod
2884 def create(cls, users_group, repository, permission):
2898 def create(cls, users_group, repository, permission):
2885 n = cls()
2899 n = cls()
2886 n.users_group = users_group
2900 n.users_group = users_group
2887 n.repository = repository
2901 n.repository = repository
2888 n.permission = permission
2902 n.permission = permission
2889 Session().add(n)
2903 Session().add(n)
2890 return n
2904 return n
2891
2905
2892 def __unicode__(self):
2906 def __unicode__(self):
2893 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
2907 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
2894
2908
2895
2909
2896 class UserGroupUserGroupToPerm(Base, BaseModel):
2910 class UserGroupUserGroupToPerm(Base, BaseModel):
2897 __tablename__ = 'user_group_user_group_to_perm'
2911 __tablename__ = 'user_group_user_group_to_perm'
2898 __table_args__ = (
2912 __table_args__ = (
2899 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
2913 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
2900 CheckConstraint('target_user_group_id != user_group_id'),
2914 CheckConstraint('target_user_group_id != user_group_id'),
2901 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2915 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2902 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2916 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2903 )
2917 )
2904 user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2918 user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2905 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2919 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2906 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2920 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2907 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2921 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2908
2922
2909 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
2923 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
2910 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
2924 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
2911 permission = relationship('Permission')
2925 permission = relationship('Permission')
2912
2926
2913 @classmethod
2927 @classmethod
2914 def create(cls, target_user_group, user_group, permission):
2928 def create(cls, target_user_group, user_group, permission):
2915 n = cls()
2929 n = cls()
2916 n.target_user_group = target_user_group
2930 n.target_user_group = target_user_group
2917 n.user_group = user_group
2931 n.user_group = user_group
2918 n.permission = permission
2932 n.permission = permission
2919 Session().add(n)
2933 Session().add(n)
2920 return n
2934 return n
2921
2935
2922 def __unicode__(self):
2936 def __unicode__(self):
2923 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
2937 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
2924
2938
2925
2939
2926 class UserGroupToPerm(Base, BaseModel):
2940 class UserGroupToPerm(Base, BaseModel):
2927 __tablename__ = 'users_group_to_perm'
2941 __tablename__ = 'users_group_to_perm'
2928 __table_args__ = (
2942 __table_args__ = (
2929 UniqueConstraint('users_group_id', 'permission_id',),
2943 UniqueConstraint('users_group_id', 'permission_id',),
2930 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2944 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2931 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2945 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2932 )
2946 )
2933 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2947 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2934 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2948 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2935 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2949 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2936
2950
2937 users_group = relationship('UserGroup')
2951 users_group = relationship('UserGroup')
2938 permission = relationship('Permission')
2952 permission = relationship('Permission')
2939
2953
2940
2954
2941 class UserRepoGroupToPerm(Base, BaseModel):
2955 class UserRepoGroupToPerm(Base, BaseModel):
2942 __tablename__ = 'user_repo_group_to_perm'
2956 __tablename__ = 'user_repo_group_to_perm'
2943 __table_args__ = (
2957 __table_args__ = (
2944 UniqueConstraint('user_id', 'group_id', 'permission_id'),
2958 UniqueConstraint('user_id', 'group_id', 'permission_id'),
2945 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2959 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2946 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2960 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2947 )
2961 )
2948
2962
2949 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2963 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2950 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2964 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2951 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2965 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2952 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2966 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2953
2967
2954 user = relationship('User')
2968 user = relationship('User')
2955 group = relationship('RepoGroup')
2969 group = relationship('RepoGroup')
2956 permission = relationship('Permission')
2970 permission = relationship('Permission')
2957
2971
2958 @classmethod
2972 @classmethod
2959 def create(cls, user, repository_group, permission):
2973 def create(cls, user, repository_group, permission):
2960 n = cls()
2974 n = cls()
2961 n.user = user
2975 n.user = user
2962 n.group = repository_group
2976 n.group = repository_group
2963 n.permission = permission
2977 n.permission = permission
2964 Session().add(n)
2978 Session().add(n)
2965 return n
2979 return n
2966
2980
2967
2981
2968 class UserGroupRepoGroupToPerm(Base, BaseModel):
2982 class UserGroupRepoGroupToPerm(Base, BaseModel):
2969 __tablename__ = 'users_group_repo_group_to_perm'
2983 __tablename__ = 'users_group_repo_group_to_perm'
2970 __table_args__ = (
2984 __table_args__ = (
2971 UniqueConstraint('users_group_id', 'group_id'),
2985 UniqueConstraint('users_group_id', 'group_id'),
2972 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2986 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2973 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2987 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2974 )
2988 )
2975
2989
2976 users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2990 users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2977 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2991 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2978 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2992 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2979 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2993 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2980
2994
2981 users_group = relationship('UserGroup')
2995 users_group = relationship('UserGroup')
2982 permission = relationship('Permission')
2996 permission = relationship('Permission')
2983 group = relationship('RepoGroup')
2997 group = relationship('RepoGroup')
2984
2998
2985 @classmethod
2999 @classmethod
2986 def create(cls, user_group, repository_group, permission):
3000 def create(cls, user_group, repository_group, permission):
2987 n = cls()
3001 n = cls()
2988 n.users_group = user_group
3002 n.users_group = user_group
2989 n.group = repository_group
3003 n.group = repository_group
2990 n.permission = permission
3004 n.permission = permission
2991 Session().add(n)
3005 Session().add(n)
2992 return n
3006 return n
2993
3007
2994 def __unicode__(self):
3008 def __unicode__(self):
2995 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3009 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
2996
3010
2997
3011
2998 class Statistics(Base, BaseModel):
3012 class Statistics(Base, BaseModel):
2999 __tablename__ = 'statistics'
3013 __tablename__ = 'statistics'
3000 __table_args__ = (
3014 __table_args__ = (
3001 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3015 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3002 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3016 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3003 )
3017 )
3004 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3018 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3005 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3019 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3006 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3020 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3007 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3021 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3008 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3022 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3009 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3023 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3010
3024
3011 repository = relationship('Repository', single_parent=True)
3025 repository = relationship('Repository', single_parent=True)
3012
3026
3013
3027
3014 class UserFollowing(Base, BaseModel):
3028 class UserFollowing(Base, BaseModel):
3015 __tablename__ = 'user_followings'
3029 __tablename__ = 'user_followings'
3016 __table_args__ = (
3030 __table_args__ = (
3017 UniqueConstraint('user_id', 'follows_repository_id'),
3031 UniqueConstraint('user_id', 'follows_repository_id'),
3018 UniqueConstraint('user_id', 'follows_user_id'),
3032 UniqueConstraint('user_id', 'follows_user_id'),
3019 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3033 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3020 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3034 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3021 )
3035 )
3022
3036
3023 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3037 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3024 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3038 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3025 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3039 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3026 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3040 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3027 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3041 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3028
3042
3029 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3043 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3030
3044
3031 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3045 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3032 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3046 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3033
3047
3034 @classmethod
3048 @classmethod
3035 def get_repo_followers(cls, repo_id):
3049 def get_repo_followers(cls, repo_id):
3036 return cls.query().filter(cls.follows_repo_id == repo_id)
3050 return cls.query().filter(cls.follows_repo_id == repo_id)
3037
3051
3038
3052
3039 class CacheKey(Base, BaseModel):
3053 class CacheKey(Base, BaseModel):
3040 __tablename__ = 'cache_invalidation'
3054 __tablename__ = 'cache_invalidation'
3041 __table_args__ = (
3055 __table_args__ = (
3042 UniqueConstraint('cache_key'),
3056 UniqueConstraint('cache_key'),
3043 Index('key_idx', 'cache_key'),
3057 Index('key_idx', 'cache_key'),
3044 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3058 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3045 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3059 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3046 )
3060 )
3047 CACHE_TYPE_ATOM = 'ATOM'
3061 CACHE_TYPE_ATOM = 'ATOM'
3048 CACHE_TYPE_RSS = 'RSS'
3062 CACHE_TYPE_RSS = 'RSS'
3049 CACHE_TYPE_README = 'README'
3063 CACHE_TYPE_README = 'README'
3050
3064
3051 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3065 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3052 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3066 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3053 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3067 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3054 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3068 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3055
3069
3056 def __init__(self, cache_key, cache_args=''):
3070 def __init__(self, cache_key, cache_args=''):
3057 self.cache_key = cache_key
3071 self.cache_key = cache_key
3058 self.cache_args = cache_args
3072 self.cache_args = cache_args
3059 self.cache_active = False
3073 self.cache_active = False
3060
3074
3061 def __unicode__(self):
3075 def __unicode__(self):
3062 return u"<%s('%s:%s[%s]')>" % (
3076 return u"<%s('%s:%s[%s]')>" % (
3063 self.__class__.__name__,
3077 self.__class__.__name__,
3064 self.cache_id, self.cache_key, self.cache_active)
3078 self.cache_id, self.cache_key, self.cache_active)
3065
3079
3066 def _cache_key_partition(self):
3080 def _cache_key_partition(self):
3067 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3081 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3068 return prefix, repo_name, suffix
3082 return prefix, repo_name, suffix
3069
3083
3070 def get_prefix(self):
3084 def get_prefix(self):
3071 """
3085 """
3072 Try to extract prefix from existing cache key. The key could consist
3086 Try to extract prefix from existing cache key. The key could consist
3073 of prefix, repo_name, suffix
3087 of prefix, repo_name, suffix
3074 """
3088 """
3075 # this returns prefix, repo_name, suffix
3089 # this returns prefix, repo_name, suffix
3076 return self._cache_key_partition()[0]
3090 return self._cache_key_partition()[0]
3077
3091
3078 def get_suffix(self):
3092 def get_suffix(self):
3079 """
3093 """
3080 get suffix that might have been used in _get_cache_key to
3094 get suffix that might have been used in _get_cache_key to
3081 generate self.cache_key. Only used for informational purposes
3095 generate self.cache_key. Only used for informational purposes
3082 in repo_edit.mako.
3096 in repo_edit.mako.
3083 """
3097 """
3084 # prefix, repo_name, suffix
3098 # prefix, repo_name, suffix
3085 return self._cache_key_partition()[2]
3099 return self._cache_key_partition()[2]
3086
3100
3087 @classmethod
3101 @classmethod
3088 def delete_all_cache(cls):
3102 def delete_all_cache(cls):
3089 """
3103 """
3090 Delete all cache keys from database.
3104 Delete all cache keys from database.
3091 Should only be run when all instances are down and all entries
3105 Should only be run when all instances are down and all entries
3092 thus stale.
3106 thus stale.
3093 """
3107 """
3094 cls.query().delete()
3108 cls.query().delete()
3095 Session().commit()
3109 Session().commit()
3096
3110
3097 @classmethod
3111 @classmethod
3098 def get_cache_key(cls, repo_name, cache_type):
3112 def get_cache_key(cls, repo_name, cache_type):
3099 """
3113 """
3100
3114
3101 Generate a cache key for this process of RhodeCode instance.
3115 Generate a cache key for this process of RhodeCode instance.
3102 Prefix most likely will be process id or maybe explicitly set
3116 Prefix most likely will be process id or maybe explicitly set
3103 instance_id from .ini file.
3117 instance_id from .ini file.
3104 """
3118 """
3105 import rhodecode
3119 import rhodecode
3106 prefix = safe_unicode(rhodecode.CONFIG.get('instance_id') or '')
3120 prefix = safe_unicode(rhodecode.CONFIG.get('instance_id') or '')
3107
3121
3108 repo_as_unicode = safe_unicode(repo_name)
3122 repo_as_unicode = safe_unicode(repo_name)
3109 key = u'{}_{}'.format(repo_as_unicode, cache_type) \
3123 key = u'{}_{}'.format(repo_as_unicode, cache_type) \
3110 if cache_type else repo_as_unicode
3124 if cache_type else repo_as_unicode
3111
3125
3112 return u'{}{}'.format(prefix, key)
3126 return u'{}{}'.format(prefix, key)
3113
3127
3114 @classmethod
3128 @classmethod
3115 def set_invalidate(cls, repo_name, delete=False):
3129 def set_invalidate(cls, repo_name, delete=False):
3116 """
3130 """
3117 Mark all caches of a repo as invalid in the database.
3131 Mark all caches of a repo as invalid in the database.
3118 """
3132 """
3119
3133
3120 try:
3134 try:
3121 qry = Session().query(cls).filter(cls.cache_args == repo_name)
3135 qry = Session().query(cls).filter(cls.cache_args == repo_name)
3122 if delete:
3136 if delete:
3123 log.debug('cache objects deleted for repo %s',
3137 log.debug('cache objects deleted for repo %s',
3124 safe_str(repo_name))
3138 safe_str(repo_name))
3125 qry.delete()
3139 qry.delete()
3126 else:
3140 else:
3127 log.debug('cache objects marked as invalid for repo %s',
3141 log.debug('cache objects marked as invalid for repo %s',
3128 safe_str(repo_name))
3142 safe_str(repo_name))
3129 qry.update({"cache_active": False})
3143 qry.update({"cache_active": False})
3130
3144
3131 Session().commit()
3145 Session().commit()
3132 except Exception:
3146 except Exception:
3133 log.exception(
3147 log.exception(
3134 'Cache key invalidation failed for repository %s',
3148 'Cache key invalidation failed for repository %s',
3135 safe_str(repo_name))
3149 safe_str(repo_name))
3136 Session().rollback()
3150 Session().rollback()
3137
3151
3138 @classmethod
3152 @classmethod
3139 def get_active_cache(cls, cache_key):
3153 def get_active_cache(cls, cache_key):
3140 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3154 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3141 if inv_obj:
3155 if inv_obj:
3142 return inv_obj
3156 return inv_obj
3143 return None
3157 return None
3144
3158
3145 @classmethod
3159 @classmethod
3146 def repo_context_cache(cls, compute_func, repo_name, cache_type,
3160 def repo_context_cache(cls, compute_func, repo_name, cache_type,
3147 thread_scoped=False):
3161 thread_scoped=False):
3148 """
3162 """
3149 @cache_region('long_term')
3163 @cache_region('long_term')
3150 def _heavy_calculation(cache_key):
3164 def _heavy_calculation(cache_key):
3151 return 'result'
3165 return 'result'
3152
3166
3153 cache_context = CacheKey.repo_context_cache(
3167 cache_context = CacheKey.repo_context_cache(
3154 _heavy_calculation, repo_name, cache_type)
3168 _heavy_calculation, repo_name, cache_type)
3155
3169
3156 with cache_context as context:
3170 with cache_context as context:
3157 context.invalidate()
3171 context.invalidate()
3158 computed = context.compute()
3172 computed = context.compute()
3159
3173
3160 assert computed == 'result'
3174 assert computed == 'result'
3161 """
3175 """
3162 from rhodecode.lib import caches
3176 from rhodecode.lib import caches
3163 return caches.InvalidationContext(
3177 return caches.InvalidationContext(
3164 compute_func, repo_name, cache_type, thread_scoped=thread_scoped)
3178 compute_func, repo_name, cache_type, thread_scoped=thread_scoped)
3165
3179
3166
3180
3167 class ChangesetComment(Base, BaseModel):
3181 class ChangesetComment(Base, BaseModel):
3168 __tablename__ = 'changeset_comments'
3182 __tablename__ = 'changeset_comments'
3169 __table_args__ = (
3183 __table_args__ = (
3170 Index('cc_revision_idx', 'revision'),
3184 Index('cc_revision_idx', 'revision'),
3171 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3185 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3172 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3186 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3173 )
3187 )
3174
3188
3175 COMMENT_OUTDATED = u'comment_outdated'
3189 COMMENT_OUTDATED = u'comment_outdated'
3176 COMMENT_TYPE_NOTE = u'note'
3190 COMMENT_TYPE_NOTE = u'note'
3177 COMMENT_TYPE_TODO = u'todo'
3191 COMMENT_TYPE_TODO = u'todo'
3178 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3192 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3179
3193
3180 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3194 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3181 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3195 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3182 revision = Column('revision', String(40), nullable=True)
3196 revision = Column('revision', String(40), nullable=True)
3183 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3197 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3184 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3198 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3185 line_no = Column('line_no', Unicode(10), nullable=True)
3199 line_no = Column('line_no', Unicode(10), nullable=True)
3186 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3200 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3187 f_path = Column('f_path', Unicode(1000), nullable=True)
3201 f_path = Column('f_path', Unicode(1000), nullable=True)
3188 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3202 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3189 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3203 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3190 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3204 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3191 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3205 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3192 renderer = Column('renderer', Unicode(64), nullable=True)
3206 renderer = Column('renderer', Unicode(64), nullable=True)
3193 display_state = Column('display_state', Unicode(128), nullable=True)
3207 display_state = Column('display_state', Unicode(128), nullable=True)
3194
3208
3195 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3209 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3196 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3210 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3197 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, backref='resolved_by')
3211 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, backref='resolved_by')
3198 author = relationship('User', lazy='joined')
3212 author = relationship('User', lazy='joined')
3199 repo = relationship('Repository')
3213 repo = relationship('Repository')
3200 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3214 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3201 pull_request = relationship('PullRequest', lazy='joined')
3215 pull_request = relationship('PullRequest', lazy='joined')
3202 pull_request_version = relationship('PullRequestVersion')
3216 pull_request_version = relationship('PullRequestVersion')
3203
3217
3204 @classmethod
3218 @classmethod
3205 def get_users(cls, revision=None, pull_request_id=None):
3219 def get_users(cls, revision=None, pull_request_id=None):
3206 """
3220 """
3207 Returns user associated with this ChangesetComment. ie those
3221 Returns user associated with this ChangesetComment. ie those
3208 who actually commented
3222 who actually commented
3209
3223
3210 :param cls:
3224 :param cls:
3211 :param revision:
3225 :param revision:
3212 """
3226 """
3213 q = Session().query(User)\
3227 q = Session().query(User)\
3214 .join(ChangesetComment.author)
3228 .join(ChangesetComment.author)
3215 if revision:
3229 if revision:
3216 q = q.filter(cls.revision == revision)
3230 q = q.filter(cls.revision == revision)
3217 elif pull_request_id:
3231 elif pull_request_id:
3218 q = q.filter(cls.pull_request_id == pull_request_id)
3232 q = q.filter(cls.pull_request_id == pull_request_id)
3219 return q.all()
3233 return q.all()
3220
3234
3221 @classmethod
3235 @classmethod
3222 def get_index_from_version(cls, pr_version, versions):
3236 def get_index_from_version(cls, pr_version, versions):
3223 num_versions = [x.pull_request_version_id for x in versions]
3237 num_versions = [x.pull_request_version_id for x in versions]
3224 try:
3238 try:
3225 return num_versions.index(pr_version) +1
3239 return num_versions.index(pr_version) +1
3226 except (IndexError, ValueError):
3240 except (IndexError, ValueError):
3227 return
3241 return
3228
3242
3229 @property
3243 @property
3230 def outdated(self):
3244 def outdated(self):
3231 return self.display_state == self.COMMENT_OUTDATED
3245 return self.display_state == self.COMMENT_OUTDATED
3232
3246
3233 def outdated_at_version(self, version):
3247 def outdated_at_version(self, version):
3234 """
3248 """
3235 Checks if comment is outdated for given pull request version
3249 Checks if comment is outdated for given pull request version
3236 """
3250 """
3237 return self.outdated and self.pull_request_version_id != version
3251 return self.outdated and self.pull_request_version_id != version
3238
3252
3239 def older_than_version(self, version):
3253 def older_than_version(self, version):
3240 """
3254 """
3241 Checks if comment is made from previous version than given
3255 Checks if comment is made from previous version than given
3242 """
3256 """
3243 if version is None:
3257 if version is None:
3244 return self.pull_request_version_id is not None
3258 return self.pull_request_version_id is not None
3245
3259
3246 return self.pull_request_version_id < version
3260 return self.pull_request_version_id < version
3247
3261
3248 @property
3262 @property
3249 def resolved(self):
3263 def resolved(self):
3250 return self.resolved_by[0] if self.resolved_by else None
3264 return self.resolved_by[0] if self.resolved_by else None
3251
3265
3252 @property
3266 @property
3253 def is_todo(self):
3267 def is_todo(self):
3254 return self.comment_type == self.COMMENT_TYPE_TODO
3268 return self.comment_type == self.COMMENT_TYPE_TODO
3255
3269
3256 @property
3270 @property
3257 def is_inline(self):
3271 def is_inline(self):
3258 return self.line_no and self.f_path
3272 return self.line_no and self.f_path
3259
3273
3260 def get_index_version(self, versions):
3274 def get_index_version(self, versions):
3261 return self.get_index_from_version(
3275 return self.get_index_from_version(
3262 self.pull_request_version_id, versions)
3276 self.pull_request_version_id, versions)
3263
3277
3264 def __repr__(self):
3278 def __repr__(self):
3265 if self.comment_id:
3279 if self.comment_id:
3266 return '<DB:Comment #%s>' % self.comment_id
3280 return '<DB:Comment #%s>' % self.comment_id
3267 else:
3281 else:
3268 return '<DB:Comment at %#x>' % id(self)
3282 return '<DB:Comment at %#x>' % id(self)
3269
3283
3270 def get_api_data(self):
3284 def get_api_data(self):
3271 comment = self
3285 comment = self
3272 data = {
3286 data = {
3273 'comment_id': comment.comment_id,
3287 'comment_id': comment.comment_id,
3274 'comment_type': comment.comment_type,
3288 'comment_type': comment.comment_type,
3275 'comment_text': comment.text,
3289 'comment_text': comment.text,
3276 'comment_status': comment.status_change,
3290 'comment_status': comment.status_change,
3277 'comment_f_path': comment.f_path,
3291 'comment_f_path': comment.f_path,
3278 'comment_lineno': comment.line_no,
3292 'comment_lineno': comment.line_no,
3279 'comment_author': comment.author,
3293 'comment_author': comment.author,
3280 'comment_created_on': comment.created_on
3294 'comment_created_on': comment.created_on
3281 }
3295 }
3282 return data
3296 return data
3283
3297
3284 def __json__(self):
3298 def __json__(self):
3285 data = dict()
3299 data = dict()
3286 data.update(self.get_api_data())
3300 data.update(self.get_api_data())
3287 return data
3301 return data
3288
3302
3289
3303
3290 class ChangesetStatus(Base, BaseModel):
3304 class ChangesetStatus(Base, BaseModel):
3291 __tablename__ = 'changeset_statuses'
3305 __tablename__ = 'changeset_statuses'
3292 __table_args__ = (
3306 __table_args__ = (
3293 Index('cs_revision_idx', 'revision'),
3307 Index('cs_revision_idx', 'revision'),
3294 Index('cs_version_idx', 'version'),
3308 Index('cs_version_idx', 'version'),
3295 UniqueConstraint('repo_id', 'revision', 'version'),
3309 UniqueConstraint('repo_id', 'revision', 'version'),
3296 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3310 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3297 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3311 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3298 )
3312 )
3299 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3313 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3300 STATUS_APPROVED = 'approved'
3314 STATUS_APPROVED = 'approved'
3301 STATUS_REJECTED = 'rejected'
3315 STATUS_REJECTED = 'rejected'
3302 STATUS_UNDER_REVIEW = 'under_review'
3316 STATUS_UNDER_REVIEW = 'under_review'
3303
3317
3304 STATUSES = [
3318 STATUSES = [
3305 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3319 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3306 (STATUS_APPROVED, _("Approved")),
3320 (STATUS_APPROVED, _("Approved")),
3307 (STATUS_REJECTED, _("Rejected")),
3321 (STATUS_REJECTED, _("Rejected")),
3308 (STATUS_UNDER_REVIEW, _("Under Review")),
3322 (STATUS_UNDER_REVIEW, _("Under Review")),
3309 ]
3323 ]
3310
3324
3311 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3325 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3312 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3326 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3313 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3327 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3314 revision = Column('revision', String(40), nullable=False)
3328 revision = Column('revision', String(40), nullable=False)
3315 status = Column('status', String(128), nullable=False, default=DEFAULT)
3329 status = Column('status', String(128), nullable=False, default=DEFAULT)
3316 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3330 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3317 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3331 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3318 version = Column('version', Integer(), nullable=False, default=0)
3332 version = Column('version', Integer(), nullable=False, default=0)
3319 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3333 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3320
3334
3321 author = relationship('User', lazy='joined')
3335 author = relationship('User', lazy='joined')
3322 repo = relationship('Repository')
3336 repo = relationship('Repository')
3323 comment = relationship('ChangesetComment', lazy='joined')
3337 comment = relationship('ChangesetComment', lazy='joined')
3324 pull_request = relationship('PullRequest', lazy='joined')
3338 pull_request = relationship('PullRequest', lazy='joined')
3325
3339
3326 def __unicode__(self):
3340 def __unicode__(self):
3327 return u"<%s('%s[v%s]:%s')>" % (
3341 return u"<%s('%s[v%s]:%s')>" % (
3328 self.__class__.__name__,
3342 self.__class__.__name__,
3329 self.status, self.version, self.author
3343 self.status, self.version, self.author
3330 )
3344 )
3331
3345
3332 @classmethod
3346 @classmethod
3333 def get_status_lbl(cls, value):
3347 def get_status_lbl(cls, value):
3334 return dict(cls.STATUSES).get(value)
3348 return dict(cls.STATUSES).get(value)
3335
3349
3336 @property
3350 @property
3337 def status_lbl(self):
3351 def status_lbl(self):
3338 return ChangesetStatus.get_status_lbl(self.status)
3352 return ChangesetStatus.get_status_lbl(self.status)
3339
3353
3340 def get_api_data(self):
3354 def get_api_data(self):
3341 status = self
3355 status = self
3342 data = {
3356 data = {
3343 'status_id': status.changeset_status_id,
3357 'status_id': status.changeset_status_id,
3344 'status': status.status,
3358 'status': status.status,
3345 }
3359 }
3346 return data
3360 return data
3347
3361
3348 def __json__(self):
3362 def __json__(self):
3349 data = dict()
3363 data = dict()
3350 data.update(self.get_api_data())
3364 data.update(self.get_api_data())
3351 return data
3365 return data
3352
3366
3353
3367
3354 class _PullRequestBase(BaseModel):
3368 class _PullRequestBase(BaseModel):
3355 """
3369 """
3356 Common attributes of pull request and version entries.
3370 Common attributes of pull request and version entries.
3357 """
3371 """
3358
3372
3359 # .status values
3373 # .status values
3360 STATUS_NEW = u'new'
3374 STATUS_NEW = u'new'
3361 STATUS_OPEN = u'open'
3375 STATUS_OPEN = u'open'
3362 STATUS_CLOSED = u'closed'
3376 STATUS_CLOSED = u'closed'
3363
3377
3364 title = Column('title', Unicode(255), nullable=True)
3378 title = Column('title', Unicode(255), nullable=True)
3365 description = Column(
3379 description = Column(
3366 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3380 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3367 nullable=True)
3381 nullable=True)
3368 # new/open/closed status of pull request (not approve/reject/etc)
3382 # new/open/closed status of pull request (not approve/reject/etc)
3369 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3383 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3370 created_on = Column(
3384 created_on = Column(
3371 'created_on', DateTime(timezone=False), nullable=False,
3385 'created_on', DateTime(timezone=False), nullable=False,
3372 default=datetime.datetime.now)
3386 default=datetime.datetime.now)
3373 updated_on = Column(
3387 updated_on = Column(
3374 'updated_on', DateTime(timezone=False), nullable=False,
3388 'updated_on', DateTime(timezone=False), nullable=False,
3375 default=datetime.datetime.now)
3389 default=datetime.datetime.now)
3376
3390
3377 @declared_attr
3391 @declared_attr
3378 def user_id(cls):
3392 def user_id(cls):
3379 return Column(
3393 return Column(
3380 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3394 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3381 unique=None)
3395 unique=None)
3382
3396
3383 # 500 revisions max
3397 # 500 revisions max
3384 _revisions = Column(
3398 _revisions = Column(
3385 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3399 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3386
3400
3387 @declared_attr
3401 @declared_attr
3388 def source_repo_id(cls):
3402 def source_repo_id(cls):
3389 # TODO: dan: rename column to source_repo_id
3403 # TODO: dan: rename column to source_repo_id
3390 return Column(
3404 return Column(
3391 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3405 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3392 nullable=False)
3406 nullable=False)
3393
3407
3394 source_ref = Column('org_ref', Unicode(255), nullable=False)
3408 source_ref = Column('org_ref', Unicode(255), nullable=False)
3395
3409
3396 @declared_attr
3410 @declared_attr
3397 def target_repo_id(cls):
3411 def target_repo_id(cls):
3398 # TODO: dan: rename column to target_repo_id
3412 # TODO: dan: rename column to target_repo_id
3399 return Column(
3413 return Column(
3400 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3414 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3401 nullable=False)
3415 nullable=False)
3402
3416
3403 target_ref = Column('other_ref', Unicode(255), nullable=False)
3417 target_ref = Column('other_ref', Unicode(255), nullable=False)
3404 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3418 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3405
3419
3406 # TODO: dan: rename column to last_merge_source_rev
3420 # TODO: dan: rename column to last_merge_source_rev
3407 _last_merge_source_rev = Column(
3421 _last_merge_source_rev = Column(
3408 'last_merge_org_rev', String(40), nullable=True)
3422 'last_merge_org_rev', String(40), nullable=True)
3409 # TODO: dan: rename column to last_merge_target_rev
3423 # TODO: dan: rename column to last_merge_target_rev
3410 _last_merge_target_rev = Column(
3424 _last_merge_target_rev = Column(
3411 'last_merge_other_rev', String(40), nullable=True)
3425 'last_merge_other_rev', String(40), nullable=True)
3412 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3426 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3413 merge_rev = Column('merge_rev', String(40), nullable=True)
3427 merge_rev = Column('merge_rev', String(40), nullable=True)
3414
3428
3415 reviewer_data = Column(
3429 reviewer_data = Column(
3416 'reviewer_data_json', MutationObj.as_mutable(
3430 'reviewer_data_json', MutationObj.as_mutable(
3417 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3431 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3418
3432
3419 @property
3433 @property
3420 def reviewer_data_json(self):
3434 def reviewer_data_json(self):
3421 return json.dumps(self.reviewer_data)
3435 return json.dumps(self.reviewer_data)
3422
3436
3423 @hybrid_property
3437 @hybrid_property
3424 def description_safe(self):
3438 def description_safe(self):
3425 from rhodecode.lib import helpers as h
3439 from rhodecode.lib import helpers as h
3426 return h.escape(self.description)
3440 return h.escape(self.description)
3427
3441
3428 @hybrid_property
3442 @hybrid_property
3429 def revisions(self):
3443 def revisions(self):
3430 return self._revisions.split(':') if self._revisions else []
3444 return self._revisions.split(':') if self._revisions else []
3431
3445
3432 @revisions.setter
3446 @revisions.setter
3433 def revisions(self, val):
3447 def revisions(self, val):
3434 self._revisions = ':'.join(val)
3448 self._revisions = ':'.join(val)
3435
3449
3436 @hybrid_property
3450 @hybrid_property
3437 def last_merge_status(self):
3451 def last_merge_status(self):
3438 return safe_int(self._last_merge_status)
3452 return safe_int(self._last_merge_status)
3439
3453
3440 @last_merge_status.setter
3454 @last_merge_status.setter
3441 def last_merge_status(self, val):
3455 def last_merge_status(self, val):
3442 self._last_merge_status = val
3456 self._last_merge_status = val
3443
3457
3444 @declared_attr
3458 @declared_attr
3445 def author(cls):
3459 def author(cls):
3446 return relationship('User', lazy='joined')
3460 return relationship('User', lazy='joined')
3447
3461
3448 @declared_attr
3462 @declared_attr
3449 def source_repo(cls):
3463 def source_repo(cls):
3450 return relationship(
3464 return relationship(
3451 'Repository',
3465 'Repository',
3452 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3466 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3453
3467
3454 @property
3468 @property
3455 def source_ref_parts(self):
3469 def source_ref_parts(self):
3456 return self.unicode_to_reference(self.source_ref)
3470 return self.unicode_to_reference(self.source_ref)
3457
3471
3458 @declared_attr
3472 @declared_attr
3459 def target_repo(cls):
3473 def target_repo(cls):
3460 return relationship(
3474 return relationship(
3461 'Repository',
3475 'Repository',
3462 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3476 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3463
3477
3464 @property
3478 @property
3465 def target_ref_parts(self):
3479 def target_ref_parts(self):
3466 return self.unicode_to_reference(self.target_ref)
3480 return self.unicode_to_reference(self.target_ref)
3467
3481
3468 @property
3482 @property
3469 def shadow_merge_ref(self):
3483 def shadow_merge_ref(self):
3470 return self.unicode_to_reference(self._shadow_merge_ref)
3484 return self.unicode_to_reference(self._shadow_merge_ref)
3471
3485
3472 @shadow_merge_ref.setter
3486 @shadow_merge_ref.setter
3473 def shadow_merge_ref(self, ref):
3487 def shadow_merge_ref(self, ref):
3474 self._shadow_merge_ref = self.reference_to_unicode(ref)
3488 self._shadow_merge_ref = self.reference_to_unicode(ref)
3475
3489
3476 def unicode_to_reference(self, raw):
3490 def unicode_to_reference(self, raw):
3477 """
3491 """
3478 Convert a unicode (or string) to a reference object.
3492 Convert a unicode (or string) to a reference object.
3479 If unicode evaluates to False it returns None.
3493 If unicode evaluates to False it returns None.
3480 """
3494 """
3481 if raw:
3495 if raw:
3482 refs = raw.split(':')
3496 refs = raw.split(':')
3483 return Reference(*refs)
3497 return Reference(*refs)
3484 else:
3498 else:
3485 return None
3499 return None
3486
3500
3487 def reference_to_unicode(self, ref):
3501 def reference_to_unicode(self, ref):
3488 """
3502 """
3489 Convert a reference object to unicode.
3503 Convert a reference object to unicode.
3490 If reference is None it returns None.
3504 If reference is None it returns None.
3491 """
3505 """
3492 if ref:
3506 if ref:
3493 return u':'.join(ref)
3507 return u':'.join(ref)
3494 else:
3508 else:
3495 return None
3509 return None
3496
3510
3497 def get_api_data(self, with_merge_state=True):
3511 def get_api_data(self, with_merge_state=True):
3498 from rhodecode.model.pull_request import PullRequestModel
3512 from rhodecode.model.pull_request import PullRequestModel
3499
3513
3500 pull_request = self
3514 pull_request = self
3501 if with_merge_state:
3515 if with_merge_state:
3502 merge_status = PullRequestModel().merge_status(pull_request)
3516 merge_status = PullRequestModel().merge_status(pull_request)
3503 merge_state = {
3517 merge_state = {
3504 'status': merge_status[0],
3518 'status': merge_status[0],
3505 'message': safe_unicode(merge_status[1]),
3519 'message': safe_unicode(merge_status[1]),
3506 }
3520 }
3507 else:
3521 else:
3508 merge_state = {'status': 'not_available',
3522 merge_state = {'status': 'not_available',
3509 'message': 'not_available'}
3523 'message': 'not_available'}
3510
3524
3511 merge_data = {
3525 merge_data = {
3512 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3526 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3513 'reference': (
3527 'reference': (
3514 pull_request.shadow_merge_ref._asdict()
3528 pull_request.shadow_merge_ref._asdict()
3515 if pull_request.shadow_merge_ref else None),
3529 if pull_request.shadow_merge_ref else None),
3516 }
3530 }
3517
3531
3518 data = {
3532 data = {
3519 'pull_request_id': pull_request.pull_request_id,
3533 'pull_request_id': pull_request.pull_request_id,
3520 'url': PullRequestModel().get_url(pull_request),
3534 'url': PullRequestModel().get_url(pull_request),
3521 'title': pull_request.title,
3535 'title': pull_request.title,
3522 'description': pull_request.description,
3536 'description': pull_request.description,
3523 'status': pull_request.status,
3537 'status': pull_request.status,
3524 'created_on': pull_request.created_on,
3538 'created_on': pull_request.created_on,
3525 'updated_on': pull_request.updated_on,
3539 'updated_on': pull_request.updated_on,
3526 'commit_ids': pull_request.revisions,
3540 'commit_ids': pull_request.revisions,
3527 'review_status': pull_request.calculated_review_status(),
3541 'review_status': pull_request.calculated_review_status(),
3528 'mergeable': merge_state,
3542 'mergeable': merge_state,
3529 'source': {
3543 'source': {
3530 'clone_url': pull_request.source_repo.clone_url(),
3544 'clone_url': pull_request.source_repo.clone_url(),
3531 'repository': pull_request.source_repo.repo_name,
3545 'repository': pull_request.source_repo.repo_name,
3532 'reference': {
3546 'reference': {
3533 'name': pull_request.source_ref_parts.name,
3547 'name': pull_request.source_ref_parts.name,
3534 'type': pull_request.source_ref_parts.type,
3548 'type': pull_request.source_ref_parts.type,
3535 'commit_id': pull_request.source_ref_parts.commit_id,
3549 'commit_id': pull_request.source_ref_parts.commit_id,
3536 },
3550 },
3537 },
3551 },
3538 'target': {
3552 'target': {
3539 'clone_url': pull_request.target_repo.clone_url(),
3553 'clone_url': pull_request.target_repo.clone_url(),
3540 'repository': pull_request.target_repo.repo_name,
3554 'repository': pull_request.target_repo.repo_name,
3541 'reference': {
3555 'reference': {
3542 'name': pull_request.target_ref_parts.name,
3556 'name': pull_request.target_ref_parts.name,
3543 'type': pull_request.target_ref_parts.type,
3557 'type': pull_request.target_ref_parts.type,
3544 'commit_id': pull_request.target_ref_parts.commit_id,
3558 'commit_id': pull_request.target_ref_parts.commit_id,
3545 },
3559 },
3546 },
3560 },
3547 'merge': merge_data,
3561 'merge': merge_data,
3548 'author': pull_request.author.get_api_data(include_secrets=False,
3562 'author': pull_request.author.get_api_data(include_secrets=False,
3549 details='basic'),
3563 details='basic'),
3550 'reviewers': [
3564 'reviewers': [
3551 {
3565 {
3552 'user': reviewer.get_api_data(include_secrets=False,
3566 'user': reviewer.get_api_data(include_secrets=False,
3553 details='basic'),
3567 details='basic'),
3554 'reasons': reasons,
3568 'reasons': reasons,
3555 'review_status': st[0][1].status if st else 'not_reviewed',
3569 'review_status': st[0][1].status if st else 'not_reviewed',
3556 }
3570 }
3557 for reviewer, reasons, mandatory, st in
3571 for reviewer, reasons, mandatory, st in
3558 pull_request.reviewers_statuses()
3572 pull_request.reviewers_statuses()
3559 ]
3573 ]
3560 }
3574 }
3561
3575
3562 return data
3576 return data
3563
3577
3564
3578
3565 class PullRequest(Base, _PullRequestBase):
3579 class PullRequest(Base, _PullRequestBase):
3566 __tablename__ = 'pull_requests'
3580 __tablename__ = 'pull_requests'
3567 __table_args__ = (
3581 __table_args__ = (
3568 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3582 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3569 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3583 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3570 )
3584 )
3571
3585
3572 pull_request_id = Column(
3586 pull_request_id = Column(
3573 'pull_request_id', Integer(), nullable=False, primary_key=True)
3587 'pull_request_id', Integer(), nullable=False, primary_key=True)
3574
3588
3575 def __repr__(self):
3589 def __repr__(self):
3576 if self.pull_request_id:
3590 if self.pull_request_id:
3577 return '<DB:PullRequest #%s>' % self.pull_request_id
3591 return '<DB:PullRequest #%s>' % self.pull_request_id
3578 else:
3592 else:
3579 return '<DB:PullRequest at %#x>' % id(self)
3593 return '<DB:PullRequest at %#x>' % id(self)
3580
3594
3581 reviewers = relationship('PullRequestReviewers',
3595 reviewers = relationship('PullRequestReviewers',
3582 cascade="all, delete, delete-orphan")
3596 cascade="all, delete, delete-orphan")
3583 statuses = relationship('ChangesetStatus',
3597 statuses = relationship('ChangesetStatus',
3584 cascade="all, delete, delete-orphan")
3598 cascade="all, delete, delete-orphan")
3585 comments = relationship('ChangesetComment',
3599 comments = relationship('ChangesetComment',
3586 cascade="all, delete, delete-orphan")
3600 cascade="all, delete, delete-orphan")
3587 versions = relationship('PullRequestVersion',
3601 versions = relationship('PullRequestVersion',
3588 cascade="all, delete, delete-orphan",
3602 cascade="all, delete, delete-orphan",
3589 lazy='dynamic')
3603 lazy='dynamic')
3590
3604
3591 @classmethod
3605 @classmethod
3592 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3606 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3593 internal_methods=None):
3607 internal_methods=None):
3594
3608
3595 class PullRequestDisplay(object):
3609 class PullRequestDisplay(object):
3596 """
3610 """
3597 Special object wrapper for showing PullRequest data via Versions
3611 Special object wrapper for showing PullRequest data via Versions
3598 It mimics PR object as close as possible. This is read only object
3612 It mimics PR object as close as possible. This is read only object
3599 just for display
3613 just for display
3600 """
3614 """
3601
3615
3602 def __init__(self, attrs, internal=None):
3616 def __init__(self, attrs, internal=None):
3603 self.attrs = attrs
3617 self.attrs = attrs
3604 # internal have priority over the given ones via attrs
3618 # internal have priority over the given ones via attrs
3605 self.internal = internal or ['versions']
3619 self.internal = internal or ['versions']
3606
3620
3607 def __getattr__(self, item):
3621 def __getattr__(self, item):
3608 if item in self.internal:
3622 if item in self.internal:
3609 return getattr(self, item)
3623 return getattr(self, item)
3610 try:
3624 try:
3611 return self.attrs[item]
3625 return self.attrs[item]
3612 except KeyError:
3626 except KeyError:
3613 raise AttributeError(
3627 raise AttributeError(
3614 '%s object has no attribute %s' % (self, item))
3628 '%s object has no attribute %s' % (self, item))
3615
3629
3616 def __repr__(self):
3630 def __repr__(self):
3617 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3631 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3618
3632
3619 def versions(self):
3633 def versions(self):
3620 return pull_request_obj.versions.order_by(
3634 return pull_request_obj.versions.order_by(
3621 PullRequestVersion.pull_request_version_id).all()
3635 PullRequestVersion.pull_request_version_id).all()
3622
3636
3623 def is_closed(self):
3637 def is_closed(self):
3624 return pull_request_obj.is_closed()
3638 return pull_request_obj.is_closed()
3625
3639
3626 @property
3640 @property
3627 def pull_request_version_id(self):
3641 def pull_request_version_id(self):
3628 return getattr(pull_request_obj, 'pull_request_version_id', None)
3642 return getattr(pull_request_obj, 'pull_request_version_id', None)
3629
3643
3630 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3644 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3631
3645
3632 attrs.author = StrictAttributeDict(
3646 attrs.author = StrictAttributeDict(
3633 pull_request_obj.author.get_api_data())
3647 pull_request_obj.author.get_api_data())
3634 if pull_request_obj.target_repo:
3648 if pull_request_obj.target_repo:
3635 attrs.target_repo = StrictAttributeDict(
3649 attrs.target_repo = StrictAttributeDict(
3636 pull_request_obj.target_repo.get_api_data())
3650 pull_request_obj.target_repo.get_api_data())
3637 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3651 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3638
3652
3639 if pull_request_obj.source_repo:
3653 if pull_request_obj.source_repo:
3640 attrs.source_repo = StrictAttributeDict(
3654 attrs.source_repo = StrictAttributeDict(
3641 pull_request_obj.source_repo.get_api_data())
3655 pull_request_obj.source_repo.get_api_data())
3642 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3656 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3643
3657
3644 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3658 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3645 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3659 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3646 attrs.revisions = pull_request_obj.revisions
3660 attrs.revisions = pull_request_obj.revisions
3647
3661
3648 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3662 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3649 attrs.reviewer_data = org_pull_request_obj.reviewer_data
3663 attrs.reviewer_data = org_pull_request_obj.reviewer_data
3650 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
3664 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
3651
3665
3652 return PullRequestDisplay(attrs, internal=internal_methods)
3666 return PullRequestDisplay(attrs, internal=internal_methods)
3653
3667
3654 def is_closed(self):
3668 def is_closed(self):
3655 return self.status == self.STATUS_CLOSED
3669 return self.status == self.STATUS_CLOSED
3656
3670
3657 def __json__(self):
3671 def __json__(self):
3658 return {
3672 return {
3659 'revisions': self.revisions,
3673 'revisions': self.revisions,
3660 }
3674 }
3661
3675
3662 def calculated_review_status(self):
3676 def calculated_review_status(self):
3663 from rhodecode.model.changeset_status import ChangesetStatusModel
3677 from rhodecode.model.changeset_status import ChangesetStatusModel
3664 return ChangesetStatusModel().calculated_review_status(self)
3678 return ChangesetStatusModel().calculated_review_status(self)
3665
3679
3666 def reviewers_statuses(self):
3680 def reviewers_statuses(self):
3667 from rhodecode.model.changeset_status import ChangesetStatusModel
3681 from rhodecode.model.changeset_status import ChangesetStatusModel
3668 return ChangesetStatusModel().reviewers_statuses(self)
3682 return ChangesetStatusModel().reviewers_statuses(self)
3669
3683
3670 @property
3684 @property
3671 def workspace_id(self):
3685 def workspace_id(self):
3672 from rhodecode.model.pull_request import PullRequestModel
3686 from rhodecode.model.pull_request import PullRequestModel
3673 return PullRequestModel()._workspace_id(self)
3687 return PullRequestModel()._workspace_id(self)
3674
3688
3675 def get_shadow_repo(self):
3689 def get_shadow_repo(self):
3676 workspace_id = self.workspace_id
3690 workspace_id = self.workspace_id
3677 vcs_obj = self.target_repo.scm_instance()
3691 vcs_obj = self.target_repo.scm_instance()
3678 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3692 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3679 workspace_id)
3693 workspace_id)
3680 return vcs_obj._get_shadow_instance(shadow_repository_path)
3694 return vcs_obj._get_shadow_instance(shadow_repository_path)
3681
3695
3682
3696
3683 class PullRequestVersion(Base, _PullRequestBase):
3697 class PullRequestVersion(Base, _PullRequestBase):
3684 __tablename__ = 'pull_request_versions'
3698 __tablename__ = 'pull_request_versions'
3685 __table_args__ = (
3699 __table_args__ = (
3686 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3700 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3687 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3701 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3688 )
3702 )
3689
3703
3690 pull_request_version_id = Column(
3704 pull_request_version_id = Column(
3691 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3705 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3692 pull_request_id = Column(
3706 pull_request_id = Column(
3693 'pull_request_id', Integer(),
3707 'pull_request_id', Integer(),
3694 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3708 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3695 pull_request = relationship('PullRequest')
3709 pull_request = relationship('PullRequest')
3696
3710
3697 def __repr__(self):
3711 def __repr__(self):
3698 if self.pull_request_version_id:
3712 if self.pull_request_version_id:
3699 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3713 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3700 else:
3714 else:
3701 return '<DB:PullRequestVersion at %#x>' % id(self)
3715 return '<DB:PullRequestVersion at %#x>' % id(self)
3702
3716
3703 @property
3717 @property
3704 def reviewers(self):
3718 def reviewers(self):
3705 return self.pull_request.reviewers
3719 return self.pull_request.reviewers
3706
3720
3707 @property
3721 @property
3708 def versions(self):
3722 def versions(self):
3709 return self.pull_request.versions
3723 return self.pull_request.versions
3710
3724
3711 def is_closed(self):
3725 def is_closed(self):
3712 # calculate from original
3726 # calculate from original
3713 return self.pull_request.status == self.STATUS_CLOSED
3727 return self.pull_request.status == self.STATUS_CLOSED
3714
3728
3715 def calculated_review_status(self):
3729 def calculated_review_status(self):
3716 return self.pull_request.calculated_review_status()
3730 return self.pull_request.calculated_review_status()
3717
3731
3718 def reviewers_statuses(self):
3732 def reviewers_statuses(self):
3719 return self.pull_request.reviewers_statuses()
3733 return self.pull_request.reviewers_statuses()
3720
3734
3721
3735
3722 class PullRequestReviewers(Base, BaseModel):
3736 class PullRequestReviewers(Base, BaseModel):
3723 __tablename__ = 'pull_request_reviewers'
3737 __tablename__ = 'pull_request_reviewers'
3724 __table_args__ = (
3738 __table_args__ = (
3725 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3739 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3726 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3740 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3727 )
3741 )
3728
3742
3729 @hybrid_property
3743 @hybrid_property
3730 def reasons(self):
3744 def reasons(self):
3731 if not self._reasons:
3745 if not self._reasons:
3732 return []
3746 return []
3733 return self._reasons
3747 return self._reasons
3734
3748
3735 @reasons.setter
3749 @reasons.setter
3736 def reasons(self, val):
3750 def reasons(self, val):
3737 val = val or []
3751 val = val or []
3738 if any(not isinstance(x, basestring) for x in val):
3752 if any(not isinstance(x, basestring) for x in val):
3739 raise Exception('invalid reasons type, must be list of strings')
3753 raise Exception('invalid reasons type, must be list of strings')
3740 self._reasons = val
3754 self._reasons = val
3741
3755
3742 pull_requests_reviewers_id = Column(
3756 pull_requests_reviewers_id = Column(
3743 'pull_requests_reviewers_id', Integer(), nullable=False,
3757 'pull_requests_reviewers_id', Integer(), nullable=False,
3744 primary_key=True)
3758 primary_key=True)
3745 pull_request_id = Column(
3759 pull_request_id = Column(
3746 "pull_request_id", Integer(),
3760 "pull_request_id", Integer(),
3747 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3761 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3748 user_id = Column(
3762 user_id = Column(
3749 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3763 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3750 _reasons = Column(
3764 _reasons = Column(
3751 'reason', MutationList.as_mutable(
3765 'reason', MutationList.as_mutable(
3752 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
3766 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
3753 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
3767 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
3754 user = relationship('User')
3768 user = relationship('User')
3755 pull_request = relationship('PullRequest')
3769 pull_request = relationship('PullRequest')
3756
3770
3757
3771
3758 class Notification(Base, BaseModel):
3772 class Notification(Base, BaseModel):
3759 __tablename__ = 'notifications'
3773 __tablename__ = 'notifications'
3760 __table_args__ = (
3774 __table_args__ = (
3761 Index('notification_type_idx', 'type'),
3775 Index('notification_type_idx', 'type'),
3762 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3776 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3763 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3777 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3764 )
3778 )
3765
3779
3766 TYPE_CHANGESET_COMMENT = u'cs_comment'
3780 TYPE_CHANGESET_COMMENT = u'cs_comment'
3767 TYPE_MESSAGE = u'message'
3781 TYPE_MESSAGE = u'message'
3768 TYPE_MENTION = u'mention'
3782 TYPE_MENTION = u'mention'
3769 TYPE_REGISTRATION = u'registration'
3783 TYPE_REGISTRATION = u'registration'
3770 TYPE_PULL_REQUEST = u'pull_request'
3784 TYPE_PULL_REQUEST = u'pull_request'
3771 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
3785 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
3772
3786
3773 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
3787 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
3774 subject = Column('subject', Unicode(512), nullable=True)
3788 subject = Column('subject', Unicode(512), nullable=True)
3775 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
3789 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
3776 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
3790 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
3777 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3791 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3778 type_ = Column('type', Unicode(255))
3792 type_ = Column('type', Unicode(255))
3779
3793
3780 created_by_user = relationship('User')
3794 created_by_user = relationship('User')
3781 notifications_to_users = relationship('UserNotification', lazy='joined',
3795 notifications_to_users = relationship('UserNotification', lazy='joined',
3782 cascade="all, delete, delete-orphan")
3796 cascade="all, delete, delete-orphan")
3783
3797
3784 @property
3798 @property
3785 def recipients(self):
3799 def recipients(self):
3786 return [x.user for x in UserNotification.query()\
3800 return [x.user for x in UserNotification.query()\
3787 .filter(UserNotification.notification == self)\
3801 .filter(UserNotification.notification == self)\
3788 .order_by(UserNotification.user_id.asc()).all()]
3802 .order_by(UserNotification.user_id.asc()).all()]
3789
3803
3790 @classmethod
3804 @classmethod
3791 def create(cls, created_by, subject, body, recipients, type_=None):
3805 def create(cls, created_by, subject, body, recipients, type_=None):
3792 if type_ is None:
3806 if type_ is None:
3793 type_ = Notification.TYPE_MESSAGE
3807 type_ = Notification.TYPE_MESSAGE
3794
3808
3795 notification = cls()
3809 notification = cls()
3796 notification.created_by_user = created_by
3810 notification.created_by_user = created_by
3797 notification.subject = subject
3811 notification.subject = subject
3798 notification.body = body
3812 notification.body = body
3799 notification.type_ = type_
3813 notification.type_ = type_
3800 notification.created_on = datetime.datetime.now()
3814 notification.created_on = datetime.datetime.now()
3801
3815
3802 for u in recipients:
3816 for u in recipients:
3803 assoc = UserNotification()
3817 assoc = UserNotification()
3804 assoc.notification = notification
3818 assoc.notification = notification
3805
3819
3806 # if created_by is inside recipients mark his notification
3820 # if created_by is inside recipients mark his notification
3807 # as read
3821 # as read
3808 if u.user_id == created_by.user_id:
3822 if u.user_id == created_by.user_id:
3809 assoc.read = True
3823 assoc.read = True
3810
3824
3811 u.notifications.append(assoc)
3825 u.notifications.append(assoc)
3812 Session().add(notification)
3826 Session().add(notification)
3813
3827
3814 return notification
3828 return notification
3815
3829
3816
3830
3817 class UserNotification(Base, BaseModel):
3831 class UserNotification(Base, BaseModel):
3818 __tablename__ = 'user_to_notification'
3832 __tablename__ = 'user_to_notification'
3819 __table_args__ = (
3833 __table_args__ = (
3820 UniqueConstraint('user_id', 'notification_id'),
3834 UniqueConstraint('user_id', 'notification_id'),
3821 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3835 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3822 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3836 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3823 )
3837 )
3824 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
3838 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
3825 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
3839 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
3826 read = Column('read', Boolean, default=False)
3840 read = Column('read', Boolean, default=False)
3827 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
3841 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
3828
3842
3829 user = relationship('User', lazy="joined")
3843 user = relationship('User', lazy="joined")
3830 notification = relationship('Notification', lazy="joined",
3844 notification = relationship('Notification', lazy="joined",
3831 order_by=lambda: Notification.created_on.desc(),)
3845 order_by=lambda: Notification.created_on.desc(),)
3832
3846
3833 def mark_as_read(self):
3847 def mark_as_read(self):
3834 self.read = True
3848 self.read = True
3835 Session().add(self)
3849 Session().add(self)
3836
3850
3837
3851
3838 class Gist(Base, BaseModel):
3852 class Gist(Base, BaseModel):
3839 __tablename__ = 'gists'
3853 __tablename__ = 'gists'
3840 __table_args__ = (
3854 __table_args__ = (
3841 Index('g_gist_access_id_idx', 'gist_access_id'),
3855 Index('g_gist_access_id_idx', 'gist_access_id'),
3842 Index('g_created_on_idx', 'created_on'),
3856 Index('g_created_on_idx', 'created_on'),
3843 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3857 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3844 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3858 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3845 )
3859 )
3846 GIST_PUBLIC = u'public'
3860 GIST_PUBLIC = u'public'
3847 GIST_PRIVATE = u'private'
3861 GIST_PRIVATE = u'private'
3848 DEFAULT_FILENAME = u'gistfile1.txt'
3862 DEFAULT_FILENAME = u'gistfile1.txt'
3849
3863
3850 ACL_LEVEL_PUBLIC = u'acl_public'
3864 ACL_LEVEL_PUBLIC = u'acl_public'
3851 ACL_LEVEL_PRIVATE = u'acl_private'
3865 ACL_LEVEL_PRIVATE = u'acl_private'
3852
3866
3853 gist_id = Column('gist_id', Integer(), primary_key=True)
3867 gist_id = Column('gist_id', Integer(), primary_key=True)
3854 gist_access_id = Column('gist_access_id', Unicode(250))
3868 gist_access_id = Column('gist_access_id', Unicode(250))
3855 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
3869 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
3856 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
3870 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
3857 gist_expires = Column('gist_expires', Float(53), nullable=False)
3871 gist_expires = Column('gist_expires', Float(53), nullable=False)
3858 gist_type = Column('gist_type', Unicode(128), nullable=False)
3872 gist_type = Column('gist_type', Unicode(128), nullable=False)
3859 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3873 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3860 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3874 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3861 acl_level = Column('acl_level', Unicode(128), nullable=True)
3875 acl_level = Column('acl_level', Unicode(128), nullable=True)
3862
3876
3863 owner = relationship('User')
3877 owner = relationship('User')
3864
3878
3865 def __repr__(self):
3879 def __repr__(self):
3866 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
3880 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
3867
3881
3868 @hybrid_property
3882 @hybrid_property
3869 def description_safe(self):
3883 def description_safe(self):
3870 from rhodecode.lib import helpers as h
3884 from rhodecode.lib import helpers as h
3871 return h.escape(self.gist_description)
3885 return h.escape(self.gist_description)
3872
3886
3873 @classmethod
3887 @classmethod
3874 def get_or_404(cls, id_):
3888 def get_or_404(cls, id_):
3875 from pyramid.httpexceptions import HTTPNotFound
3889 from pyramid.httpexceptions import HTTPNotFound
3876
3890
3877 res = cls.query().filter(cls.gist_access_id == id_).scalar()
3891 res = cls.query().filter(cls.gist_access_id == id_).scalar()
3878 if not res:
3892 if not res:
3879 raise HTTPNotFound()
3893 raise HTTPNotFound()
3880 return res
3894 return res
3881
3895
3882 @classmethod
3896 @classmethod
3883 def get_by_access_id(cls, gist_access_id):
3897 def get_by_access_id(cls, gist_access_id):
3884 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
3898 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
3885
3899
3886 def gist_url(self):
3900 def gist_url(self):
3887 from rhodecode.model.gist import GistModel
3901 from rhodecode.model.gist import GistModel
3888 return GistModel().get_url(self)
3902 return GistModel().get_url(self)
3889
3903
3890 @classmethod
3904 @classmethod
3891 def base_path(cls):
3905 def base_path(cls):
3892 """
3906 """
3893 Returns base path when all gists are stored
3907 Returns base path when all gists are stored
3894
3908
3895 :param cls:
3909 :param cls:
3896 """
3910 """
3897 from rhodecode.model.gist import GIST_STORE_LOC
3911 from rhodecode.model.gist import GIST_STORE_LOC
3898 q = Session().query(RhodeCodeUi)\
3912 q = Session().query(RhodeCodeUi)\
3899 .filter(RhodeCodeUi.ui_key == URL_SEP)
3913 .filter(RhodeCodeUi.ui_key == URL_SEP)
3900 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
3914 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
3901 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
3915 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
3902
3916
3903 def get_api_data(self):
3917 def get_api_data(self):
3904 """
3918 """
3905 Common function for generating gist related data for API
3919 Common function for generating gist related data for API
3906 """
3920 """
3907 gist = self
3921 gist = self
3908 data = {
3922 data = {
3909 'gist_id': gist.gist_id,
3923 'gist_id': gist.gist_id,
3910 'type': gist.gist_type,
3924 'type': gist.gist_type,
3911 'access_id': gist.gist_access_id,
3925 'access_id': gist.gist_access_id,
3912 'description': gist.gist_description,
3926 'description': gist.gist_description,
3913 'url': gist.gist_url(),
3927 'url': gist.gist_url(),
3914 'expires': gist.gist_expires,
3928 'expires': gist.gist_expires,
3915 'created_on': gist.created_on,
3929 'created_on': gist.created_on,
3916 'modified_at': gist.modified_at,
3930 'modified_at': gist.modified_at,
3917 'content': None,
3931 'content': None,
3918 'acl_level': gist.acl_level,
3932 'acl_level': gist.acl_level,
3919 }
3933 }
3920 return data
3934 return data
3921
3935
3922 def __json__(self):
3936 def __json__(self):
3923 data = dict(
3937 data = dict(
3924 )
3938 )
3925 data.update(self.get_api_data())
3939 data.update(self.get_api_data())
3926 return data
3940 return data
3927 # SCM functions
3941 # SCM functions
3928
3942
3929 def scm_instance(self, **kwargs):
3943 def scm_instance(self, **kwargs):
3930 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
3944 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
3931 return get_vcs_instance(
3945 return get_vcs_instance(
3932 repo_path=safe_str(full_repo_path), create=False)
3946 repo_path=safe_str(full_repo_path), create=False)
3933
3947
3934
3948
3935 class ExternalIdentity(Base, BaseModel):
3949 class ExternalIdentity(Base, BaseModel):
3936 __tablename__ = 'external_identities'
3950 __tablename__ = 'external_identities'
3937 __table_args__ = (
3951 __table_args__ = (
3938 Index('local_user_id_idx', 'local_user_id'),
3952 Index('local_user_id_idx', 'local_user_id'),
3939 Index('external_id_idx', 'external_id'),
3953 Index('external_id_idx', 'external_id'),
3940 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3954 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3941 'mysql_charset': 'utf8'})
3955 'mysql_charset': 'utf8'})
3942
3956
3943 external_id = Column('external_id', Unicode(255), default=u'',
3957 external_id = Column('external_id', Unicode(255), default=u'',
3944 primary_key=True)
3958 primary_key=True)
3945 external_username = Column('external_username', Unicode(1024), default=u'')
3959 external_username = Column('external_username', Unicode(1024), default=u'')
3946 local_user_id = Column('local_user_id', Integer(),
3960 local_user_id = Column('local_user_id', Integer(),
3947 ForeignKey('users.user_id'), primary_key=True)
3961 ForeignKey('users.user_id'), primary_key=True)
3948 provider_name = Column('provider_name', Unicode(255), default=u'',
3962 provider_name = Column('provider_name', Unicode(255), default=u'',
3949 primary_key=True)
3963 primary_key=True)
3950 access_token = Column('access_token', String(1024), default=u'')
3964 access_token = Column('access_token', String(1024), default=u'')
3951 alt_token = Column('alt_token', String(1024), default=u'')
3965 alt_token = Column('alt_token', String(1024), default=u'')
3952 token_secret = Column('token_secret', String(1024), default=u'')
3966 token_secret = Column('token_secret', String(1024), default=u'')
3953
3967
3954 @classmethod
3968 @classmethod
3955 def by_external_id_and_provider(cls, external_id, provider_name,
3969 def by_external_id_and_provider(cls, external_id, provider_name,
3956 local_user_id=None):
3970 local_user_id=None):
3957 """
3971 """
3958 Returns ExternalIdentity instance based on search params
3972 Returns ExternalIdentity instance based on search params
3959
3973
3960 :param external_id:
3974 :param external_id:
3961 :param provider_name:
3975 :param provider_name:
3962 :return: ExternalIdentity
3976 :return: ExternalIdentity
3963 """
3977 """
3964 query = cls.query()
3978 query = cls.query()
3965 query = query.filter(cls.external_id == external_id)
3979 query = query.filter(cls.external_id == external_id)
3966 query = query.filter(cls.provider_name == provider_name)
3980 query = query.filter(cls.provider_name == provider_name)
3967 if local_user_id:
3981 if local_user_id:
3968 query = query.filter(cls.local_user_id == local_user_id)
3982 query = query.filter(cls.local_user_id == local_user_id)
3969 return query.first()
3983 return query.first()
3970
3984
3971 @classmethod
3985 @classmethod
3972 def user_by_external_id_and_provider(cls, external_id, provider_name):
3986 def user_by_external_id_and_provider(cls, external_id, provider_name):
3973 """
3987 """
3974 Returns User instance based on search params
3988 Returns User instance based on search params
3975
3989
3976 :param external_id:
3990 :param external_id:
3977 :param provider_name:
3991 :param provider_name:
3978 :return: User
3992 :return: User
3979 """
3993 """
3980 query = User.query()
3994 query = User.query()
3981 query = query.filter(cls.external_id == external_id)
3995 query = query.filter(cls.external_id == external_id)
3982 query = query.filter(cls.provider_name == provider_name)
3996 query = query.filter(cls.provider_name == provider_name)
3983 query = query.filter(User.user_id == cls.local_user_id)
3997 query = query.filter(User.user_id == cls.local_user_id)
3984 return query.first()
3998 return query.first()
3985
3999
3986 @classmethod
4000 @classmethod
3987 def by_local_user_id(cls, local_user_id):
4001 def by_local_user_id(cls, local_user_id):
3988 """
4002 """
3989 Returns all tokens for user
4003 Returns all tokens for user
3990
4004
3991 :param local_user_id:
4005 :param local_user_id:
3992 :return: ExternalIdentity
4006 :return: ExternalIdentity
3993 """
4007 """
3994 query = cls.query()
4008 query = cls.query()
3995 query = query.filter(cls.local_user_id == local_user_id)
4009 query = query.filter(cls.local_user_id == local_user_id)
3996 return query
4010 return query
3997
4011
3998
4012
3999 class Integration(Base, BaseModel):
4013 class Integration(Base, BaseModel):
4000 __tablename__ = 'integrations'
4014 __tablename__ = 'integrations'
4001 __table_args__ = (
4015 __table_args__ = (
4002 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4016 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4003 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
4017 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
4004 )
4018 )
4005
4019
4006 integration_id = Column('integration_id', Integer(), primary_key=True)
4020 integration_id = Column('integration_id', Integer(), primary_key=True)
4007 integration_type = Column('integration_type', String(255))
4021 integration_type = Column('integration_type', String(255))
4008 enabled = Column('enabled', Boolean(), nullable=False)
4022 enabled = Column('enabled', Boolean(), nullable=False)
4009 name = Column('name', String(255), nullable=False)
4023 name = Column('name', String(255), nullable=False)
4010 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4024 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4011 default=False)
4025 default=False)
4012
4026
4013 settings = Column(
4027 settings = Column(
4014 'settings_json', MutationObj.as_mutable(
4028 'settings_json', MutationObj.as_mutable(
4015 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4029 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4016 repo_id = Column(
4030 repo_id = Column(
4017 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4031 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4018 nullable=True, unique=None, default=None)
4032 nullable=True, unique=None, default=None)
4019 repo = relationship('Repository', lazy='joined')
4033 repo = relationship('Repository', lazy='joined')
4020
4034
4021 repo_group_id = Column(
4035 repo_group_id = Column(
4022 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4036 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4023 nullable=True, unique=None, default=None)
4037 nullable=True, unique=None, default=None)
4024 repo_group = relationship('RepoGroup', lazy='joined')
4038 repo_group = relationship('RepoGroup', lazy='joined')
4025
4039
4026 @property
4040 @property
4027 def scope(self):
4041 def scope(self):
4028 if self.repo:
4042 if self.repo:
4029 return repr(self.repo)
4043 return repr(self.repo)
4030 if self.repo_group:
4044 if self.repo_group:
4031 if self.child_repos_only:
4045 if self.child_repos_only:
4032 return repr(self.repo_group) + ' (child repos only)'
4046 return repr(self.repo_group) + ' (child repos only)'
4033 else:
4047 else:
4034 return repr(self.repo_group) + ' (recursive)'
4048 return repr(self.repo_group) + ' (recursive)'
4035 if self.child_repos_only:
4049 if self.child_repos_only:
4036 return 'root_repos'
4050 return 'root_repos'
4037 return 'global'
4051 return 'global'
4038
4052
4039 def __repr__(self):
4053 def __repr__(self):
4040 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4054 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4041
4055
4042
4056
4043 class RepoReviewRuleUser(Base, BaseModel):
4057 class RepoReviewRuleUser(Base, BaseModel):
4044 __tablename__ = 'repo_review_rules_users'
4058 __tablename__ = 'repo_review_rules_users'
4045 __table_args__ = (
4059 __table_args__ = (
4046 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4060 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4047 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4061 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4048 )
4062 )
4049 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4063 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4050 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4064 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4051 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4065 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4052 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4066 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4053 user = relationship('User')
4067 user = relationship('User')
4054
4068
4055 def rule_data(self):
4069 def rule_data(self):
4056 return {
4070 return {
4057 'mandatory': self.mandatory
4071 'mandatory': self.mandatory
4058 }
4072 }
4059
4073
4060
4074
4061 class RepoReviewRuleUserGroup(Base, BaseModel):
4075 class RepoReviewRuleUserGroup(Base, BaseModel):
4062 __tablename__ = 'repo_review_rules_users_groups'
4076 __tablename__ = 'repo_review_rules_users_groups'
4063 __table_args__ = (
4077 __table_args__ = (
4064 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4078 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4065 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4079 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4066 )
4080 )
4067 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4081 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4068 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4082 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4069 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4083 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4070 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4084 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4071 users_group = relationship('UserGroup')
4085 users_group = relationship('UserGroup')
4072
4086
4073 def rule_data(self):
4087 def rule_data(self):
4074 return {
4088 return {
4075 'mandatory': self.mandatory
4089 'mandatory': self.mandatory
4076 }
4090 }
4077
4091
4078
4092
4079 class RepoReviewRule(Base, BaseModel):
4093 class RepoReviewRule(Base, BaseModel):
4080 __tablename__ = 'repo_review_rules'
4094 __tablename__ = 'repo_review_rules'
4081 __table_args__ = (
4095 __table_args__ = (
4082 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4096 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4083 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4097 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4084 )
4098 )
4085
4099
4086 repo_review_rule_id = Column(
4100 repo_review_rule_id = Column(
4087 'repo_review_rule_id', Integer(), primary_key=True)
4101 'repo_review_rule_id', Integer(), primary_key=True)
4088 repo_id = Column(
4102 repo_id = Column(
4089 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4103 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4090 repo = relationship('Repository', backref='review_rules')
4104 repo = relationship('Repository', backref='review_rules')
4091
4105
4092 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4106 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4093 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4107 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4094
4108
4095 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4109 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4096 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4110 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4097 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4111 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4098 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4112 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4099
4113
4100 rule_users = relationship('RepoReviewRuleUser')
4114 rule_users = relationship('RepoReviewRuleUser')
4101 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4115 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4102
4116
4103 @hybrid_property
4117 @hybrid_property
4104 def branch_pattern(self):
4118 def branch_pattern(self):
4105 return self._branch_pattern or '*'
4119 return self._branch_pattern or '*'
4106
4120
4107 def _validate_glob(self, value):
4121 def _validate_glob(self, value):
4108 re.compile('^' + glob2re(value) + '$')
4122 re.compile('^' + glob2re(value) + '$')
4109
4123
4110 @branch_pattern.setter
4124 @branch_pattern.setter
4111 def branch_pattern(self, value):
4125 def branch_pattern(self, value):
4112 self._validate_glob(value)
4126 self._validate_glob(value)
4113 self._branch_pattern = value or '*'
4127 self._branch_pattern = value or '*'
4114
4128
4115 @hybrid_property
4129 @hybrid_property
4116 def file_pattern(self):
4130 def file_pattern(self):
4117 return self._file_pattern or '*'
4131 return self._file_pattern or '*'
4118
4132
4119 @file_pattern.setter
4133 @file_pattern.setter
4120 def file_pattern(self, value):
4134 def file_pattern(self, value):
4121 self._validate_glob(value)
4135 self._validate_glob(value)
4122 self._file_pattern = value or '*'
4136 self._file_pattern = value or '*'
4123
4137
4124 def matches(self, branch, files_changed):
4138 def matches(self, branch, files_changed):
4125 """
4139 """
4126 Check if this review rule matches a branch/files in a pull request
4140 Check if this review rule matches a branch/files in a pull request
4127
4141
4128 :param branch: branch name for the commit
4142 :param branch: branch name for the commit
4129 :param files_changed: list of file paths changed in the pull request
4143 :param files_changed: list of file paths changed in the pull request
4130 """
4144 """
4131
4145
4132 branch = branch or ''
4146 branch = branch or ''
4133 files_changed = files_changed or []
4147 files_changed = files_changed or []
4134
4148
4135 branch_matches = True
4149 branch_matches = True
4136 if branch:
4150 if branch:
4137 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
4151 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
4138 branch_matches = bool(branch_regex.search(branch))
4152 branch_matches = bool(branch_regex.search(branch))
4139
4153
4140 files_matches = True
4154 files_matches = True
4141 if self.file_pattern != '*':
4155 if self.file_pattern != '*':
4142 files_matches = False
4156 files_matches = False
4143 file_regex = re.compile(glob2re(self.file_pattern))
4157 file_regex = re.compile(glob2re(self.file_pattern))
4144 for filename in files_changed:
4158 for filename in files_changed:
4145 if file_regex.search(filename):
4159 if file_regex.search(filename):
4146 files_matches = True
4160 files_matches = True
4147 break
4161 break
4148
4162
4149 return branch_matches and files_matches
4163 return branch_matches and files_matches
4150
4164
4151 @property
4165 @property
4152 def review_users(self):
4166 def review_users(self):
4153 """ Returns the users which this rule applies to """
4167 """ Returns the users which this rule applies to """
4154
4168
4155 users = collections.OrderedDict()
4169 users = collections.OrderedDict()
4156
4170
4157 for rule_user in self.rule_users:
4171 for rule_user in self.rule_users:
4158 if rule_user.user.active:
4172 if rule_user.user.active:
4159 if rule_user.user not in users:
4173 if rule_user.user not in users:
4160 users[rule_user.user.username] = {
4174 users[rule_user.user.username] = {
4161 'user': rule_user.user,
4175 'user': rule_user.user,
4162 'source': 'user',
4176 'source': 'user',
4163 'source_data': {},
4177 'source_data': {},
4164 'data': rule_user.rule_data()
4178 'data': rule_user.rule_data()
4165 }
4179 }
4166
4180
4167 for rule_user_group in self.rule_user_groups:
4181 for rule_user_group in self.rule_user_groups:
4168 source_data = {
4182 source_data = {
4169 'name': rule_user_group.users_group.users_group_name,
4183 'name': rule_user_group.users_group.users_group_name,
4170 'members': len(rule_user_group.users_group.members)
4184 'members': len(rule_user_group.users_group.members)
4171 }
4185 }
4172 for member in rule_user_group.users_group.members:
4186 for member in rule_user_group.users_group.members:
4173 if member.user.active:
4187 if member.user.active:
4174 users[member.user.username] = {
4188 users[member.user.username] = {
4175 'user': member.user,
4189 'user': member.user,
4176 'source': 'user_group',
4190 'source': 'user_group',
4177 'source_data': source_data,
4191 'source_data': source_data,
4178 'data': rule_user_group.rule_data()
4192 'data': rule_user_group.rule_data()
4179 }
4193 }
4180
4194
4181 return users
4195 return users
4182
4196
4183 def __repr__(self):
4197 def __repr__(self):
4184 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4198 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4185 self.repo_review_rule_id, self.repo)
4199 self.repo_review_rule_id, self.repo)
4186
4200
4187
4201
4188 class DbMigrateVersion(Base, BaseModel):
4202 class DbMigrateVersion(Base, BaseModel):
4189 __tablename__ = 'db_migrate_version'
4203 __tablename__ = 'db_migrate_version'
4190 __table_args__ = (
4204 __table_args__ = (
4191 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4205 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4192 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
4206 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
4193 )
4207 )
4194 repository_id = Column('repository_id', String(250), primary_key=True)
4208 repository_id = Column('repository_id', String(250), primary_key=True)
4195 repository_path = Column('repository_path', Text)
4209 repository_path = Column('repository_path', Text)
4196 version = Column('version', Integer)
4210 version = Column('version', Integer)
4197
4211
4198
4212
4199 class DbSession(Base, BaseModel):
4213 class DbSession(Base, BaseModel):
4200 __tablename__ = 'db_session'
4214 __tablename__ = 'db_session'
4201 __table_args__ = (
4215 __table_args__ = (
4202 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4216 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4203 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
4217 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
4204 )
4218 )
4205
4219
4206 def __repr__(self):
4220 def __repr__(self):
4207 return '<DB:DbSession({})>'.format(self.id)
4221 return '<DB:DbSession({})>'.format(self.id)
4208
4222
4209 id = Column('id', Integer())
4223 id = Column('id', Integer())
4210 namespace = Column('namespace', String(255), primary_key=True)
4224 namespace = Column('namespace', String(255), primary_key=True)
4211 accessed = Column('accessed', DateTime, nullable=False)
4225 accessed = Column('accessed', DateTime, nullable=False)
4212 created = Column('created', DateTime, nullable=False)
4226 created = Column('created', DateTime, nullable=False)
4213 data = Column('data', PickleType, nullable=False)
4227 data = Column('data', PickleType, nullable=False)
@@ -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,57 +1,57 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 ${_('%s user settings') % c.user.username}
5 ${_('%s user settings') % c.user.username}
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
10
11 <%def name="breadcrumbs_links()">
11 <%def name="breadcrumbs_links()">
12 ${h.link_to(_('Admin'),h.route_path('admin_home'))}
12 ${h.link_to(_('Admin'),h.route_path('admin_home'))}
13 &raquo;
13 &raquo;
14 ${h.link_to(_('Users'),h.route_path('users'))}
14 ${h.link_to(_('Users'),h.route_path('users'))}
15 &raquo;
15 &raquo;
16 % if c.user.active:
16 % if c.user.active:
17 ${c.user.username}
17 ${c.user.username}
18 % else:
18 % else:
19 <strike title="${_('This user is set as disabled')}">${c.user.username}</strike>
19 <strike title="${_('This user is set as disabled')}">${c.user.username}</strike>
20 % endif
20 % endif
21
21
22 </%def>
22 </%def>
23
23
24 <%def name="menu_bar_nav()">
24 <%def name="menu_bar_nav()">
25 ${self.menu_items(active='admin')}
25 ${self.menu_items(active='admin')}
26 </%def>
26 </%def>
27
27
28 <%def name="main()">
28 <%def name="main()">
29 <div class="box user_settings">
29 <div class="box user_settings">
30 <div class="title">
30 <div class="title">
31 ${self.breadcrumbs()}
31 ${self.breadcrumbs()}
32 </div>
32 </div>
33
33
34 ##main
34 ##main
35 <div class="sidebar-col-wrapper">
35 <div class="sidebar-col-wrapper">
36 <div class="sidebar">
36 <div class="sidebar">
37 <ul class="nav nav-pills nav-stacked">
37 <ul class="nav nav-pills nav-stacked">
38 <li class="${'active' if c.active=='profile' else ''}"><a href="${h.url('edit_user', user_id=c.user.user_id)}">${_('User Profile')}</a></li>
38 <li class="${'active' if c.active=='profile' else ''}"><a href="${h.route_path('user_edit', user_id=c.user.user_id)}">${_('User Profile')}</a></li>
39 <li class="${'active' if c.active=='auth_tokens' else ''}"><a href="${h.route_path('edit_user_auth_tokens', user_id=c.user.user_id)}">${_('Auth tokens')}</a></li>
39 <li class="${'active' if c.active=='auth_tokens' else ''}"><a href="${h.route_path('edit_user_auth_tokens', user_id=c.user.user_id)}">${_('Auth tokens')}</a></li>
40 <li class="${'active' if c.active in ['ssh_keys','ssh_keys_generate'] else ''}"><a href="${h.route_path('edit_user_ssh_keys', user_id=c.user.user_id)}">${_('SSH Keys')}</a></li>
40 <li class="${'active' if c.active in ['ssh_keys','ssh_keys_generate'] else ''}"><a href="${h.route_path('edit_user_ssh_keys', user_id=c.user.user_id)}">${_('SSH Keys')}</a></li>
41 <li class="${'active' if c.active=='advanced' else ''}"><a href="${h.url('edit_user_advanced', user_id=c.user.user_id)}">${_('Advanced')}</a></li>
41 <li class="${'active' if c.active=='advanced' else ''}"><a href="${h.route_path('user_edit_advanced', user_id=c.user.user_id)}">${_('Advanced')}</a></li>
42 <li class="${'active' if c.active=='global_perms' else ''}"><a href="${h.url('edit_user_global_perms', user_id=c.user.user_id)}">${_('Global permissions')}</a></li>
42 <li class="${'active' if c.active=='global_perms' else ''}"><a href="${h.route_path('user_edit_global_perms', user_id=c.user.user_id)}">${_('Global permissions')}</a></li>
43 <li class="${'active' if c.active=='perms_summary' else ''}"><a href="${h.route_path('edit_user_perms_summary', user_id=c.user.user_id)}">${_('Permissions summary')}</a></li>
43 <li class="${'active' if c.active=='perms_summary' else ''}"><a href="${h.route_path('edit_user_perms_summary', user_id=c.user.user_id)}">${_('Permissions summary')}</a></li>
44 <li class="${'active' if c.active=='emails' else ''}"><a href="${h.route_path('edit_user_emails', user_id=c.user.user_id)}">${_('Emails')}</a></li>
44 <li class="${'active' if c.active=='emails' else ''}"><a href="${h.route_path('edit_user_emails', user_id=c.user.user_id)}">${_('Emails')}</a></li>
45 <li class="${'active' if c.active=='ips' else ''}"><a href="${h.route_path('edit_user_ips', user_id=c.user.user_id)}">${_('Ip Whitelist')}</a></li>
45 <li class="${'active' if c.active=='ips' else ''}"><a href="${h.route_path('edit_user_ips', user_id=c.user.user_id)}">${_('Ip Whitelist')}</a></li>
46 <li class="${'active' if c.active=='groups' else ''}"><a href="${h.route_path('edit_user_groups_management', user_id=c.user.user_id)}">${_('User Groups Management')}</a></li>
46 <li class="${'active' if c.active=='groups' else ''}"><a href="${h.route_path('edit_user_groups_management', user_id=c.user.user_id)}">${_('User Groups Management')}</a></li>
47 <li class="${'active' if c.active=='audit' else ''}"><a href="${h.route_path('edit_user_audit_logs', user_id=c.user.user_id)}">${_('User audit')}</a></li>
47 <li class="${'active' if c.active=='audit' else ''}"><a href="${h.route_path('edit_user_audit_logs', user_id=c.user.user_id)}">${_('User audit')}</a></li>
48 </ul>
48 </ul>
49 </div>
49 </div>
50
50
51 <div class="main-content-full-width">
51 <div class="main-content-full-width">
52 <%include file="/admin/users/user_edit_${c.active}.mako"/>
52 <%include file="/admin/users/user_edit_${c.active}.mako"/>
53 </div>
53 </div>
54 </div>
54 </div>
55 </div>
55 </div>
56
56
57 </%def>
57 </%def>
@@ -1,161 +1,161 b''
1 <%namespace name="base" file="/base/base.mako"/>
1 <%namespace name="base" file="/base/base.mako"/>
2
2
3 <%
3 <%
4 elems = [
4 elems = [
5 (_('Created on'), h.format_date(c.user.created_on), '', ''),
5 (_('Created on'), h.format_date(c.user.created_on), '', ''),
6 (_('Source of Record'), c.user.extern_type, '', ''),
6 (_('Source of Record'), c.user.extern_type, '', ''),
7
7
8 (_('Last login'), c.user.last_login or '-', '', ''),
8 (_('Last login'), c.user.last_login or '-', '', ''),
9 (_('Last activity'), c.user.last_activity, '', ''),
9 (_('Last activity'), c.user.last_activity, '', ''),
10
10
11 (_('Repositories'), len(c.user.repositories), '', [x.repo_name for x in c.user.repositories]),
11 (_('Repositories'), len(c.user.repositories), '', [x.repo_name for x in c.user.repositories]),
12 (_('Repository groups'), len(c.user.repository_groups), '', [x.group_name for x in c.user.repository_groups]),
12 (_('Repository groups'), len(c.user.repository_groups), '', [x.group_name for x in c.user.repository_groups]),
13 (_('User groups'), len(c.user.user_groups), '', [x.users_group_name for x in c.user.user_groups]),
13 (_('User groups'), len(c.user.user_groups), '', [x.users_group_name for x in c.user.user_groups]),
14
14
15 (_('Reviewer of pull requests'), len(c.user.reviewer_pull_requests), '', ['Pull Request #{}'.format(x.pull_request.pull_request_id) for x in c.user.reviewer_pull_requests]),
15 (_('Reviewer of pull requests'), len(c.user.reviewer_pull_requests), '', ['Pull Request #{}'.format(x.pull_request.pull_request_id) for x in c.user.reviewer_pull_requests]),
16 (_('Assigned to review rules'), len(c.user_to_review_rules), '', [x for x in c.user_to_review_rules]),
16 (_('Assigned to review rules'), len(c.user_to_review_rules), '', [x for x in c.user_to_review_rules]),
17
17
18 (_('Member of User groups'), len(c.user.group_member), '', [x.users_group.users_group_name for x in c.user.group_member]),
18 (_('Member of User groups'), len(c.user.group_member), '', [x.users_group.users_group_name for x in c.user.group_member]),
19 (_('Force password change'), c.user.user_data.get('force_password_change', 'False'), '', ''),
19 (_('Force password change'), c.user.user_data.get('force_password_change', 'False'), '', ''),
20 ]
20 ]
21 %>
21 %>
22
22
23 <div class="panel panel-default">
23 <div class="panel panel-default">
24 <div class="panel-heading">
24 <div class="panel-heading">
25 <h3 class="panel-title">${_('User: %s') % c.user.username}</h3>
25 <h3 class="panel-title">${_('User: %s') % c.user.username}</h3>
26 </div>
26 </div>
27 <div class="panel-body">
27 <div class="panel-body">
28 ${base.dt_info_panel(elems)}
28 ${base.dt_info_panel(elems)}
29 </div>
29 </div>
30 </div>
30 </div>
31
31
32 <div class="panel panel-default">
32 <div class="panel panel-default">
33 <div class="panel-heading">
33 <div class="panel-heading">
34 <h3 class="panel-title">${_('Force Password Reset')}</h3>
34 <h3 class="panel-title">${_('Force Password Reset')}</h3>
35 </div>
35 </div>
36 <div class="panel-body">
36 <div class="panel-body">
37 ${h.secure_form(h.url('force_password_reset_user', user_id=c.user.user_id), method='post')}
37 ${h.secure_form(h.route_path('user_force_password_reset', user_id=c.user.user_id), request=request)}
38 <div class="field">
38 <div class="field">
39 <button class="btn btn-default" type="submit">
39 <button class="btn btn-default" type="submit">
40 <i class="icon-lock"></i>
40 <i class="icon-lock"></i>
41 %if c.user.user_data.get('force_password_change'):
41 %if c.user.user_data.get('force_password_change'):
42 ${_('Disable forced password reset')}
42 ${_('Disable forced password reset')}
43 %else:
43 %else:
44 ${_('Enable forced password reset')}
44 ${_('Enable forced password reset')}
45 %endif
45 %endif
46 </button>
46 </button>
47 </div>
47 </div>
48 <div class="field">
48 <div class="field">
49 <span class="help-block">
49 <span class="help-block">
50 ${_("When this is enabled user will have to change they password when they next use RhodeCode system. This will also forbid vcs operations until someone makes a password change in the web interface")}
50 ${_("When this is enabled user will have to change they password when they next use RhodeCode system. This will also forbid vcs operations until someone makes a password change in the web interface")}
51 </span>
51 </span>
52 </div>
52 </div>
53 ${h.end_form()}
53 ${h.end_form()}
54 </div>
54 </div>
55 </div>
55 </div>
56
56
57 <div class="panel panel-default">
57 <div class="panel panel-default">
58 <div class="panel-heading">
58 <div class="panel-heading">
59 <h3 class="panel-title">${_('Personal Repository Group')}</h3>
59 <h3 class="panel-title">${_('Personal Repository Group')}</h3>
60 </div>
60 </div>
61 <div class="panel-body">
61 <div class="panel-body">
62 ${h.secure_form(h.url('create_personal_repo_group', user_id=c.user.user_id), method='post')}
62 ${h.secure_form(h.route_path('user_create_personal_repo_group', user_id=c.user.user_id), request=request)}
63
63
64 %if c.personal_repo_group:
64 %if c.personal_repo_group:
65 <div class="panel-body-title-text">${_('Users personal repository group')} : ${h.link_to(c.personal_repo_group.group_name, h.route_path('repo_group_home', repo_group_name=c.personal_repo_group.group_name))}</div>
65 <div class="panel-body-title-text">${_('Users personal repository group')} : ${h.link_to(c.personal_repo_group.group_name, h.route_path('repo_group_home', repo_group_name=c.personal_repo_group.group_name))}</div>
66 %else:
66 %else:
67 <div class="panel-body-title-text">
67 <div class="panel-body-title-text">
68 ${_('This user currently does not have a personal repository group')}
68 ${_('This user currently does not have a personal repository group')}
69 <br/>
69 <br/>
70 ${_('New group will be created at: `/%(path)s`') % {'path': c.personal_repo_group_name}}
70 ${_('New group will be created at: `/%(path)s`') % {'path': c.personal_repo_group_name}}
71 </div>
71 </div>
72 %endif
72 %endif
73 <button class="btn btn-default" type="submit" ${'disabled="disabled"' if c.personal_repo_group else ''}>
73 <button class="btn btn-default" type="submit" ${'disabled="disabled"' if c.personal_repo_group else ''}>
74 <i class="icon-folder-close"></i>
74 <i class="icon-folder-close"></i>
75 ${_('Create personal repository group')}
75 ${_('Create personal repository group')}
76 </button>
76 </button>
77 ${h.end_form()}
77 ${h.end_form()}
78 </div>
78 </div>
79 </div>
79 </div>
80
80
81
81
82 <div class="panel panel-danger">
82 <div class="panel panel-danger">
83 <div class="panel-heading">
83 <div class="panel-heading">
84 <h3 class="panel-title">${_('Delete User')}</h3>
84 <h3 class="panel-title">${_('Delete User')}</h3>
85 </div>
85 </div>
86 <div class="panel-body">
86 <div class="panel-body">
87 ${h.secure_form(h.url('delete_user', user_id=c.user.user_id), method='delete')}
87 ${h.secure_form(h.route_path('user_delete', user_id=c.user.user_id), request=request)}
88
88
89 <table class="display">
89 <table class="display">
90 <tr>
90 <tr>
91 <td>
91 <td>
92 ${_ungettext('This user owns %s repository.', 'This user owns %s repositories.', len(c.user.repositories)) % len(c.user.repositories)}
92 ${_ungettext('This user owns %s repository.', 'This user owns %s repositories.', len(c.user.repositories)) % len(c.user.repositories)}
93 </td>
93 </td>
94 <td>
94 <td>
95 %if len(c.user.repositories) > 0:
95 %if len(c.user.repositories) > 0:
96 <input type="radio" id="user_repos_1" name="user_repos" value="detach" checked="checked"/> <label for="user_repos_1">${_('Detach repositories')}</label>
96 <input type="radio" id="user_repos_1" name="user_repos" value="detach" checked="checked"/> <label for="user_repos_1">${_('Detach repositories')}</label>
97 %endif
97 %endif
98 </td>
98 </td>
99 <td>
99 <td>
100 %if len(c.user.repositories) > 0:
100 %if len(c.user.repositories) > 0:
101 <input type="radio" id="user_repos_2" name="user_repos" value="delete" /> <label for="user_repos_2">${_('Delete repositories')}</label>
101 <input type="radio" id="user_repos_2" name="user_repos" value="delete" /> <label for="user_repos_2">${_('Delete repositories')}</label>
102 %endif
102 %endif
103 </td>
103 </td>
104 </tr>
104 </tr>
105
105
106 <tr>
106 <tr>
107 <td>
107 <td>
108 ${_ungettext('This user owns %s repository group.', 'This user owns %s repository groups.', len(c.user.repository_groups)) % len(c.user.repository_groups)}
108 ${_ungettext('This user owns %s repository group.', 'This user owns %s repository groups.', len(c.user.repository_groups)) % len(c.user.repository_groups)}
109 </td>
109 </td>
110 <td>
110 <td>
111 %if len(c.user.repository_groups) > 0:
111 %if len(c.user.repository_groups) > 0:
112 <input type="radio" id="user_repo_groups_1" name="user_repo_groups" value="detach" checked="checked"/> <label for="user_repo_groups_1">${_('Detach repository groups')}</label>
112 <input type="radio" id="user_repo_groups_1" name="user_repo_groups" value="detach" checked="checked"/> <label for="user_repo_groups_1">${_('Detach repository groups')}</label>
113 %endif
113 %endif
114 </td>
114 </td>
115 <td>
115 <td>
116 %if len(c.user.repository_groups) > 0:
116 %if len(c.user.repository_groups) > 0:
117 <input type="radio" id="user_repo_groups_2" name="user_repo_groups" value="delete" /> <label for="user_repo_groups_2">${_('Delete repositories')}</label>
117 <input type="radio" id="user_repo_groups_2" name="user_repo_groups" value="delete" /> <label for="user_repo_groups_2">${_('Delete repositories')}</label>
118 %endif
118 %endif
119 </td>
119 </td>
120 </tr>
120 </tr>
121
121
122 <tr>
122 <tr>
123 <td>
123 <td>
124 ${_ungettext('This user owns %s user group.', 'This user owns %s user groups.', len(c.user.user_groups)) % len(c.user.user_groups)}
124 ${_ungettext('This user owns %s user group.', 'This user owns %s user groups.', len(c.user.user_groups)) % len(c.user.user_groups)}
125 </td>
125 </td>
126 <td>
126 <td>
127 %if len(c.user.user_groups) > 0:
127 %if len(c.user.user_groups) > 0:
128 <input type="radio" id="user_user_groups_1" name="user_user_groups" value="detach" checked="checked"/> <label for="user_user_groups_1">${_('Detach user groups')}</label>
128 <input type="radio" id="user_user_groups_1" name="user_user_groups" value="detach" checked="checked"/> <label for="user_user_groups_1">${_('Detach user groups')}</label>
129 %endif
129 %endif
130 </td>
130 </td>
131 <td>
131 <td>
132 %if len(c.user.user_groups) > 0:
132 %if len(c.user.user_groups) > 0:
133 <input type="radio" id="user_user_groups_2" name="user_user_groups" value="delete" /> <label for="user_user_groups_2">${_('Delete repositories')}</label>
133 <input type="radio" id="user_user_groups_2" name="user_user_groups" value="delete" /> <label for="user_user_groups_2">${_('Delete repositories')}</label>
134 %endif
134 %endif
135 </td>
135 </td>
136 </tr>
136 </tr>
137 </table>
137 </table>
138 <div style="margin: 0 0 20px 0" class="fake-space"></div>
138 <div style="margin: 0 0 20px 0" class="fake-space"></div>
139
139
140 <div class="field">
140 <div class="field">
141 <button class="btn btn-small btn-danger" type="submit"
141 <button class="btn btn-small btn-danger" type="submit"
142 onclick="return confirm('${_('Confirm to delete this user: %s') % c.user.username}');"
142 onclick="return confirm('${_('Confirm to delete this user: %s') % c.user.username}');"
143 ${"disabled" if not c.can_delete_user else ""}>
143 ${"disabled" if not c.can_delete_user else ""}>
144 ${_('Delete this user')}
144 ${_('Delete this user')}
145 </button>
145 </button>
146 </div>
146 </div>
147 % if c.can_delete_user_message:
147 % if c.can_delete_user_message:
148 <p class="help-block pre-formatting">${c.can_delete_user_message}</p>
148 <p class="help-block pre-formatting">${c.can_delete_user_message}</p>
149 % endif
149 % endif
150
150
151 <div class="field">
151 <div class="field">
152 <span class="help-block">
152 <span class="help-block">
153 %if len(c.user.repositories) > 0 or len(c.user.repository_groups) > 0 or len(c.user.user_groups) > 0:
153 %if len(c.user.repositories) > 0 or len(c.user.repository_groups) > 0 or len(c.user.user_groups) > 0:
154 <p class="help-block">${_("When selecting the detach option, the depending objects owned by this user will be assigned to the `%s` super admin in the system. The delete option will delete the user's repositories!") % (c.first_admin.full_name)}</p>
154 <p class="help-block">${_("When selecting the detach option, the depending objects owned by this user will be assigned to the `%s` super admin in the system. The delete option will delete the user's repositories!") % (c.first_admin.full_name)}</p>
155 %endif
155 %endif
156 </span>
156 </span>
157 </div>
157 </div>
158
158
159 ${h.end_form()}
159 ${h.end_form()}
160 </div>
160 </div>
161 </div>
161 </div>
@@ -1,176 +1,177 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"><div class="user_auth_tokens truncate autoexpand"><code>${auth_token.api_key}</code></div></td>
23 <td class="truncate-wrap td-authtoken"><div class="user_auth_tokens truncate autoexpand"><code>${auth_token.api_key}</code></div></td>
24 <td class="td">${auth_token.scope_humanized}</td>
24 <td class="td">${auth_token.scope_humanized}</td>
25 <td class="td-wrap">${auth_token.description}</td>
25 <td class="td-wrap">${auth_token.description}</td>
26 <td class="td-tags">
26 <td class="td-tags">
27 <span class="tag disabled">${auth_token.role_humanized}</span>
27 <span class="tag disabled">${auth_token.role_humanized}</span>
28 </td>
28 </td>
29 <td class="td-exp">
29 <td class="td-exp">
30 %if auth_token.expires == -1:
30 %if auth_token.expires == -1:
31 ${_('never')}
31 ${_('never')}
32 %else:
32 %else:
33 %if auth_token.expired:
33 %if auth_token.expired:
34 <span style="text-decoration: line-through">${h.age_component(h.time_to_utcdatetime(auth_token.expires))}</span>
34 <span style="text-decoration: line-through">${h.age_component(h.time_to_utcdatetime(auth_token.expires))}</span>
35 %else:
35 %else:
36 ${h.age_component(h.time_to_utcdatetime(auth_token.expires))}
36 ${h.age_component(h.time_to_utcdatetime(auth_token.expires))}
37 %endif
37 %endif
38 %endif
38 %endif
39 </td>
39 </td>
40 <td class="td-action">
40 <td class="td-action">
41 ${h.secure_form(h.route_path('edit_user_auth_tokens_delete', user_id=c.user.user_id), request=request)}
41 ${h.secure_form(h.route_path('edit_user_auth_tokens_delete', user_id=c.user.user_id), request=request)}
42 ${h.hidden('del_auth_token', auth_token.user_api_key_id)}
42 ${h.hidden('del_auth_token', auth_token.user_api_key_id)}
43 <button class="btn btn-link btn-danger" type="submit"
43 <button class="btn btn-link btn-danger" type="submit"
44 onclick="return confirm('${_('Confirm to remove this auth token: %s') % auth_token.token_obfuscated}');">
44 onclick="return confirm('${_('Confirm to remove this auth token: %s') % auth_token.token_obfuscated}');">
45 ${_('Delete')}
45 ${_('Delete')}
46 </button>
46 </button>
47 ${h.end_form()}
47 ${h.end_form()}
48 </td>
48 </td>
49 </tr>
49 </tr>
50 %endfor
50 %endfor
51 %else:
51 %else:
52 <tr><td><div class="ip">${_('No additional auth tokens specified')}</div></td></tr>
52 <tr><td><div class="ip">${_('No additional auth tokens specified')}</div></td></tr>
53 %endif
53 %endif
54 </table>
54 </table>
55 </div>
55 </div>
56
56
57 <div class="user_auth_tokens">
57 <div class="user_auth_tokens">
58 ${h.secure_form(h.route_path('edit_user_auth_tokens_add', user_id=c.user.user_id), request=request)}
58 ${h.secure_form(h.route_path('edit_user_auth_tokens_add', user_id=c.user.user_id), request=request)}
59 <div class="form form-vertical">
59 <div class="form form-vertical">
60 <!-- fields -->
60 <!-- fields -->
61 <div class="fields">
61 <div class="fields">
62 <div class="field">
62 <div class="field">
63 <div class="label">
63 <div class="label">
64 <label for="new_email">${_('New authentication token')}:</label>
64 <label for="new_email">${_('New authentication token')}:</label>
65 </div>
65 </div>
66 <div class="input">
66 <div class="input">
67 ${h.text('description', class_='medium', placeholder=_('Description'))}
67 ${h.text('description', class_='medium', placeholder=_('Description'))}
68 ${h.hidden('lifetime')}
68 ${h.hidden('lifetime')}
69 ${h.select('role', '', c.role_options)}
69 ${h.select('role', '', c.role_options)}
70
70
71 % if c.allow_scoped_tokens:
71 % if c.allow_scoped_tokens:
72 ${h.hidden('scope_repo_id')}
72 ${h.hidden('scope_repo_id')}
73 % else:
73 % else:
74 ${h.select('scope_repo_id_disabled', '', ['Scopes available in EE edition'], disabled='disabled')}
74 ${h.select('scope_repo_id_disabled', '', ['Scopes available in EE edition'], disabled='disabled')}
75 % endif
75 % endif
76 </div>
76 </div>
77 <p class="help-block">
77 <p class="help-block">
78 ${_('Repository scope works only with tokens with VCS type.')}
78 ${_('Repository scope works only with tokens with VCS type.')}
79 </p>
79 </p>
80 </div>
80 </div>
81 <div class="buttons">
81 <div class="buttons">
82 ${h.submit('save',_('Add'),class_="btn")}
82 ${h.submit('save',_('Add'),class_="btn")}
83 ${h.reset('reset',_('Reset'),class_="btn")}
83 ${h.reset('reset',_('Reset'),class_="btn")}
84 </div>
84 </div>
85 </div>
85 </div>
86 </div>
86 </div>
87 ${h.end_form()}
87 ${h.end_form()}
88 </div>
88 </div>
89 </div>
89 </div>
90 </div>
90 </div>
91
91
92 <script>
92 <script>
93
93
94 $(document).ready(function(){
94 $(document).ready(function(){
95
95 var select2Options = {
96 var select2Options = {
96 'containerCssClass': "drop-menu",
97 'containerCssClass': "drop-menu",
97 'dropdownCssClass': "drop-menu-dropdown",
98 'dropdownCssClass': "drop-menu-dropdown",
98 'dropdownAutoWidth': true
99 'dropdownAutoWidth': true
99 };
100 };
100 $("#role").select2(select2Options);
101 $("#role").select2(select2Options);
101
102
102 var preloadData = {
103 var preloadData = {
103 results: [
104 results: [
104 % for entry in c.lifetime_values:
105 % for entry in c.lifetime_values:
105 {id:${entry[0]}, text:"${entry[1]}"}${'' if loop.last else ','}
106 {id:${entry[0]}, text:"${entry[1]}"}${'' if loop.last else ','}
106 % endfor
107 % endfor
107 ]
108 ]
108 };
109 };
109
110
110 $("#lifetime").select2({
111 $("#lifetime").select2({
111 containerCssClass: "drop-menu",
112 containerCssClass: "drop-menu",
112 dropdownCssClass: "drop-menu-dropdown",
113 dropdownCssClass: "drop-menu-dropdown",
113 dropdownAutoWidth: true,
114 dropdownAutoWidth: true,
114 data: preloadData,
115 data: preloadData,
115 placeholder: "${_('Select or enter expiration date')}",
116 placeholder: "${_('Select or enter expiration date')}",
116 query: function(query) {
117 query: function(query) {
117 feedLifetimeOptions(query, preloadData);
118 feedLifetimeOptions(query, preloadData);
118 }
119 }
119 });
120 });
120
121
121
122
122 var repoFilter = function(data) {
123 var repoFilter = function(data) {
123 var results = [];
124 var results = [];
124
125
125 if (!data.results[0]) {
126 if (!data.results[0]) {
126 return data
127 return data
127 }
128 }
128
129
129 $.each(data.results[0].children, function() {
130 $.each(data.results[0].children, function() {
130 // replace name to ID for submision
131 // replace name to ID for submision
131 this.id = this.obj.repo_id;
132 this.id = this.obj.repo_id;
132 results.push(this);
133 results.push(this);
133 });
134 });
134
135
135 data.results[0].children = results;
136 data.results[0].children = results;
136 return data;
137 return data;
137 };
138 };
138
139
139 $("#scope_repo_id_disabled").select2(select2Options);
140 $("#scope_repo_id_disabled").select2(select2Options);
140
141
141 $("#scope_repo_id").select2({
142 $("#scope_repo_id").select2({
142 cachedDataSource: {},
143 cachedDataSource: {},
143 minimumInputLength: 2,
144 minimumInputLength: 2,
144 placeholder: "${_('repository scope')}",
145 placeholder: "${_('repository scope')}",
145 dropdownAutoWidth: true,
146 dropdownAutoWidth: true,
146 containerCssClass: "drop-menu",
147 containerCssClass: "drop-menu",
147 dropdownCssClass: "drop-menu-dropdown",
148 dropdownCssClass: "drop-menu-dropdown",
148 formatResult: formatResult,
149 formatResult: formatResult,
149 query: $.debounce(250, function(query){
150 query: $.debounce(250, function(query){
150 self = this;
151 self = this;
151 var cacheKey = query.term;
152 var cacheKey = query.term;
152 var cachedData = self.cachedDataSource[cacheKey];
153 var cachedData = self.cachedDataSource[cacheKey];
153
154
154 if (cachedData) {
155 if (cachedData) {
155 query.callback({results: cachedData.results});
156 query.callback({results: cachedData.results});
156 } else {
157 } else {
157 $.ajax({
158 $.ajax({
158 url: pyroutes.url('repo_list_data'),
159 url: pyroutes.url('repo_list_data'),
159 data: {'query': query.term},
160 data: {'query': query.term},
160 dataType: 'json',
161 dataType: 'json',
161 type: 'GET',
162 type: 'GET',
162 success: function(data) {
163 success: function(data) {
163 data = repoFilter(data);
164 data = repoFilter(data);
164 self.cachedDataSource[cacheKey] = data;
165 self.cachedDataSource[cacheKey] = data;
165 query.callback({results: data.results});
166 query.callback({results: data.results});
166 },
167 },
167 error: function(data, textStatus, errorThrown) {
168 error: function(data, textStatus, errorThrown) {
168 alert("Error while fetching entries.\nError code {0} ({1}).".format(data.status, data.statusText));
169 alert("Error while fetching entries.\nError code {0} ({1}).".format(data.status, data.statusText));
169 }
170 }
170 })
171 })
171 }
172 }
172 })
173 })
173 });
174 });
174
175
175 });
176 });
176 </script>
177 </script>
@@ -1,2 +1,2 b''
1 <%namespace name="dpb" file="/base/default_perms_box.mako"/>
1 <%namespace name="dpb" file="/base/default_perms_box.mako"/>
2 ${dpb.default_perms_box(h.url('edit_user_global_perms', user_id=c.user.user_id))}
2 ${dpb.default_perms_box(form_url=h.route_path('user_edit_global_perms_update', user_id=c.user.user_id))}
@@ -1,147 +1,147 b''
1 ## -*- coding: utf-8 -*-
1 ## -*- coding: utf-8 -*-
2
2
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 groups administration')}</h3>
6 <h3 class="panel-title">${_('User groups administration')}</h3>
7 </div>
7 </div>
8 <div class="panel-body">
8 <div class="panel-body">
9 <div class="fields">
9 <div class="fields">
10 <div class="field">
10 <div class="field">
11 <div class="label label-checkbox">
11 <div class="label label-checkbox">
12 <label for="users_group_active">${_('Add `%s` to user group') % c.user.username}:</label>
12 <label for="users_group_active">${_('Add `%s` to user group') % c.user.username}:</label>
13 </div>
13 </div>
14 <div class="input">
14 <div class="input">
15 ${h.text('add_user_to_group', placeholder="user group name", class_="medium")}
15 ${h.text('add_user_to_group', placeholder="user group name", class_="medium")}
16 </div>
16 </div>
17
17
18 </div>
18 </div>
19 </div>
19 </div>
20
20
21 <div class="groups_management">
21 <div class="groups_management">
22 ${h.secure_form(h.route_path('edit_user_groups_management_updates', user_id=c.user.user_id), request=request)}
22 ${h.secure_form(h.route_path('edit_user_groups_management_updates', user_id=c.user.user_id), request=request)}
23 <div id="repos_list_wrap">
23 <div id="repos_list_wrap">
24 <table id="user_group_list_table" class="display"></table>
24 <table id="user_group_list_table" class="display"></table>
25 </div>
25 </div>
26 <div class="buttons">
26 <div class="buttons">
27 ${h.submit('save',_('Save'),class_="btn")}
27 ${h.submit('save',_('Save'),class_="btn")}
28 </div>
28 </div>
29 ${h.end_form()}
29 ${h.end_form()}
30 </div>
30 </div>
31 </div>
31 </div>
32 </div>
32 </div>
33 <script>
33 <script>
34 var api;
34 var api;
35 $(document).ready(function() {
35 $(document).ready(function() {
36
36
37 var get_datatable_count = function(){
37 var get_datatable_count = function(){
38 $('#user_group_count').text(api.page.info().recordsDisplay);
38 $('#user_group_count').text(api.page.info().recordsDisplay);
39 };
39 };
40
40
41 $('#user_group_list_table').on('click', 'a.editor_remove', function (e) {
41 $('#user_group_list_table').on('click', 'a.editor_remove', function (e) {
42 e.preventDefault();
42 e.preventDefault();
43 var row = api.row($(this).closest('tr'));
43 var row = api.row($(this).closest('tr'));
44 row.remove().draw();
44 row.remove().draw();
45 } );
45 } );
46
46
47 $('#user_group_list_table').DataTable({
47 $('#user_group_list_table').DataTable({
48 data: ${c.groups|n},
48 data: ${c.groups|n},
49 dom: 'rtp',
49 dom: 'rtp',
50 pageLength: ${c.visual.admin_grid_items},
50 pageLength: ${c.visual.admin_grid_items},
51 order: [[ 0, "asc" ]],
51 order: [[ 0, "asc" ]],
52 columns: [
52 columns: [
53 { data: {"_": "group_name",
53 { data: {"_": "group_name",
54 "sort": "group_name"}, title: "${_('Name')}", className: "td-componentname," ,
54 "sort": "group_name"}, title: "${_('Name')}", className: "td-componentname," ,
55 render: function (data,type,full,meta)
55 render: function (data,type,full,meta)
56 {return '<div><i class="icon-group" title="User group">'+data+'</i></div>'}},
56 {return '<div><i class="icon-group" title="User group">'+data+'</i></div>'}},
57
57
58 { data: {"_": "group_description",
58 { data: {"_": "group_description",
59 "sort": "group_description"}, title: "${_('Description')}", className: "td-description" },
59 "sort": "group_description"}, title: "${_('Description')}", className: "td-description" },
60 { data: {"_": "users_group_id"}, className: "td-user",
60 { data: {"_": "users_group_id"}, className: "td-user",
61 render: function (data,type,full,meta)
61 render: function (data,type,full,meta)
62 {return '<input type="hidden" name="users_group_id" value="'+data+'">'}},
62 {return '<input type="hidden" name="users_group_id" value="'+data+'">'}},
63 { data: {"_": "active",
63 { data: {"_": "active",
64 "sort": "active"}, title: "${_('Active')}", className: "td-active", className: "td-number"},
64 "sort": "active"}, title: "${_('Active')}", className: "td-active"},
65 { data: {"_": "owner_data"}, title: "${_('Owner')}", className: "td-user",
65 { data: {"_": "owner_data"}, title: "${_('Owner')}", className: "td-user",
66 render: function (data,type,full,meta)
66 render: function (data,type,full,meta)
67 {return '<div class="rc-user tooltip">'+
67 {return '<div class="rc-user tooltip">'+
68 '<img class="gravatar" src="'+ data.owner_icon +'" height="16" width="16">'+
68 '<img class="gravatar" src="'+ data.owner_icon +'" height="16" width="16">'+
69 data.owner +'</div>'
69 data.owner +'</div>'
70 }
70 }
71 },
71 },
72 { data: null,
72 { data: null,
73 title: "${_('Action')}",
73 title: "${_('Action')}",
74 className: "td-action",
74 className: "td-action",
75 defaultContent: '<a href="" class="btn btn-link btn-danger">Delete</a>'
75 defaultContent: '-'
76 },
76 }
77 ],
77 ],
78 language: {
78 language: {
79 paginate: DEFAULT_GRID_PAGINATION,
79 paginate: DEFAULT_GRID_PAGINATION,
80 emptyTable: _gettext("No user groups available yet.")
80 emptyTable: _gettext("No user groups available yet.")
81 },
81 },
82 "initComplete": function( settings, json ) {
82 "initComplete": function( settings, json ) {
83 var data_grid = $('#user_group_list_table').dataTable();
83 var data_grid = $('#user_group_list_table').dataTable();
84 api = data_grid.api();
84 api = data_grid.api();
85 get_datatable_count();
85 get_datatable_count();
86 }
86 }
87 });
87 });
88
88
89 // update the counter when doing search
89 // update the counter when doing search
90 $('#user_group_list_table').on( 'search.dt', function (e,settings) {
90 $('#user_group_list_table').on( 'search.dt', function (e,settings) {
91 get_datatable_count();
91 get_datatable_count();
92 });
92 });
93
93
94 // filter, filter both grids
94 // filter, filter both grids
95 $('#q_filter').on( 'keyup', function () {
95 $('#q_filter').on( 'keyup', function () {
96 var user_api = $('#user_group_list_table').dataTable().api();
96 var user_api = $('#user_group_list_table').dataTable().api();
97 user_api
97 user_api
98 .columns(0)
98 .columns(0)
99 .search(this.value)
99 .search(this.value)
100 .draw();
100 .draw();
101 });
101 });
102
102
103 // refilter table if page load via back button
103 // refilter table if page load via back button
104 $("#q_filter").trigger('keyup');
104 $("#q_filter").trigger('keyup');
105
105
106 });
106 });
107
107
108 $('#language').select2({
108 $('#language').select2({
109 'containerCssClass': "drop-menu",
109 'containerCssClass': "drop-menu",
110 'dropdownCssClass': "drop-menu-dropdown",
110 'dropdownCssClass': "drop-menu-dropdown",
111 'dropdownAutoWidth': true
111 'dropdownAutoWidth': true
112 });
112 });
113
113
114
114
115
115
116 $(document).ready(function(){
116 $(document).ready(function(){
117 $("#group_parent_id").select2({
117 $("#group_parent_id").select2({
118 'containerCssClass': "drop-menu",
118 'containerCssClass': "drop-menu",
119 'dropdownCssClass': "drop-menu-dropdown",
119 'dropdownCssClass': "drop-menu-dropdown",
120 'dropdownAutoWidth': true
120 'dropdownAutoWidth': true
121 });
121 });
122
122
123 $('#add_user_to_group').autocomplete({
123 $('#add_user_to_group').autocomplete({
124 serviceUrl: pyroutes.url('user_group_autocomplete_data'),
124 serviceUrl: pyroutes.url('user_group_autocomplete_data'),
125 minChars:2,
125 minChars:2,
126 maxHeight:400,
126 maxHeight:400,
127 width:300,
127 width:300,
128 deferRequestBy: 300, //miliseconds
128 deferRequestBy: 300, //miliseconds
129 showNoSuggestionNotice: true,
129 showNoSuggestionNotice: true,
130 params: { user_groups:true },
130 params: { user_groups:true },
131 formatResult: autocompleteFormatResult,
131 formatResult: autocompleteFormatResult,
132 lookupFilter: autocompleteFilterResult,
132 lookupFilter: autocompleteFilterResult,
133 onSelect: function(element, suggestion){
133 onSelect: function(element, suggestion){
134 var owner = {owner_icon: suggestion.owner_icon, owner:suggestion.owner};
134 var owner = {owner_icon: suggestion.owner_icon, owner:suggestion.owner};
135 api.row.add(
135 api.row.add(
136 {"active": suggestion.active,
136 {"active": suggestion.active,
137 "owner_data": owner,
137 "owner_data": owner,
138 "users_group_id": suggestion.id,
138 "users_group_id": suggestion.id,
139 "group_description": suggestion.description,
139 "group_description": suggestion.description,
140 "group_name": suggestion.value}).draw();
140 "group_name": suggestion.value}).draw();
141 }
141 }
142 });
142 });
143 })
143 })
144
144
145 </script>
145 </script>
146
146
147
147
@@ -1,150 +1,150 b''
1 <%namespace name="base" file="/base/base.mako"/>
1 <%namespace name="base" file="/base/base.mako"/>
2
2
3 <div class="panel panel-default user-profile">
3 <div class="panel panel-default user-profile">
4 <div class="panel-heading">
4 <div class="panel-heading">
5 <h3 class="panel-title">${_('User Profile')}</h3>
5 <h3 class="panel-title">${_('User Profile')}</h3>
6 </div>
6 </div>
7 <div class="panel-body">
7 <div class="panel-body">
8 <div class="user-profile-content">
8 <div class="user-profile-content">
9 ${h.secure_form(h.url('update_user', user_id=c.user.user_id),method='put', class_='form')}
9 ${h.secure_form(h.route_path('user_update', user_id=c.user.user_id), class_='form', request=request)}
10 <% readonly = None %>
10 <% readonly = None %>
11 <% disabled = "" %>
11 <% disabled = "" %>
12 %if c.extern_type != 'rhodecode':
12 %if c.extern_type != 'rhodecode':
13 <% readonly = "readonly" %>
13 <% readonly = "readonly" %>
14 <% disabled = " disabled" %>
14 <% disabled = " disabled" %>
15 <div class="infoform">
15 <div class="infoform">
16 <div class="fields">
16 <div class="fields">
17 <p>${_('This user was created from external source (%s). Editing some of the settings is limited.' % c.extern_type)}</p>
17 <p>${_('This user was created from external source (%s). Editing some of the settings is limited.' % c.extern_type)}</p>
18 </div>
18 </div>
19 </div>
19 </div>
20 %endif
20 %endif
21 <div class="form">
21 <div class="form">
22 <div class="fields">
22 <div class="fields">
23 <div class="field">
23 <div class="field">
24 <div class="label photo">
24 <div class="label photo">
25 ${_('Photo')}:
25 ${_('Photo')}:
26 </div>
26 </div>
27 <div class="input profile">
27 <div class="input profile">
28 %if c.visual.use_gravatar:
28 %if c.visual.use_gravatar:
29 ${base.gravatar(c.user.email, 100)}
29 ${base.gravatar(c.user.email, 100)}
30 <p class="help-block">${_('Change the avatar at')} <a href="http://gravatar.com">gravatar.com</a>.</p>
30 <p class="help-block">${_('Change the avatar at')} <a href="http://gravatar.com">gravatar.com</a>.</p>
31 %else:
31 %else:
32 ${base.gravatar(c.user.email, 20)}
32 ${base.gravatar(c.user.email, 20)}
33 ${_('Avatars are disabled')}
33 ${_('Avatars are disabled')}
34 %endif
34 %endif
35 </div>
35 </div>
36 </div>
36 </div>
37 <div class="field">
37 <div class="field">
38 <div class="label">
38 <div class="label">
39 ${_('Username')}:
39 ${_('Username')}:
40 </div>
40 </div>
41 <div class="input">
41 <div class="input">
42 ${h.text('username', class_='%s medium' % disabled, readonly=readonly)}
42 ${h.text('username', class_='%s medium' % disabled, readonly=readonly)}
43 </div>
43 </div>
44 </div>
44 </div>
45 <div class="field">
45 <div class="field">
46 <div class="label">
46 <div class="label">
47 <label for="name">${_('First Name')}:</label>
47 <label for="name">${_('First Name')}:</label>
48 </div>
48 </div>
49 <div class="input">
49 <div class="input">
50 ${h.text('firstname', class_="medium")}
50 ${h.text('firstname', class_="medium")}
51 </div>
51 </div>
52 </div>
52 </div>
53
53
54 <div class="field">
54 <div class="field">
55 <div class="label">
55 <div class="label">
56 <label for="lastname">${_('Last Name')}:</label>
56 <label for="lastname">${_('Last Name')}:</label>
57 </div>
57 </div>
58 <div class="input">
58 <div class="input">
59 ${h.text('lastname', class_="medium")}
59 ${h.text('lastname', class_="medium")}
60 </div>
60 </div>
61 </div>
61 </div>
62
62
63 <div class="field">
63 <div class="field">
64 <div class="label">
64 <div class="label">
65 <label for="email">${_('Email')}:</label>
65 <label for="email">${_('Email')}:</label>
66 </div>
66 </div>
67 <div class="input">
67 <div class="input">
68 ## we should be able to edit email !
68 ## we should be able to edit email !
69 ${h.text('email', class_="medium")}
69 ${h.text('email', class_="medium")}
70 </div>
70 </div>
71 </div>
71 </div>
72 <div class="field">
72 <div class="field">
73 <div class="label">
73 <div class="label">
74 ${_('New Password')}:
74 ${_('New Password')}:
75 </div>
75 </div>
76 <div class="input">
76 <div class="input">
77 ${h.password('new_password',class_='%s medium' % disabled,autocomplete="off",readonly=readonly)}
77 ${h.password('new_password',class_='%s medium' % disabled,autocomplete="off",readonly=readonly)}
78 </div>
78 </div>
79 </div>
79 </div>
80 <div class="field">
80 <div class="field">
81 <div class="label">
81 <div class="label">
82 ${_('New Password Confirmation')}:
82 ${_('New Password Confirmation')}:
83 </div>
83 </div>
84 <div class="input">
84 <div class="input">
85 ${h.password('password_confirmation',class_="%s medium" % disabled,autocomplete="off",readonly=readonly)}
85 ${h.password('password_confirmation',class_="%s medium" % disabled,autocomplete="off",readonly=readonly)}
86 </div>
86 </div>
87 </div>
87 </div>
88 <div class="field">
88 <div class="field">
89 <div class="label-text">
89 <div class="label-text">
90 ${_('Active')}:
90 ${_('Active')}:
91 </div>
91 </div>
92 <div class="input user-checkbox">
92 <div class="input user-checkbox">
93 ${h.checkbox('active',value=True)}
93 ${h.checkbox('active',value=True)}
94 </div>
94 </div>
95 </div>
95 </div>
96 <div class="field">
96 <div class="field">
97 <div class="label-text">
97 <div class="label-text">
98 ${_('Super Admin')}:
98 ${_('Super Admin')}:
99 </div>
99 </div>
100 <div class="input user-checkbox">
100 <div class="input user-checkbox">
101 ${h.checkbox('admin',value=True)}
101 ${h.checkbox('admin',value=True)}
102 </div>
102 </div>
103 </div>
103 </div>
104 <div class="field">
104 <div class="field">
105 <div class="label-text">
105 <div class="label-text">
106 ${_('Source of Record')}:
106 ${_('Source of Record')}:
107 </div>
107 </div>
108 <div class="input">
108 <div class="input">
109 <p>${c.extern_type}</p>
109 <p>${c.extern_type}</p>
110 ${h.hidden('extern_type', readonly="readonly")}
110 ${h.hidden('extern_type', readonly="readonly")}
111 </div>
111 </div>
112 </div>
112 </div>
113 <div class="field">
113 <div class="field">
114 <div class="label-text">
114 <div class="label-text">
115 ${_('Name in Source of Record')}:
115 ${_('Name in Source of Record')}:
116 </div>
116 </div>
117 <div class="input">
117 <div class="input">
118 <p>${c.extern_name}</p>
118 <p>${c.extern_name}</p>
119 ${h.hidden('extern_name', readonly="readonly")}
119 ${h.hidden('extern_name', readonly="readonly")}
120 </div>
120 </div>
121 </div>
121 </div>
122 <div class="field">
122 <div class="field">
123 <div class="label">
123 <div class="label">
124 ${_('Language')}:
124 ${_('Language')}:
125 </div>
125 </div>
126 <div class="input">
126 <div class="input">
127 ## allowed_languages is defined in the users.py
127 ## allowed_languages is defined in the users.py
128 ## c.language comes from base.py as a default language
128 ## c.language comes from base.py as a default language
129 ${h.select('language', c.language, c.allowed_languages)}
129 ${h.select('language', c.language, c.allowed_languages)}
130 <p class="help-block">${h.literal(_('Help translate %(rc_link)s into your language.') % {'rc_link': h.link_to('RhodeCode Enterprise', h.route_url('rhodecode_translations'))})}</p>
130 <p class="help-block">${h.literal(_('Help translate %(rc_link)s into your language.') % {'rc_link': h.link_to('RhodeCode Enterprise', h.route_url('rhodecode_translations'))})}</p>
131 </div>
131 </div>
132 </div>
132 </div>
133 <div class="buttons">
133 <div class="buttons">
134 ${h.submit('save', _('Save'), class_="btn")}
134 ${h.submit('save', _('Save'), class_="btn")}
135 ${h.reset('reset', _('Reset'), class_="btn")}
135 ${h.reset('reset', _('Reset'), class_="btn")}
136 </div>
136 </div>
137 </div>
137 </div>
138 </div>
138 </div>
139 ${h.end_form()}
139 ${h.end_form()}
140 </div>
140 </div>
141 </div>
141 </div>
142 </div>
142 </div>
143
143
144 <script>
144 <script>
145 $('#language').select2({
145 $('#language').select2({
146 'containerCssClass': "drop-menu",
146 'containerCssClass': "drop-menu",
147 'dropdownCssClass': "drop-menu-dropdown",
147 'dropdownCssClass': "drop-menu-dropdown",
148 'dropdownAutoWidth': true
148 'dropdownAutoWidth': true
149 });
149 });
150 </script>
150 </script>
@@ -1,120 +1,120 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 ${_('Users administration')}
5 ${_('Users administration')}
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
10
11 <%def name="breadcrumbs_links()">
11 <%def name="breadcrumbs_links()">
12 <input class="q_filter_box" id="q_filter" size="15" type="text" name="filter" placeholder="${_('quick filter...')}" value=""/>
12 <input class="q_filter_box" id="q_filter" size="15" type="text" name="filter" placeholder="${_('quick filter...')}" value=""/>
13 ${h.link_to(_('Admin'),h.route_path('admin_home'))} &raquo; <span id="user_count">0</span>
13 ${h.link_to(_('Admin'),h.route_path('admin_home'))} &raquo; <span id="user_count">0</span>
14 </%def>
14 </%def>
15
15
16 <%def name="menu_bar_nav()">
16 <%def name="menu_bar_nav()">
17 ${self.menu_items(active='admin')}
17 ${self.menu_items(active='admin')}
18 </%def>
18 </%def>
19
19
20 <%def name="main()">
20 <%def name="main()">
21
21
22 <div class="box">
22 <div class="box">
23
23
24 <div class="title">
24 <div class="title">
25 ${self.breadcrumbs()}
25 ${self.breadcrumbs()}
26 <ul class="links">
26 <ul class="links">
27 <li>
27 <li>
28 <a href="${h.url('new_user')}" class="btn btn-small btn-success">${_(u'Add User')}</a>
28 <a href="${h.route_path('users_new')}" class="btn btn-small btn-success">${_(u'Add User')}</a>
29 </li>
29 </li>
30 </ul>
30 </ul>
31 </div>
31 </div>
32
32
33 <div id="repos_list_wrap">
33 <div id="repos_list_wrap">
34 <table id="user_list_table" class="display"></table>
34 <table id="user_list_table" class="display"></table>
35 </div>
35 </div>
36 </div>
36 </div>
37
37
38 <script type="text/javascript">
38 <script type="text/javascript">
39
39
40 $(document).ready(function() {
40 $(document).ready(function() {
41 var $userListTable = $('#user_list_table');
41 var $userListTable = $('#user_list_table');
42
42
43 var getDatatableCount = function(){
43 var getDatatableCount = function(){
44 var table = $userListTable.dataTable();
44 var table = $userListTable.dataTable();
45 var page = table.api().page.info();
45 var page = table.api().page.info();
46 var active = page.recordsDisplay;
46 var active = page.recordsDisplay;
47 var total = page.recordsTotal;
47 var total = page.recordsTotal;
48
48
49 var _text = _gettext("{0} out of {1} users").format(active, total);
49 var _text = _gettext("{0} out of {1} users").format(active, total);
50 $('#user_count').text(_text);
50 $('#user_count').text(_text);
51 };
51 };
52
52
53 // user list
53 // user list
54 $userListTable.DataTable({
54 $userListTable.DataTable({
55 processing: true,
55 processing: true,
56 serverSide: true,
56 serverSide: true,
57 ajax: "${h.route_path('users_data')}",
57 ajax: "${h.route_path('users_data')}",
58 dom: 'rtp',
58 dom: 'rtp',
59 pageLength: ${c.visual.admin_grid_items},
59 pageLength: ${c.visual.admin_grid_items},
60 order: [[ 0, "asc" ]],
60 order: [[ 0, "asc" ]],
61 columns: [
61 columns: [
62 { data: {"_": "username",
62 { data: {"_": "username",
63 "sort": "username"}, title: "${_('Username')}", className: "td-user" },
63 "sort": "username"}, title: "${_('Username')}", className: "td-user" },
64 { data: {"_": "email",
64 { data: {"_": "email",
65 "sort": "email"}, title: "${_('Email')}", className: "td-email" },
65 "sort": "email"}, title: "${_('Email')}", className: "td-email" },
66 { data: {"_": "first_name",
66 { data: {"_": "first_name",
67 "sort": "first_name"}, title: "${_('First Name')}", className: "td-user" },
67 "sort": "first_name"}, title: "${_('First Name')}", className: "td-user" },
68 { data: {"_": "last_name",
68 { data: {"_": "last_name",
69 "sort": "last_name"}, title: "${_('Last Name')}", className: "td-user" },
69 "sort": "last_name"}, title: "${_('Last Name')}", className: "td-user" },
70 { data: {"_": "last_activity",
70 { data: {"_": "last_activity",
71 "sort": "last_activity",
71 "sort": "last_activity",
72 "type": Number}, title: "${_('Last activity')}", className: "td-time" },
72 "type": Number}, title: "${_('Last activity')}", className: "td-time" },
73 { data: {"_": "active",
73 { data: {"_": "active",
74 "sort": "active"}, title: "${_('Active')}", className: "td-active" },
74 "sort": "active"}, title: "${_('Active')}", className: "td-active" },
75 { data: {"_": "admin",
75 { data: {"_": "admin",
76 "sort": "admin"}, title: "${_('Admin')}", className: "td-admin" },
76 "sort": "admin"}, title: "${_('Admin')}", className: "td-admin" },
77 { data: {"_": "extern_type",
77 { data: {"_": "extern_type",
78 "sort": "extern_type"}, title: "${_('Auth type')}", className: "td-type" },
78 "sort": "extern_type"}, title: "${_('Auth type')}", className: "td-type" },
79 { data: {"_": "action",
79 { data: {"_": "action",
80 "sort": "action"}, title: "${_('Action')}", className: "td-action", orderable: false }
80 "sort": "action"}, title: "${_('Action')}", className: "td-action", orderable: false }
81 ],
81 ],
82 language: {
82 language: {
83 paginate: DEFAULT_GRID_PAGINATION,
83 paginate: DEFAULT_GRID_PAGINATION,
84 sProcessing: _gettext('loading...'),
84 sProcessing: _gettext('loading...'),
85 emptyTable: _gettext("No users available yet.")
85 emptyTable: _gettext("No users available yet.")
86 },
86 },
87
87
88 "createdRow": function ( row, data, index ) {
88 "createdRow": function ( row, data, index ) {
89 if (!data['active_raw']){
89 if (!data['active_raw']){
90 $(row).addClass('closed')
90 $(row).addClass('closed')
91 }
91 }
92 }
92 }
93 });
93 });
94
94
95 $userListTable.on('xhr.dt', function(e, settings, json, xhr){
95 $userListTable.on('xhr.dt', function(e, settings, json, xhr){
96 $userListTable.css('opacity', 1);
96 $userListTable.css('opacity', 1);
97 });
97 });
98
98
99 $userListTable.on('preXhr.dt', function(e, settings, data){
99 $userListTable.on('preXhr.dt', function(e, settings, data){
100 $userListTable.css('opacity', 0.3);
100 $userListTable.css('opacity', 0.3);
101 });
101 });
102
102
103 // refresh counters on draw
103 // refresh counters on draw
104 $userListTable.on('draw.dt', function(){
104 $userListTable.on('draw.dt', function(){
105 getDatatableCount();
105 getDatatableCount();
106 });
106 });
107
107
108 // filter
108 // filter
109 $('#q_filter').on('keyup',
109 $('#q_filter').on('keyup',
110 $.debounce(250, function() {
110 $.debounce(250, function() {
111 $userListTable.DataTable().search(
111 $userListTable.DataTable().search(
112 $('#q_filter').val()
112 $('#q_filter').val()
113 ).draw();
113 ).draw();
114 })
114 })
115 );
115 );
116
116
117 });
117 });
118 </script>
118 </script>
119
119
120 </%def>
120 </%def>
@@ -1,268 +1,268 b''
1 ## snippet for displaying permissions overview for users
1 ## snippet for displaying permissions overview for users
2 ## usage:
2 ## usage:
3 ## <%namespace name="p" file="/base/perms_summary.mako"/>
3 ## <%namespace name="p" file="/base/perms_summary.mako"/>
4 ## ${p.perms_summary(c.perm_user.permissions)}
4 ## ${p.perms_summary(c.perm_user.permissions)}
5
5
6 <%def name="perms_summary(permissions, show_all=False, actions=True, side_link=None)">
6 <%def name="perms_summary(permissions, show_all=False, actions=True, side_link=None)">
7 <div id="perms" class="table fields">
7 <div id="perms" class="table fields">
8 %for section in sorted(permissions.keys()):
8 %for section in sorted(permissions.keys()):
9 <div class="panel panel-default">
9 <div class="panel panel-default">
10 <div class="panel-heading">
10 <div class="panel-heading">
11 <h3 class="panel-title">${section.replace("_"," ").capitalize()}</h3>
11 <h3 class="panel-title">${section.replace("_"," ").capitalize()}</h3>
12 % if side_link:
12 % if side_link:
13 <div class="pull-right">
13 <div class="pull-right">
14 <a href="${side_link}">${_('in JSON format')}</a>
14 <a href="${side_link}">${_('in JSON format')}</a>
15 </div>
15 </div>
16 % endif
16 % endif
17 </div>
17 </div>
18 <div class="panel-body">
18 <div class="panel-body">
19 <div class="perms_section_head field">
19 <div class="perms_section_head field">
20 <div class="radios">
20 <div class="radios">
21 %if section != 'global':
21 %if section != 'global':
22 <span class="permissions_boxes">
22 <span class="permissions_boxes">
23 <span class="desc">${_('show')}: </span>
23 <span class="desc">${_('show')}: </span>
24 ${h.checkbox('perms_filter_none_%s' % section, 'none', 'checked', class_='perm_filter filter_%s' % section, section=section, perm_type='none')} <label for="${'perms_filter_none_%s' % section}"><span class="perm_tag none">${_('none')}</span></label>
24 ${h.checkbox('perms_filter_none_%s' % section, 'none', 'checked', class_='perm_filter filter_%s' % section, section=section, perm_type='none')} <label for="${'perms_filter_none_%s' % section}"><span class="perm_tag none">${_('none')}</span></label>
25 ${h.checkbox('perms_filter_read_%s' % section, 'read', 'checked', class_='perm_filter filter_%s' % section, section=section, perm_type='read')} <label for="${'perms_filter_read_%s' % section}"><span class="perm_tag read">${_('read')}</span></label>
25 ${h.checkbox('perms_filter_read_%s' % section, 'read', 'checked', class_='perm_filter filter_%s' % section, section=section, perm_type='read')} <label for="${'perms_filter_read_%s' % section}"><span class="perm_tag read">${_('read')}</span></label>
26 ${h.checkbox('perms_filter_write_%s' % section, 'write', 'checked', class_='perm_filter filter_%s' % section, section=section, perm_type='write')} <label for="${'perms_filter_write_%s' % section}"> <span class="perm_tag write">${_('write')}</span></label>
26 ${h.checkbox('perms_filter_write_%s' % section, 'write', 'checked', class_='perm_filter filter_%s' % section, section=section, perm_type='write')} <label for="${'perms_filter_write_%s' % section}"> <span class="perm_tag write">${_('write')}</span></label>
27 ${h.checkbox('perms_filter_admin_%s' % section, 'admin', 'checked', class_='perm_filter filter_%s' % section, section=section, perm_type='admin')} <label for="${'perms_filter_admin_%s' % section}"><span class="perm_tag admin">${_('admin')}</span></label>
27 ${h.checkbox('perms_filter_admin_%s' % section, 'admin', 'checked', class_='perm_filter filter_%s' % section, section=section, perm_type='admin')} <label for="${'perms_filter_admin_%s' % section}"><span class="perm_tag admin">${_('admin')}</span></label>
28 </span>
28 </span>
29 %endif
29 %endif
30 </div>
30 </div>
31 </div>
31 </div>
32 <div class="field">
32 <div class="field">
33 %if not permissions[section]:
33 %if not permissions[section]:
34 <p class="empty_data help-block">${_('No permissions defined')}</p>
34 <p class="empty_data help-block">${_('No permissions defined')}</p>
35 %else:
35 %else:
36 <div id='tbl_list_wrap_${section}'>
36 <div id='tbl_list_wrap_${section}'>
37 <table id="tbl_list_${section}" class="rctable">
37 <table id="tbl_list_${section}" class="rctable">
38 ## global permission box
38 ## global permission box
39 %if section == 'global':
39 %if section == 'global':
40 <thead>
40 <thead>
41 <tr>
41 <tr>
42 <th colspan="2" class="left">${_('Permission')}</th>
42 <th colspan="2" class="left">${_('Permission')}</th>
43 %if actions:
43 %if actions:
44 <th colspan="2">${_('Edit Permission')}</th>
44 <th colspan="2">${_('Edit Permission')}</th>
45 %endif
45 %endif
46 </thead>
46 </thead>
47 <tbody>
47 <tbody>
48
48
49 <%
49 <%
50 def get_section_perms(prefix, opts):
50 def get_section_perms(prefix, opts):
51 _selected = []
51 _selected = []
52 for op in opts:
52 for op in opts:
53 if op.startswith(prefix) and not op.startswith('hg.create.write_on_repogroup'):
53 if op.startswith(prefix) and not op.startswith('hg.create.write_on_repogroup'):
54 _selected.append(op)
54 _selected.append(op)
55 admin = 'hg.admin' in opts
55 admin = 'hg.admin' in opts
56 _selected_vals = [x.partition(prefix)[-1] for x in _selected]
56 _selected_vals = [x.partition(prefix)[-1] for x in _selected]
57 return admin, _selected_vals, _selected
57 return admin, _selected_vals, _selected
58 %>
58 %>
59
59
60 <%def name="glob(lbl, val, val_lbl=None, edit_url=None, edit_global_url=None)">
60 <%def name="glob(lbl, val, val_lbl=None, edit_url=None, edit_global_url=None)">
61 <tr>
61 <tr>
62 <td class="td-tags">
62 <td class="td-tags">
63 ${lbl}
63 ${lbl}
64 </td>
64 </td>
65 <td class="td-tags">
65 <td class="td-tags">
66 %if val[0]:
66 %if val[0]:
67 %if not val_lbl:
67 %if not val_lbl:
68 ## super admin case
68 ## super admin case
69 True
69 True
70 %else:
70 %else:
71 <span class="perm_tag admin">${val_lbl}.admin</span>
71 <span class="perm_tag admin">${val_lbl}.admin</span>
72 %endif
72 %endif
73 %else:
73 %else:
74 %if not val_lbl:
74 %if not val_lbl:
75 ${
75 ${
76 {'false': False,
76 {'false': False,
77 'true': True,
77 'true': True,
78 'none': False,
78 'none': False,
79 'repository': True}.get(val[1][0] if 0 < len(val[1]) else 'false')
79 'repository': True}.get(val[1][0] if 0 < len(val[1]) else 'false')
80 }
80 }
81 %else:
81 %else:
82 <span class="perm_tag ${val[1][0]}">${val_lbl}.${val[1][0]}</span>
82 <span class="perm_tag ${val[1][0]}">${val_lbl}.${val[1][0]}</span>
83 %endif
83 %endif
84 %endif
84 %endif
85 </td>
85 </td>
86 %if actions:
86 %if actions:
87
87
88 % if edit_url or edit_global_url:
88 % if edit_url or edit_global_url:
89
89
90 <td class="td-action">
90 <td class="td-action">
91 % if edit_url:
91 % if edit_url:
92 <a href="${edit_url}">${_('edit')}</a>
92 <a href="${edit_url}">${_('edit')}</a>
93 % else:
93 % else:
94 -
94 -
95 % endif
95 % endif
96 </td>
96 </td>
97
97
98 <td class="td-action">
98 <td class="td-action">
99 % if edit_global_url:
99 % if edit_global_url:
100 <a href="${edit_global_url}">${_('edit global')}</a>
100 <a href="${edit_global_url}">${_('edit global')}</a>
101 % else:
101 % else:
102 -
102 -
103 % endif
103 % endif
104 </td>
104 </td>
105
105
106 % else:
106 % else:
107 <td class="td-action"></td>
107 <td class="td-action"></td>
108 <td class="td-action">
108 <td class="td-action">
109 <a href="${h.route_path('admin_permissions_global')}">${_('edit global')}</a>
109 <a href="${h.route_path('admin_permissions_global')}">${_('edit global')}</a>
110 <td class="td-action">
110 <td class="td-action">
111 % endif
111 % endif
112
112
113 %endif
113 %endif
114 </tr>
114 </tr>
115 </%def>
115 </%def>
116
116
117 ${glob(_('Repository default permission'), get_section_perms('repository.', permissions[section]), 'repository',
117 ${glob(_('Repository default permission'), get_section_perms('repository.', permissions[section]), 'repository',
118 edit_url=None, edit_global_url=h.route_path('admin_permissions_object'))}
118 edit_url=None, edit_global_url=h.route_path('admin_permissions_object'))}
119
119
120 ${glob(_('Repository group default permission'), get_section_perms('group.', permissions[section]), 'group',
120 ${glob(_('Repository group default permission'), get_section_perms('group.', permissions[section]), 'group',
121 edit_url=None, edit_global_url=h.route_path('admin_permissions_object'))}
121 edit_url=None, edit_global_url=h.route_path('admin_permissions_object'))}
122
122
123 ${glob(_('User group default permission'), get_section_perms('usergroup.', permissions[section]), 'usergroup',
123 ${glob(_('User group default permission'), get_section_perms('usergroup.', permissions[section]), 'usergroup',
124 edit_url=None, edit_global_url=h.route_path('admin_permissions_object'))}
124 edit_url=None, edit_global_url=h.route_path('admin_permissions_object'))}
125
125
126 ${glob(_('Super admin'), get_section_perms('hg.admin', permissions[section]),
126 ${glob(_('Super admin'), get_section_perms('hg.admin', permissions[section]),
127 edit_url=h.url('edit_user', user_id=c.user.user_id, anchor='admin'), edit_global_url=None)}
127 edit_url=h.route_path('user_edit', user_id=c.user.user_id, _anchor='admin'), edit_global_url=None)}
128
128
129 ${glob(_('Inherit permissions'), get_section_perms('hg.inherit_default_perms.', permissions[section]),
129 ${glob(_('Inherit permissions'), get_section_perms('hg.inherit_default_perms.', permissions[section]),
130 edit_url=h.url('edit_user_global_perms', user_id=c.user.user_id), edit_global_url=None)}
130 edit_url=h.route_path('user_edit_global_perms', user_id=c.user.user_id), edit_global_url=None)}
131
131
132 ${glob(_('Create repositories'), get_section_perms('hg.create.', permissions[section]),
132 ${glob(_('Create repositories'), get_section_perms('hg.create.', permissions[section]),
133 edit_url=h.url('edit_user_global_perms', user_id=c.user.user_id), edit_global_url=h.route_path('admin_permissions_object'))}
133 edit_url=h.route_path('user_edit_global_perms', user_id=c.user.user_id), edit_global_url=h.route_path('admin_permissions_object'))}
134
134
135 ${glob(_('Fork repositories'), get_section_perms('hg.fork.', permissions[section]),
135 ${glob(_('Fork repositories'), get_section_perms('hg.fork.', permissions[section]),
136 edit_url=h.url('edit_user_global_perms', user_id=c.user.user_id), edit_global_url=h.route_path('admin_permissions_object'))}
136 edit_url=h.route_path('user_edit_global_perms', user_id=c.user.user_id), edit_global_url=h.route_path('admin_permissions_object'))}
137
137
138 ${glob(_('Create repository groups'), get_section_perms('hg.repogroup.create.', permissions[section]),
138 ${glob(_('Create repository groups'), get_section_perms('hg.repogroup.create.', permissions[section]),
139 edit_url=h.url('edit_user_global_perms', user_id=c.user.user_id), edit_global_url=h.route_path('admin_permissions_object'))}
139 edit_url=h.route_path('user_edit_global_perms', user_id=c.user.user_id), edit_global_url=h.route_path('admin_permissions_object'))}
140
140
141 ${glob(_('Create user groups'), get_section_perms('hg.usergroup.create.', permissions[section]),
141 ${glob(_('Create user groups'), get_section_perms('hg.usergroup.create.', permissions[section]),
142 edit_url=h.url('edit_user_global_perms', user_id=c.user.user_id), edit_global_url=h.route_path('admin_permissions_object'))}
142 edit_url=h.route_path('user_edit_global_perms', user_id=c.user.user_id), edit_global_url=h.route_path('admin_permissions_object'))}
143
143
144 </tbody>
144 </tbody>
145 %else:
145 %else:
146 ## none/read/write/admin permissions on groups/repos etc
146 ## none/read/write/admin permissions on groups/repos etc
147 <thead>
147 <thead>
148 <tr>
148 <tr>
149 <th>${_('Name')}</th>
149 <th>${_('Name')}</th>
150 <th>${_('Permission')}</th>
150 <th>${_('Permission')}</th>
151 %if actions:
151 %if actions:
152 <th>${_('Edit Permission')}</th>
152 <th>${_('Edit Permission')}</th>
153 %endif
153 %endif
154 </thead>
154 </thead>
155 <tbody class="section_${section}">
155 <tbody class="section_${section}">
156 <%
156 <%
157 def sorter(permissions):
157 def sorter(permissions):
158 def custom_sorter(item):
158 def custom_sorter(item):
159 ## read/write/admin
159 ## read/write/admin
160 section = item[1].split('.')[-1]
160 section = item[1].split('.')[-1]
161 section_importance = {'none': u'0',
161 section_importance = {'none': u'0',
162 'read': u'1',
162 'read': u'1',
163 'write':u'2',
163 'write':u'2',
164 'admin':u'3'}.get(section)
164 'admin':u'3'}.get(section)
165 ## sort by group importance+name
165 ## sort by group importance+name
166 return section_importance+item[0]
166 return section_importance+item[0]
167 return sorted(permissions, key=custom_sorter)
167 return sorted(permissions, key=custom_sorter)
168 %>
168 %>
169 %for k, section_perm in sorter(permissions[section].items()):
169 %for k, section_perm in sorter(permissions[section].items()):
170 %if section_perm.split('.')[-1] != 'none' or show_all:
170 %if section_perm.split('.')[-1] != 'none' or show_all:
171 <tr class="perm_row ${'%s_%s' % (section, section_perm.split('.')[-1])}">
171 <tr class="perm_row ${'%s_%s' % (section, section_perm.split('.')[-1])}">
172 <td class="td-name">
172 <td class="td-name">
173 %if section == 'repositories':
173 %if section == 'repositories':
174 <a href="${h.route_path('repo_summary',repo_name=k)}">${k}</a>
174 <a href="${h.route_path('repo_summary',repo_name=k)}">${k}</a>
175 %elif section == 'repositories_groups':
175 %elif section == 'repositories_groups':
176 <a href="${h.route_path('repo_group_home', repo_group_name=k)}">${k}</a>
176 <a href="${h.route_path('repo_group_home', repo_group_name=k)}">${k}</a>
177 %elif section == 'user_groups':
177 %elif section == 'user_groups':
178 ##<a href="${h.route_path('edit_user_group',user_group_id=k)}">${k}</a>
178 ##<a href="${h.route_path('edit_user_group',user_group_id=k)}">${k}</a>
179 ${k}
179 ${k}
180 %endif
180 %endif
181 </td>
181 </td>
182 <td class="td-tags">
182 <td class="td-tags">
183 %if hasattr(permissions[section], 'perm_origin_stack'):
183 %if hasattr(permissions[section], 'perm_origin_stack'):
184 <div>
184 <div>
185 %for i, (perm, origin) in enumerate(reversed(permissions[section].perm_origin_stack[k])):
185 %for i, (perm, origin) in enumerate(reversed(permissions[section].perm_origin_stack[k])):
186
186
187 % if i > 0:
187 % if i > 0:
188 <div style="color: #979797">
188 <div style="color: #979797">
189 <i class="icon-arrow_up"></i>
189 <i class="icon-arrow_up"></i>
190 ${_('overridden by')}
190 ${_('overridden by')}
191 <i class="icon-arrow_up"></i>
191 <i class="icon-arrow_up"></i>
192 </div>
192 </div>
193 % endif
193 % endif
194
194
195 <div>
195 <div>
196 <span class="${i > 0 and 'perm_overriden' or ''} perm_tag ${perm.split('.')[-1]}">
196 <span class="${i > 0 and 'perm_overriden' or ''} perm_tag ${perm.split('.')[-1]}">
197 ${perm} (${origin})
197 ${perm} (${origin})
198 </span>
198 </span>
199 </div>
199 </div>
200
200
201 %endfor
201 %endfor
202 </div>
202 </div>
203 %else:
203 %else:
204 <span class="perm_tag ${section_perm.split('.')[-1]}">${section_perm}</span>
204 <span class="perm_tag ${section_perm.split('.')[-1]}">${section_perm}</span>
205 %endif
205 %endif
206 </td>
206 </td>
207 %if actions:
207 %if actions:
208 <td class="td-action">
208 <td class="td-action">
209 %if section == 'repositories':
209 %if section == 'repositories':
210 <a href="${h.route_path('edit_repo_perms',repo_name=k,_anchor='permissions_manage')}">${_('edit')}</a>
210 <a href="${h.route_path('edit_repo_perms',repo_name=k,_anchor='permissions_manage')}">${_('edit')}</a>
211 %elif section == 'repositories_groups':
211 %elif section == 'repositories_groups':
212 <a href="${h.url('edit_repo_group_perms',group_name=k,anchor='permissions_manage')}">${_('edit')}</a>
212 <a href="${h.url('edit_repo_group_perms',group_name=k,anchor='permissions_manage')}">${_('edit')}</a>
213 %elif section == 'user_groups':
213 %elif section == 'user_groups':
214 ##<a href="${h.route_path('edit_user_group',user_group_id=k)}">${_('edit')}</a>
214 ##<a href="${h.route_path('edit_user_group',user_group_id=k)}">${_('edit')}</a>
215 %endif
215 %endif
216 </td>
216 </td>
217 %endif
217 %endif
218 </tr>
218 </tr>
219 %endif
219 %endif
220 %endfor
220 %endfor
221
221
222 <tr id="empty_${section}" class="noborder" style="display:none;">
222 <tr id="empty_${section}" class="noborder" style="display:none;">
223 <td colspan="6">${_('No permission defined')}</td>
223 <td colspan="6">${_('No permission defined')}</td>
224 </tr>
224 </tr>
225
225
226 </tbody>
226 </tbody>
227 %endif
227 %endif
228 </table>
228 </table>
229 </div>
229 </div>
230 %endif
230 %endif
231 </div>
231 </div>
232 </div>
232 </div>
233 </div>
233 </div>
234 %endfor
234 %endfor
235 </div>
235 </div>
236
236
237 <script>
237 <script>
238 $(document).ready(function(){
238 $(document).ready(function(){
239 var show_empty = function(section){
239 var show_empty = function(section){
240 var visible = $('.section_{0} tr.perm_row:visible'.format(section)).length;
240 var visible = $('.section_{0} tr.perm_row:visible'.format(section)).length;
241 if(visible == 0){
241 if(visible == 0){
242 $('#empty_{0}'.format(section)).show();
242 $('#empty_{0}'.format(section)).show();
243 }
243 }
244 else{
244 else{
245 $('#empty_{0}'.format(section)).hide();
245 $('#empty_{0}'.format(section)).hide();
246 }
246 }
247 };
247 };
248 $('.perm_filter').on('change', function(e){
248 $('.perm_filter').on('change', function(e){
249 var self = this;
249 var self = this;
250 var section = $(this).attr('section');
250 var section = $(this).attr('section');
251
251
252 var opts = {};
252 var opts = {};
253 var elems = $('.filter_' + section).each(function(el){
253 var elems = $('.filter_' + section).each(function(el){
254 var perm_type = $(this).attr('perm_type');
254 var perm_type = $(this).attr('perm_type');
255 var checked = this.checked;
255 var checked = this.checked;
256 opts[perm_type] = checked;
256 opts[perm_type] = checked;
257 if(checked){
257 if(checked){
258 $('.'+section+'_'+perm_type).show();
258 $('.'+section+'_'+perm_type).show();
259 }
259 }
260 else{
260 else{
261 $('.'+section+'_'+perm_type).hide();
261 $('.'+section+'_'+perm_type).hide();
262 }
262 }
263 });
263 });
264 show_empty(section);
264 show_empty(section);
265 })
265 })
266 })
266 })
267 </script>
267 </script>
268 </%def>
268 </%def>
@@ -1,377 +1,377 b''
1 ## DATA TABLE RE USABLE ELEMENTS
1 ## DATA TABLE RE USABLE ELEMENTS
2 ## usage:
2 ## usage:
3 ## <%namespace name="dt" file="/data_table/_dt_elements.mako"/>
3 ## <%namespace name="dt" file="/data_table/_dt_elements.mako"/>
4 <%namespace name="base" file="/base/base.mako"/>
4 <%namespace name="base" file="/base/base.mako"/>
5
5
6 <%def name="metatags_help()">
6 <%def name="metatags_help()">
7 <table>
7 <table>
8 <%
8 <%
9 example_tags = [
9 example_tags = [
10 ('state','[stable]'),
10 ('state','[stable]'),
11 ('state','[stale]'),
11 ('state','[stale]'),
12 ('state','[featured]'),
12 ('state','[featured]'),
13 ('state','[dev]'),
13 ('state','[dev]'),
14 ('state','[dead]'),
14 ('state','[dead]'),
15 ('state','[deprecated]'),
15 ('state','[deprecated]'),
16
16
17 ('label','[personal]'),
17 ('label','[personal]'),
18 ('generic','[v2.0.0]'),
18 ('generic','[v2.0.0]'),
19
19
20 ('lang','[lang =&gt; JavaScript]'),
20 ('lang','[lang =&gt; JavaScript]'),
21 ('license','[license =&gt; LicenseName]'),
21 ('license','[license =&gt; LicenseName]'),
22
22
23 ('ref','[requires =&gt; RepoName]'),
23 ('ref','[requires =&gt; RepoName]'),
24 ('ref','[recommends =&gt; GroupName]'),
24 ('ref','[recommends =&gt; GroupName]'),
25 ('ref','[conflicts =&gt; SomeName]'),
25 ('ref','[conflicts =&gt; SomeName]'),
26 ('ref','[base =&gt; SomeName]'),
26 ('ref','[base =&gt; SomeName]'),
27 ('url','[url =&gt; [linkName](https://rhodecode.com)]'),
27 ('url','[url =&gt; [linkName](https://rhodecode.com)]'),
28 ('see','[see =&gt; http://rhodecode.com]'),
28 ('see','[see =&gt; http://rhodecode.com]'),
29 ]
29 ]
30 %>
30 %>
31 % for tag_type, tag in example_tags:
31 % for tag_type, tag in example_tags:
32 <tr>
32 <tr>
33 <td>${tag|n}</td>
33 <td>${tag|n}</td>
34 <td>${h.style_metatag(tag_type, tag)|n}</td>
34 <td>${h.style_metatag(tag_type, tag)|n}</td>
35 </tr>
35 </tr>
36 % endfor
36 % endfor
37 </table>
37 </table>
38 </%def>
38 </%def>
39
39
40 ## REPOSITORY RENDERERS
40 ## REPOSITORY RENDERERS
41 <%def name="quick_menu(repo_name)">
41 <%def name="quick_menu(repo_name)">
42 <i class="icon-more"></i>
42 <i class="icon-more"></i>
43 <div class="menu_items_container hidden">
43 <div class="menu_items_container hidden">
44 <ul class="menu_items">
44 <ul class="menu_items">
45 <li>
45 <li>
46 <a title="${_('Summary')}" href="${h.route_path('repo_summary',repo_name=repo_name)}">
46 <a title="${_('Summary')}" href="${h.route_path('repo_summary',repo_name=repo_name)}">
47 <span>${_('Summary')}</span>
47 <span>${_('Summary')}</span>
48 </a>
48 </a>
49 </li>
49 </li>
50 <li>
50 <li>
51 <a title="${_('Changelog')}" href="${h.route_path('repo_changelog',repo_name=repo_name)}">
51 <a title="${_('Changelog')}" href="${h.route_path('repo_changelog',repo_name=repo_name)}">
52 <span>${_('Changelog')}</span>
52 <span>${_('Changelog')}</span>
53 </a>
53 </a>
54 </li>
54 </li>
55 <li>
55 <li>
56 <a title="${_('Files')}" href="${h.route_path('repo_files:default_commit',repo_name=repo_name)}">
56 <a title="${_('Files')}" href="${h.route_path('repo_files:default_commit',repo_name=repo_name)}">
57 <span>${_('Files')}</span>
57 <span>${_('Files')}</span>
58 </a>
58 </a>
59 </li>
59 </li>
60 <li>
60 <li>
61 <a title="${_('Fork')}" href="${h.route_path('repo_fork_new',repo_name=repo_name)}">
61 <a title="${_('Fork')}" href="${h.route_path('repo_fork_new',repo_name=repo_name)}">
62 <span>${_('Fork')}</span>
62 <span>${_('Fork')}</span>
63 </a>
63 </a>
64 </li>
64 </li>
65 </ul>
65 </ul>
66 </div>
66 </div>
67 </%def>
67 </%def>
68
68
69 <%def name="repo_name(name,rtype,rstate,private,fork_of,short_name=False,admin=False)">
69 <%def name="repo_name(name,rtype,rstate,private,fork_of,short_name=False,admin=False)">
70 <%
70 <%
71 def get_name(name,short_name=short_name):
71 def get_name(name,short_name=short_name):
72 if short_name:
72 if short_name:
73 return name.split('/')[-1]
73 return name.split('/')[-1]
74 else:
74 else:
75 return name
75 return name
76 %>
76 %>
77 <div class="${'repo_state_pending' if rstate == 'repo_state_pending' else ''} truncate">
77 <div class="${'repo_state_pending' if rstate == 'repo_state_pending' else ''} truncate">
78 ##NAME
78 ##NAME
79 <a href="${h.route_path('edit_repo',repo_name=name) if admin else h.route_path('repo_summary',repo_name=name)}">
79 <a href="${h.route_path('edit_repo',repo_name=name) if admin else h.route_path('repo_summary',repo_name=name)}">
80
80
81 ##TYPE OF REPO
81 ##TYPE OF REPO
82 %if h.is_hg(rtype):
82 %if h.is_hg(rtype):
83 <span title="${_('Mercurial repository')}"><i class="icon-hg" style="font-size: 14px;"></i></span>
83 <span title="${_('Mercurial repository')}"><i class="icon-hg" style="font-size: 14px;"></i></span>
84 %elif h.is_git(rtype):
84 %elif h.is_git(rtype):
85 <span title="${_('Git repository')}"><i class="icon-git" style="font-size: 14px"></i></span>
85 <span title="${_('Git repository')}"><i class="icon-git" style="font-size: 14px"></i></span>
86 %elif h.is_svn(rtype):
86 %elif h.is_svn(rtype):
87 <span title="${_('Subversion repository')}"><i class="icon-svn" style="font-size: 14px"></i></span>
87 <span title="${_('Subversion repository')}"><i class="icon-svn" style="font-size: 14px"></i></span>
88 %endif
88 %endif
89
89
90 ##PRIVATE/PUBLIC
90 ##PRIVATE/PUBLIC
91 %if private and c.visual.show_private_icon:
91 %if private and c.visual.show_private_icon:
92 <i class="icon-lock" title="${_('Private repository')}"></i>
92 <i class="icon-lock" title="${_('Private repository')}"></i>
93 %elif not private and c.visual.show_public_icon:
93 %elif not private and c.visual.show_public_icon:
94 <i class="icon-unlock-alt" title="${_('Public repository')}"></i>
94 <i class="icon-unlock-alt" title="${_('Public repository')}"></i>
95 %else:
95 %else:
96 <span></span>
96 <span></span>
97 %endif
97 %endif
98 ${get_name(name)}
98 ${get_name(name)}
99 </a>
99 </a>
100 %if fork_of:
100 %if fork_of:
101 <a href="${h.route_path('repo_summary',repo_name=fork_of.repo_name)}"><i class="icon-code-fork"></i></a>
101 <a href="${h.route_path('repo_summary',repo_name=fork_of.repo_name)}"><i class="icon-code-fork"></i></a>
102 %endif
102 %endif
103 %if rstate == 'repo_state_pending':
103 %if rstate == 'repo_state_pending':
104 <span class="creation_in_progress tooltip" title="${_('This repository is being created in a background task')}">
104 <span class="creation_in_progress tooltip" title="${_('This repository is being created in a background task')}">
105 (${_('creating...')})
105 (${_('creating...')})
106 </span>
106 </span>
107 %endif
107 %endif
108 </div>
108 </div>
109 </%def>
109 </%def>
110
110
111 <%def name="repo_desc(description, stylify_metatags)">
111 <%def name="repo_desc(description, stylify_metatags)">
112 <%
112 <%
113 tags, description = h.extract_metatags(description)
113 tags, description = h.extract_metatags(description)
114 %>
114 %>
115
115
116 <div class="truncate-wrap">
116 <div class="truncate-wrap">
117 % if stylify_metatags:
117 % if stylify_metatags:
118 % for tag_type, tag in tags:
118 % for tag_type, tag in tags:
119 ${h.style_metatag(tag_type, tag)|n}
119 ${h.style_metatag(tag_type, tag)|n}
120 % endfor
120 % endfor
121 % endif
121 % endif
122 ${description}
122 ${description}
123 </div>
123 </div>
124
124
125 </%def>
125 </%def>
126
126
127 <%def name="last_change(last_change)">
127 <%def name="last_change(last_change)">
128 ${h.age_component(last_change)}
128 ${h.age_component(last_change)}
129 </%def>
129 </%def>
130
130
131 <%def name="revision(name,rev,tip,author,last_msg)">
131 <%def name="revision(name,rev,tip,author,last_msg)">
132 <div>
132 <div>
133 %if rev >= 0:
133 %if rev >= 0:
134 <code><a title="${h.tooltip('%s:\n\n%s' % (author,last_msg))}" class="tooltip" href="${h.route_path('repo_commit',repo_name=name,commit_id=tip)}">${'r%s:%s' % (rev,h.short_id(tip))}</a></code>
134 <code><a title="${h.tooltip('%s:\n\n%s' % (author,last_msg))}" class="tooltip" href="${h.route_path('repo_commit',repo_name=name,commit_id=tip)}">${'r%s:%s' % (rev,h.short_id(tip))}</a></code>
135 %else:
135 %else:
136 ${_('No commits yet')}
136 ${_('No commits yet')}
137 %endif
137 %endif
138 </div>
138 </div>
139 </%def>
139 </%def>
140
140
141 <%def name="rss(name)">
141 <%def name="rss(name)">
142 %if c.rhodecode_user.username != h.DEFAULT_USER:
142 %if c.rhodecode_user.username != h.DEFAULT_USER:
143 <a title="${h.tooltip(_('Subscribe to %s rss feed')% name)}" href="${h.route_path('rss_feed_home', repo_name=name, _query=dict(auth_token=c.rhodecode_user.feed_token))}"><i class="icon-rss-sign"></i></a>
143 <a title="${h.tooltip(_('Subscribe to %s rss feed')% name)}" href="${h.route_path('rss_feed_home', repo_name=name, _query=dict(auth_token=c.rhodecode_user.feed_token))}"><i class="icon-rss-sign"></i></a>
144 %else:
144 %else:
145 <a title="${h.tooltip(_('Subscribe to %s rss feed')% name)}" href="${h.route_path('rss_feed_home', repo_name=name)}"><i class="icon-rss-sign"></i></a>
145 <a title="${h.tooltip(_('Subscribe to %s rss feed')% name)}" href="${h.route_path('rss_feed_home', repo_name=name)}"><i class="icon-rss-sign"></i></a>
146 %endif
146 %endif
147 </%def>
147 </%def>
148
148
149 <%def name="atom(name)">
149 <%def name="atom(name)">
150 %if c.rhodecode_user.username != h.DEFAULT_USER:
150 %if c.rhodecode_user.username != h.DEFAULT_USER:
151 <a title="${h.tooltip(_('Subscribe to %s atom feed')% name)}" href="${h.route_path('atom_feed_home', repo_name=name, _query=dict(auth_token=c.rhodecode_user.feed_token))}"><i class="icon-rss-sign"></i></a>
151 <a title="${h.tooltip(_('Subscribe to %s atom feed')% name)}" href="${h.route_path('atom_feed_home', repo_name=name, _query=dict(auth_token=c.rhodecode_user.feed_token))}"><i class="icon-rss-sign"></i></a>
152 %else:
152 %else:
153 <a title="${h.tooltip(_('Subscribe to %s atom feed')% name)}" href="${h.route_path('atom_feed_home', repo_name=name)}"><i class="icon-rss-sign"></i></a>
153 <a title="${h.tooltip(_('Subscribe to %s atom feed')% name)}" href="${h.route_path('atom_feed_home', repo_name=name)}"><i class="icon-rss-sign"></i></a>
154 %endif
154 %endif
155 </%def>
155 </%def>
156
156
157 <%def name="user_gravatar(email, size=16)">
157 <%def name="user_gravatar(email, size=16)">
158 <div class="rc-user tooltip" title="${h.tooltip(h.author_string(email))}">
158 <div class="rc-user tooltip" title="${h.tooltip(h.author_string(email))}">
159 ${base.gravatar(email, 16)}
159 ${base.gravatar(email, 16)}
160 </div>
160 </div>
161 </%def>
161 </%def>
162
162
163 <%def name="repo_actions(repo_name, super_user=True)">
163 <%def name="repo_actions(repo_name, super_user=True)">
164 <div>
164 <div>
165 <div class="grid_edit">
165 <div class="grid_edit">
166 <a href="${h.route_path('edit_repo',repo_name=repo_name)}" title="${_('Edit')}">
166 <a href="${h.route_path('edit_repo',repo_name=repo_name)}" title="${_('Edit')}">
167 <i class="icon-pencil"></i>Edit</a>
167 <i class="icon-pencil"></i>Edit</a>
168 </div>
168 </div>
169 <div class="grid_delete">
169 <div class="grid_delete">
170 ${h.secure_form(h.route_path('edit_repo_advanced_delete', repo_name=repo_name), request=request)}
170 ${h.secure_form(h.route_path('edit_repo_advanced_delete', repo_name=repo_name), request=request)}
171 ${h.submit('remove_%s' % repo_name,_('Delete'),class_="btn btn-link btn-danger",
171 ${h.submit('remove_%s' % repo_name,_('Delete'),class_="btn btn-link btn-danger",
172 onclick="return confirm('"+_('Confirm to delete this repository: %s') % repo_name+"');")}
172 onclick="return confirm('"+_('Confirm to delete this repository: %s') % repo_name+"');")}
173 ${h.end_form()}
173 ${h.end_form()}
174 </div>
174 </div>
175 </div>
175 </div>
176 </%def>
176 </%def>
177
177
178 <%def name="repo_state(repo_state)">
178 <%def name="repo_state(repo_state)">
179 <div>
179 <div>
180 %if repo_state == 'repo_state_pending':
180 %if repo_state == 'repo_state_pending':
181 <div class="tag tag4">${_('Creating')}</div>
181 <div class="tag tag4">${_('Creating')}</div>
182 %elif repo_state == 'repo_state_created':
182 %elif repo_state == 'repo_state_created':
183 <div class="tag tag1">${_('Created')}</div>
183 <div class="tag tag1">${_('Created')}</div>
184 %else:
184 %else:
185 <div class="tag alert2" title="${h.tooltip(repo_state)}">invalid</div>
185 <div class="tag alert2" title="${h.tooltip(repo_state)}">invalid</div>
186 %endif
186 %endif
187 </div>
187 </div>
188 </%def>
188 </%def>
189
189
190
190
191 ## REPO GROUP RENDERERS
191 ## REPO GROUP RENDERERS
192 <%def name="quick_repo_group_menu(repo_group_name)">
192 <%def name="quick_repo_group_menu(repo_group_name)">
193 <i class="icon-more"></i>
193 <i class="icon-more"></i>
194 <div class="menu_items_container hidden">
194 <div class="menu_items_container hidden">
195 <ul class="menu_items">
195 <ul class="menu_items">
196 <li>
196 <li>
197 <a href="${h.route_path('repo_group_home', repo_group_name=repo_group_name)}">${_('Summary')}</a>
197 <a href="${h.route_path('repo_group_home', repo_group_name=repo_group_name)}">${_('Summary')}</a>
198 </li>
198 </li>
199
199
200 </ul>
200 </ul>
201 </div>
201 </div>
202 </%def>
202 </%def>
203
203
204 <%def name="repo_group_name(repo_group_name, children_groups=None)">
204 <%def name="repo_group_name(repo_group_name, children_groups=None)">
205 <div>
205 <div>
206 <a href="${h.route_path('repo_group_home', repo_group_name=repo_group_name)}">
206 <a href="${h.route_path('repo_group_home', repo_group_name=repo_group_name)}">
207 <i class="icon-folder-close" title="${_('Repository group')}" style="font-size: 16px"></i>
207 <i class="icon-folder-close" title="${_('Repository group')}" style="font-size: 16px"></i>
208 %if children_groups:
208 %if children_groups:
209 ${h.literal(' &raquo; '.join(children_groups))}
209 ${h.literal(' &raquo; '.join(children_groups))}
210 %else:
210 %else:
211 ${repo_group_name}
211 ${repo_group_name}
212 %endif
212 %endif
213 </a>
213 </a>
214 </div>
214 </div>
215 </%def>
215 </%def>
216
216
217 <%def name="repo_group_desc(description, personal, stylify_metatags)">
217 <%def name="repo_group_desc(description, personal, stylify_metatags)">
218
218
219 <%
219 <%
220 tags, description = h.extract_metatags(description)
220 tags, description = h.extract_metatags(description)
221 %>
221 %>
222
222
223 <div class="truncate-wrap">
223 <div class="truncate-wrap">
224 % if personal:
224 % if personal:
225 <div class="metatag" tag="personal">${_('personal')}</div>
225 <div class="metatag" tag="personal">${_('personal')}</div>
226 % endif
226 % endif
227
227
228 % if stylify_metatags:
228 % if stylify_metatags:
229 % for tag_type, tag in tags:
229 % for tag_type, tag in tags:
230 ${h.style_metatag(tag_type, tag)|n}
230 ${h.style_metatag(tag_type, tag)|n}
231 % endfor
231 % endfor
232 % endif
232 % endif
233 ${description}
233 ${description}
234 </div>
234 </div>
235
235
236 </%def>
236 </%def>
237
237
238 <%def name="repo_group_actions(repo_group_id, repo_group_name, gr_count)">
238 <%def name="repo_group_actions(repo_group_id, repo_group_name, gr_count)">
239 <div class="grid_edit">
239 <div class="grid_edit">
240 <a href="${h.url('edit_repo_group',group_name=repo_group_name)}" title="${_('Edit')}">Edit</a>
240 <a href="${h.url('edit_repo_group',group_name=repo_group_name)}" title="${_('Edit')}">Edit</a>
241 </div>
241 </div>
242 <div class="grid_delete">
242 <div class="grid_delete">
243 ${h.secure_form(h.url('delete_repo_group', group_name=repo_group_name),method='delete', request=request)}
243 ${h.secure_form(h.url('delete_repo_group', group_name=repo_group_name),method='delete', request=request)}
244 ${h.submit('remove_%s' % repo_group_name,_('Delete'),class_="btn btn-link btn-danger",
244 ${h.submit('remove_%s' % repo_group_name,_('Delete'),class_="btn btn-link btn-danger",
245 onclick="return confirm('"+_ungettext('Confirm to delete this group: %s with %s repository','Confirm to delete this group: %s with %s repositories',gr_count) % (repo_group_name, gr_count)+"');")}
245 onclick="return confirm('"+_ungettext('Confirm to delete this group: %s with %s repository','Confirm to delete this group: %s with %s repositories',gr_count) % (repo_group_name, gr_count)+"');")}
246 ${h.end_form()}
246 ${h.end_form()}
247 </div>
247 </div>
248 </%def>
248 </%def>
249
249
250
250
251 <%def name="user_actions(user_id, username)">
251 <%def name="user_actions(user_id, username)">
252 <div class="grid_edit">
252 <div class="grid_edit">
253 <a href="${h.url('edit_user',user_id=user_id)}" title="${_('Edit')}">
253 <a href="${h.route_path('user_edit',user_id=user_id)}" title="${_('Edit')}">
254 <i class="icon-pencil"></i>Edit</a>
254 <i class="icon-pencil"></i>${_('Edit')}</a>
255 </div>
255 </div>
256 <div class="grid_delete">
256 <div class="grid_delete">
257 ${h.secure_form(h.url('delete_user', user_id=user_id),method='delete')}
257 ${h.secure_form(h.route_path('user_delete', user_id=user_id), request=request)}
258 ${h.submit('remove_',_('Delete'),id="remove_user_%s" % user_id, class_="btn btn-link btn-danger",
258 ${h.submit('remove_',_('Delete'),id="remove_user_%s" % user_id, class_="btn btn-link btn-danger",
259 onclick="return confirm('"+_('Confirm to delete this user: %s') % username+"');")}
259 onclick="return confirm('"+_('Confirm to delete this user: %s') % username+"');")}
260 ${h.end_form()}
260 ${h.end_form()}
261 </div>
261 </div>
262 </%def>
262 </%def>
263
263
264 <%def name="user_group_actions(user_group_id, user_group_name)">
264 <%def name="user_group_actions(user_group_id, user_group_name)">
265 <div class="grid_edit">
265 <div class="grid_edit">
266 <a href="${h.route_path('edit_user_group', user_group_id=user_group_id)}" title="${_('Edit')}">Edit</a>
266 <a href="${h.route_path('edit_user_group', user_group_id=user_group_id)}" title="${_('Edit')}">Edit</a>
267 </div>
267 </div>
268 <div class="grid_delete">
268 <div class="grid_delete">
269 ${h.secure_form(h.route_path('user_groups_delete', user_group_id=user_group_id), request=request)}
269 ${h.secure_form(h.route_path('user_groups_delete', user_group_id=user_group_id), request=request)}
270 ${h.submit('remove_',_('Delete'),id="remove_group_%s" % user_group_id, class_="btn btn-link btn-danger",
270 ${h.submit('remove_',_('Delete'),id="remove_group_%s" % user_group_id, class_="btn btn-link btn-danger",
271 onclick="return confirm('"+_('Confirm to delete this user group: %s') % user_group_name+"');")}
271 onclick="return confirm('"+_('Confirm to delete this user group: %s') % user_group_name+"');")}
272 ${h.end_form()}
272 ${h.end_form()}
273 </div>
273 </div>
274 </%def>
274 </%def>
275
275
276
276
277 <%def name="user_name(user_id, username)">
277 <%def name="user_name(user_id, username)">
278 ${h.link_to(h.person(username, 'username_or_name_or_email'), h.url('edit_user', user_id=user_id))}
278 ${h.link_to(h.person(username, 'username_or_name_or_email'), h.route_path('user_edit', user_id=user_id))}
279 </%def>
279 </%def>
280
280
281 <%def name="user_profile(username)">
281 <%def name="user_profile(username)">
282 ${base.gravatar_with_user(username, 16)}
282 ${base.gravatar_with_user(username, 16)}
283 </%def>
283 </%def>
284
284
285 <%def name="user_group_name(user_group_id, user_group_name)">
285 <%def name="user_group_name(user_group_id, user_group_name)">
286 <div>
286 <div>
287 <a href="${h.route_path('edit_user_group', user_group_id=user_group_id)}">
287 <a href="${h.route_path('edit_user_group', user_group_id=user_group_id)}">
288 <i class="icon-group" title="${_('User group')}"></i> ${user_group_name}</a>
288 <i class="icon-group" title="${_('User group')}"></i> ${user_group_name}</a>
289 </div>
289 </div>
290 </%def>
290 </%def>
291
291
292
292
293 ## GISTS
293 ## GISTS
294
294
295 <%def name="gist_gravatar(full_contact)">
295 <%def name="gist_gravatar(full_contact)">
296 <div class="gist_gravatar">
296 <div class="gist_gravatar">
297 ${base.gravatar(full_contact, 30)}
297 ${base.gravatar(full_contact, 30)}
298 </div>
298 </div>
299 </%def>
299 </%def>
300
300
301 <%def name="gist_access_id(gist_access_id, full_contact)">
301 <%def name="gist_access_id(gist_access_id, full_contact)">
302 <div>
302 <div>
303 <b>
303 <b>
304 <a href="${h.route_path('gist_show', gist_id=gist_access_id)}">gist: ${gist_access_id}</a>
304 <a href="${h.route_path('gist_show', gist_id=gist_access_id)}">gist: ${gist_access_id}</a>
305 </b>
305 </b>
306 </div>
306 </div>
307 </%def>
307 </%def>
308
308
309 <%def name="gist_author(full_contact, created_on, expires)">
309 <%def name="gist_author(full_contact, created_on, expires)">
310 ${base.gravatar_with_user(full_contact, 16)}
310 ${base.gravatar_with_user(full_contact, 16)}
311 </%def>
311 </%def>
312
312
313
313
314 <%def name="gist_created(created_on)">
314 <%def name="gist_created(created_on)">
315 <div class="created">
315 <div class="created">
316 ${h.age_component(created_on, time_is_local=True)}
316 ${h.age_component(created_on, time_is_local=True)}
317 </div>
317 </div>
318 </%def>
318 </%def>
319
319
320 <%def name="gist_expires(expires)">
320 <%def name="gist_expires(expires)">
321 <div class="created">
321 <div class="created">
322 %if expires == -1:
322 %if expires == -1:
323 ${_('never')}
323 ${_('never')}
324 %else:
324 %else:
325 ${h.age_component(h.time_to_utcdatetime(expires))}
325 ${h.age_component(h.time_to_utcdatetime(expires))}
326 %endif
326 %endif
327 </div>
327 </div>
328 </%def>
328 </%def>
329
329
330 <%def name="gist_type(gist_type)">
330 <%def name="gist_type(gist_type)">
331 %if gist_type != 'public':
331 %if gist_type != 'public':
332 <div class="tag">${_('Private')}</div>
332 <div class="tag">${_('Private')}</div>
333 %endif
333 %endif
334 </%def>
334 </%def>
335
335
336 <%def name="gist_description(gist_description)">
336 <%def name="gist_description(gist_description)">
337 ${gist_description}
337 ${gist_description}
338 </%def>
338 </%def>
339
339
340
340
341 ## PULL REQUESTS GRID RENDERERS
341 ## PULL REQUESTS GRID RENDERERS
342
342
343 <%def name="pullrequest_target_repo(repo_name)">
343 <%def name="pullrequest_target_repo(repo_name)">
344 <div class="truncate">
344 <div class="truncate">
345 ${h.link_to(repo_name,h.route_path('repo_summary',repo_name=repo_name))}
345 ${h.link_to(repo_name,h.route_path('repo_summary',repo_name=repo_name))}
346 </div>
346 </div>
347 </%def>
347 </%def>
348 <%def name="pullrequest_status(status)">
348 <%def name="pullrequest_status(status)">
349 <div class="${'flag_status %s' % status} pull-left"></div>
349 <div class="${'flag_status %s' % status} pull-left"></div>
350 </%def>
350 </%def>
351
351
352 <%def name="pullrequest_title(title, description)">
352 <%def name="pullrequest_title(title, description)">
353 ${title} <br/>
353 ${title} <br/>
354 ${h.shorter(description, 40)}
354 ${h.shorter(description, 40)}
355 </%def>
355 </%def>
356
356
357 <%def name="pullrequest_comments(comments_nr)">
357 <%def name="pullrequest_comments(comments_nr)">
358 <i class="icon-comment"></i> ${comments_nr}
358 <i class="icon-comment"></i> ${comments_nr}
359 </%def>
359 </%def>
360
360
361 <%def name="pullrequest_name(pull_request_id, target_repo_name, short=False)">
361 <%def name="pullrequest_name(pull_request_id, target_repo_name, short=False)">
362 <a href="${h.route_path('pullrequest_show',repo_name=target_repo_name,pull_request_id=pull_request_id)}">
362 <a href="${h.route_path('pullrequest_show',repo_name=target_repo_name,pull_request_id=pull_request_id)}">
363 % if short:
363 % if short:
364 #${pull_request_id}
364 #${pull_request_id}
365 % else:
365 % else:
366 ${_('Pull request #%(pr_number)s') % {'pr_number': pull_request_id,}}
366 ${_('Pull request #%(pr_number)s') % {'pr_number': pull_request_id,}}
367 % endif
367 % endif
368 </a>
368 </a>
369 </%def>
369 </%def>
370
370
371 <%def name="pullrequest_updated_on(updated_on)">
371 <%def name="pullrequest_updated_on(updated_on)">
372 ${h.age_component(h.time_to_utcdatetime(updated_on))}
372 ${h.age_component(h.time_to_utcdatetime(updated_on))}
373 </%def>
373 </%def>
374
374
375 <%def name="pullrequest_author(full_contact)">
375 <%def name="pullrequest_author(full_contact)">
376 ${base.gravatar_with_user(full_contact, 16)}
376 ${base.gravatar_with_user(full_contact, 16)}
377 </%def>
377 </%def>
@@ -1,58 +1,58 b''
1 <%namespace name="base" file="/base/base.mako"/>
1 <%namespace name="base" file="/base/base.mako"/>
2
2
3 <div class="panel panel-default user-profile">
3 <div class="panel panel-default user-profile">
4 <div class="panel-heading">
4 <div class="panel-heading">
5 <h3 class="panel-title">${_('Profile')}</h3>
5 <h3 class="panel-title">${_('Profile')}</h3>
6 %if h.HasPermissionAny('hg.admin')():
6 %if h.HasPermissionAny('hg.admin')():
7 ${h.link_to(_('Edit'), h.url('edit_user', user_id=c.user.user_id), class_='panel-edit')}
7 ${h.link_to(_('Edit'), h.route_path('user_edit', user_id=c.user.user_id), class_='panel-edit')}
8 %endif
8 %endif
9 </div>
9 </div>
10
10
11 <div class="panel-body user-profile-content">
11 <div class="panel-body user-profile-content">
12 <div class="fieldset">
12 <div class="fieldset">
13 <div class="left-label">
13 <div class="left-label">
14 ${_('Photo')}:
14 ${_('Photo')}:
15 </div>
15 </div>
16 <div class="right-content">
16 <div class="right-content">
17 %if c.visual.use_gravatar:
17 %if c.visual.use_gravatar:
18 ${base.gravatar(c.user.email, 100)}
18 ${base.gravatar(c.user.email, 100)}
19 %else:
19 %else:
20 ${base.gravatar(c.user.email, 20)}
20 ${base.gravatar(c.user.email, 20)}
21 ${_('Avatars are disabled')}
21 ${_('Avatars are disabled')}
22 %endif
22 %endif
23 </div>
23 </div>
24 </div>
24 </div>
25 <div class="fieldset">
25 <div class="fieldset">
26 <div class="left-label">
26 <div class="left-label">
27 ${_('Username')}:
27 ${_('Username')}:
28 </div>
28 </div>
29 <div class="right-content">
29 <div class="right-content">
30 ${c.user.username}
30 ${c.user.username}
31 </div>
31 </div>
32 </div>
32 </div>
33 <div class="fieldset">
33 <div class="fieldset">
34 <div class="left-label">
34 <div class="left-label">
35 ${_('First name')}:
35 ${_('First name')}:
36 </div>
36 </div>
37 <div class="right-content">
37 <div class="right-content">
38 ${c.user.first_name}
38 ${c.user.first_name}
39 </div>
39 </div>
40 </div>
40 </div>
41 <div class="fieldset">
41 <div class="fieldset">
42 <div class="left-label">
42 <div class="left-label">
43 ${_('Last name')}:
43 ${_('Last name')}:
44 </div>
44 </div>
45 <div class="right-content">
45 <div class="right-content">
46 ${c.user.last_name}
46 ${c.user.last_name}
47 </div>
47 </div>
48 </div>
48 </div>
49 <div class="fieldset">
49 <div class="fieldset">
50 <div class="left-label">
50 <div class="left-label">
51 ${_('Email')}:
51 ${_('Email')}:
52 </div>
52 </div>
53 <div class="right-content">
53 <div class="right-content">
54 ${c.user.email or _('Missing email, please update your user email address.')}
54 ${c.user.email or _('Missing email, please update your user email address.')}
55 </div>
55 </div>
56 </div>
56 </div>
57 </div>
57 </div>
58 </div> No newline at end of file
58 </div>
@@ -1,496 +0,0 b''
1 # -*- coding: utf-8 -*-
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 #
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
7 # (only), as published by the Free Software Foundation.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
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/>.
16 #
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
21 """
22 Users crud controller for pylons
23 """
24
25 import logging
26 import formencode
27
28 from formencode import htmlfill
29 from pylons import request, tmpl_context as c, url, config
30 from pylons.controllers.util import redirect
31 from pylons.i18n.translation import _
32
33 from rhodecode.authentication.plugins import auth_rhodecode
34
35 from rhodecode.lib import helpers as h
36 from rhodecode.lib import auth
37 from rhodecode.lib import audit_logger
38 from rhodecode.lib.auth import (
39 LoginRequired, HasPermissionAllDecorator, AuthUser)
40 from rhodecode.lib.base import BaseController, render
41 from rhodecode.lib.exceptions import (
42 DefaultUserException, UserOwnsReposException, UserOwnsRepoGroupsException,
43 UserOwnsUserGroupsException, UserCreationError)
44 from rhodecode.lib.utils2 import safe_int, AttributeDict
45
46 from rhodecode.model.db import (
47 PullRequestReviewers, User, UserEmailMap, UserIpMap, RepoGroup)
48 from rhodecode.model.forms import (
49 UserForm, UserPermissionsForm, UserIndividualPermissionsForm)
50 from rhodecode.model.repo_group import RepoGroupModel
51 from rhodecode.model.user import UserModel
52 from rhodecode.model.meta import Session
53 from rhodecode.model.permission import PermissionModel
54
55 log = logging.getLogger(__name__)
56
57
58 class UsersController(BaseController):
59 """REST Controller styled on the Atom Publishing Protocol"""
60
61 @LoginRequired()
62 def __before__(self):
63 super(UsersController, self).__before__()
64 c.available_permissions = config['available_permissions']
65 c.allowed_languages = [
66 ('en', 'English (en)'),
67 ('de', 'German (de)'),
68 ('fr', 'French (fr)'),
69 ('it', 'Italian (it)'),
70 ('ja', 'Japanese (ja)'),
71 ('pl', 'Polish (pl)'),
72 ('pt', 'Portuguese (pt)'),
73 ('ru', 'Russian (ru)'),
74 ('zh', 'Chinese (zh)'),
75 ]
76 PermissionModel().set_global_permission_choices(c, gettext_translator=_)
77
78 def _get_personal_repo_group_template_vars(self):
79 DummyUser = AttributeDict({
80 'username': '${username}',
81 'user_id': '${user_id}',
82 })
83 c.default_create_repo_group = RepoGroupModel() \
84 .get_default_create_personal_repo_group()
85 c.personal_repo_group_name = RepoGroupModel() \
86 .get_personal_group_name(DummyUser)
87
88 @HasPermissionAllDecorator('hg.admin')
89 @auth.CSRFRequired()
90 def create(self):
91 c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.name
92 user_model = UserModel()
93 user_form = UserForm()()
94 try:
95 form_result = user_form.to_python(dict(request.POST))
96 user = user_model.create(form_result)
97 Session().flush()
98 creation_data = user.get_api_data()
99 username = form_result['username']
100
101 audit_logger.store_web(
102 'user.create', action_data={'data': creation_data},
103 user=c.rhodecode_user)
104
105 user_link = h.link_to(h.escape(username),
106 url('edit_user',
107 user_id=user.user_id))
108 h.flash(h.literal(_('Created user %(user_link)s')
109 % {'user_link': user_link}), category='success')
110 Session().commit()
111 except formencode.Invalid as errors:
112 self._get_personal_repo_group_template_vars()
113 return htmlfill.render(
114 render('admin/users/user_add.mako'),
115 defaults=errors.value,
116 errors=errors.error_dict or {},
117 prefix_error=False,
118 encoding="UTF-8",
119 force_defaults=False)
120 except UserCreationError as e:
121 h.flash(e, 'error')
122 except Exception:
123 log.exception("Exception creation of user")
124 h.flash(_('Error occurred during creation of user %s')
125 % request.POST.get('username'), category='error')
126 return redirect(h.route_path('users'))
127
128 @HasPermissionAllDecorator('hg.admin')
129 def new(self):
130 c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.name
131 self._get_personal_repo_group_template_vars()
132 return render('admin/users/user_add.mako')
133
134 @HasPermissionAllDecorator('hg.admin')
135 @auth.CSRFRequired()
136 def update(self, user_id):
137
138 user_id = safe_int(user_id)
139 c.user = User.get_or_404(user_id)
140 c.active = 'profile'
141 c.extern_type = c.user.extern_type
142 c.extern_name = c.user.extern_name
143 c.perm_user = AuthUser(user_id=user_id, ip_addr=self.ip_addr)
144 available_languages = [x[0] for x in c.allowed_languages]
145 _form = UserForm(edit=True, available_languages=available_languages,
146 old_data={'user_id': user_id,
147 'email': c.user.email})()
148 form_result = {}
149 old_values = c.user.get_api_data()
150 try:
151 form_result = _form.to_python(dict(request.POST))
152 skip_attrs = ['extern_type', 'extern_name']
153 # TODO: plugin should define if username can be updated
154 if c.extern_type != "rhodecode":
155 # forbid updating username for external accounts
156 skip_attrs.append('username')
157
158 UserModel().update_user(
159 user_id, skip_attrs=skip_attrs, **form_result)
160
161 audit_logger.store_web(
162 'user.edit', action_data={'old_data': old_values},
163 user=c.rhodecode_user)
164
165 Session().commit()
166 h.flash(_('User updated successfully'), category='success')
167 except formencode.Invalid as errors:
168 defaults = errors.value
169 e = errors.error_dict or {}
170
171 return htmlfill.render(
172 render('admin/users/user_edit.mako'),
173 defaults=defaults,
174 errors=e,
175 prefix_error=False,
176 encoding="UTF-8",
177 force_defaults=False)
178 except UserCreationError as e:
179 h.flash(e, 'error')
180 except Exception:
181 log.exception("Exception updating user")
182 h.flash(_('Error occurred during update of user %s')
183 % form_result.get('username'), category='error')
184 return redirect(url('edit_user', user_id=user_id))
185
186 @HasPermissionAllDecorator('hg.admin')
187 @auth.CSRFRequired()
188 def delete(self, user_id):
189 user_id = safe_int(user_id)
190 c.user = User.get_or_404(user_id)
191
192 _repos = c.user.repositories
193 _repo_groups = c.user.repository_groups
194 _user_groups = c.user.user_groups
195
196 handle_repos = None
197 handle_repo_groups = None
198 handle_user_groups = None
199 # dummy call for flash of handle
200 set_handle_flash_repos = lambda: None
201 set_handle_flash_repo_groups = lambda: None
202 set_handle_flash_user_groups = lambda: None
203
204 if _repos and request.POST.get('user_repos'):
205 do = request.POST['user_repos']
206 if do == 'detach':
207 handle_repos = 'detach'
208 set_handle_flash_repos = lambda: h.flash(
209 _('Detached %s repositories') % len(_repos),
210 category='success')
211 elif do == 'delete':
212 handle_repos = 'delete'
213 set_handle_flash_repos = lambda: h.flash(
214 _('Deleted %s repositories') % len(_repos),
215 category='success')
216
217 if _repo_groups and request.POST.get('user_repo_groups'):
218 do = request.POST['user_repo_groups']
219 if do == 'detach':
220 handle_repo_groups = 'detach'
221 set_handle_flash_repo_groups = lambda: h.flash(
222 _('Detached %s repository groups') % len(_repo_groups),
223 category='success')
224 elif do == 'delete':
225 handle_repo_groups = 'delete'
226 set_handle_flash_repo_groups = lambda: h.flash(
227 _('Deleted %s repository groups') % len(_repo_groups),
228 category='success')
229
230 if _user_groups and request.POST.get('user_user_groups'):
231 do = request.POST['user_user_groups']
232 if do == 'detach':
233 handle_user_groups = 'detach'
234 set_handle_flash_user_groups = lambda: h.flash(
235 _('Detached %s user groups') % len(_user_groups),
236 category='success')
237 elif do == 'delete':
238 handle_user_groups = 'delete'
239 set_handle_flash_user_groups = lambda: h.flash(
240 _('Deleted %s user groups') % len(_user_groups),
241 category='success')
242
243 old_values = c.user.get_api_data()
244 try:
245 UserModel().delete(c.user, handle_repos=handle_repos,
246 handle_repo_groups=handle_repo_groups,
247 handle_user_groups=handle_user_groups)
248
249 audit_logger.store_web(
250 'user.delete', action_data={'old_data': old_values},
251 user=c.rhodecode_user)
252
253 Session().commit()
254 set_handle_flash_repos()
255 set_handle_flash_repo_groups()
256 set_handle_flash_user_groups()
257 h.flash(_('Successfully deleted user'), category='success')
258 except (UserOwnsReposException, UserOwnsRepoGroupsException,
259 UserOwnsUserGroupsException, DefaultUserException) as e:
260 h.flash(e, category='warning')
261 except Exception:
262 log.exception("Exception during deletion of user")
263 h.flash(_('An error occurred during deletion of user'),
264 category='error')
265 return redirect(h.route_path('users'))
266
267 @HasPermissionAllDecorator('hg.admin')
268 @auth.CSRFRequired()
269 def reset_password(self, user_id):
270 """
271 toggle reset password flag for this user
272 """
273 user_id = safe_int(user_id)
274 c.user = User.get_or_404(user_id)
275 try:
276 old_value = c.user.user_data.get('force_password_change')
277 c.user.update_userdata(force_password_change=not old_value)
278
279 if old_value:
280 msg = _('Force password change disabled for user')
281 audit_logger.store_web(
282 'user.edit.password_reset.disabled',
283 user=c.rhodecode_user)
284 else:
285 msg = _('Force password change enabled for user')
286 audit_logger.store_web(
287 'user.edit.password_reset.enabled',
288 user=c.rhodecode_user)
289
290 Session().commit()
291 h.flash(msg, category='success')
292 except Exception:
293 log.exception("Exception during password reset for user")
294 h.flash(_('An error occurred during password reset for user'),
295 category='error')
296
297 return redirect(url('edit_user_advanced', user_id=user_id))
298
299 @HasPermissionAllDecorator('hg.admin')
300 @auth.CSRFRequired()
301 def create_personal_repo_group(self, user_id):
302 """
303 Create personal repository group for this user
304 """
305 from rhodecode.model.repo_group import RepoGroupModel
306
307 user_id = safe_int(user_id)
308 c.user = User.get_or_404(user_id)
309 personal_repo_group = RepoGroup.get_user_personal_repo_group(
310 c.user.user_id)
311 if personal_repo_group:
312 return redirect(url('edit_user_advanced', user_id=user_id))
313
314 personal_repo_group_name = RepoGroupModel().get_personal_group_name(
315 c.user)
316 named_personal_group = RepoGroup.get_by_group_name(
317 personal_repo_group_name)
318 try:
319
320 if named_personal_group and named_personal_group.user_id == c.user.user_id:
321 # migrate the same named group, and mark it as personal
322 named_personal_group.personal = True
323 Session().add(named_personal_group)
324 Session().commit()
325 msg = _('Linked repository group `%s` as personal' % (
326 personal_repo_group_name,))
327 h.flash(msg, category='success')
328 elif not named_personal_group:
329 RepoGroupModel().create_personal_repo_group(c.user)
330
331 msg = _('Created repository group `%s`' % (
332 personal_repo_group_name,))
333 h.flash(msg, category='success')
334 else:
335 msg = _('Repository group `%s` is already taken' % (
336 personal_repo_group_name,))
337 h.flash(msg, category='warning')
338 except Exception:
339 log.exception("Exception during repository group creation")
340 msg = _(
341 'An error occurred during repository group creation for user')
342 h.flash(msg, category='error')
343 Session().rollback()
344
345 return redirect(url('edit_user_advanced', user_id=user_id))
346
347 @HasPermissionAllDecorator('hg.admin')
348 def show(self, user_id):
349 """GET /users/user_id: Show a specific item"""
350 # url('user', user_id=ID)
351 User.get_or_404(-1)
352
353 @HasPermissionAllDecorator('hg.admin')
354 def edit(self, user_id):
355 """GET /users/user_id/edit: Form to edit an existing item"""
356 # url('edit_user', user_id=ID)
357 user_id = safe_int(user_id)
358 c.user = User.get_or_404(user_id)
359 if c.user.username == User.DEFAULT_USER:
360 h.flash(_("You can't edit this user"), category='warning')
361 return redirect(h.route_path('users'))
362
363 c.active = 'profile'
364 c.extern_type = c.user.extern_type
365 c.extern_name = c.user.extern_name
366 c.perm_user = AuthUser(user_id=user_id, ip_addr=self.ip_addr)
367
368 defaults = c.user.get_dict()
369 defaults.update({'language': c.user.user_data.get('language')})
370 return htmlfill.render(
371 render('admin/users/user_edit.mako'),
372 defaults=defaults,
373 encoding="UTF-8",
374 force_defaults=False)
375
376 @HasPermissionAllDecorator('hg.admin')
377 def edit_advanced(self, user_id):
378 user_id = safe_int(user_id)
379 user = c.user = User.get_or_404(user_id)
380 if user.username == User.DEFAULT_USER:
381 h.flash(_("You can't edit this user"), category='warning')
382 return redirect(h.route_path('users'))
383
384 c.active = 'advanced'
385 c.personal_repo_group = RepoGroup.get_user_personal_repo_group(user_id)
386 c.personal_repo_group_name = RepoGroupModel()\
387 .get_personal_group_name(user)
388
389 c.user_to_review_rules = sorted(
390 (x.user for x in c.user.user_review_rules),
391 key=lambda u: u.username.lower())
392
393 c.first_admin = User.get_first_super_admin()
394 defaults = user.get_dict()
395
396 # Interim workaround if the user participated on any pull requests as a
397 # reviewer.
398 has_review = len(user.reviewer_pull_requests)
399 c.can_delete_user = not has_review
400 c.can_delete_user_message = ''
401 inactive_link = h.link_to(
402 'inactive', h.url('edit_user', user_id=user_id, anchor='active'))
403 if has_review == 1:
404 c.can_delete_user_message = h.literal(_(
405 'The user participates as reviewer in {} pull request and '
406 'cannot be deleted. \nYou can set the user to '
407 '"{}" instead of deleting it.').format(
408 has_review, inactive_link))
409 elif has_review:
410 c.can_delete_user_message = h.literal(_(
411 'The user participates as reviewer in {} pull requests and '
412 'cannot be deleted. \nYou can set the user to '
413 '"{}" instead of deleting it.').format(
414 has_review, inactive_link))
415
416 return htmlfill.render(
417 render('admin/users/user_edit.mako'),
418 defaults=defaults,
419 encoding="UTF-8",
420 force_defaults=False)
421
422 @HasPermissionAllDecorator('hg.admin')
423 def edit_global_perms(self, user_id):
424 user_id = safe_int(user_id)
425 c.user = User.get_or_404(user_id)
426 if c.user.username == User.DEFAULT_USER:
427 h.flash(_("You can't edit this user"), category='warning')
428 return redirect(h.route_path('users'))
429
430 c.active = 'global_perms'
431
432 c.default_user = User.get_default_user()
433 defaults = c.user.get_dict()
434 defaults.update(c.default_user.get_default_perms(suffix='_inherited'))
435 defaults.update(c.default_user.get_default_perms())
436 defaults.update(c.user.get_default_perms())
437
438 return htmlfill.render(
439 render('admin/users/user_edit.mako'),
440 defaults=defaults,
441 encoding="UTF-8",
442 force_defaults=False)
443
444 @HasPermissionAllDecorator('hg.admin')
445 @auth.CSRFRequired()
446 def update_global_perms(self, user_id):
447 user_id = safe_int(user_id)
448 user = User.get_or_404(user_id)
449 c.active = 'global_perms'
450 try:
451 # first stage that verifies the checkbox
452 _form = UserIndividualPermissionsForm()
453 form_result = _form.to_python(dict(request.POST))
454 inherit_perms = form_result['inherit_default_permissions']
455 user.inherit_default_permissions = inherit_perms
456 Session().add(user)
457
458 if not inherit_perms:
459 # only update the individual ones if we un check the flag
460 _form = UserPermissionsForm(
461 [x[0] for x in c.repo_create_choices],
462 [x[0] for x in c.repo_create_on_write_choices],
463 [x[0] for x in c.repo_group_create_choices],
464 [x[0] for x in c.user_group_create_choices],
465 [x[0] for x in c.fork_choices],
466 [x[0] for x in c.inherit_default_permission_choices])()
467
468 form_result = _form.to_python(dict(request.POST))
469 form_result.update({'perm_user_id': user.user_id})
470
471 PermissionModel().update_user_permissions(form_result)
472
473 # TODO(marcink): implement global permissions
474 # audit_log.store_web('user.edit.permissions')
475
476 Session().commit()
477 h.flash(_('User global permissions updated successfully'),
478 category='success')
479
480 except formencode.Invalid as errors:
481 defaults = errors.value
482 c.user = user
483 return htmlfill.render(
484 render('admin/users/user_edit.mako'),
485 defaults=defaults,
486 errors=errors.error_dict or {},
487 prefix_error=False,
488 encoding="UTF-8",
489 force_defaults=False)
490 except Exception:
491 log.exception("Exception during permissions saving")
492 h.flash(_('An error occurred during permissions saving'),
493 category='error')
494 return redirect(url('edit_user_global_perms', user_id=user_id))
495
496
This diff has been collapsed as it changes many lines, (512 lines changed) Show them Hide them
@@ -1,512 +0,0 b''
1 # -*- coding: utf-8 -*-
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 #
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
7 # (only), as published by the Free Software Foundation.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
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/>.
16 #
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
21 import pytest
22 from sqlalchemy.orm.exc import NoResultFound
23
24 from rhodecode.lib.auth import check_password
25 from rhodecode.lib import helpers as h
26 from rhodecode.model import validators
27 from rhodecode.model.db import User, UserIpMap, UserApiKeys
28 from rhodecode.model.meta import Session
29 from rhodecode.model.user import UserModel
30 from rhodecode.tests import (
31 TestController, url, link_to, TEST_USER_ADMIN_LOGIN,
32 TEST_USER_REGULAR_LOGIN, assert_session_flash)
33 from rhodecode.tests.fixture import Fixture
34 from rhodecode.tests.utils import AssertResponse
35
36 fixture = Fixture()
37
38
39 def route_path(name, params=None, **kwargs):
40 import urllib
41 from rhodecode.apps._base import ADMIN_PREFIX
42
43 base_url = {
44 'users_data':
45 ADMIN_PREFIX + '/users_data',
46 }[name].format(**kwargs)
47
48 if params:
49 base_url = '{}?{}'.format(base_url, urllib.urlencode(params))
50 return base_url
51
52
53 class TestAdminUsersController(TestController):
54 test_user_1 = 'testme'
55 destroy_users = set()
56
57 @classmethod
58 def teardown_method(cls, method):
59 fixture.destroy_users(cls.destroy_users)
60
61 def test_create(self, xhr_header):
62 self.log_user()
63 username = 'newtestuser'
64 password = 'test12'
65 password_confirmation = password
66 name = 'name'
67 lastname = 'lastname'
68 email = 'mail@mail.com'
69
70 self.app.get(url('new_user'))
71
72 response = self.app.post(url('users'), params={
73 'username': username,
74 'password': password,
75 'password_confirmation': password_confirmation,
76 'firstname': name,
77 'active': True,
78 'lastname': lastname,
79 'extern_name': 'rhodecode',
80 'extern_type': 'rhodecode',
81 'email': email,
82 'csrf_token': self.csrf_token,
83 })
84 user_link = link_to(
85 username,
86 url('edit_user', user_id=User.get_by_username(username).user_id))
87 assert_session_flash(response, 'Created user %s' % (user_link,))
88 self.destroy_users.add(username)
89
90 new_user = User.query().filter(User.username == username).one()
91
92 assert new_user.username == username
93 assert check_password(password, new_user.password)
94 assert new_user.name == name
95 assert new_user.lastname == lastname
96 assert new_user.email == email
97
98 response = self.app.get(route_path('users_data'),
99 extra_environ=xhr_header)
100 response.mustcontain(username)
101
102 def test_create_err(self):
103 self.log_user()
104 username = 'new_user'
105 password = ''
106 name = 'name'
107 lastname = 'lastname'
108 email = 'errmail.com'
109
110 self.app.get(url('new_user'))
111
112 response = self.app.post(url('users'), params={
113 'username': username,
114 'password': password,
115 'name': name,
116 'active': False,
117 'lastname': lastname,
118 'email': email,
119 'csrf_token': self.csrf_token,
120 })
121
122 msg = validators.ValidUsername(
123 False, {})._messages['system_invalid_username']
124 msg = h.html_escape(msg % {'username': 'new_user'})
125 response.mustcontain('<span class="error-message">%s</span>' % msg)
126 response.mustcontain(
127 '<span class="error-message">Please enter a value</span>')
128 response.mustcontain(
129 '<span class="error-message">An email address must contain a'
130 ' single @</span>')
131
132 def get_user():
133 Session().query(User).filter(User.username == username).one()
134
135 with pytest.raises(NoResultFound):
136 get_user()
137
138 def test_new(self):
139 self.log_user()
140 self.app.get(url('new_user'))
141
142 @pytest.mark.parametrize("name, attrs", [
143 ('firstname', {'firstname': 'new_username'}),
144 ('lastname', {'lastname': 'new_username'}),
145 ('admin', {'admin': True}),
146 ('admin', {'admin': False}),
147 ('extern_type', {'extern_type': 'ldap'}),
148 ('extern_type', {'extern_type': None}),
149 ('extern_name', {'extern_name': 'test'}),
150 ('extern_name', {'extern_name': None}),
151 ('active', {'active': False}),
152 ('active', {'active': True}),
153 ('email', {'email': 'some@email.com'}),
154 ('language', {'language': 'de'}),
155 ('language', {'language': 'en'}),
156 # ('new_password', {'new_password': 'foobar123',
157 # 'password_confirmation': 'foobar123'})
158 ])
159 def test_update(self, name, attrs):
160 self.log_user()
161 usr = fixture.create_user(self.test_user_1, password='qweqwe',
162 email='testme@rhodecode.org',
163 extern_type='rhodecode',
164 extern_name=self.test_user_1,
165 skip_if_exists=True)
166 Session().commit()
167 self.destroy_users.add(self.test_user_1)
168 params = usr.get_api_data()
169 cur_lang = params['language'] or 'en'
170 params.update({
171 'password_confirmation': '',
172 'new_password': '',
173 'language': cur_lang,
174 '_method': 'put',
175 'csrf_token': self.csrf_token,
176 })
177 params.update({'new_password': ''})
178 params.update(attrs)
179 if name == 'email':
180 params['emails'] = [attrs['email']]
181 elif name == 'extern_type':
182 # cannot update this via form, expected value is original one
183 params['extern_type'] = "rhodecode"
184 elif name == 'extern_name':
185 # cannot update this via form, expected value is original one
186 params['extern_name'] = self.test_user_1
187 # special case since this user is not
188 # logged in yet his data is not filled
189 # so we use creation data
190
191 response = self.app.post(url('user', user_id=usr.user_id), params)
192 assert response.status_int == 302
193 assert_session_flash(response, 'User updated successfully')
194
195 updated_user = User.get_by_username(self.test_user_1)
196 updated_params = updated_user.get_api_data()
197 updated_params.update({'password_confirmation': ''})
198 updated_params.update({'new_password': ''})
199
200 del params['_method']
201 del params['csrf_token']
202 assert params == updated_params
203
204 def test_update_and_migrate_password(
205 self, autologin_user, real_crypto_backend):
206 from rhodecode.lib import auth
207
208 # create new user, with sha256 password
209 temp_user = 'test_admin_sha256'
210 user = fixture.create_user(temp_user)
211 user.password = auth._RhodeCodeCryptoSha256().hash_create(
212 b'test123')
213 Session().add(user)
214 Session().commit()
215 self.destroy_users.add('test_admin_sha256')
216
217 params = user.get_api_data()
218
219 params.update({
220 'password_confirmation': 'qweqwe123',
221 'new_password': 'qweqwe123',
222 'language': 'en',
223 '_method': 'put',
224 'csrf_token': autologin_user.csrf_token,
225 })
226
227 response = self.app.post(url('user', user_id=user.user_id), params)
228 assert response.status_int == 302
229 assert_session_flash(response, 'User updated successfully')
230
231 # new password should be bcrypted, after log-in and transfer
232 user = User.get_by_username(temp_user)
233 assert user.password.startswith('$')
234
235 updated_user = User.get_by_username(temp_user)
236 updated_params = updated_user.get_api_data()
237 updated_params.update({'password_confirmation': 'qweqwe123'})
238 updated_params.update({'new_password': 'qweqwe123'})
239
240 del params['_method']
241 del params['csrf_token']
242 assert params == updated_params
243
244 def test_delete(self):
245 self.log_user()
246 username = 'newtestuserdeleteme'
247
248 fixture.create_user(name=username)
249
250 new_user = Session().query(User)\
251 .filter(User.username == username).one()
252 response = self.app.post(url('user', user_id=new_user.user_id),
253 params={'_method': 'delete',
254 'csrf_token': self.csrf_token})
255
256 assert_session_flash(response, 'Successfully deleted user')
257
258 def test_delete_owner_of_repository(self):
259 self.log_user()
260 username = 'newtestuserdeleteme_repo_owner'
261 obj_name = 'test_repo'
262 usr = fixture.create_user(name=username)
263 self.destroy_users.add(username)
264 fixture.create_repo(obj_name, cur_user=usr.username)
265
266 new_user = Session().query(User)\
267 .filter(User.username == username).one()
268 response = self.app.post(url('user', user_id=new_user.user_id),
269 params={'_method': 'delete',
270 'csrf_token': self.csrf_token})
271
272 msg = 'user "%s" still owns 1 repositories and cannot be removed. ' \
273 'Switch owners or remove those repositories:%s' % (username,
274 obj_name)
275 assert_session_flash(response, msg)
276 fixture.destroy_repo(obj_name)
277
278 def test_delete_owner_of_repository_detaching(self):
279 self.log_user()
280 username = 'newtestuserdeleteme_repo_owner_detach'
281 obj_name = 'test_repo'
282 usr = fixture.create_user(name=username)
283 self.destroy_users.add(username)
284 fixture.create_repo(obj_name, cur_user=usr.username)
285
286 new_user = Session().query(User)\
287 .filter(User.username == username).one()
288 response = self.app.post(url('user', user_id=new_user.user_id),
289 params={'_method': 'delete',
290 'user_repos': 'detach',
291 'csrf_token': self.csrf_token})
292
293 msg = 'Detached 1 repositories'
294 assert_session_flash(response, msg)
295 fixture.destroy_repo(obj_name)
296
297 def test_delete_owner_of_repository_deleting(self):
298 self.log_user()
299 username = 'newtestuserdeleteme_repo_owner_delete'
300 obj_name = 'test_repo'
301 usr = fixture.create_user(name=username)
302 self.destroy_users.add(username)
303 fixture.create_repo(obj_name, cur_user=usr.username)
304
305 new_user = Session().query(User)\
306 .filter(User.username == username).one()
307 response = self.app.post(url('user', user_id=new_user.user_id),
308 params={'_method': 'delete',
309 'user_repos': 'delete',
310 'csrf_token': self.csrf_token})
311
312 msg = 'Deleted 1 repositories'
313 assert_session_flash(response, msg)
314
315 def test_delete_owner_of_repository_group(self):
316 self.log_user()
317 username = 'newtestuserdeleteme_repo_group_owner'
318 obj_name = 'test_group'
319 usr = fixture.create_user(name=username)
320 self.destroy_users.add(username)
321 fixture.create_repo_group(obj_name, cur_user=usr.username)
322
323 new_user = Session().query(User)\
324 .filter(User.username == username).one()
325 response = self.app.post(url('user', user_id=new_user.user_id),
326 params={'_method': 'delete',
327 'csrf_token': self.csrf_token})
328
329 msg = 'user "%s" still owns 1 repository groups and cannot be removed. ' \
330 'Switch owners or remove those repository groups:%s' % (username,
331 obj_name)
332 assert_session_flash(response, msg)
333 fixture.destroy_repo_group(obj_name)
334
335 def test_delete_owner_of_repository_group_detaching(self):
336 self.log_user()
337 username = 'newtestuserdeleteme_repo_group_owner_detach'
338 obj_name = 'test_group'
339 usr = fixture.create_user(name=username)
340 self.destroy_users.add(username)
341 fixture.create_repo_group(obj_name, cur_user=usr.username)
342
343 new_user = Session().query(User)\
344 .filter(User.username == username).one()
345 response = self.app.post(url('user', user_id=new_user.user_id),
346 params={'_method': 'delete',
347 'user_repo_groups': 'delete',
348 'csrf_token': self.csrf_token})
349
350 msg = 'Deleted 1 repository groups'
351 assert_session_flash(response, msg)
352
353 def test_delete_owner_of_repository_group_deleting(self):
354 self.log_user()
355 username = 'newtestuserdeleteme_repo_group_owner_delete'
356 obj_name = 'test_group'
357 usr = fixture.create_user(name=username)
358 self.destroy_users.add(username)
359 fixture.create_repo_group(obj_name, cur_user=usr.username)
360
361 new_user = Session().query(User)\
362 .filter(User.username == username).one()
363 response = self.app.post(url('user', user_id=new_user.user_id),
364 params={'_method': 'delete',
365 'user_repo_groups': 'detach',
366 'csrf_token': self.csrf_token})
367
368 msg = 'Detached 1 repository groups'
369 assert_session_flash(response, msg)
370 fixture.destroy_repo_group(obj_name)
371
372 def test_delete_owner_of_user_group(self):
373 self.log_user()
374 username = 'newtestuserdeleteme_user_group_owner'
375 obj_name = 'test_user_group'
376 usr = fixture.create_user(name=username)
377 self.destroy_users.add(username)
378 fixture.create_user_group(obj_name, cur_user=usr.username)
379
380 new_user = Session().query(User)\
381 .filter(User.username == username).one()
382 response = self.app.post(url('user', user_id=new_user.user_id),
383 params={'_method': 'delete',
384 'csrf_token': self.csrf_token})
385
386 msg = 'user "%s" still owns 1 user groups and cannot be removed. ' \
387 'Switch owners or remove those user groups:%s' % (username,
388 obj_name)
389 assert_session_flash(response, msg)
390 fixture.destroy_user_group(obj_name)
391
392 def test_delete_owner_of_user_group_detaching(self):
393 self.log_user()
394 username = 'newtestuserdeleteme_user_group_owner_detaching'
395 obj_name = 'test_user_group'
396 usr = fixture.create_user(name=username)
397 self.destroy_users.add(username)
398 fixture.create_user_group(obj_name, cur_user=usr.username)
399
400 new_user = Session().query(User)\
401 .filter(User.username == username).one()
402 try:
403 response = self.app.post(url('user', user_id=new_user.user_id),
404 params={'_method': 'delete',
405 'user_user_groups': 'detach',
406 'csrf_token': self.csrf_token})
407
408 msg = 'Detached 1 user groups'
409 assert_session_flash(response, msg)
410 finally:
411 fixture.destroy_user_group(obj_name)
412
413 def test_delete_owner_of_user_group_deleting(self):
414 self.log_user()
415 username = 'newtestuserdeleteme_user_group_owner_deleting'
416 obj_name = 'test_user_group'
417 usr = fixture.create_user(name=username)
418 self.destroy_users.add(username)
419 fixture.create_user_group(obj_name, cur_user=usr.username)
420
421 new_user = Session().query(User)\
422 .filter(User.username == username).one()
423 response = self.app.post(url('user', user_id=new_user.user_id),
424 params={'_method': 'delete',
425 'user_user_groups': 'delete',
426 'csrf_token': self.csrf_token})
427
428 msg = 'Deleted 1 user groups'
429 assert_session_flash(response, msg)
430
431 def test_edit(self):
432 self.log_user()
433 user = User.get_by_username(TEST_USER_ADMIN_LOGIN)
434 self.app.get(url('edit_user', user_id=user.user_id))
435
436 @pytest.mark.parametrize(
437 'repo_create, repo_create_write, user_group_create, repo_group_create,'
438 'fork_create, inherit_default_permissions, expect_error,'
439 'expect_form_error', [
440 ('hg.create.none', 'hg.create.write_on_repogroup.false',
441 'hg.usergroup.create.false', 'hg.repogroup.create.false',
442 'hg.fork.none', 'hg.inherit_default_perms.false', False, False),
443 ('hg.create.repository', 'hg.create.write_on_repogroup.false',
444 'hg.usergroup.create.false', 'hg.repogroup.create.false',
445 'hg.fork.none', 'hg.inherit_default_perms.false', False, False),
446 ('hg.create.repository', 'hg.create.write_on_repogroup.true',
447 'hg.usergroup.create.true', 'hg.repogroup.create.true',
448 'hg.fork.repository', 'hg.inherit_default_perms.false', False,
449 False),
450 ('hg.create.XXX', 'hg.create.write_on_repogroup.true',
451 'hg.usergroup.create.true', 'hg.repogroup.create.true',
452 'hg.fork.repository', 'hg.inherit_default_perms.false', False,
453 True),
454 ('', '', '', '', '', '', True, False),
455 ])
456 def test_global_perms_on_user(
457 self, repo_create, repo_create_write, user_group_create,
458 repo_group_create, fork_create, expect_error, expect_form_error,
459 inherit_default_permissions):
460 self.log_user()
461 user = fixture.create_user('dummy')
462 uid = user.user_id
463
464 # ENABLE REPO CREATE ON A GROUP
465 perm_params = {
466 'inherit_default_permissions': False,
467 'default_repo_create': repo_create,
468 'default_repo_create_on_write': repo_create_write,
469 'default_user_group_create': user_group_create,
470 'default_repo_group_create': repo_group_create,
471 'default_fork_create': fork_create,
472 'default_inherit_default_permissions': inherit_default_permissions,
473 '_method': 'put',
474 'csrf_token': self.csrf_token,
475 }
476 response = self.app.post(
477 url('edit_user_global_perms', user_id=uid),
478 params=perm_params)
479
480 if expect_form_error:
481 assert response.status_int == 200
482 response.mustcontain('Value must be one of')
483 else:
484 if expect_error:
485 msg = 'An error occurred during permissions saving'
486 else:
487 msg = 'User global permissions updated successfully'
488 ug = User.get(uid)
489 del perm_params['_method']
490 del perm_params['inherit_default_permissions']
491 del perm_params['csrf_token']
492 assert perm_params == ug.get_default_perms()
493 assert_session_flash(response, msg)
494 fixture.destroy_user(uid)
495
496 def test_global_permissions_initial_values(self, user_util):
497 self.log_user()
498 user = user_util.create_user()
499 uid = user.user_id
500 response = self.app.get(url('edit_user_global_perms', user_id=uid))
501 default_user = User.get_default_user()
502 default_permissions = default_user.get_default_perms()
503 assert_response = AssertResponse(response)
504 expected_permissions = (
505 'default_repo_create', 'default_repo_create_on_write',
506 'default_fork_create', 'default_repo_group_create',
507 'default_user_group_create', 'default_inherit_default_permissions')
508 for permission in expected_permissions:
509 css_selector = '[name={}][checked=checked]'.format(permission)
510 element = assert_response.get_element(css_selector)
511 assert element.value == default_permissions[permission]
512
General Comments 0
You need to be logged in to leave comments. Login now