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

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

@@ -1,505 +1,570 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2016-2017 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import time
22 22 import logging
23 23 import operator
24 24
25 25 from pyramid.httpexceptions import HTTPFound
26 26
27 27 from rhodecode.lib import helpers as h
28 28 from rhodecode.lib.utils2 import StrictAttributeDict, safe_int, datetime_to_time
29 29 from rhodecode.lib.vcs.exceptions import RepositoryRequirementError
30 30 from rhodecode.model import repo
31 31 from rhodecode.model import repo_group
32 32 from rhodecode.model import user_group
33 from rhodecode.model import user
33 34 from rhodecode.model.db import User
34 35 from rhodecode.model.scm import ScmModel
35 36
36 37 log = logging.getLogger(__name__)
37 38
38 39
39 40 ADMIN_PREFIX = '/_admin'
40 41 STATIC_FILE_PREFIX = '/_static'
41 42
42 43 URL_NAME_REQUIREMENTS = {
43 44 # group name can have a slash in them, but they must not end with a slash
44 45 'group_name': r'.*?[^/]',
45 46 'repo_group_name': r'.*?[^/]',
46 47 # repo names can have a slash in them, but they must not end with a slash
47 48 'repo_name': r'.*?[^/]',
48 49 # file path eats up everything at the end
49 50 'f_path': r'.*',
50 51 # reference types
51 52 'source_ref_type': '(branch|book|tag|rev|\%\(source_ref_type\)s)',
52 53 'target_ref_type': '(branch|book|tag|rev|\%\(target_ref_type\)s)',
53 54 }
54 55
55 56
56 57 def add_route_with_slash(config,name, pattern, **kw):
57 58 config.add_route(name, pattern, **kw)
58 59 if not pattern.endswith('/'):
59 60 config.add_route(name + '_slash', pattern + '/', **kw)
60 61
61 62
62 63 def add_route_requirements(route_path, requirements=URL_NAME_REQUIREMENTS):
63 64 """
64 65 Adds regex requirements to pyramid routes using a mapping dict
65 66 e.g::
66 67 add_route_requirements('{repo_name}/settings')
67 68 """
68 69 for key, regex in requirements.items():
69 70 route_path = route_path.replace('{%s}' % key, '{%s:%s}' % (key, regex))
70 71 return route_path
71 72
72 73
73 74 def get_format_ref_id(repo):
74 75 """Returns a `repo` specific reference formatter function"""
75 76 if h.is_svn(repo):
76 77 return _format_ref_id_svn
77 78 else:
78 79 return _format_ref_id
79 80
80 81
81 82 def _format_ref_id(name, raw_id):
82 83 """Default formatting of a given reference `name`"""
83 84 return name
84 85
85 86
86 87 def _format_ref_id_svn(name, raw_id):
87 88 """Special way of formatting a reference for Subversion including path"""
88 89 return '%s@%s' % (name, raw_id)
89 90
90 91
91 92 class TemplateArgs(StrictAttributeDict):
92 93 pass
93 94
94 95
95 96 class BaseAppView(object):
96 97
97 98 def __init__(self, context, request):
98 99 self.request = request
99 100 self.context = context
100 101 self.session = request.session
101 102 self._rhodecode_user = request.user # auth user
102 103 self._rhodecode_db_user = self._rhodecode_user.get_instance()
103 104 self._maybe_needs_password_change(
104 105 request.matched_route.name, self._rhodecode_db_user)
105 106
106 107 def _maybe_needs_password_change(self, view_name, user_obj):
107 108 log.debug('Checking if user %s needs password change on view %s',
108 109 user_obj, view_name)
109 110 skip_user_views = [
110 111 'logout', 'login',
111 112 'my_account_password', 'my_account_password_update'
112 113 ]
113 114
114 115 if not user_obj:
115 116 return
116 117
117 118 if user_obj.username == User.DEFAULT_USER:
118 119 return
119 120
120 121 now = time.time()
121 122 should_change = user_obj.user_data.get('force_password_change')
122 123 change_after = safe_int(should_change) or 0
123 124 if should_change and now > change_after:
124 125 log.debug('User %s requires password change', user_obj)
125 126 h.flash('You are required to change your password', 'warning',
126 127 ignore_duplicate=True)
127 128
128 129 if view_name not in skip_user_views:
129 130 raise HTTPFound(
130 131 self.request.route_path('my_account_password'))
131 132
132 133 def _log_creation_exception(self, e, repo_name):
133 134 _ = self.request.translate
134 135 reason = None
135 136 if len(e.args) == 2:
136 137 reason = e.args[1]
137 138
138 139 if reason == 'INVALID_CERTIFICATE':
139 140 log.exception(
140 141 'Exception creating a repository: invalid certificate')
141 142 msg = (_('Error creating repository %s: invalid certificate')
142 143 % repo_name)
143 144 else:
144 145 log.exception("Exception creating a repository")
145 146 msg = (_('Error creating repository %s')
146 147 % repo_name)
147 148 return msg
148 149
149 150 def _get_local_tmpl_context(self, include_app_defaults=False):
150 151 c = TemplateArgs()
151 152 c.auth_user = self.request.user
152 153 # TODO(marcink): migrate the usage of c.rhodecode_user to c.auth_user
153 154 c.rhodecode_user = self.request.user
154 155
155 156 if include_app_defaults:
156 157 # NOTE(marcink): after full pyramid migration include_app_defaults
157 158 # should be turned on by default
158 159 from rhodecode.lib.base import attach_context_attributes
159 160 attach_context_attributes(c, self.request, self.request.user.user_id)
160 161
161 162 return c
162 163
163 164 def _register_global_c(self, tmpl_args):
164 165 """
165 166 Registers attributes to pylons global `c`
166 167 """
167 168
168 169 # TODO(marcink): remove once pyramid migration is finished
169 170 from pylons import tmpl_context as c
170 171 try:
171 172 for k, v in tmpl_args.items():
172 173 setattr(c, k, v)
173 174 except TypeError:
174 175 log.exception('Failed to register pylons C')
175 176 pass
176 177
177 178 def _get_template_context(self, tmpl_args):
178 179 self._register_global_c(tmpl_args)
179 180
180 181 local_tmpl_args = {
181 182 'defaults': {},
182 183 'errors': {},
183 184 # register a fake 'c' to be used in templates instead of global
184 185 # pylons c, after migration to pyramid we should rename it to 'c'
185 186 # make sure we replace usage of _c in templates too
186 187 '_c': tmpl_args
187 188 }
188 189 local_tmpl_args.update(tmpl_args)
189 190 return local_tmpl_args
190 191
191 192 def load_default_context(self):
192 193 """
193 194 example:
194 195
195 196 def load_default_context(self):
196 197 c = self._get_local_tmpl_context()
197 198 c.custom_var = 'foobar'
198 199 self._register_global_c(c)
199 200 return c
200 201 """
201 202 raise NotImplementedError('Needs implementation in view class')
202 203
203 204
204 205 class RepoAppView(BaseAppView):
205 206
206 207 def __init__(self, context, request):
207 208 super(RepoAppView, self).__init__(context, request)
208 209 self.db_repo = request.db_repo
209 210 self.db_repo_name = self.db_repo.repo_name
210 211 self.db_repo_pull_requests = ScmModel().get_pull_requests(self.db_repo)
211 212
212 213 def _handle_missing_requirements(self, error):
213 214 log.error(
214 215 'Requirements are missing for repository %s: %s',
215 216 self.db_repo_name, error.message)
216 217
217 218 def _get_local_tmpl_context(self, include_app_defaults=False):
218 219 _ = self.request.translate
219 220 c = super(RepoAppView, self)._get_local_tmpl_context(
220 221 include_app_defaults=include_app_defaults)
221 222
222 223 # register common vars for this type of view
223 224 c.rhodecode_db_repo = self.db_repo
224 225 c.repo_name = self.db_repo_name
225 226 c.repository_pull_requests = self.db_repo_pull_requests
226 227
227 228 c.repository_requirements_missing = False
228 229 try:
229 230 self.rhodecode_vcs_repo = self.db_repo.scm_instance()
230 231 except RepositoryRequirementError as e:
231 232 c.repository_requirements_missing = True
232 233 self._handle_missing_requirements(e)
233 234 self.rhodecode_vcs_repo = None
234 235
235 236 if (not c.repository_requirements_missing
236 237 and self.rhodecode_vcs_repo is None):
237 238 # unable to fetch this repo as vcs instance, report back to user
238 239 h.flash(_(
239 240 "The repository `%(repo_name)s` cannot be loaded in filesystem. "
240 241 "Please check if it exist, or is not damaged.") %
241 242 {'repo_name': c.repo_name},
242 243 category='error', ignore_duplicate=True)
243 244 raise HTTPFound(h.route_path('home'))
244 245
245 246 return c
246 247
247 248 def _get_f_path(self, matchdict, default=None):
248 249 f_path = matchdict.get('f_path')
249 250 if f_path:
250 251 # fix for multiple initial slashes that causes errors for GIT
251 252 return f_path.lstrip('/')
252 253
253 254 return default
254 255
255 256
256 257 class RepoGroupAppView(BaseAppView):
257 258 def __init__(self, context, request):
258 259 super(RepoGroupAppView, self).__init__(context, request)
259 260 self.db_repo_group = request.db_repo_group
260 261 self.db_repo_group_name = self.db_repo_group.group_name
261 262
262 263
263 264 class UserGroupAppView(BaseAppView):
264 265 def __init__(self, context, request):
265 266 super(UserGroupAppView, self).__init__(context, request)
266 267 self.db_user_group = request.db_user_group
267 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 285 class DataGridAppView(object):
271 286 """
272 287 Common class to have re-usable grid rendering components
273 288 """
274 289
275 290 def _extract_ordering(self, request, column_map=None):
276 291 column_map = column_map or {}
277 292 column_index = safe_int(request.GET.get('order[0][column]'))
278 293 order_dir = request.GET.get(
279 294 'order[0][dir]', 'desc')
280 295 order_by = request.GET.get(
281 296 'columns[%s][data][sort]' % column_index, 'name_raw')
282 297
283 298 # translate datatable to DB columns
284 299 order_by = column_map.get(order_by) or order_by
285 300
286 301 search_q = request.GET.get('search[value]')
287 302 return search_q, order_by, order_dir
288 303
289 304 def _extract_chunk(self, request):
290 305 start = safe_int(request.GET.get('start'), 0)
291 306 length = safe_int(request.GET.get('length'), 25)
292 307 draw = safe_int(request.GET.get('draw'))
293 308 return draw, start, length
294 309
295 310 def _get_order_col(self, order_by, model):
296 311 if isinstance(order_by, basestring):
297 312 try:
298 313 return operator.attrgetter(order_by)(model)
299 314 except AttributeError:
300 315 return None
301 316 else:
302 317 return order_by
303 318
304 319
305 320 class BaseReferencesView(RepoAppView):
306 321 """
307 322 Base for reference view for branches, tags and bookmarks.
308 323 """
309 324 def load_default_context(self):
310 325 c = self._get_local_tmpl_context()
311 326
312 327 self._register_global_c(c)
313 328 return c
314 329
315 330 def load_refs_context(self, ref_items, partials_template):
316 331 _render = self.request.get_partial_renderer(partials_template)
317 332 pre_load = ["author", "date", "message"]
318 333
319 334 is_svn = h.is_svn(self.rhodecode_vcs_repo)
320 335 is_hg = h.is_hg(self.rhodecode_vcs_repo)
321 336
322 337 format_ref_id = get_format_ref_id(self.rhodecode_vcs_repo)
323 338
324 339 closed_refs = {}
325 340 if is_hg:
326 341 closed_refs = self.rhodecode_vcs_repo.branches_closed
327 342
328 343 data = []
329 344 for ref_name, commit_id in ref_items:
330 345 commit = self.rhodecode_vcs_repo.get_commit(
331 346 commit_id=commit_id, pre_load=pre_load)
332 347 closed = ref_name in closed_refs
333 348
334 349 # TODO: johbo: Unify generation of reference links
335 350 use_commit_id = '/' in ref_name or is_svn
336 351
337 352 if use_commit_id:
338 353 files_url = h.route_path(
339 354 'repo_files',
340 355 repo_name=self.db_repo_name,
341 356 f_path=ref_name if is_svn else '',
342 357 commit_id=commit_id)
343 358
344 359 else:
345 360 files_url = h.route_path(
346 361 'repo_files',
347 362 repo_name=self.db_repo_name,
348 363 f_path=ref_name if is_svn else '',
349 364 commit_id=ref_name,
350 365 _query=dict(at=ref_name))
351 366
352 367 data.append({
353 368 "name": _render('name', ref_name, files_url, closed),
354 369 "name_raw": ref_name,
355 370 "date": _render('date', commit.date),
356 371 "date_raw": datetime_to_time(commit.date),
357 372 "author": _render('author', commit.author),
358 373 "commit": _render(
359 374 'commit', commit.message, commit.raw_id, commit.idx),
360 375 "commit_raw": commit.idx,
361 376 "compare": _render(
362 377 'compare', format_ref_id(ref_name, commit.raw_id)),
363 378 })
364 379
365 380 return data
366 381
367 382
368 383 class RepoRoutePredicate(object):
369 384 def __init__(self, val, config):
370 385 self.val = val
371 386
372 387 def text(self):
373 388 return 'repo_route = %s' % self.val
374 389
375 390 phash = text
376 391
377 392 def __call__(self, info, request):
378 393
379 394 if hasattr(request, 'vcs_call'):
380 395 # skip vcs calls
381 396 return
382 397
383 398 repo_name = info['match']['repo_name']
384 399 repo_model = repo.RepoModel()
385 400 by_name_match = repo_model.get_by_repo_name(repo_name, cache=True)
386 401
387 402 def redirect_if_creating(db_repo):
388 403 if db_repo.repo_state in [repo.Repository.STATE_PENDING]:
389 404 raise HTTPFound(
390 405 request.route_path('repo_creating',
391 406 repo_name=db_repo.repo_name))
392 407
393 408 if by_name_match:
394 409 # register this as request object we can re-use later
395 410 request.db_repo = by_name_match
396 411 redirect_if_creating(by_name_match)
397 412 return True
398 413
399 414 by_id_match = repo_model.get_repo_by_id(repo_name)
400 415 if by_id_match:
401 416 request.db_repo = by_id_match
402 417 redirect_if_creating(by_id_match)
403 418 return True
404 419
405 420 return False
406 421
407 422
408 423 class RepoTypeRoutePredicate(object):
409 424 def __init__(self, val, config):
410 425 self.val = val or ['hg', 'git', 'svn']
411 426
412 427 def text(self):
413 428 return 'repo_accepted_type = %s' % self.val
414 429
415 430 phash = text
416 431
417 432 def __call__(self, info, request):
418 433 if hasattr(request, 'vcs_call'):
419 434 # skip vcs calls
420 435 return
421 436
422 437 rhodecode_db_repo = request.db_repo
423 438
424 439 log.debug(
425 440 '%s checking repo type for %s in %s',
426 441 self.__class__.__name__, rhodecode_db_repo.repo_type, self.val)
427 442
428 443 if rhodecode_db_repo.repo_type in self.val:
429 444 return True
430 445 else:
431 446 log.warning('Current view is not supported for repo type:%s',
432 447 rhodecode_db_repo.repo_type)
433 448 #
434 449 # h.flash(h.literal(
435 450 # _('Action not supported for %s.' % rhodecode_repo.alias)),
436 451 # category='warning')
437 452 # return redirect(
438 453 # route_path('repo_summary', repo_name=cls.rhodecode_db_repo.repo_name))
439 454
440 455 return False
441 456
442 457
443 458 class RepoGroupRoutePredicate(object):
444 459 def __init__(self, val, config):
445 460 self.val = val
446 461
447 462 def text(self):
448 463 return 'repo_group_route = %s' % self.val
449 464
450 465 phash = text
451 466
452 467 def __call__(self, info, request):
453 468 if hasattr(request, 'vcs_call'):
454 469 # skip vcs calls
455 470 return
456 471
457 472 repo_group_name = info['match']['repo_group_name']
458 473 repo_group_model = repo_group.RepoGroupModel()
459 474 by_name_match = repo_group_model.get_by_group_name(
460 475 repo_group_name, cache=True)
461 476
462 477 if by_name_match:
463 478 # register this as request object we can re-use later
464 479 request.db_repo_group = by_name_match
465 480 return True
466 481
467 482 return False
468 483
469 484
470 485 class UserGroupRoutePredicate(object):
471 486 def __init__(self, val, config):
472 487 self.val = val
473 488
474 489 def text(self):
475 490 return 'user_group_route = %s' % self.val
476 491
477 492 phash = text
478 493
479 494 def __call__(self, info, request):
480 495 if hasattr(request, 'vcs_call'):
481 496 # skip vcs calls
482 497 return
483 498
484 499 user_group_id = info['match']['user_group_id']
485 500 user_group_model = user_group.UserGroup()
486 by_name_match = user_group_model.get(
501 by_id_match = user_group_model.get(
487 502 user_group_id, cache=True)
488 503
489 if by_name_match:
504 if by_id_match:
490 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 507 return True
493 508
494 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 558 def includeme(config):
498 559 config.add_route_predicate(
499 560 'repo_route', RepoRoutePredicate)
500 561 config.add_route_predicate(
501 562 'repo_accepted_types', RepoTypeRoutePredicate)
502 563 config.add_route_predicate(
503 564 'repo_group_route', RepoGroupRoutePredicate)
504 565 config.add_route_predicate(
505 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 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2016-2017 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21
22 22 from rhodecode.apps.admin.navigation import NavigationRegistry
23 23 from rhodecode.config.routing import ADMIN_PREFIX
24 24 from rhodecode.lib.utils2 import str2bool
25 25
26 26
27 27 def admin_routes(config):
28 28 """
29 29 Admin prefixed routes
30 30 """
31 31
32 32 config.add_route(
33 33 name='admin_audit_logs',
34 34 pattern='/audit_logs')
35 35
36 36 config.add_route(
37 37 name='admin_audit_log_entry',
38 38 pattern='/audit_logs/{audit_log_id}')
39 39
40 40 config.add_route(
41 41 name='pull_requests_global_0', # backward compat
42 42 pattern='/pull_requests/{pull_request_id:\d+}')
43 43 config.add_route(
44 44 name='pull_requests_global_1', # backward compat
45 45 pattern='/pull-requests/{pull_request_id:\d+}')
46 46 config.add_route(
47 47 name='pull_requests_global',
48 48 pattern='/pull-request/{pull_request_id:\d+}')
49 49
50 50 config.add_route(
51 51 name='admin_settings_open_source',
52 52 pattern='/settings/open_source')
53 53 config.add_route(
54 54 name='admin_settings_vcs_svn_generate_cfg',
55 55 pattern='/settings/vcs/svn_generate_cfg')
56 56
57 57 config.add_route(
58 58 name='admin_settings_system',
59 59 pattern='/settings/system')
60 60 config.add_route(
61 61 name='admin_settings_system_update',
62 62 pattern='/settings/system/updates')
63 63
64 64 config.add_route(
65 65 name='admin_settings_sessions',
66 66 pattern='/settings/sessions')
67 67 config.add_route(
68 68 name='admin_settings_sessions_cleanup',
69 69 pattern='/settings/sessions/cleanup')
70 70
71 71 config.add_route(
72 72 name='admin_settings_process_management',
73 73 pattern='/settings/process_management')
74 74 config.add_route(
75 75 name='admin_settings_process_management_signal',
76 76 pattern='/settings/process_management/signal')
77 77
78 78 # default settings
79 79 config.add_route(
80 80 name='admin_defaults_repositories',
81 81 pattern='/defaults/repositories')
82 82 config.add_route(
83 83 name='admin_defaults_repositories_update',
84 84 pattern='/defaults/repositories/update')
85 85
86 86 # global permissions
87 87
88 88 config.add_route(
89 89 name='admin_permissions_application',
90 90 pattern='/permissions/application')
91 91 config.add_route(
92 92 name='admin_permissions_application_update',
93 93 pattern='/permissions/application/update')
94 94
95 95 config.add_route(
96 96 name='admin_permissions_global',
97 97 pattern='/permissions/global')
98 98 config.add_route(
99 99 name='admin_permissions_global_update',
100 100 pattern='/permissions/global/update')
101 101
102 102 config.add_route(
103 103 name='admin_permissions_object',
104 104 pattern='/permissions/object')
105 105 config.add_route(
106 106 name='admin_permissions_object_update',
107 107 pattern='/permissions/object/update')
108 108
109 109 config.add_route(
110 110 name='admin_permissions_ips',
111 111 pattern='/permissions/ips')
112 112
113 113 config.add_route(
114 114 name='admin_permissions_overview',
115 115 pattern='/permissions/overview')
116 116
117 117 config.add_route(
118 118 name='admin_permissions_auth_token_access',
119 119 pattern='/permissions/auth_token_access')
120 120
121 121 config.add_route(
122 122 name='admin_permissions_ssh_keys',
123 123 pattern='/permissions/ssh_keys')
124 124 config.add_route(
125 125 name='admin_permissions_ssh_keys_data',
126 126 pattern='/permissions/ssh_keys/data')
127 127 config.add_route(
128 128 name='admin_permissions_ssh_keys_update',
129 129 pattern='/permissions/ssh_keys/update')
130 130
131 131 # users admin
132 132 config.add_route(
133 133 name='users',
134 134 pattern='/users')
135 135
136 136 config.add_route(
137 137 name='users_data',
138 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 182 # user auth tokens
141 183 config.add_route(
142 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 187 config.add_route(
145 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 191 config.add_route(
148 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 196 # user ssh keys
152 197 config.add_route(
153 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 201 config.add_route(
156 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 205 config.add_route(
159 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 209 config.add_route(
162 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 214 # user emails
166 215 config.add_route(
167 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 219 config.add_route(
170 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 223 config.add_route(
173 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 228 # user IPs
177 229 config.add_route(
178 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 233 config.add_route(
181 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 237 config.add_route(
184 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 242 # user perms
188 243 config.add_route(
189 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 247 config.add_route(
192 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 252 # user user groups management
196 253 config.add_route(
197 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 258 config.add_route(
201 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 263 # user audit logs
205 264 config.add_route(
206 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 268 # user-groups admin
210 269 config.add_route(
211 270 name='user_groups',
212 271 pattern='/user_groups')
213 272
214 273 config.add_route(
215 274 name='user_groups_data',
216 275 pattern='/user_groups_data')
217 276
218 277 config.add_route(
219 278 name='user_groups_new',
220 279 pattern='/user_groups/new')
221 280
222 281 config.add_route(
223 282 name='user_groups_create',
224 283 pattern='/user_groups/create')
225 284
226 285 # repos admin
227 286 config.add_route(
228 287 name='repos',
229 288 pattern='/repos')
230 289
231 290 config.add_route(
232 291 name='repo_new',
233 292 pattern='/repos/new')
234 293
235 294 config.add_route(
236 295 name='repo_create',
237 296 pattern='/repos/create')
238 297
239 298
240 299 def includeme(config):
241 300 settings = config.get_settings()
242 301
243 302 # Create admin navigation registry and add it to the pyramid registry.
244 303 labs_active = str2bool(settings.get('labs_settings_active', False))
245 304 navigation_registry = NavigationRegistry(labs_active=labs_active)
246 305 config.registry.registerUtility(navigation_registry)
247 306
248 307 # main admin routes
249 308 config.add_route(name='admin_home', pattern=ADMIN_PREFIX)
250 309 config.include(admin_routes, route_prefix=ADMIN_PREFIX)
251 310
252 311 # Scan module for configuration decorators.
253 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 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import 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 28 from rhodecode.model.meta import Session
25 29 from rhodecode.model.user import UserModel
26 30
27 31 from rhodecode.tests import (
28 32 TestController, TEST_USER_REGULAR_LOGIN, assert_session_flash)
29 33 from rhodecode.tests.fixture import Fixture
30 34
31 35 fixture = Fixture()
32 36
33 37
34 38 def route_path(name, params=None, **kwargs):
35 39 import urllib
36 40 from rhodecode.apps._base import ADMIN_PREFIX
37 41
38 42 base_url = {
39 43 'users':
40 44 ADMIN_PREFIX + '/users',
41 45 'users_data':
42 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 68 'edit_user_auth_tokens':
44 69 ADMIN_PREFIX + '/users/{user_id}/edit/auth_tokens',
45 70 'edit_user_auth_tokens_add':
46 71 ADMIN_PREFIX + '/users/{user_id}/edit/auth_tokens/new',
47 72 'edit_user_auth_tokens_delete':
48 73 ADMIN_PREFIX + '/users/{user_id}/edit/auth_tokens/delete',
49 74
50 75 'edit_user_emails':
51 76 ADMIN_PREFIX + '/users/{user_id}/edit/emails',
52 77 'edit_user_emails_add':
53 78 ADMIN_PREFIX + '/users/{user_id}/edit/emails/new',
54 79 'edit_user_emails_delete':
55 80 ADMIN_PREFIX + '/users/{user_id}/edit/emails/delete',
56 81
57 82 'edit_user_ips':
58 83 ADMIN_PREFIX + '/users/{user_id}/edit/ips',
59 84 'edit_user_ips_add':
60 85 ADMIN_PREFIX + '/users/{user_id}/edit/ips/new',
61 86 'edit_user_ips_delete':
62 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 97 }[name].format(**kwargs)
64 98
65 99 if params:
66 100 base_url = '{}?{}'.format(base_url, urllib.urlencode(params))
67 101 return base_url
68 102
69 103
70 104 class TestAdminUsersView(TestController):
71 105
72 106 def test_show_users(self):
73 107 self.log_user()
74 108 self.app.get(route_path('users'))
75 109
76 110 def test_show_users_data(self, xhr_header):
77 111 self.log_user()
78 112 response = self.app.get(route_path(
79 113 'users_data'), extra_environ=xhr_header)
80 114
81 115 all_users = User.query().filter(
82 116 User.username != User.DEFAULT_USER).count()
83 117 assert response.json['recordsTotal'] == all_users
84 118
85 119 def test_show_users_data_filtered(self, xhr_header):
86 120 self.log_user()
87 121 response = self.app.get(route_path(
88 122 'users_data', params={'search[value]': 'empty_search'}),
89 123 extra_environ=xhr_header)
90 124
91 125 all_users = User.query().filter(
92 126 User.username != User.DEFAULT_USER).count()
93 127 assert response.json['recordsTotal'] == all_users
94 128 assert response.json['recordsFiltered'] == 0
95 129
96 130 def test_auth_tokens_default_user(self):
97 131 self.log_user()
98 132 user = User.get_default_user()
99 133 response = self.app.get(
100 134 route_path('edit_user_auth_tokens', user_id=user.user_id),
101 135 status=302)
102 136
103 137 def test_auth_tokens(self):
104 138 self.log_user()
105 139
106 140 user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
107 141 response = self.app.get(
108 142 route_path('edit_user_auth_tokens', user_id=user.user_id))
109 143 for token in user.auth_tokens:
110 144 response.mustcontain(token)
111 145 response.mustcontain('never')
112 146
113 147 @pytest.mark.parametrize("desc, lifetime", [
114 148 ('forever', -1),
115 149 ('5mins', 60*5),
116 150 ('30days', 60*60*24*30),
117 151 ])
118 152 def test_add_auth_token(self, desc, lifetime, user_util):
119 153 self.log_user()
120 154 user = user_util.create_user()
121 155 user_id = user.user_id
122 156
123 157 response = self.app.post(
124 158 route_path('edit_user_auth_tokens_add', user_id=user_id),
125 159 {'description': desc, 'lifetime': lifetime,
126 160 'csrf_token': self.csrf_token})
127 161 assert_session_flash(response, 'Auth token successfully created')
128 162
129 163 response = response.follow()
130 164 user = User.get(user_id)
131 165 for auth_token in user.auth_tokens:
132 166 response.mustcontain(auth_token)
133 167
134 168 def test_delete_auth_token(self, user_util):
135 169 self.log_user()
136 170 user = user_util.create_user()
137 171 user_id = user.user_id
138 172 keys = user.auth_tokens
139 173 assert 2 == len(keys)
140 174
141 175 response = self.app.post(
142 176 route_path('edit_user_auth_tokens_add', user_id=user_id),
143 177 {'description': 'desc', 'lifetime': -1,
144 178 'csrf_token': self.csrf_token})
145 179 assert_session_flash(response, 'Auth token successfully created')
146 180 response.follow()
147 181
148 182 # now delete our key
149 183 keys = UserApiKeys.query().filter(UserApiKeys.user_id == user_id).all()
150 184 assert 3 == len(keys)
151 185
152 186 response = self.app.post(
153 187 route_path('edit_user_auth_tokens_delete', user_id=user_id),
154 188 {'del_auth_token': keys[0].user_api_key_id,
155 189 'csrf_token': self.csrf_token})
156 190
157 191 assert_session_flash(response, 'Auth token successfully deleted')
158 192 keys = UserApiKeys.query().filter(UserApiKeys.user_id == user_id).all()
159 193 assert 2 == len(keys)
160 194
161 195 def test_ips(self):
162 196 self.log_user()
163 197 user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
164 198 response = self.app.get(route_path('edit_user_ips', user_id=user.user_id))
165 199 response.mustcontain('All IP addresses are allowed')
166 200
167 201 @pytest.mark.parametrize("test_name, ip, ip_range, failure", [
168 202 ('127/24', '127.0.0.1/24', '127.0.0.0 - 127.0.0.255', False),
169 203 ('10/32', '10.0.0.10/32', '10.0.0.10 - 10.0.0.10', False),
170 204 ('0/16', '0.0.0.0/16', '0.0.0.0 - 0.0.255.255', False),
171 205 ('0/8', '0.0.0.0/8', '0.0.0.0 - 0.255.255.255', False),
172 206 ('127_bad_mask', '127.0.0.1/99', '127.0.0.1 - 127.0.0.1', True),
173 207 ('127_bad_ip', 'foobar', 'foobar', True),
174 208 ])
175 209 def test_ips_add(self, user_util, test_name, ip, ip_range, failure):
176 210 self.log_user()
177 211 user = user_util.create_user(username=test_name)
178 212 user_id = user.user_id
179 213
180 214 response = self.app.post(
181 215 route_path('edit_user_ips_add', user_id=user_id),
182 216 params={'new_ip': ip, 'csrf_token': self.csrf_token})
183 217
184 218 if failure:
185 219 assert_session_flash(
186 220 response, 'Please enter a valid IPv4 or IpV6 address')
187 221 response = self.app.get(route_path('edit_user_ips', user_id=user_id))
188 222
189 223 response.mustcontain(no=[ip])
190 224 response.mustcontain(no=[ip_range])
191 225
192 226 else:
193 227 response = self.app.get(route_path('edit_user_ips', user_id=user_id))
194 228 response.mustcontain(ip)
195 229 response.mustcontain(ip_range)
196 230
197 231 def test_ips_delete(self, user_util):
198 232 self.log_user()
199 233 user = user_util.create_user()
200 234 user_id = user.user_id
201 235 ip = '127.0.0.1/32'
202 236 ip_range = '127.0.0.1 - 127.0.0.1'
203 237 new_ip = UserModel().add_extra_ip(user_id, ip)
204 238 Session().commit()
205 239 new_ip_id = new_ip.ip_id
206 240
207 241 response = self.app.get(route_path('edit_user_ips', user_id=user_id))
208 242 response.mustcontain(ip)
209 243 response.mustcontain(ip_range)
210 244
211 245 self.app.post(
212 246 route_path('edit_user_ips_delete', user_id=user_id),
213 247 params={'del_ip_id': new_ip_id, 'csrf_token': self.csrf_token})
214 248
215 249 response = self.app.get(route_path('edit_user_ips', user_id=user_id))
216 250 response.mustcontain('All IP addresses are allowed')
217 251 response.mustcontain(no=[ip])
218 252 response.mustcontain(no=[ip_range])
219 253
220 254 def test_emails(self):
221 255 self.log_user()
222 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 259 response.mustcontain('No additional emails specified')
225 260
226 261 def test_emails_add(self, user_util):
227 262 self.log_user()
228 263 user = user_util.create_user()
229 264 user_id = user.user_id
230 265
231 266 self.app.post(
232 267 route_path('edit_user_emails_add', user_id=user_id),
233 268 params={'new_email': 'example@rhodecode.com',
234 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 273 response.mustcontain('example@rhodecode.com')
238 274
239 275 def test_emails_add_existing_email(self, user_util, user_regular):
240 276 existing_email = user_regular.email
241 277
242 278 self.log_user()
243 279 user = user_util.create_user()
244 280 user_id = user.user_id
245 281
246 282 response = self.app.post(
247 283 route_path('edit_user_emails_add', user_id=user_id),
248 284 params={'new_email': existing_email,
249 285 'csrf_token': self.csrf_token})
250 286 assert_session_flash(
251 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 291 response.mustcontain(no=[existing_email])
255 292
256 293 def test_emails_delete(self, user_util):
257 294 self.log_user()
258 295 user = user_util.create_user()
259 296 user_id = user.user_id
260 297
261 298 self.app.post(
262 299 route_path('edit_user_emails_add', user_id=user_id),
263 300 params={'new_email': 'example@rhodecode.com',
264 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 305 response.mustcontain('example@rhodecode.com')
268 306
269 307 user_email = UserEmailMap.query()\
270 308 .filter(UserEmailMap.email == 'example@rhodecode.com') \
271 309 .filter(UserEmailMap.user_id == user_id)\
272 310 .one()
273 311
274 312 del_email_id = user_email.email_id
275 313 self.app.post(
276 314 route_path('edit_user_emails_delete', user_id=user_id),
277 315 params={'del_email_id': del_email_id,
278 316 'csrf_token': self.csrf_token})
279 317
280 response = self.app.get(route_path('edit_user_emails', user_id=user_id))
281 response.mustcontain(no=['example@rhodecode.com']) No newline at end of file
318 response = self.app.get(
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 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2016-2017 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 import time
22 21 import logging
23 22 import datetime
24 23 import formencode
25 24 import formencode.htmlfill
26 25
27 26 from pyramid.httpexceptions import HTTPFound
28 27 from pyramid.view import view_config
29 from sqlalchemy.sql.functions import coalesce
30 from sqlalchemy.exc import IntegrityError
28 from pyramid.renderers import render
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 32 from rhodecode.apps.ssh_support import SshKeyFileChangeEvent
33 from rhodecode.authentication.plugins import auth_rhodecode
34 34 from rhodecode.events import trigger
35 35
36 36 from rhodecode.lib import audit_logger
37 from rhodecode.lib.exceptions import (
38 UserCreationError, UserOwnsReposException, UserOwnsRepoGroupsException,
39 UserOwnsUserGroupsException, DefaultUserException)
37 40 from rhodecode.lib.ext_json import json
38 41 from rhodecode.lib.auth import (
39 42 LoginRequired, HasPermissionAllDecorator, CSRFRequired)
40 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 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 50 from rhodecode.model.ssh_key import SshKeyModel
44 51 from rhodecode.model.user import UserModel
45 52 from rhodecode.model.user_group import UserGroupModel
46 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 56 from rhodecode.model.meta import Session
49 57
50 58 log = logging.getLogger(__name__)
51 59
52 60
53 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 63 def load_default_context(self):
61 64 c = self._get_local_tmpl_context()
62 c.allow_scoped_tokens = self.ALLOW_SCOPED_TOKENS
63 65 self._register_global_c(c)
64 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 68 @LoginRequired()
75 69 @HasPermissionAllDecorator('hg.admin')
76 70 @view_config(
77 71 route_name='users', request_method='GET',
78 72 renderer='rhodecode:templates/admin/users/users.mako')
79 73 def users_list(self):
80 74 c = self.load_default_context()
81 75 return self._get_template_context(c)
82 76
83 77 @LoginRequired()
84 78 @HasPermissionAllDecorator('hg.admin')
85 79 @view_config(
86 80 # renderer defined below
87 81 route_name='users_data', request_method='GET',
88 82 renderer='json_ext', xhr=True)
89 83 def users_list_data(self):
90 84 column_map = {
91 85 'first_name': 'name',
92 86 'last_name': 'lastname',
93 87 }
94 88 draw, start, limit = self._extract_chunk(self.request)
95 89 search_q, order_by, order_dir = self._extract_ordering(
96 90 self.request, column_map=column_map)
97 91
98 92 _render = self.request.get_partial_renderer(
99 93 'data_table/_dt_elements.mako')
100 94
101 95 def user_actions(user_id, username):
102 96 return _render("user_actions", user_id, username)
103 97
104 98 users_data_total_count = User.query()\
105 99 .filter(User.username != User.DEFAULT_USER) \
106 100 .count()
107 101
108 102 # json generate
109 103 base_q = User.query().filter(User.username != User.DEFAULT_USER)
110 104
111 105 if search_q:
112 106 like_expression = u'%{}%'.format(safe_unicode(search_q))
113 107 base_q = base_q.filter(or_(
114 108 User.username.ilike(like_expression),
115 109 User._email.ilike(like_expression),
116 110 User.name.ilike(like_expression),
117 111 User.lastname.ilike(like_expression),
118 112 ))
119 113
120 114 users_data_total_filtered_count = base_q.count()
121 115
122 116 sort_col = getattr(User, order_by, None)
123 117 if sort_col:
124 118 if order_dir == 'asc':
125 119 # handle null values properly to order by NULL last
126 120 if order_by in ['last_activity']:
127 121 sort_col = coalesce(sort_col, datetime.date.max)
128 122 sort_col = sort_col.asc()
129 123 else:
130 124 # handle null values properly to order by NULL last
131 125 if order_by in ['last_activity']:
132 126 sort_col = coalesce(sort_col, datetime.date.min)
133 127 sort_col = sort_col.desc()
134 128
135 129 base_q = base_q.order_by(sort_col)
136 130 base_q = base_q.offset(start).limit(limit)
137 131
138 132 users_list = base_q.all()
139 133
140 134 users_data = []
141 135 for user in users_list:
142 136 users_data.append({
143 137 "username": h.gravatar_with_user(self.request, user.username),
144 138 "email": user.email,
145 139 "first_name": user.first_name,
146 140 "last_name": user.last_name,
147 141 "last_login": h.format_date(user.last_login),
148 142 "last_activity": h.format_date(user.last_activity),
149 143 "active": h.bool2icon(user.active),
150 144 "active_raw": user.active,
151 145 "admin": h.bool2icon(user.admin),
152 146 "extern_type": user.extern_type,
153 147 "extern_name": user.extern_name,
154 148 "action": user_actions(user.user_id, user.username),
155 149 })
156 150
157 151 data = ({
158 152 'draw': draw,
159 153 'data': users_data,
160 154 'recordsTotal': users_data_total_count,
161 155 'recordsFiltered': users_data_total_filtered_count,
162 156 })
163 157
164 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 683 @LoginRequired()
167 684 @HasPermissionAllDecorator('hg.admin')
168 685 @view_config(
169 686 route_name='edit_user_auth_tokens', request_method='GET',
170 687 renderer='rhodecode:templates/admin/users/user_edit.mako')
171 688 def auth_tokens(self):
172 689 _ = self.request.translate
173 690 c = self.load_default_context()
174
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)
691 c.user = self.db_user
178 692
179 693 c.active = 'auth_tokens'
180 694
181 695 c.lifetime_values = AuthTokenModel.get_lifetime_values(translator=_)
182 696 c.role_values = [
183 697 (x, AuthTokenModel.cls._get_role_name(x))
184 698 for x in AuthTokenModel.cls.ROLES]
185 699 c.role_options = [(c.role_values, _("Role"))]
186 700 c.user_auth_tokens = AuthTokenModel().get_auth_tokens(
187 701 c.user.user_id, show_expired=True)
188 702 return self._get_template_context(c)
189 703
190 704 def maybe_attach_token_scope(self, token):
191 705 # implemented in EE edition
192 706 pass
193 707
194 708 @LoginRequired()
195 709 @HasPermissionAllDecorator('hg.admin')
196 710 @CSRFRequired()
197 711 @view_config(
198 712 route_name='edit_user_auth_tokens_add', request_method='POST')
199 713 def auth_tokens_add(self):
200 714 _ = self.request.translate
201 715 c = self.load_default_context()
202 716
203 user_id = self.request.matchdict.get('user_id')
204 c.user = User.get_or_404(user_id)
205
206 self._redirect_for_default_user(c.user.username)
717 user_id = self.db_user_id
718 c.user = self.db_user
207 719
208 720 user_data = c.user.get_api_data()
209 721 lifetime = safe_int(self.request.POST.get('lifetime'), -1)
210 722 description = self.request.POST.get('description')
211 723 role = self.request.POST.get('role')
212 724
213 725 token = AuthTokenModel().create(
214 726 c.user.user_id, description, lifetime, role)
215 727 token_data = token.get_api_data()
216 728
217 729 self.maybe_attach_token_scope(token)
218 730 audit_logger.store_web(
219 731 'user.edit.token.add', action_data={
220 732 'data': {'token': token_data, 'user': user_data}},
221 733 user=self._rhodecode_user, )
222 734 Session().commit()
223 735
224 736 h.flash(_("Auth token successfully created"), category='success')
225 737 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
226 738
227 739 @LoginRequired()
228 740 @HasPermissionAllDecorator('hg.admin')
229 741 @CSRFRequired()
230 742 @view_config(
231 743 route_name='edit_user_auth_tokens_delete', request_method='POST')
232 744 def auth_tokens_delete(self):
233 745 _ = self.request.translate
234 746 c = self.load_default_context()
235 747
236 user_id = self.request.matchdict.get('user_id')
237 c.user = User.get_or_404(user_id)
238 self._redirect_for_default_user(c.user.username)
748 user_id = self.db_user_id
749 c.user = self.db_user
750
239 751 user_data = c.user.get_api_data()
240 752
241 753 del_auth_token = self.request.POST.get('del_auth_token')
242 754
243 755 if del_auth_token:
244 756 token = UserApiKeys.get_or_404(del_auth_token)
245 757 token_data = token.get_api_data()
246 758
247 759 AuthTokenModel().delete(del_auth_token, c.user.user_id)
248 760 audit_logger.store_web(
249 761 'user.edit.token.delete', action_data={
250 762 'data': {'token': token_data, 'user': user_data}},
251 763 user=self._rhodecode_user,)
252 764 Session().commit()
253 765 h.flash(_("Auth token successfully deleted"), category='success')
254 766
255 767 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
256 768
257 769 @LoginRequired()
258 770 @HasPermissionAllDecorator('hg.admin')
259 771 @view_config(
260 772 route_name='edit_user_ssh_keys', request_method='GET',
261 773 renderer='rhodecode:templates/admin/users/user_edit.mako')
262 774 def ssh_keys(self):
263 775 _ = self.request.translate
264 776 c = self.load_default_context()
265
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)
777 c.user = self.db_user
269 778
270 779 c.active = 'ssh_keys'
271 780 c.default_key = self.request.GET.get('default_key')
272 781 c.user_ssh_keys = SshKeyModel().get_ssh_keys(c.user.user_id)
273 782 return self._get_template_context(c)
274 783
275 784 @LoginRequired()
276 785 @HasPermissionAllDecorator('hg.admin')
277 786 @view_config(
278 787 route_name='edit_user_ssh_keys_generate_keypair', request_method='GET',
279 788 renderer='rhodecode:templates/admin/users/user_edit.mako')
280 789 def ssh_keys_generate_keypair(self):
281 790 _ = self.request.translate
282 791 c = self.load_default_context()
283 792
284 user_id = self.request.matchdict.get('user_id')
285 c.user = User.get_or_404(user_id)
286 self._redirect_for_default_user(c.user.username)
793 c.user = self.db_user
287 794
288 795 c.active = 'ssh_keys_generate'
289 796 comment = 'RhodeCode-SSH {}'.format(c.user.email or '')
290 797 c.private, c.public = SshKeyModel().generate_keypair(comment=comment)
291 798
292 799 return self._get_template_context(c)
293 800
294 801 @LoginRequired()
295 802 @HasPermissionAllDecorator('hg.admin')
296 803 @CSRFRequired()
297 804 @view_config(
298 805 route_name='edit_user_ssh_keys_add', request_method='POST')
299 806 def ssh_keys_add(self):
300 807 _ = self.request.translate
301 808 c = self.load_default_context()
302 809
303 user_id = self.request.matchdict.get('user_id')
304 c.user = User.get_or_404(user_id)
305
306 self._redirect_for_default_user(c.user.username)
810 user_id = self.db_user_id
811 c.user = self.db_user
307 812
308 813 user_data = c.user.get_api_data()
309 814 key_data = self.request.POST.get('key_data')
310 815 description = self.request.POST.get('description')
311 816
312 817 try:
313 818 if not key_data:
314 819 raise ValueError('Please add a valid public key')
315 820
316 821 key = SshKeyModel().parse_key(key_data.strip())
317 822 fingerprint = key.hash_md5()
318 823
319 824 ssh_key = SshKeyModel().create(
320 825 c.user.user_id, fingerprint, key_data, description)
321 826 ssh_key_data = ssh_key.get_api_data()
322 827
323 828 audit_logger.store_web(
324 829 'user.edit.ssh_key.add', action_data={
325 830 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
326 831 user=self._rhodecode_user, )
327 832 Session().commit()
328 833
329 834 # Trigger an event on change of keys.
330 835 trigger(SshKeyFileChangeEvent(), self.request.registry)
331 836
332 837 h.flash(_("Ssh Key successfully created"), category='success')
333 838
334 839 except IntegrityError:
335 840 log.exception("Exception during ssh key saving")
336 841 h.flash(_('An error occurred during ssh key saving: {}').format(
337 842 'Such key already exists, please use a different one'),
338 843 category='error')
339 844 except Exception as e:
340 845 log.exception("Exception during ssh key saving")
341 846 h.flash(_('An error occurred during ssh key saving: {}').format(e),
342 847 category='error')
343 848
344 849 return HTTPFound(
345 850 h.route_path('edit_user_ssh_keys', user_id=user_id))
346 851
347 852 @LoginRequired()
348 853 @HasPermissionAllDecorator('hg.admin')
349 854 @CSRFRequired()
350 855 @view_config(
351 856 route_name='edit_user_ssh_keys_delete', request_method='POST')
352 857 def ssh_keys_delete(self):
353 858 _ = self.request.translate
354 859 c = self.load_default_context()
355 860
356 user_id = self.request.matchdict.get('user_id')
357 c.user = User.get_or_404(user_id)
358 self._redirect_for_default_user(c.user.username)
861 user_id = self.db_user_id
862 c.user = self.db_user
863
359 864 user_data = c.user.get_api_data()
360 865
361 866 del_ssh_key = self.request.POST.get('del_ssh_key')
362 867
363 868 if del_ssh_key:
364 869 ssh_key = UserSshKeys.get_or_404(del_ssh_key)
365 870 ssh_key_data = ssh_key.get_api_data()
366 871
367 872 SshKeyModel().delete(del_ssh_key, c.user.user_id)
368 873 audit_logger.store_web(
369 874 'user.edit.ssh_key.delete', action_data={
370 875 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
371 876 user=self._rhodecode_user,)
372 877 Session().commit()
373 878 # Trigger an event on change of keys.
374 879 trigger(SshKeyFileChangeEvent(), self.request.registry)
375 880 h.flash(_("Ssh key successfully deleted"), category='success')
376 881
377 882 return HTTPFound(h.route_path('edit_user_ssh_keys', user_id=user_id))
378 883
379 884 @LoginRequired()
380 885 @HasPermissionAllDecorator('hg.admin')
381 886 @view_config(
382 887 route_name='edit_user_emails', request_method='GET',
383 888 renderer='rhodecode:templates/admin/users/user_edit.mako')
384 889 def emails(self):
385 890 _ = self.request.translate
386 891 c = self.load_default_context()
387
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)
892 c.user = self.db_user
391 893
392 894 c.active = 'emails'
393 895 c.user_email_map = UserEmailMap.query() \
394 896 .filter(UserEmailMap.user == c.user).all()
395 897
396 898 return self._get_template_context(c)
397 899
398 900 @LoginRequired()
399 901 @HasPermissionAllDecorator('hg.admin')
400 902 @CSRFRequired()
401 903 @view_config(
402 904 route_name='edit_user_emails_add', request_method='POST')
403 905 def emails_add(self):
404 906 _ = self.request.translate
405 907 c = self.load_default_context()
406 908
407 user_id = self.request.matchdict.get('user_id')
408 c.user = User.get_or_404(user_id)
409 self._redirect_for_default_user(c.user.username)
909 user_id = self.db_user_id
910 c.user = self.db_user
410 911
411 912 email = self.request.POST.get('new_email')
412 913 user_data = c.user.get_api_data()
413 914 try:
414 915 UserModel().add_extra_email(c.user.user_id, email)
415 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 919 user=self._rhodecode_user)
418 920 Session().commit()
419 921 h.flash(_("Added new email address `%s` for user account") % email,
420 922 category='success')
421 923 except formencode.Invalid as error:
422 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 929 except Exception:
424 930 log.exception("Exception during email saving")
425 931 h.flash(_('An error occurred during email saving'),
426 932 category='error')
427 933 raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id))
428 934
429 935 @LoginRequired()
430 936 @HasPermissionAllDecorator('hg.admin')
431 937 @CSRFRequired()
432 938 @view_config(
433 939 route_name='edit_user_emails_delete', request_method='POST')
434 940 def emails_delete(self):
435 941 _ = self.request.translate
436 942 c = self.load_default_context()
437 943
438 user_id = self.request.matchdict.get('user_id')
439 c.user = User.get_or_404(user_id)
440 self._redirect_for_default_user(c.user.username)
944 user_id = self.db_user_id
945 c.user = self.db_user
441 946
442 947 email_id = self.request.POST.get('del_email_id')
443 948 user_model = UserModel()
444 949
445 950 email = UserEmailMap.query().get(email_id).email
446 951 user_data = c.user.get_api_data()
447 952 user_model.delete_extra_email(c.user.user_id, email_id)
448 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 956 user=self._rhodecode_user)
451 957 Session().commit()
452 958 h.flash(_("Removed email address from user account"),
453 959 category='success')
454 960 raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id))
455 961
456 962 @LoginRequired()
457 963 @HasPermissionAllDecorator('hg.admin')
458 964 @view_config(
459 965 route_name='edit_user_ips', request_method='GET',
460 966 renderer='rhodecode:templates/admin/users/user_edit.mako')
461 967 def ips(self):
462 968 _ = self.request.translate
463 969 c = self.load_default_context()
464
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)
970 c.user = self.db_user
468 971
469 972 c.active = 'ips'
470 973 c.user_ip_map = UserIpMap.query() \
471 974 .filter(UserIpMap.user == c.user).all()
472 975
473 976 c.inherit_default_ips = c.user.inherit_default_permissions
474 977 c.default_user_ip_map = UserIpMap.query() \
475 978 .filter(UserIpMap.user == User.get_default_user()).all()
476 979
477 980 return self._get_template_context(c)
478 981
479 982 @LoginRequired()
480 983 @HasPermissionAllDecorator('hg.admin')
481 984 @CSRFRequired()
482 985 @view_config(
483 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 989 def ips_add(self):
485 990 _ = self.request.translate
486 991 c = self.load_default_context()
487 992
488 user_id = self.request.matchdict.get('user_id')
489 c.user = User.get_or_404(user_id)
490 # NOTE(marcink): this view is allowed for default users, as we can
491 # edit their IP white list
993 user_id = self.db_user_id
994 c.user = self.db_user
492 995
493 996 user_model = UserModel()
494 997 desc = self.request.POST.get('description')
495 998 try:
496 999 ip_list = user_model.parse_ip_range(
497 1000 self.request.POST.get('new_ip'))
498 1001 except Exception as e:
499 1002 ip_list = []
500 1003 log.exception("Exception during ip saving")
501 1004 h.flash(_('An error occurred during ip saving:%s' % (e,)),
502 1005 category='error')
503 1006 added = []
504 1007 user_data = c.user.get_api_data()
505 1008 for ip in ip_list:
506 1009 try:
507 1010 user_model.add_extra_ip(c.user.user_id, ip, desc)
508 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 1014 user=self._rhodecode_user)
511 1015 Session().commit()
512 1016 added.append(ip)
513 1017 except formencode.Invalid as error:
514 1018 msg = error.error_dict['ip']
515 1019 h.flash(msg, category='error')
516 1020 except Exception:
517 1021 log.exception("Exception during ip saving")
518 1022 h.flash(_('An error occurred during ip saving'),
519 1023 category='error')
520 1024 if added:
521 1025 h.flash(
522 1026 _("Added ips %s to user whitelist") % (', '.join(ip_list), ),
523 1027 category='success')
524 1028 if 'default_user' in self.request.POST:
525 1029 # case for editing global IP list we do it for 'DEFAULT' user
526 1030 raise HTTPFound(h.route_path('admin_permissions_ips'))
527 1031 raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id))
528 1032
529 1033 @LoginRequired()
530 1034 @HasPermissionAllDecorator('hg.admin')
531 1035 @CSRFRequired()
532 1036 @view_config(
533 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 1040 def ips_delete(self):
535 1041 _ = self.request.translate
536 1042 c = self.load_default_context()
537 1043
538 user_id = self.request.matchdict.get('user_id')
539 c.user = User.get_or_404(user_id)
540 # NOTE(marcink): this view is allowed for default users, as we can
541 # edit their IP white list
1044 user_id = self.db_user_id
1045 c.user = self.db_user
542 1046
543 1047 ip_id = self.request.POST.get('del_ip_id')
544 1048 user_model = UserModel()
545 1049 user_data = c.user.get_api_data()
546 1050 ip = UserIpMap.query().get(ip_id).ip_addr
547 1051 user_model.delete_extra_ip(c.user.user_id, ip_id)
548 1052 audit_logger.store_web(
549 1053 'user.edit.ip.delete', action_data={'ip': ip, 'user': user_data},
550 1054 user=self._rhodecode_user)
551 1055 Session().commit()
552 1056 h.flash(_("Removed ip address from user whitelist"), category='success')
553 1057
554 1058 if 'default_user' in self.request.POST:
555 1059 # case for editing global IP list we do it for 'DEFAULT' user
556 1060 raise HTTPFound(h.route_path('admin_permissions_ips'))
557 1061 raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id))
558 1062
559 1063 @LoginRequired()
560 1064 @HasPermissionAllDecorator('hg.admin')
561 1065 @view_config(
562 1066 route_name='edit_user_groups_management', request_method='GET',
563 1067 renderer='rhodecode:templates/admin/users/user_edit.mako')
564 1068 def groups_management(self):
565 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 1073 groups = [UserGroupModel.get_user_groups_as_dict(group.users_group)
572 1074 for group in c.user.group_member]
573 1075 c.groups = json.dumps(groups)
574 1076 c.active = 'groups'
575 1077
576 1078 return self._get_template_context(c)
577 1079
578 1080 @LoginRequired()
579 1081 @HasPermissionAllDecorator('hg.admin')
580 1082 @CSRFRequired()
581 1083 @view_config(
582 1084 route_name='edit_user_groups_management_updates', request_method='POST')
583 1085 def groups_management_updates(self):
584 1086 _ = self.request.translate
585 1087 c = self.load_default_context()
586 1088
587 user_id = self.request.matchdict.get('user_id')
588 c.user = User.get_or_404(user_id)
589 self._redirect_for_default_user(c.user.username)
1089 user_id = self.db_user_id
1090 c.user = self.db_user
590 1091
591 1092 user_groups = set(self.request.POST.getall('users_group_id'))
592 1093 user_groups_objects = []
593 1094
594 1095 for ugid in user_groups:
595 1096 user_groups_objects.append(
596 1097 UserGroupModel().get_group(safe_int(ugid)))
597 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 1119 Session().commit()
601 1120 c.active = 'user_groups_management'
602 1121 h.flash(_("Groups successfully changed"), category='success')
603 1122
604 1123 return HTTPFound(h.route_path(
605 1124 'edit_user_groups_management', user_id=user_id))
606 1125
607 1126 @LoginRequired()
608 1127 @HasPermissionAllDecorator('hg.admin')
609 1128 @view_config(
610 1129 route_name='edit_user_audit_logs', request_method='GET',
611 1130 renderer='rhodecode:templates/admin/users/user_edit.mako')
612 1131 def user_audit_logs(self):
613 1132 _ = self.request.translate
614 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 1136 c.active = 'audit'
620 1137
621 1138 p = safe_int(self.request.GET.get('page', 1), 1)
622 1139
623 1140 filter_term = self.request.GET.get('filter')
624 1141 user_log = UserModel().get_user_log(c.user, filter_term)
625 1142
626 1143 def url_generator(**kw):
627 1144 if filter_term:
628 1145 kw['filter'] = filter_term
629 1146 return self.request.current_route_path(_query=kw)
630 1147
631 1148 c.audit_logs = h.Page(
632 1149 user_log, page=p, items_per_page=10, url=url_generator)
633 1150 c.filter_term = filter_term
634 1151 return self._get_template_context(c)
635 1152
636 1153 @LoginRequired()
637 1154 @HasPermissionAllDecorator('hg.admin')
638 1155 @view_config(
639 1156 route_name='edit_user_perms_summary', request_method='GET',
640 1157 renderer='rhodecode:templates/admin/users/user_edit.mako')
641 1158 def user_perms_summary(self):
642 1159 _ = self.request.translate
643 1160 c = self.load_default_context()
644
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)
1161 c.user = self.db_user
648 1162
649 1163 c.active = 'perms_summary'
650 1164 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
651 1165
652 1166 return self._get_template_context(c)
653 1167
654 1168 @LoginRequired()
655 1169 @HasPermissionAllDecorator('hg.admin')
656 1170 @view_config(
657 1171 route_name='edit_user_perms_summary_json', request_method='GET',
658 1172 renderer='json_ext')
659 1173 def user_perms_summary_json(self):
660 1174 self.load_default_context()
661
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)
1175 perm_user = self.db_user.AuthUser(ip_addr=self.request.remote_addr)
667 1176
668 1177 return perm_user.permissions
@@ -1,182 +1,182 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 Pylons environment configuration
23 23 """
24 24
25 25 import os
26 26 import logging
27 27 import rhodecode
28 28 import platform
29 29 import re
30 30 import io
31 31
32 32 from mako.lookup import TemplateLookup
33 33 from pylons.configuration import PylonsConfig
34 34 from pylons.error import handle_mako_error
35 35 from pyramid.settings import asbool
36 36
37 37 # ------------------------------------------------------------------------------
38 38 # CELERY magic until refactor - issue #4163 - import order matters here:
39 39 from rhodecode.lib import celerypylons # this must be first, celerypylons
40 40 # sets config settings upon import
41 41
42 42 import rhodecode.integrations # any modules using celery task
43 43 # decorators should be added afterwards:
44 44 # ------------------------------------------------------------------------------
45 45
46 46 from rhodecode.lib import app_globals
47 47 from rhodecode.config import utils
48 48 from rhodecode.config.routing import make_map
49 49 from rhodecode.config.jsroutes import generate_jsroutes_content
50 50
51 51 from rhodecode.lib import helpers
52 52 from rhodecode.lib.auth import set_available_permissions
53 53 from rhodecode.lib.utils import (
54 54 repo2db_mapper, make_db_config, set_rhodecode_config,
55 55 load_rcextensions)
56 56 from rhodecode.lib.utils2 import str2bool, aslist
57 57 from rhodecode.lib.vcs import connect_vcs, start_vcs_server
58 58 from rhodecode.model.scm import ScmModel
59 59
60 60 log = logging.getLogger(__name__)
61 61
62 62 def load_environment(global_conf, app_conf, initial=False,
63 63 test_env=None, test_index=None):
64 64 """
65 65 Configure the Pylons environment via the ``pylons.config``
66 66 object
67 67 """
68 68 config = PylonsConfig()
69 69
70 70
71 71 # Pylons paths
72 72 root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
73 73 paths = {
74 74 'root': root,
75 75 'controllers': os.path.join(root, 'controllers'),
76 76 'static_files': os.path.join(root, 'public'),
77 77 'templates': [os.path.join(root, 'templates')],
78 78 }
79 79
80 80 # Initialize config with the basic options
81 81 config.init_app(global_conf, app_conf, package='rhodecode', paths=paths)
82 82
83 83 # store some globals into rhodecode
84 84 rhodecode.CELERY_ENABLED = str2bool(config['app_conf'].get('use_celery'))
85 85 rhodecode.CELERY_EAGER = str2bool(
86 86 config['app_conf'].get('celery.always.eager'))
87 87
88 88 config['routes.map'] = make_map(config)
89 89
90 90 config['pylons.app_globals'] = app_globals.Globals(config)
91 91 config['pylons.h'] = helpers
92 92 rhodecode.CONFIG = config
93 93
94 94 load_rcextensions(root_path=config['here'])
95 95
96 96 # Setup cache object as early as possible
97 97 import pylons
98 98 pylons.cache._push_object(config['pylons.app_globals'].cache)
99 99
100 100 # Create the Mako TemplateLookup, with the default auto-escaping
101 101 config['pylons.app_globals'].mako_lookup = TemplateLookup(
102 102 directories=paths['templates'],
103 103 error_handler=handle_mako_error,
104 104 module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
105 105 input_encoding='utf-8', default_filters=['escape'],
106 106 imports=['from webhelpers.html import escape'])
107 107
108 108 # sets the c attribute access when don't existing attribute are accessed
109 109 config['pylons.strict_tmpl_context'] = True
110 110
111 111 # configure channelstream
112 112 config['channelstream_config'] = {
113 113 'enabled': asbool(config.get('channelstream.enabled', False)),
114 114 'server': config.get('channelstream.server'),
115 115 'secret': config.get('channelstream.secret')
116 116 }
117 117
118 set_available_permissions(config)
119 118 db_cfg = make_db_config(clear_session=True)
120 119
121 120 repos_path = list(db_cfg.items('paths'))[0][1]
122 121 config['base_path'] = repos_path
123 122
124 123 # store db config also in main global CONFIG
125 124 set_rhodecode_config(config)
126 125
127 126 # configure instance id
128 127 utils.set_instance_id(config)
129 128
130 129 # CONFIGURATION OPTIONS HERE (note: all config options will override
131 130 # any Pylons config options)
132 131
133 132 # store config reference into our module to skip import magic of pylons
134 133 rhodecode.CONFIG.update(config)
135 134
136 135 return config
137 136
138 137
139 138 def load_pyramid_environment(global_config, settings):
140 139 # Some parts of the code expect a merge of global and app settings.
141 140 settings_merged = global_config.copy()
142 141 settings_merged.update(settings)
143 142
144 143 # Store the settings to make them available to other modules.
145 144 rhodecode.PYRAMID_SETTINGS = settings_merged
146 145 # NOTE(marcink): needs to be enabled after full port to pyramid
147 146 # rhodecode.CONFIG = config
148 147
149 148 # If this is a test run we prepare the test environment like
150 149 # creating a test database, test search index and test repositories.
151 150 # This has to be done before the database connection is initialized.
152 151 if settings['is_test']:
153 152 rhodecode.is_test = True
154 153 rhodecode.disable_error_handler = True
155 154
156 155 utils.initialize_test_environment(settings_merged)
157 156
158 157 # Initialize the database connection.
159 158 utils.initialize_database(settings_merged)
160 159
161 160 # Limit backends to `vcs.backends` from configuration
162 161 for alias in rhodecode.BACKENDS.keys():
163 162 if alias not in settings['vcs.backends']:
164 163 del rhodecode.BACKENDS[alias]
165 164 log.info('Enabled VCS backends: %s', rhodecode.BACKENDS.keys())
166 165
167 166 # initialize vcs client and optionally run the server if enabled
168 167 vcs_server_uri = settings['vcs.server']
169 168 vcs_server_enabled = settings['vcs.server.enable']
170 169 start_server = (
171 170 settings['vcs.start_server'] and
172 171 not int(os.environ.get('RC_VCSSERVER_TEST_DISABLE', '0')))
173 172
174 173 if vcs_server_enabled and start_server:
175 174 log.info("Starting vcsserver")
176 175 start_vcs_server(server_and_port=vcs_server_uri,
177 176 protocol=utils.get_vcs_server_protocol(settings),
178 177 log_level=settings['vcs.server.log_level'])
179 178
180 179 utils.configure_vcs(settings)
180
181 181 if vcs_server_enabled:
182 182 connect_vcs(vcs_server_uri, utils.get_vcs_server_protocol(settings))
@@ -1,536 +1,542 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 Pylons middleware initialization
23 23 """
24 24 import logging
25 25 import traceback
26 26 from collections import OrderedDict
27 27
28 28 from paste.registry import RegistryManager
29 29 from paste.gzipper import make_gzip_middleware
30 30 from pylons.wsgiapp import PylonsApp
31 31 from pyramid.authorization import ACLAuthorizationPolicy
32 32 from pyramid.config import Configurator
33 33 from pyramid.settings import asbool, aslist
34 34 from pyramid.wsgi import wsgiapp
35 35 from pyramid.httpexceptions import (
36 36 HTTPException, HTTPError, HTTPInternalServerError, HTTPFound)
37 37 from pyramid.events import ApplicationCreated
38 38 from pyramid.renderers import render_to_response
39 39 from routes.middleware import RoutesMiddleware
40 40 import rhodecode
41 41
42 42 from rhodecode.model import meta
43 43 from rhodecode.config import patches
44 from rhodecode.config import utils as config_utils
44 45 from rhodecode.config.routing import STATIC_FILE_PREFIX
45 46 from rhodecode.config.environment import (
46 47 load_environment, load_pyramid_environment)
47 48
48 49 from rhodecode.lib.vcs import VCSCommunicationError
49 50 from rhodecode.lib.exceptions import VCSServerUnavailable
50 51 from rhodecode.lib.middleware.appenlight import wrap_in_appenlight_if_enabled
51 52 from rhodecode.lib.middleware.error_handling import (
52 53 PylonsErrorHandlingMiddleware)
53 54 from rhodecode.lib.middleware.https_fixup import HttpsFixup
54 55 from rhodecode.lib.middleware.vcs import VCSMiddleware
55 56 from rhodecode.lib.plugins.utils import register_rhodecode_plugin
56 57 from rhodecode.lib.utils2 import aslist as rhodecode_aslist, AttributeDict
57 58 from rhodecode.subscribers import (
58 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 63 log = logging.getLogger(__name__)
63 64
64 65
65 66 # this is used to avoid avoid the route lookup overhead in routesmiddleware
66 67 # for certain routes which won't go to pylons to - eg. static files, debugger
67 68 # it is only needed for the pylons migration and can be removed once complete
68 69 class SkippableRoutesMiddleware(RoutesMiddleware):
69 70 """ Routes middleware that allows you to skip prefixes """
70 71
71 72 def __init__(self, *args, **kw):
72 73 self.skip_prefixes = kw.pop('skip_prefixes', [])
73 74 super(SkippableRoutesMiddleware, self).__init__(*args, **kw)
74 75
75 76 def __call__(self, environ, start_response):
76 77 for prefix in self.skip_prefixes:
77 78 if environ['PATH_INFO'].startswith(prefix):
78 79 # added to avoid the case when a missing /_static route falls
79 80 # through to pylons and causes an exception as pylons is
80 81 # expecting wsgiorg.routingargs to be set in the environ
81 82 # by RoutesMiddleware.
82 83 if 'wsgiorg.routing_args' not in environ:
83 84 environ['wsgiorg.routing_args'] = (None, {})
84 85 return self.app(environ, start_response)
85 86
86 87 return super(SkippableRoutesMiddleware, self).__call__(
87 88 environ, start_response)
88 89
89 90
90 91 def make_app(global_conf, static_files=True, **app_conf):
91 92 """Create a Pylons WSGI application and return it
92 93
93 94 ``global_conf``
94 95 The inherited configuration for this application. Normally from
95 96 the [DEFAULT] section of the Paste ini file.
96 97
97 98 ``app_conf``
98 99 The application's local configuration. Normally specified in
99 100 the [app:<name>] section of the Paste ini file (where <name>
100 101 defaults to main).
101 102
102 103 """
103 104 # Apply compatibility patches
104 105 patches.kombu_1_5_1_python_2_7_11()
105 106 patches.inspect_getargspec()
106 107
107 108 # Configure the Pylons environment
108 109 config = load_environment(global_conf, app_conf)
109 110
110 111 # The Pylons WSGI app
111 112 app = PylonsApp(config=config)
112 113
113 114 # Establish the Registry for this application
114 115 app = RegistryManager(app)
115 116
116 117 app.config = config
117 118
118 119 return app
119 120
120 121
121 122 def make_pyramid_app(global_config, **settings):
122 123 """
123 124 Constructs the WSGI application based on Pyramid and wraps the Pylons based
124 125 application.
125 126
126 127 Specials:
127 128
128 129 * We migrate from Pylons to Pyramid. While doing this, we keep both
129 130 frameworks functional. This involves moving some WSGI middlewares around
130 131 and providing access to some data internals, so that the old code is
131 132 still functional.
132 133
133 134 * The application can also be integrated like a plugin via the call to
134 135 `includeme`. This is accompanied with the other utility functions which
135 136 are called. Changing this should be done with great care to not break
136 137 cases when these fragments are assembled from another place.
137 138
138 139 """
139 140 # The edition string should be available in pylons too, so we add it here
140 141 # before copying the settings.
141 142 settings.setdefault('rhodecode.edition', 'Community Edition')
142 143
143 144 # As long as our Pylons application does expect "unprepared" settings, make
144 145 # sure that we keep an unmodified copy. This avoids unintentional change of
145 146 # behavior in the old application.
146 147 settings_pylons = settings.copy()
147 148
148 149 sanitize_settings_and_apply_defaults(settings)
150
149 151 config = Configurator(settings=settings)
152 load_pyramid_environment(global_config, settings)
153
150 154 add_pylons_compat_data(config.registry, global_config, settings_pylons)
151 155
152 load_pyramid_environment(global_config, settings)
153
154 156 includeme_first(config)
155 157 includeme(config)
156 158
157 159 pyramid_app = config.make_wsgi_app()
158 160 pyramid_app = wrap_app_in_wsgi_middlewares(pyramid_app, config)
159 161 pyramid_app.config = config
160 162
161 163 # creating the app uses a connection - return it after we are done
162 164 meta.Session.remove()
163 165
164 166 return pyramid_app
165 167
166 168
167 169 def make_not_found_view(config):
168 170 """
169 171 This creates the view which should be registered as not-found-view to
170 172 pyramid. Basically it contains of the old pylons app, converted to a view.
171 173 Additionally it is wrapped by some other middlewares.
172 174 """
173 175 settings = config.registry.settings
174 176 vcs_server_enabled = settings['vcs.server.enable']
175 177
176 178 # Make pylons app from unprepared settings.
177 179 pylons_app = make_app(
178 180 config.registry._pylons_compat_global_config,
179 181 **config.registry._pylons_compat_settings)
180 182 config.registry._pylons_compat_config = pylons_app.config
181 183
182 184 # Appenlight monitoring.
183 185 pylons_app, appenlight_client = wrap_in_appenlight_if_enabled(
184 186 pylons_app, settings)
185 187
186 188 # The pylons app is executed inside of the pyramid 404 exception handler.
187 189 # Exceptions which are raised inside of it are not handled by pyramid
188 190 # again. Therefore we add a middleware that invokes the error handler in
189 191 # case of an exception or error response. This way we return proper error
190 192 # HTML pages in case of an error.
191 193 reraise = (settings.get('debugtoolbar.enabled', False) or
192 194 rhodecode.disable_error_handler)
193 195 pylons_app = PylonsErrorHandlingMiddleware(
194 196 pylons_app, error_handler, reraise)
195 197
196 198 # The VCSMiddleware shall operate like a fallback if pyramid doesn't find a
197 199 # view to handle the request. Therefore it is wrapped around the pylons
198 200 # app. It has to be outside of the error handling otherwise error responses
199 201 # from the vcsserver are converted to HTML error pages. This confuses the
200 202 # command line tools and the user won't get a meaningful error message.
201 203 if vcs_server_enabled:
202 204 pylons_app = VCSMiddleware(
203 205 pylons_app, settings, appenlight_client, registry=config.registry)
204 206
205 207 # Convert WSGI app to pyramid view and return it.
206 208 return wsgiapp(pylons_app)
207 209
208 210
209 211 def add_pylons_compat_data(registry, global_config, settings):
210 212 """
211 213 Attach data to the registry to support the Pylons integration.
212 214 """
213 215 registry._pylons_compat_global_config = global_config
214 216 registry._pylons_compat_settings = settings
215 217
216 218
217 219 def error_handler(exception, request):
218 220 import rhodecode
219 221 from rhodecode.lib import helpers
220 222
221 223 rhodecode_title = rhodecode.CONFIG.get('rhodecode_title') or 'RhodeCode'
222 224
223 225 base_response = HTTPInternalServerError()
224 226 # prefer original exception for the response since it may have headers set
225 227 if isinstance(exception, HTTPException):
226 228 base_response = exception
227 229 elif isinstance(exception, VCSCommunicationError):
228 230 base_response = VCSServerUnavailable()
229 231
230 232 def is_http_error(response):
231 233 # error which should have traceback
232 234 return response.status_code > 499
233 235
234 236 if is_http_error(base_response):
235 237 log.exception(
236 238 'error occurred handling this request for path: %s', request.path)
237 239
238 240 c = AttributeDict()
239 241 c.error_message = base_response.status
240 242 c.error_explanation = base_response.explanation or str(base_response)
241 243 c.visual = AttributeDict()
242 244
243 245 c.visual.rhodecode_support_url = (
244 246 request.registry.settings.get('rhodecode_support_url') or
245 247 request.route_url('rhodecode_support')
246 248 )
247 249 c.redirect_time = 0
248 250 c.rhodecode_name = rhodecode_title
249 251 if not c.rhodecode_name:
250 252 c.rhodecode_name = 'Rhodecode'
251 253
252 254 c.causes = []
253 255 if hasattr(base_response, 'causes'):
254 256 c.causes = base_response.causes
255 257 c.messages = helpers.flash.pop_messages(request=request)
256 258 c.traceback = traceback.format_exc()
257 259 response = render_to_response(
258 260 '/errors/error_document.mako', {'c': c, 'h': helpers}, request=request,
259 261 response=base_response)
260 262
261 263 return response
262 264
263 265
264 266 def includeme(config):
265 267 settings = config.registry.settings
266 268
267 269 # plugin information
268 270 config.registry.rhodecode_plugins = OrderedDict()
269 271
270 272 config.add_directive(
271 273 'register_rhodecode_plugin', register_rhodecode_plugin)
272 274
273 275 if asbool(settings.get('appenlight', 'false')):
274 276 config.include('appenlight_client.ext.pyramid_tween')
275 277
276 278 if 'mako.default_filters' not in settings:
277 279 # set custom default filters if we don't have it defined
278 280 settings['mako.imports'] = 'from rhodecode.lib.base import h_filter'
279 281 settings['mako.default_filters'] = 'h_filter'
280 282
281 283 # Includes which are required. The application would fail without them.
282 284 config.include('pyramid_mako')
283 285 config.include('pyramid_beaker')
284 286
285 287 config.include('rhodecode.authentication')
286 288 config.include('rhodecode.integrations')
287 289
288 290 # apps
289 291 config.include('rhodecode.apps._base')
290 292 config.include('rhodecode.apps.ops')
291 293
292 294 config.include('rhodecode.apps.admin')
293 295 config.include('rhodecode.apps.channelstream')
294 296 config.include('rhodecode.apps.login')
295 297 config.include('rhodecode.apps.home')
296 298 config.include('rhodecode.apps.journal')
297 299 config.include('rhodecode.apps.repository')
298 300 config.include('rhodecode.apps.repo_group')
299 301 config.include('rhodecode.apps.user_group')
300 302 config.include('rhodecode.apps.search')
301 303 config.include('rhodecode.apps.user_profile')
302 304 config.include('rhodecode.apps.my_account')
303 305 config.include('rhodecode.apps.svn_support')
304 306 config.include('rhodecode.apps.ssh_support')
305 307 config.include('rhodecode.apps.gist')
306 308
307 309 config.include('rhodecode.apps.debug_style')
308 310 config.include('rhodecode.tweens')
309 311 config.include('rhodecode.api')
310 312
311 313 config.add_route(
312 314 'rhodecode_support', 'https://rhodecode.com/help/', static=True)
313 315
314 316 config.add_translation_dirs('rhodecode:i18n/')
315 317 settings['default_locale_name'] = settings.get('lang', 'en')
316 318
317 319 # Add subscribers.
320 config.add_subscriber(inject_app_settings, ApplicationCreated)
318 321 config.add_subscriber(scan_repositories_if_enabled, ApplicationCreated)
319 322 config.add_subscriber(write_metadata_if_needed, ApplicationCreated)
320 323 config.add_subscriber(write_js_routes_if_enabled, ApplicationCreated)
321 324
322 325 config.add_request_method(
323 326 'rhodecode.lib.partial_renderer.get_partial_renderer',
324 327 'get_partial_renderer')
325 328
326 329 # events
327 330 # TODO(marcink): this should be done when pyramid migration is finished
328 331 # config.add_subscriber(
329 332 # 'rhodecode.integrations.integrations_event_handler',
330 333 # 'rhodecode.events.RhodecodeEvent')
331 334
332 335 # Set the authorization policy.
333 336 authz_policy = ACLAuthorizationPolicy()
334 337 config.set_authorization_policy(authz_policy)
335 338
336 339 # Set the default renderer for HTML templates to mako.
337 340 config.add_mako_renderer('.html')
338 341
339 342 config.add_renderer(
340 343 name='json_ext',
341 344 factory='rhodecode.lib.ext_json_renderer.pyramid_ext_json')
342 345
343 346 # include RhodeCode plugins
344 347 includes = aslist(settings.get('rhodecode.includes', []))
345 348 for inc in includes:
346 349 config.include(inc)
347 350
348 351 # This is the glue which allows us to migrate in chunks. By registering the
349 352 # pylons based application as the "Not Found" view in Pyramid, we will
350 353 # fallback to the old application each time the new one does not yet know
351 354 # how to handle a request.
352 355 config.add_notfound_view(make_not_found_view(config))
353 356
354 357 if not settings.get('debugtoolbar.enabled', False):
355 358 # disabled debugtoolbar handle all exceptions via the error_handlers
356 359 config.add_view(error_handler, context=Exception)
357 360
358 361 config.add_view(error_handler, context=HTTPError)
359 362
360 363
361 364 def includeme_first(config):
362 365 # redirect automatic browser favicon.ico requests to correct place
363 366 def favicon_redirect(context, request):
364 367 return HTTPFound(
365 368 request.static_path('rhodecode:public/images/favicon.ico'))
366 369
367 370 config.add_view(favicon_redirect, route_name='favicon')
368 371 config.add_route('favicon', '/favicon.ico')
369 372
370 373 def robots_redirect(context, request):
371 374 return HTTPFound(
372 375 request.static_path('rhodecode:public/robots.txt'))
373 376
374 377 config.add_view(robots_redirect, route_name='robots')
375 378 config.add_route('robots', '/robots.txt')
376 379
377 380 config.add_static_view(
378 381 '_static/deform', 'deform:static')
379 382 config.add_static_view(
380 383 '_static/rhodecode', path='rhodecode:public', cache_max_age=3600 * 24)
381 384
382 385
383 386 def wrap_app_in_wsgi_middlewares(pyramid_app, config):
384 387 """
385 388 Apply outer WSGI middlewares around the application.
386 389
387 390 Part of this has been moved up from the Pylons layer, so that the
388 391 data is also available if old Pylons code is hit through an already ported
389 392 view.
390 393 """
391 394 settings = config.registry.settings
392 395
393 396 # enable https redirects based on HTTP_X_URL_SCHEME set by proxy
394 397 pyramid_app = HttpsFixup(pyramid_app, settings)
395 398
396 399 # Add RoutesMiddleware to support the pylons compatibility tween during
397 400 # migration to pyramid.
398 401
399 402 # TODO(marcink): remove after migration to pyramid
400 403 if hasattr(config.registry, '_pylons_compat_config'):
401 404 routes_map = config.registry._pylons_compat_config['routes.map']
402 405 pyramid_app = SkippableRoutesMiddleware(
403 406 pyramid_app, routes_map,
404 407 skip_prefixes=(STATIC_FILE_PREFIX, '/_debug_toolbar'))
405 408
406 409 pyramid_app, _ = wrap_in_appenlight_if_enabled(pyramid_app, settings)
407 410
408 411 if settings['gzip_responses']:
409 412 pyramid_app = make_gzip_middleware(
410 413 pyramid_app, settings, compress_level=1)
411 414
412 415 # this should be the outer most middleware in the wsgi stack since
413 416 # middleware like Routes make database calls
414 417 def pyramid_app_with_cleanup(environ, start_response):
415 418 try:
416 419 return pyramid_app(environ, start_response)
417 420 finally:
418 421 # Dispose current database session and rollback uncommitted
419 422 # transactions.
420 423 meta.Session.remove()
421 424
422 425 # In a single threaded mode server, on non sqlite db we should have
423 426 # '0 Current Checked out connections' at the end of a request,
424 427 # if not, then something, somewhere is leaving a connection open
425 428 pool = meta.Base.metadata.bind.engine.pool
426 429 log.debug('sa pool status: %s', pool.status())
427 430
428 431 return pyramid_app_with_cleanup
429 432
430 433
431 434 def sanitize_settings_and_apply_defaults(settings):
432 435 """
433 436 Applies settings defaults and does all type conversion.
434 437
435 438 We would move all settings parsing and preparation into this place, so that
436 439 we have only one place left which deals with this part. The remaining parts
437 440 of the application would start to rely fully on well prepared settings.
438 441
439 442 This piece would later be split up per topic to avoid a big fat monster
440 443 function.
441 444 """
442 445
443 446 # Pyramid's mako renderer has to search in the templates folder so that the
444 447 # old templates still work. Ported and new templates are expected to use
445 448 # real asset specifications for the includes.
446 449 mako_directories = settings.setdefault('mako.directories', [
447 450 # Base templates of the original Pylons application
448 451 'rhodecode:templates',
449 452 ])
450 453 log.debug(
451 454 "Using the following Mako template directories: %s",
452 455 mako_directories)
453 456
454 457 # Default includes, possible to change as a user
455 458 pyramid_includes = settings.setdefault('pyramid.includes', [
456 459 'rhodecode.lib.middleware.request_wrapper',
457 460 ])
458 461 log.debug(
459 462 "Using the following pyramid.includes: %s",
460 463 pyramid_includes)
461 464
462 465 # TODO: johbo: Re-think this, usually the call to config.include
463 466 # should allow to pass in a prefix.
464 467 settings.setdefault('rhodecode.api.url', '/_admin/api')
465 468
466 469 # Sanitize generic settings.
467 470 _list_setting(settings, 'default_encoding', 'UTF-8')
468 471 _bool_setting(settings, 'is_test', 'false')
469 472 _bool_setting(settings, 'gzip_responses', 'false')
470 473
471 474 # Call split out functions that sanitize settings for each topic.
472 475 _sanitize_appenlight_settings(settings)
473 476 _sanitize_vcs_settings(settings)
474 477
478 # configure instance id
479 config_utils.set_instance_id(settings)
480
475 481 return settings
476 482
477 483
478 484 def _sanitize_appenlight_settings(settings):
479 485 _bool_setting(settings, 'appenlight', 'false')
480 486
481 487
482 488 def _sanitize_vcs_settings(settings):
483 489 """
484 490 Applies settings defaults and does type conversion for all VCS related
485 491 settings.
486 492 """
487 493 _string_setting(settings, 'vcs.svn.compatible_version', '')
488 494 _string_setting(settings, 'git_rev_filter', '--all')
489 495 _string_setting(settings, 'vcs.hooks.protocol', 'http')
490 496 _string_setting(settings, 'vcs.scm_app_implementation', 'http')
491 497 _string_setting(settings, 'vcs.server', '')
492 498 _string_setting(settings, 'vcs.server.log_level', 'debug')
493 499 _string_setting(settings, 'vcs.server.protocol', 'http')
494 500 _bool_setting(settings, 'startup.import_repos', 'false')
495 501 _bool_setting(settings, 'vcs.hooks.direct_calls', 'false')
496 502 _bool_setting(settings, 'vcs.server.enable', 'true')
497 503 _bool_setting(settings, 'vcs.start_server', 'false')
498 504 _list_setting(settings, 'vcs.backends', 'hg, git, svn')
499 505 _int_setting(settings, 'vcs.connection_timeout', 3600)
500 506
501 507 # Support legacy values of vcs.scm_app_implementation. Legacy
502 508 # configurations may use 'rhodecode.lib.middleware.utils.scm_app_http'
503 509 # which is now mapped to 'http'.
504 510 scm_app_impl = settings['vcs.scm_app_implementation']
505 511 if scm_app_impl == 'rhodecode.lib.middleware.utils.scm_app_http':
506 512 settings['vcs.scm_app_implementation'] = 'http'
507 513
508 514
509 515 def _int_setting(settings, name, default):
510 516 settings[name] = int(settings.get(name, default))
511 517
512 518
513 519 def _bool_setting(settings, name, default):
514 520 input = settings.get(name, default)
515 521 if isinstance(input, unicode):
516 522 input = input.encode('utf8')
517 523 settings[name] = asbool(input)
518 524
519 525
520 526 def _list_setting(settings, name, default):
521 527 raw_value = settings.get(name, default)
522 528
523 529 old_separator = ','
524 530 if old_separator in raw_value:
525 531 # If we get a comma separated list, pass it to our own function.
526 532 settings[name] = rhodecode_aslist(raw_value, sep=old_separator)
527 533 else:
528 534 # Otherwise we assume it uses pyramids space/newline separation.
529 535 settings[name] = aslist(raw_value)
530 536
531 537
532 538 def _string_setting(settings, name, default, lower=True):
533 539 value = settings.get(name, default)
534 540 if lower:
535 541 value = value.lower()
536 542 settings[name] = value
@@ -1,343 +1,311 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 Routes configuration
23 23
24 24 The more specific and detailed routes should be defined first so they
25 25 may take precedent over the more generic routes. For more information
26 26 refer to the routes manual at http://routes.groovie.org/docs/
27 27
28 28 IMPORTANT: if you change any routing here, make sure to take a look at lib/base.py
29 29 and _route_name variable which uses some of stored naming here to do redirects.
30 30 """
31 31 import os
32 32 import re
33 33 from routes import Mapper
34 34
35 35 # prefix for non repository related links needs to be prefixed with `/`
36 36 ADMIN_PREFIX = '/_admin'
37 37 STATIC_FILE_PREFIX = '/_static'
38 38
39 39 # Default requirements for URL parts
40 40 URL_NAME_REQUIREMENTS = {
41 41 # group name can have a slash in them, but they must not end with a slash
42 42 'group_name': r'.*?[^/]',
43 43 'repo_group_name': r'.*?[^/]',
44 44 # repo names can have a slash in them, but they must not end with a slash
45 45 'repo_name': r'.*?[^/]',
46 46 # file path eats up everything at the end
47 47 'f_path': r'.*',
48 48 # reference types
49 49 'source_ref_type': '(branch|book|tag|rev|\%\(source_ref_type\)s)',
50 50 'target_ref_type': '(branch|book|tag|rev|\%\(target_ref_type\)s)',
51 51 }
52 52
53 53
54 54 class JSRoutesMapper(Mapper):
55 55 """
56 56 Wrapper for routes.Mapper to make pyroutes compatible url definitions
57 57 """
58 58 _named_route_regex = re.compile(r'^[a-z-_0-9A-Z]+$')
59 59 _argument_prog = re.compile('\{(.*?)\}|:\((.*)\)')
60 60 def __init__(self, *args, **kw):
61 61 super(JSRoutesMapper, self).__init__(*args, **kw)
62 62 self._jsroutes = []
63 63
64 64 def connect(self, *args, **kw):
65 65 """
66 66 Wrapper for connect to take an extra argument jsroute=True
67 67
68 68 :param jsroute: boolean, if True will add the route to the pyroutes list
69 69 """
70 70 if kw.pop('jsroute', False):
71 71 if not self._named_route_regex.match(args[0]):
72 72 raise Exception('only named routes can be added to pyroutes')
73 73 self._jsroutes.append(args[0])
74 74
75 75 super(JSRoutesMapper, self).connect(*args, **kw)
76 76
77 77 def _extract_route_information(self, route):
78 78 """
79 79 Convert a route into tuple(name, path, args), eg:
80 80 ('show_user', '/profile/%(username)s', ['username'])
81 81 """
82 82 routepath = route.routepath
83 83 def replace(matchobj):
84 84 if matchobj.group(1):
85 85 return "%%(%s)s" % matchobj.group(1).split(':')[0]
86 86 else:
87 87 return "%%(%s)s" % matchobj.group(2)
88 88
89 89 routepath = self._argument_prog.sub(replace, routepath)
90 90 return (
91 91 route.name,
92 92 routepath,
93 93 [(arg[0].split(':')[0] if arg[0] != '' else arg[1])
94 94 for arg in self._argument_prog.findall(route.routepath)]
95 95 )
96 96
97 97 def jsroutes(self):
98 98 """
99 99 Return a list of pyroutes.js compatible routes
100 100 """
101 101 for route_name in self._jsroutes:
102 102 yield self._extract_route_information(self._routenames[route_name])
103 103
104 104
105 105 def make_map(config):
106 106 """Create, configure and return the routes Mapper"""
107 107 rmap = JSRoutesMapper(
108 108 directory=config['pylons.paths']['controllers'],
109 109 always_scan=config['debug'])
110 110 rmap.minimization = False
111 111 rmap.explicit = False
112 112
113 113 from rhodecode.lib.utils2 import str2bool
114 114 from rhodecode.model import repo, repo_group
115 115
116 116 def check_repo(environ, match_dict):
117 117 """
118 118 check for valid repository for proper 404 handling
119 119
120 120 :param environ:
121 121 :param match_dict:
122 122 """
123 123 repo_name = match_dict.get('repo_name')
124 124
125 125 if match_dict.get('f_path'):
126 126 # fix for multiple initial slashes that causes errors
127 127 match_dict['f_path'] = match_dict['f_path'].lstrip('/')
128 128 repo_model = repo.RepoModel()
129 129 by_name_match = repo_model.get_by_repo_name(repo_name)
130 130 # if we match quickly from database, short circuit the operation,
131 131 # and validate repo based on the type.
132 132 if by_name_match:
133 133 return True
134 134
135 135 by_id_match = repo_model.get_repo_by_id(repo_name)
136 136 if by_id_match:
137 137 repo_name = by_id_match.repo_name
138 138 match_dict['repo_name'] = repo_name
139 139 return True
140 140
141 141 return False
142 142
143 143 def check_group(environ, match_dict):
144 144 """
145 145 check for valid repository group path for proper 404 handling
146 146
147 147 :param environ:
148 148 :param match_dict:
149 149 """
150 150 repo_group_name = match_dict.get('group_name')
151 151 repo_group_model = repo_group.RepoGroupModel()
152 152 by_name_match = repo_group_model.get_by_group_name(repo_group_name)
153 153 if by_name_match:
154 154 return True
155 155
156 156 return False
157 157
158 158 def check_user_group(environ, match_dict):
159 159 """
160 160 check for valid user group for proper 404 handling
161 161
162 162 :param environ:
163 163 :param match_dict:
164 164 """
165 165 return True
166 166
167 167 def check_int(environ, match_dict):
168 168 return match_dict.get('id').isdigit()
169 169
170 170
171 171 #==========================================================================
172 172 # CUSTOM ROUTES HERE
173 173 #==========================================================================
174 174
175 175 # ADMIN REPOSITORY GROUPS ROUTES
176 176 with rmap.submapper(path_prefix=ADMIN_PREFIX,
177 177 controller='admin/repo_groups') as m:
178 178 m.connect('repo_groups', '/repo_groups',
179 179 action='create', conditions={'method': ['POST']})
180 180 m.connect('repo_groups', '/repo_groups',
181 181 action='index', conditions={'method': ['GET']})
182 182 m.connect('new_repo_group', '/repo_groups/new',
183 183 action='new', conditions={'method': ['GET']})
184 184 m.connect('update_repo_group', '/repo_groups/{group_name}',
185 185 action='update', conditions={'method': ['PUT'],
186 186 'function': check_group},
187 187 requirements=URL_NAME_REQUIREMENTS)
188 188
189 189 # EXTRAS REPO GROUP ROUTES
190 190 m.connect('edit_repo_group', '/repo_groups/{group_name}/edit',
191 191 action='edit',
192 192 conditions={'method': ['GET'], 'function': check_group},
193 193 requirements=URL_NAME_REQUIREMENTS)
194 194 m.connect('edit_repo_group', '/repo_groups/{group_name}/edit',
195 195 action='edit',
196 196 conditions={'method': ['PUT'], 'function': check_group},
197 197 requirements=URL_NAME_REQUIREMENTS)
198 198
199 199 m.connect('edit_repo_group_advanced', '/repo_groups/{group_name}/edit/advanced',
200 200 action='edit_repo_group_advanced',
201 201 conditions={'method': ['GET'], 'function': check_group},
202 202 requirements=URL_NAME_REQUIREMENTS)
203 203 m.connect('edit_repo_group_advanced', '/repo_groups/{group_name}/edit/advanced',
204 204 action='edit_repo_group_advanced',
205 205 conditions={'method': ['PUT'], 'function': check_group},
206 206 requirements=URL_NAME_REQUIREMENTS)
207 207
208 208 m.connect('edit_repo_group_perms', '/repo_groups/{group_name}/edit/permissions',
209 209 action='edit_repo_group_perms',
210 210 conditions={'method': ['GET'], 'function': check_group},
211 211 requirements=URL_NAME_REQUIREMENTS)
212 212 m.connect('edit_repo_group_perms', '/repo_groups/{group_name}/edit/permissions',
213 213 action='update_perms',
214 214 conditions={'method': ['PUT'], 'function': check_group},
215 215 requirements=URL_NAME_REQUIREMENTS)
216 216
217 217 m.connect('delete_repo_group', '/repo_groups/{group_name}',
218 218 action='delete', conditions={'method': ['DELETE'],
219 219 'function': check_group},
220 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 222 # ADMIN SETTINGS ROUTES
254 223 with rmap.submapper(path_prefix=ADMIN_PREFIX,
255 224 controller='admin/settings') as m:
256 225
257 226 # default
258 227 m.connect('admin_settings', '/settings',
259 228 action='settings_global_update',
260 229 conditions={'method': ['POST']})
261 230 m.connect('admin_settings', '/settings',
262 231 action='settings_global', conditions={'method': ['GET']})
263 232
264 233 m.connect('admin_settings_vcs', '/settings/vcs',
265 234 action='settings_vcs_update',
266 235 conditions={'method': ['POST']})
267 236 m.connect('admin_settings_vcs', '/settings/vcs',
268 237 action='settings_vcs',
269 238 conditions={'method': ['GET']})
270 239 m.connect('admin_settings_vcs', '/settings/vcs',
271 240 action='delete_svn_pattern',
272 241 conditions={'method': ['DELETE']})
273 242
274 243 m.connect('admin_settings_mapping', '/settings/mapping',
275 244 action='settings_mapping_update',
276 245 conditions={'method': ['POST']})
277 246 m.connect('admin_settings_mapping', '/settings/mapping',
278 247 action='settings_mapping', conditions={'method': ['GET']})
279 248
280 249 m.connect('admin_settings_global', '/settings/global',
281 250 action='settings_global_update',
282 251 conditions={'method': ['POST']})
283 252 m.connect('admin_settings_global', '/settings/global',
284 253 action='settings_global', conditions={'method': ['GET']})
285 254
286 255 m.connect('admin_settings_visual', '/settings/visual',
287 256 action='settings_visual_update',
288 257 conditions={'method': ['POST']})
289 258 m.connect('admin_settings_visual', '/settings/visual',
290 259 action='settings_visual', conditions={'method': ['GET']})
291 260
292 261 m.connect('admin_settings_issuetracker',
293 262 '/settings/issue-tracker', action='settings_issuetracker',
294 263 conditions={'method': ['GET']})
295 264 m.connect('admin_settings_issuetracker_save',
296 265 '/settings/issue-tracker/save',
297 266 action='settings_issuetracker_save',
298 267 conditions={'method': ['POST']})
299 268 m.connect('admin_issuetracker_test', '/settings/issue-tracker/test',
300 269 action='settings_issuetracker_test',
301 270 conditions={'method': ['POST']})
302 271 m.connect('admin_issuetracker_delete',
303 272 '/settings/issue-tracker/delete',
304 273 action='settings_issuetracker_delete',
305 274 conditions={'method': ['DELETE']})
306 275
307 276 m.connect('admin_settings_email', '/settings/email',
308 277 action='settings_email_update',
309 278 conditions={'method': ['POST']})
310 279 m.connect('admin_settings_email', '/settings/email',
311 280 action='settings_email', conditions={'method': ['GET']})
312 281
313 282 m.connect('admin_settings_hooks', '/settings/hooks',
314 283 action='settings_hooks_update',
315 284 conditions={'method': ['POST', 'DELETE']})
316 285 m.connect('admin_settings_hooks', '/settings/hooks',
317 286 action='settings_hooks', conditions={'method': ['GET']})
318 287
319 288 m.connect('admin_settings_search', '/settings/search',
320 289 action='settings_search', conditions={'method': ['GET']})
321 290
322 291 m.connect('admin_settings_supervisor', '/settings/supervisor',
323 292 action='settings_supervisor', conditions={'method': ['GET']})
324 293 m.connect('admin_settings_supervisor_log', '/settings/supervisor/{procid}/log',
325 294 action='settings_supervisor_log', conditions={'method': ['GET']})
326 295
327 296 m.connect('admin_settings_labs', '/settings/labs',
328 297 action='settings_labs_update',
329 298 conditions={'method': ['POST']})
330 299 m.connect('admin_settings_labs', '/settings/labs',
331 300 action='settings_labs', conditions={'method': ['GET']})
332 301
333 302 # ADMIN MY ACCOUNT
334 303 with rmap.submapper(path_prefix=ADMIN_PREFIX,
335 304 controller='admin/my_account') as m:
336 305
337 306 # NOTE(marcink): this needs to be kept for password force flag to be
338 307 # handled in pylons controllers, remove after full migration to pyramid
339 308 m.connect('my_account_password', '/my_account/password',
340 309 action='my_account_password', conditions={'method': ['GET']})
341 310
342
343 311 return rmap
@@ -1,2170 +1,2174 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 authentication and permission libraries
23 23 """
24 24
25 25 import os
26 26 import inspect
27 27 import collections
28 28 import fnmatch
29 29 import hashlib
30 30 import itertools
31 31 import logging
32 32 import random
33 33 import traceback
34 34 from functools import wraps
35 35
36 36 import ipaddress
37 37 from beaker.cache import cache_region
38 38 from pyramid.httpexceptions import HTTPForbidden, HTTPFound, HTTPNotFound
39 39 from pylons.i18n.translation import _
40 40 # NOTE(marcink): this has to be removed only after pyramid migration,
41 41 # replace with _ = request.translate
42 42 from sqlalchemy.orm.exc import ObjectDeletedError
43 43 from sqlalchemy.orm import joinedload
44 44 from zope.cachedescriptors.property import Lazy as LazyProperty
45 45
46 46 import rhodecode
47 47 from rhodecode.model import meta
48 48 from rhodecode.model.meta import Session
49 49 from rhodecode.model.user import UserModel
50 50 from rhodecode.model.db import (
51 51 User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember,
52 52 UserIpMap, UserApiKeys, RepoGroup, UserGroup)
53 53 from rhodecode.lib import caches
54 54 from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5
55 55 from rhodecode.lib.utils import (
56 56 get_repo_slug, get_repo_group_slug, get_user_group_slug)
57 57 from rhodecode.lib.caching_query import FromCache
58 58
59 59
60 60 if rhodecode.is_unix:
61 61 import bcrypt
62 62
63 63 log = logging.getLogger(__name__)
64 64
65 65 csrf_token_key = "csrf_token"
66 66
67 67
68 68 class PasswordGenerator(object):
69 69 """
70 70 This is a simple class for generating password from different sets of
71 71 characters
72 72 usage::
73 73
74 74 passwd_gen = PasswordGenerator()
75 75 #print 8-letter password containing only big and small letters
76 76 of alphabet
77 77 passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
78 78 """
79 79 ALPHABETS_NUM = r'''1234567890'''
80 80 ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
81 81 ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
82 82 ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
83 83 ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
84 84 + ALPHABETS_NUM + ALPHABETS_SPECIAL
85 85 ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
86 86 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
87 87 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
88 88 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
89 89
90 90 def __init__(self, passwd=''):
91 91 self.passwd = passwd
92 92
93 93 def gen_password(self, length, type_=None):
94 94 if type_ is None:
95 95 type_ = self.ALPHABETS_FULL
96 96 self.passwd = ''.join([random.choice(type_) for _ in xrange(length)])
97 97 return self.passwd
98 98
99 99
100 100 class _RhodeCodeCryptoBase(object):
101 101 ENC_PREF = None
102 102
103 103 def hash_create(self, str_):
104 104 """
105 105 hash the string using
106 106
107 107 :param str_: password to hash
108 108 """
109 109 raise NotImplementedError
110 110
111 111 def hash_check_with_upgrade(self, password, hashed):
112 112 """
113 113 Returns tuple in which first element is boolean that states that
114 114 given password matches it's hashed version, and the second is new hash
115 115 of the password, in case this password should be migrated to new
116 116 cipher.
117 117 """
118 118 checked_hash = self.hash_check(password, hashed)
119 119 return checked_hash, None
120 120
121 121 def hash_check(self, password, hashed):
122 122 """
123 123 Checks matching password with it's hashed value.
124 124
125 125 :param password: password
126 126 :param hashed: password in hashed form
127 127 """
128 128 raise NotImplementedError
129 129
130 130 def _assert_bytes(self, value):
131 131 """
132 132 Passing in an `unicode` object can lead to hard to detect issues
133 133 if passwords contain non-ascii characters. Doing a type check
134 134 during runtime, so that such mistakes are detected early on.
135 135 """
136 136 if not isinstance(value, str):
137 137 raise TypeError(
138 138 "Bytestring required as input, got %r." % (value, ))
139 139
140 140
141 141 class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase):
142 142 ENC_PREF = ('$2a$10', '$2b$10')
143 143
144 144 def hash_create(self, str_):
145 145 self._assert_bytes(str_)
146 146 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
147 147
148 148 def hash_check_with_upgrade(self, password, hashed):
149 149 """
150 150 Returns tuple in which first element is boolean that states that
151 151 given password matches it's hashed version, and the second is new hash
152 152 of the password, in case this password should be migrated to new
153 153 cipher.
154 154
155 155 This implements special upgrade logic which works like that:
156 156 - check if the given password == bcrypted hash, if yes then we
157 157 properly used password and it was already in bcrypt. Proceed
158 158 without any changes
159 159 - if bcrypt hash check is not working try with sha256. If hash compare
160 160 is ok, it means we using correct but old hashed password. indicate
161 161 hash change and proceed
162 162 """
163 163
164 164 new_hash = None
165 165
166 166 # regular pw check
167 167 password_match_bcrypt = self.hash_check(password, hashed)
168 168
169 169 # now we want to know if the password was maybe from sha256
170 170 # basically calling _RhodeCodeCryptoSha256().hash_check()
171 171 if not password_match_bcrypt:
172 172 if _RhodeCodeCryptoSha256().hash_check(password, hashed):
173 173 new_hash = self.hash_create(password) # make new bcrypt hash
174 174 password_match_bcrypt = True
175 175
176 176 return password_match_bcrypt, new_hash
177 177
178 178 def hash_check(self, password, hashed):
179 179 """
180 180 Checks matching password with it's hashed value.
181 181
182 182 :param password: password
183 183 :param hashed: password in hashed form
184 184 """
185 185 self._assert_bytes(password)
186 186 try:
187 187 return bcrypt.hashpw(password, hashed) == hashed
188 188 except ValueError as e:
189 189 # we're having a invalid salt here probably, we should not crash
190 190 # just return with False as it would be a wrong password.
191 191 log.debug('Failed to check password hash using bcrypt %s',
192 192 safe_str(e))
193 193
194 194 return False
195 195
196 196
197 197 class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase):
198 198 ENC_PREF = '_'
199 199
200 200 def hash_create(self, str_):
201 201 self._assert_bytes(str_)
202 202 return hashlib.sha256(str_).hexdigest()
203 203
204 204 def hash_check(self, password, hashed):
205 205 """
206 206 Checks matching password with it's hashed value.
207 207
208 208 :param password: password
209 209 :param hashed: password in hashed form
210 210 """
211 211 self._assert_bytes(password)
212 212 return hashlib.sha256(password).hexdigest() == hashed
213 213
214 214
215 215 class _RhodeCodeCryptoMd5(_RhodeCodeCryptoBase):
216 216 ENC_PREF = '_'
217 217
218 218 def hash_create(self, str_):
219 219 self._assert_bytes(str_)
220 220 return hashlib.md5(str_).hexdigest()
221 221
222 222 def hash_check(self, password, hashed):
223 223 """
224 224 Checks matching password with it's hashed value.
225 225
226 226 :param password: password
227 227 :param hashed: password in hashed form
228 228 """
229 229 self._assert_bytes(password)
230 230 return hashlib.md5(password).hexdigest() == hashed
231 231
232 232
233 233 def crypto_backend():
234 234 """
235 235 Return the matching crypto backend.
236 236
237 237 Selection is based on if we run tests or not, we pick md5 backend to run
238 238 tests faster since BCRYPT is expensive to calculate
239 239 """
240 240 if rhodecode.is_test:
241 241 RhodeCodeCrypto = _RhodeCodeCryptoMd5()
242 242 else:
243 243 RhodeCodeCrypto = _RhodeCodeCryptoBCrypt()
244 244
245 245 return RhodeCodeCrypto
246 246
247 247
248 248 def get_crypt_password(password):
249 249 """
250 250 Create the hash of `password` with the active crypto backend.
251 251
252 252 :param password: The cleartext password.
253 253 :type password: unicode
254 254 """
255 255 password = safe_str(password)
256 256 return crypto_backend().hash_create(password)
257 257
258 258
259 259 def check_password(password, hashed):
260 260 """
261 261 Check if the value in `password` matches the hash in `hashed`.
262 262
263 263 :param password: The cleartext password.
264 264 :type password: unicode
265 265
266 266 :param hashed: The expected hashed version of the password.
267 267 :type hashed: The hash has to be passed in in text representation.
268 268 """
269 269 password = safe_str(password)
270 270 return crypto_backend().hash_check(password, hashed)
271 271
272 272
273 273 def generate_auth_token(data, salt=None):
274 274 """
275 275 Generates API KEY from given string
276 276 """
277 277
278 278 if salt is None:
279 279 salt = os.urandom(16)
280 280 return hashlib.sha1(safe_str(data) + salt).hexdigest()
281 281
282 282
283 283 def get_came_from(request):
284 284 """
285 285 get query_string+path from request sanitized after removing auth_token
286 286 """
287 287 _req = request
288 288
289 289 path = _req.path
290 290 if 'auth_token' in _req.GET:
291 291 # sanitize the request and remove auth_token for redirection
292 292 _req.GET.pop('auth_token')
293 293 qs = _req.query_string
294 294 if qs:
295 295 path += '?' + qs
296 296
297 297 return path
298 298
299 299
300 300 class CookieStoreWrapper(object):
301 301
302 302 def __init__(self, cookie_store):
303 303 self.cookie_store = cookie_store
304 304
305 305 def __repr__(self):
306 306 return 'CookieStore<%s>' % (self.cookie_store)
307 307
308 308 def get(self, key, other=None):
309 309 if isinstance(self.cookie_store, dict):
310 310 return self.cookie_store.get(key, other)
311 311 elif isinstance(self.cookie_store, AuthUser):
312 312 return self.cookie_store.__dict__.get(key, other)
313 313
314 314
315 315 def _cached_perms_data(user_id, scope, user_is_admin,
316 316 user_inherit_default_permissions, explicit, algo,
317 317 calculate_super_admin):
318 318
319 319 permissions = PermissionCalculator(
320 320 user_id, scope, user_is_admin, user_inherit_default_permissions,
321 321 explicit, algo, calculate_super_admin)
322 322 return permissions.calculate()
323 323
324 324
325 325 class PermOrigin(object):
326 326 SUPER_ADMIN = 'superadmin'
327 327
328 328 REPO_USER = 'user:%s'
329 329 REPO_USERGROUP = 'usergroup:%s'
330 330 REPO_OWNER = 'repo.owner'
331 331 REPO_DEFAULT = 'repo.default'
332 332 REPO_DEFAULT_NO_INHERIT = 'repo.default.no.inherit'
333 333 REPO_PRIVATE = 'repo.private'
334 334
335 335 REPOGROUP_USER = 'user:%s'
336 336 REPOGROUP_USERGROUP = 'usergroup:%s'
337 337 REPOGROUP_OWNER = 'group.owner'
338 338 REPOGROUP_DEFAULT = 'group.default'
339 339 REPOGROUP_DEFAULT_NO_INHERIT = 'group.default.no.inherit'
340 340
341 341 USERGROUP_USER = 'user:%s'
342 342 USERGROUP_USERGROUP = 'usergroup:%s'
343 343 USERGROUP_OWNER = 'usergroup.owner'
344 344 USERGROUP_DEFAULT = 'usergroup.default'
345 345 USERGROUP_DEFAULT_NO_INHERIT = 'usergroup.default.no.inherit'
346 346
347 347
348 348 class PermOriginDict(dict):
349 349 """
350 350 A special dict used for tracking permissions along with their origins.
351 351
352 352 `__setitem__` has been overridden to expect a tuple(perm, origin)
353 353 `__getitem__` will return only the perm
354 354 `.perm_origin_stack` will return the stack of (perm, origin) set per key
355 355
356 356 >>> perms = PermOriginDict()
357 357 >>> perms['resource'] = 'read', 'default'
358 358 >>> perms['resource']
359 359 'read'
360 360 >>> perms['resource'] = 'write', 'admin'
361 361 >>> perms['resource']
362 362 'write'
363 363 >>> perms.perm_origin_stack
364 364 {'resource': [('read', 'default'), ('write', 'admin')]}
365 365 """
366 366
367 367 def __init__(self, *args, **kw):
368 368 dict.__init__(self, *args, **kw)
369 369 self.perm_origin_stack = collections.OrderedDict()
370 370
371 371 def __setitem__(self, key, (perm, origin)):
372 372 self.perm_origin_stack.setdefault(key, []).append((perm, origin))
373 373 dict.__setitem__(self, key, perm)
374 374
375 375
376 376 class PermissionCalculator(object):
377 377
378 378 def __init__(
379 379 self, user_id, scope, user_is_admin,
380 380 user_inherit_default_permissions, explicit, algo,
381 381 calculate_super_admin=False):
382 382
383 383 self.user_id = user_id
384 384 self.user_is_admin = user_is_admin
385 385 self.inherit_default_permissions = user_inherit_default_permissions
386 386 self.explicit = explicit
387 387 self.algo = algo
388 388 self.calculate_super_admin = calculate_super_admin
389 389
390 390 scope = scope or {}
391 391 self.scope_repo_id = scope.get('repo_id')
392 392 self.scope_repo_group_id = scope.get('repo_group_id')
393 393 self.scope_user_group_id = scope.get('user_group_id')
394 394
395 395 self.default_user_id = User.get_default_user(cache=True).user_id
396 396
397 397 self.permissions_repositories = PermOriginDict()
398 398 self.permissions_repository_groups = PermOriginDict()
399 399 self.permissions_user_groups = PermOriginDict()
400 400 self.permissions_global = set()
401 401
402 402 self.default_repo_perms = Permission.get_default_repo_perms(
403 403 self.default_user_id, self.scope_repo_id)
404 404 self.default_repo_groups_perms = Permission.get_default_group_perms(
405 405 self.default_user_id, self.scope_repo_group_id)
406 406 self.default_user_group_perms = \
407 407 Permission.get_default_user_group_perms(
408 408 self.default_user_id, self.scope_user_group_id)
409 409
410 410 def calculate(self):
411 411 if self.user_is_admin and not self.calculate_super_admin:
412 412 return self._admin_permissions()
413 413
414 414 self._calculate_global_default_permissions()
415 415 self._calculate_global_permissions()
416 416 self._calculate_default_permissions()
417 417 self._calculate_repository_permissions()
418 418 self._calculate_repository_group_permissions()
419 419 self._calculate_user_group_permissions()
420 420 return self._permission_structure()
421 421
422 422 def _admin_permissions(self):
423 423 """
424 424 admin user have all default rights for repositories
425 425 and groups set to admin
426 426 """
427 427 self.permissions_global.add('hg.admin')
428 428 self.permissions_global.add('hg.create.write_on_repogroup.true')
429 429
430 430 # repositories
431 431 for perm in self.default_repo_perms:
432 432 r_k = perm.UserRepoToPerm.repository.repo_name
433 433 p = 'repository.admin'
434 434 self.permissions_repositories[r_k] = p, PermOrigin.SUPER_ADMIN
435 435
436 436 # repository groups
437 437 for perm in self.default_repo_groups_perms:
438 438 rg_k = perm.UserRepoGroupToPerm.group.group_name
439 439 p = 'group.admin'
440 440 self.permissions_repository_groups[rg_k] = p, PermOrigin.SUPER_ADMIN
441 441
442 442 # user groups
443 443 for perm in self.default_user_group_perms:
444 444 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
445 445 p = 'usergroup.admin'
446 446 self.permissions_user_groups[u_k] = p, PermOrigin.SUPER_ADMIN
447 447
448 448 return self._permission_structure()
449 449
450 450 def _calculate_global_default_permissions(self):
451 451 """
452 452 global permissions taken from the default user
453 453 """
454 454 default_global_perms = UserToPerm.query()\
455 455 .filter(UserToPerm.user_id == self.default_user_id)\
456 456 .options(joinedload(UserToPerm.permission))
457 457
458 458 for perm in default_global_perms:
459 459 self.permissions_global.add(perm.permission.permission_name)
460 460
461 461 if self.user_is_admin:
462 462 self.permissions_global.add('hg.admin')
463 463 self.permissions_global.add('hg.create.write_on_repogroup.true')
464 464
465 465 def _calculate_global_permissions(self):
466 466 """
467 467 Set global system permissions with user permissions or permissions
468 468 taken from the user groups of the current user.
469 469
470 470 The permissions include repo creating, repo group creating, forking
471 471 etc.
472 472 """
473 473
474 474 # now we read the defined permissions and overwrite what we have set
475 475 # before those can be configured from groups or users explicitly.
476 476
477 477 # TODO: johbo: This seems to be out of sync, find out the reason
478 478 # for the comment below and update it.
479 479
480 480 # In case we want to extend this list we should be always in sync with
481 481 # User.DEFAULT_USER_PERMISSIONS definitions
482 482 _configurable = frozenset([
483 483 'hg.fork.none', 'hg.fork.repository',
484 484 'hg.create.none', 'hg.create.repository',
485 485 'hg.usergroup.create.false', 'hg.usergroup.create.true',
486 486 'hg.repogroup.create.false', 'hg.repogroup.create.true',
487 487 'hg.create.write_on_repogroup.false',
488 488 'hg.create.write_on_repogroup.true',
489 489 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true'
490 490 ])
491 491
492 492 # USER GROUPS comes first user group global permissions
493 493 user_perms_from_users_groups = Session().query(UserGroupToPerm)\
494 494 .options(joinedload(UserGroupToPerm.permission))\
495 495 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
496 496 UserGroupMember.users_group_id))\
497 497 .filter(UserGroupMember.user_id == self.user_id)\
498 498 .order_by(UserGroupToPerm.users_group_id)\
499 499 .all()
500 500
501 501 # need to group here by groups since user can be in more than
502 502 # one group, so we get all groups
503 503 _explicit_grouped_perms = [
504 504 [x, list(y)] for x, y in
505 505 itertools.groupby(user_perms_from_users_groups,
506 506 lambda _x: _x.users_group)]
507 507
508 508 for gr, perms in _explicit_grouped_perms:
509 509 # since user can be in multiple groups iterate over them and
510 510 # select the lowest permissions first (more explicit)
511 511 # TODO: marcink: do this^^
512 512
513 513 # group doesn't inherit default permissions so we actually set them
514 514 if not gr.inherit_default_permissions:
515 515 # NEED TO IGNORE all previously set configurable permissions
516 516 # and replace them with explicitly set from this user
517 517 # group permissions
518 518 self.permissions_global = self.permissions_global.difference(
519 519 _configurable)
520 520 for perm in perms:
521 521 self.permissions_global.add(perm.permission.permission_name)
522 522
523 523 # user explicit global permissions
524 524 user_perms = Session().query(UserToPerm)\
525 525 .options(joinedload(UserToPerm.permission))\
526 526 .filter(UserToPerm.user_id == self.user_id).all()
527 527
528 528 if not self.inherit_default_permissions:
529 529 # NEED TO IGNORE all configurable permissions and
530 530 # replace them with explicitly set from this user permissions
531 531 self.permissions_global = self.permissions_global.difference(
532 532 _configurable)
533 533 for perm in user_perms:
534 534 self.permissions_global.add(perm.permission.permission_name)
535 535
536 536 def _calculate_default_permissions(self):
537 537 """
538 538 Set default user permissions for repositories, repository groups
539 539 taken from the default user.
540 540
541 541 Calculate inheritance of object permissions based on what we have now
542 542 in GLOBAL permissions. We check if .false is in GLOBAL since this is
543 543 explicitly set. Inherit is the opposite of .false being there.
544 544
545 545 .. note::
546 546
547 547 the syntax is little bit odd but what we need to check here is
548 548 the opposite of .false permission being in the list so even for
549 549 inconsistent state when both .true/.false is there
550 550 .false is more important
551 551
552 552 """
553 553 user_inherit_object_permissions = not ('hg.inherit_default_perms.false'
554 554 in self.permissions_global)
555 555
556 556 # defaults for repositories, taken from `default` user permissions
557 557 # on given repo
558 558 for perm in self.default_repo_perms:
559 559 r_k = perm.UserRepoToPerm.repository.repo_name
560 560 p = perm.Permission.permission_name
561 561 o = PermOrigin.REPO_DEFAULT
562 562 self.permissions_repositories[r_k] = p, o
563 563
564 564 # if we decide this user isn't inheriting permissions from
565 565 # default user we set him to .none so only explicit
566 566 # permissions work
567 567 if not user_inherit_object_permissions:
568 568 p = 'repository.none'
569 569 o = PermOrigin.REPO_DEFAULT_NO_INHERIT
570 570 self.permissions_repositories[r_k] = p, o
571 571
572 572 if perm.Repository.private and not (
573 573 perm.Repository.user_id == self.user_id):
574 574 # disable defaults for private repos,
575 575 p = 'repository.none'
576 576 o = PermOrigin.REPO_PRIVATE
577 577 self.permissions_repositories[r_k] = p, o
578 578
579 579 elif perm.Repository.user_id == self.user_id:
580 580 # set admin if owner
581 581 p = 'repository.admin'
582 582 o = PermOrigin.REPO_OWNER
583 583 self.permissions_repositories[r_k] = p, o
584 584
585 585 if self.user_is_admin:
586 586 p = 'repository.admin'
587 587 o = PermOrigin.SUPER_ADMIN
588 588 self.permissions_repositories[r_k] = p, o
589 589
590 590 # defaults for repository groups taken from `default` user permission
591 591 # on given group
592 592 for perm in self.default_repo_groups_perms:
593 593 rg_k = perm.UserRepoGroupToPerm.group.group_name
594 594 p = perm.Permission.permission_name
595 595 o = PermOrigin.REPOGROUP_DEFAULT
596 596 self.permissions_repository_groups[rg_k] = p, o
597 597
598 598 # if we decide this user isn't inheriting permissions from default
599 599 # user we set him to .none so only explicit permissions work
600 600 if not user_inherit_object_permissions:
601 601 p = 'group.none'
602 602 o = PermOrigin.REPOGROUP_DEFAULT_NO_INHERIT
603 603 self.permissions_repository_groups[rg_k] = p, o
604 604
605 605 if perm.RepoGroup.user_id == self.user_id:
606 606 # set admin if owner
607 607 p = 'group.admin'
608 608 o = PermOrigin.REPOGROUP_OWNER
609 609 self.permissions_repository_groups[rg_k] = p, o
610 610
611 611 if self.user_is_admin:
612 612 p = 'group.admin'
613 613 o = PermOrigin.SUPER_ADMIN
614 614 self.permissions_repository_groups[rg_k] = p, o
615 615
616 616 # defaults for user groups taken from `default` user permission
617 617 # on given user group
618 618 for perm in self.default_user_group_perms:
619 619 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
620 620 p = perm.Permission.permission_name
621 621 o = PermOrigin.USERGROUP_DEFAULT
622 622 self.permissions_user_groups[u_k] = p, o
623 623
624 624 # if we decide this user isn't inheriting permissions from default
625 625 # user we set him to .none so only explicit permissions work
626 626 if not user_inherit_object_permissions:
627 627 p = 'usergroup.none'
628 628 o = PermOrigin.USERGROUP_DEFAULT_NO_INHERIT
629 629 self.permissions_user_groups[u_k] = p, o
630 630
631 631 if perm.UserGroup.user_id == self.user_id:
632 632 # set admin if owner
633 633 p = 'usergroup.admin'
634 634 o = PermOrigin.USERGROUP_OWNER
635 635 self.permissions_user_groups[u_k] = p, o
636 636
637 637 if self.user_is_admin:
638 638 p = 'usergroup.admin'
639 639 o = PermOrigin.SUPER_ADMIN
640 640 self.permissions_user_groups[u_k] = p, o
641 641
642 642 def _calculate_repository_permissions(self):
643 643 """
644 644 Repository permissions for the current user.
645 645
646 646 Check if the user is part of user groups for this repository and
647 647 fill in the permission from it. `_choose_permission` decides of which
648 648 permission should be selected based on selected method.
649 649 """
650 650
651 651 # user group for repositories permissions
652 652 user_repo_perms_from_user_group = Permission\
653 653 .get_default_repo_perms_from_user_group(
654 654 self.user_id, self.scope_repo_id)
655 655
656 656 multiple_counter = collections.defaultdict(int)
657 657 for perm in user_repo_perms_from_user_group:
658 658 r_k = perm.UserGroupRepoToPerm.repository.repo_name
659 659 multiple_counter[r_k] += 1
660 660 p = perm.Permission.permission_name
661 661 o = PermOrigin.REPO_USERGROUP % perm.UserGroupRepoToPerm\
662 662 .users_group.users_group_name
663 663
664 664 if multiple_counter[r_k] > 1:
665 665 cur_perm = self.permissions_repositories[r_k]
666 666 p = self._choose_permission(p, cur_perm)
667 667
668 668 self.permissions_repositories[r_k] = p, o
669 669
670 670 if perm.Repository.user_id == self.user_id:
671 671 # set admin if owner
672 672 p = 'repository.admin'
673 673 o = PermOrigin.REPO_OWNER
674 674 self.permissions_repositories[r_k] = p, o
675 675
676 676 if self.user_is_admin:
677 677 p = 'repository.admin'
678 678 o = PermOrigin.SUPER_ADMIN
679 679 self.permissions_repositories[r_k] = p, o
680 680
681 681 # user explicit permissions for repositories, overrides any specified
682 682 # by the group permission
683 683 user_repo_perms = Permission.get_default_repo_perms(
684 684 self.user_id, self.scope_repo_id)
685 685 for perm in user_repo_perms:
686 686 r_k = perm.UserRepoToPerm.repository.repo_name
687 687 p = perm.Permission.permission_name
688 688 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
689 689
690 690 if not self.explicit:
691 691 cur_perm = self.permissions_repositories.get(
692 692 r_k, 'repository.none')
693 693 p = self._choose_permission(p, cur_perm)
694 694
695 695 self.permissions_repositories[r_k] = p, o
696 696
697 697 if perm.Repository.user_id == self.user_id:
698 698 # set admin if owner
699 699 p = 'repository.admin'
700 700 o = PermOrigin.REPO_OWNER
701 701 self.permissions_repositories[r_k] = p, o
702 702
703 703 if self.user_is_admin:
704 704 p = 'repository.admin'
705 705 o = PermOrigin.SUPER_ADMIN
706 706 self.permissions_repositories[r_k] = p, o
707 707
708 708 def _calculate_repository_group_permissions(self):
709 709 """
710 710 Repository group permissions for the current user.
711 711
712 712 Check if the user is part of user groups for repository groups and
713 713 fill in the permissions from it. `_choose_permission` decides of which
714 714 permission should be selected based on selected method.
715 715 """
716 716 # user group for repo groups permissions
717 717 user_repo_group_perms_from_user_group = Permission\
718 718 .get_default_group_perms_from_user_group(
719 719 self.user_id, self.scope_repo_group_id)
720 720
721 721 multiple_counter = collections.defaultdict(int)
722 722 for perm in user_repo_group_perms_from_user_group:
723 723 rg_k = perm.UserGroupRepoGroupToPerm.group.group_name
724 724 multiple_counter[rg_k] += 1
725 725 o = PermOrigin.REPOGROUP_USERGROUP % perm.UserGroupRepoGroupToPerm\
726 726 .users_group.users_group_name
727 727 p = perm.Permission.permission_name
728 728
729 729 if multiple_counter[rg_k] > 1:
730 730 cur_perm = self.permissions_repository_groups[rg_k]
731 731 p = self._choose_permission(p, cur_perm)
732 732 self.permissions_repository_groups[rg_k] = p, o
733 733
734 734 if perm.RepoGroup.user_id == self.user_id:
735 735 # set admin if owner, even for member of other user group
736 736 p = 'group.admin'
737 737 o = PermOrigin.REPOGROUP_OWNER
738 738 self.permissions_repository_groups[rg_k] = p, o
739 739
740 740 if self.user_is_admin:
741 741 p = 'group.admin'
742 742 o = PermOrigin.SUPER_ADMIN
743 743 self.permissions_repository_groups[rg_k] = p, o
744 744
745 745 # user explicit permissions for repository groups
746 746 user_repo_groups_perms = Permission.get_default_group_perms(
747 747 self.user_id, self.scope_repo_group_id)
748 748 for perm in user_repo_groups_perms:
749 749 rg_k = perm.UserRepoGroupToPerm.group.group_name
750 750 o = PermOrigin.REPOGROUP_USER % perm.UserRepoGroupToPerm\
751 751 .user.username
752 752 p = perm.Permission.permission_name
753 753
754 754 if not self.explicit:
755 755 cur_perm = self.permissions_repository_groups.get(
756 756 rg_k, 'group.none')
757 757 p = self._choose_permission(p, cur_perm)
758 758
759 759 self.permissions_repository_groups[rg_k] = p, o
760 760
761 761 if perm.RepoGroup.user_id == self.user_id:
762 762 # set admin if owner
763 763 p = 'group.admin'
764 764 o = PermOrigin.REPOGROUP_OWNER
765 765 self.permissions_repository_groups[rg_k] = p, o
766 766
767 767 if self.user_is_admin:
768 768 p = 'group.admin'
769 769 o = PermOrigin.SUPER_ADMIN
770 770 self.permissions_repository_groups[rg_k] = p, o
771 771
772 772 def _calculate_user_group_permissions(self):
773 773 """
774 774 User group permissions for the current user.
775 775 """
776 776 # user group for user group permissions
777 777 user_group_from_user_group = Permission\
778 778 .get_default_user_group_perms_from_user_group(
779 779 self.user_id, self.scope_user_group_id)
780 780
781 781 multiple_counter = collections.defaultdict(int)
782 782 for perm in user_group_from_user_group:
783 783 ug_k = perm.UserGroupUserGroupToPerm\
784 784 .target_user_group.users_group_name
785 785 multiple_counter[ug_k] += 1
786 786 o = PermOrigin.USERGROUP_USERGROUP % perm.UserGroupUserGroupToPerm\
787 787 .user_group.users_group_name
788 788 p = perm.Permission.permission_name
789 789
790 790 if multiple_counter[ug_k] > 1:
791 791 cur_perm = self.permissions_user_groups[ug_k]
792 792 p = self._choose_permission(p, cur_perm)
793 793
794 794 self.permissions_user_groups[ug_k] = p, o
795 795
796 796 if perm.UserGroup.user_id == self.user_id:
797 797 # set admin if owner, even for member of other user group
798 798 p = 'usergroup.admin'
799 799 o = PermOrigin.USERGROUP_OWNER
800 800 self.permissions_user_groups[ug_k] = p, o
801 801
802 802 if self.user_is_admin:
803 803 p = 'usergroup.admin'
804 804 o = PermOrigin.SUPER_ADMIN
805 805 self.permissions_user_groups[ug_k] = p, o
806 806
807 807 # user explicit permission for user groups
808 808 user_user_groups_perms = Permission.get_default_user_group_perms(
809 809 self.user_id, self.scope_user_group_id)
810 810 for perm in user_user_groups_perms:
811 811 ug_k = perm.UserUserGroupToPerm.user_group.users_group_name
812 812 o = PermOrigin.USERGROUP_USER % perm.UserUserGroupToPerm\
813 813 .user.username
814 814 p = perm.Permission.permission_name
815 815
816 816 if not self.explicit:
817 817 cur_perm = self.permissions_user_groups.get(
818 818 ug_k, 'usergroup.none')
819 819 p = self._choose_permission(p, cur_perm)
820 820
821 821 self.permissions_user_groups[ug_k] = p, o
822 822
823 823 if perm.UserGroup.user_id == self.user_id:
824 824 # set admin if owner
825 825 p = 'usergroup.admin'
826 826 o = PermOrigin.USERGROUP_OWNER
827 827 self.permissions_user_groups[ug_k] = p, o
828 828
829 829 if self.user_is_admin:
830 830 p = 'usergroup.admin'
831 831 o = PermOrigin.SUPER_ADMIN
832 832 self.permissions_user_groups[ug_k] = p, o
833 833
834 834 def _choose_permission(self, new_perm, cur_perm):
835 835 new_perm_val = Permission.PERM_WEIGHTS[new_perm]
836 836 cur_perm_val = Permission.PERM_WEIGHTS[cur_perm]
837 837 if self.algo == 'higherwin':
838 838 if new_perm_val > cur_perm_val:
839 839 return new_perm
840 840 return cur_perm
841 841 elif self.algo == 'lowerwin':
842 842 if new_perm_val < cur_perm_val:
843 843 return new_perm
844 844 return cur_perm
845 845
846 846 def _permission_structure(self):
847 847 return {
848 848 'global': self.permissions_global,
849 849 'repositories': self.permissions_repositories,
850 850 'repositories_groups': self.permissions_repository_groups,
851 851 'user_groups': self.permissions_user_groups,
852 852 }
853 853
854 854
855 855 def allowed_auth_token_access(view_name, auth_token, whitelist=None):
856 856 """
857 857 Check if given controller_name is in whitelist of auth token access
858 858 """
859 859 if not whitelist:
860 860 from rhodecode import CONFIG
861 861 whitelist = aslist(
862 862 CONFIG.get('api_access_controllers_whitelist'), sep=',')
863 863 # backward compat translation
864 864 compat = {
865 865 # old controller, new VIEW
866 866 'ChangesetController:*': 'RepoCommitsView:*',
867 867 'ChangesetController:changeset_patch': 'RepoCommitsView:repo_commit_patch',
868 868 'ChangesetController:changeset_raw': 'RepoCommitsView:repo_commit_raw',
869 869 'FilesController:raw': 'RepoCommitsView:repo_commit_raw',
870 870 'FilesController:archivefile': 'RepoFilesView:repo_archivefile',
871 871 'GistsController:*': 'GistView:*',
872 872 }
873 873
874 874 log.debug(
875 875 'Allowed views for AUTH TOKEN access: %s' % (whitelist,))
876 876 auth_token_access_valid = False
877 877
878 878 for entry in whitelist:
879 879 token_match = True
880 880 if entry in compat:
881 881 # translate from old Controllers to Pyramid Views
882 882 entry = compat[entry]
883 883
884 884 if '@' in entry:
885 885 # specific AuthToken
886 886 entry, allowed_token = entry.split('@', 1)
887 887 token_match = auth_token == allowed_token
888 888
889 889 if fnmatch.fnmatch(view_name, entry) and token_match:
890 890 auth_token_access_valid = True
891 891 break
892 892
893 893 if auth_token_access_valid:
894 894 log.debug('view: `%s` matches entry in whitelist: %s'
895 895 % (view_name, whitelist))
896 896 else:
897 897 msg = ('view: `%s` does *NOT* match any entry in whitelist: %s'
898 898 % (view_name, whitelist))
899 899 if auth_token:
900 900 # if we use auth token key and don't have access it's a warning
901 901 log.warning(msg)
902 902 else:
903 903 log.debug(msg)
904 904
905 905 return auth_token_access_valid
906 906
907 907
908 908 class AuthUser(object):
909 909 """
910 910 A simple object that handles all attributes of user in RhodeCode
911 911
912 912 It does lookup based on API key,given user, or user present in session
913 913 Then it fills all required information for such user. It also checks if
914 914 anonymous access is enabled and if so, it returns default user as logged in
915 915 """
916 916 GLOBAL_PERMS = [x[0] for x in Permission.PERMS]
917 917
918 918 def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None):
919 919
920 920 self.user_id = user_id
921 921 self._api_key = api_key
922 922
923 923 self.api_key = None
924 924 self.feed_token = ''
925 925 self.username = username
926 926 self.ip_addr = ip_addr
927 927 self.name = ''
928 928 self.lastname = ''
929 929 self.first_name = ''
930 930 self.last_name = ''
931 931 self.email = ''
932 932 self.is_authenticated = False
933 933 self.admin = False
934 934 self.inherit_default_permissions = False
935 935 self.password = ''
936 936
937 937 self.anonymous_user = None # propagated on propagate_data
938 938 self.propagate_data()
939 939 self._instance = None
940 940 self._permissions_scoped_cache = {} # used to bind scoped calculation
941 941
942 942 @LazyProperty
943 943 def permissions(self):
944 944 return self.get_perms(user=self, cache=False)
945 945
946 946 @LazyProperty
947 947 def permissions_full_details(self):
948 948 return self.get_perms(
949 949 user=self, cache=False, calculate_super_admin=True)
950 950
951 951 def permissions_with_scope(self, scope):
952 952 """
953 953 Call the get_perms function with scoped data. The scope in that function
954 954 narrows the SQL calls to the given ID of objects resulting in fetching
955 955 Just particular permission we want to obtain. If scope is an empty dict
956 956 then it basically narrows the scope to GLOBAL permissions only.
957 957
958 958 :param scope: dict
959 959 """
960 960 if 'repo_name' in scope:
961 961 obj = Repository.get_by_repo_name(scope['repo_name'])
962 962 if obj:
963 963 scope['repo_id'] = obj.repo_id
964 964 _scope = {
965 965 'repo_id': -1,
966 966 'user_group_id': -1,
967 967 'repo_group_id': -1,
968 968 }
969 969 _scope.update(scope)
970 970 cache_key = "_".join(map(safe_str, reduce(lambda a, b: a+b,
971 971 _scope.items())))
972 972 if cache_key not in self._permissions_scoped_cache:
973 973 # store in cache to mimic how the @LazyProperty works,
974 974 # the difference here is that we use the unique key calculated
975 975 # from params and values
976 976 res = self.get_perms(user=self, cache=False, scope=_scope)
977 977 self._permissions_scoped_cache[cache_key] = res
978 978 return self._permissions_scoped_cache[cache_key]
979 979
980 980 def get_instance(self):
981 981 return User.get(self.user_id)
982 982
983 983 def update_lastactivity(self):
984 984 if self.user_id:
985 985 User.get(self.user_id).update_lastactivity()
986 986
987 987 def propagate_data(self):
988 988 """
989 989 Fills in user data and propagates values to this instance. Maps fetched
990 990 user attributes to this class instance attributes
991 991 """
992 992 log.debug('AuthUser: starting data propagation for new potential user')
993 993 user_model = UserModel()
994 994 anon_user = self.anonymous_user = User.get_default_user(cache=True)
995 995 is_user_loaded = False
996 996
997 997 # lookup by userid
998 998 if self.user_id is not None and self.user_id != anon_user.user_id:
999 999 log.debug('Trying Auth User lookup by USER ID: `%s`', self.user_id)
1000 1000 is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
1001 1001
1002 1002 # try go get user by api key
1003 1003 elif self._api_key and self._api_key != anon_user.api_key:
1004 1004 log.debug('Trying Auth User lookup by API KEY: `%s`', self._api_key)
1005 1005 is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
1006 1006
1007 1007 # lookup by username
1008 1008 elif self.username:
1009 1009 log.debug('Trying Auth User lookup by USER NAME: `%s`', self.username)
1010 1010 is_user_loaded = user_model.fill_data(self, username=self.username)
1011 1011 else:
1012 1012 log.debug('No data in %s that could been used to log in', self)
1013 1013
1014 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 1017 # if we cannot authenticate user try anonymous
1017 1018 if anon_user.active:
1019 log.debug('default user is active, using it as a session user')
1018 1020 user_model.fill_data(self, user_id=anon_user.user_id)
1019 1021 # then we set this user is logged in
1020 1022 self.is_authenticated = True
1021 1023 else:
1024 log.debug('default user is NOT active')
1022 1025 # in case of disabled anonymous user we reset some of the
1023 1026 # parameters so such user is "corrupted", skipping the fill_data
1024 1027 for attr in ['user_id', 'username', 'admin', 'active']:
1025 1028 setattr(self, attr, None)
1026 1029 self.is_authenticated = False
1027 1030
1028 1031 if not self.username:
1029 1032 self.username = 'None'
1030 1033
1031 1034 log.debug('AuthUser: propagated user is now %s', self)
1032 1035
1033 1036 def get_perms(self, user, scope=None, explicit=True, algo='higherwin',
1034 1037 calculate_super_admin=False, cache=False):
1035 1038 """
1036 1039 Fills user permission attribute with permissions taken from database
1037 1040 works for permissions given for repositories, and for permissions that
1038 1041 are granted to groups
1039 1042
1040 1043 :param user: instance of User object from database
1041 1044 :param explicit: In case there are permissions both for user and a group
1042 1045 that user is part of, explicit flag will defiine if user will
1043 1046 explicitly override permissions from group, if it's False it will
1044 1047 make decision based on the algo
1045 1048 :param algo: algorithm to decide what permission should be choose if
1046 1049 it's multiple defined, eg user in two different groups. It also
1047 1050 decides if explicit flag is turned off how to specify the permission
1048 1051 for case when user is in a group + have defined separate permission
1049 1052 """
1050 1053 user_id = user.user_id
1051 1054 user_is_admin = user.is_admin
1052 1055
1053 1056 # inheritance of global permissions like create repo/fork repo etc
1054 1057 user_inherit_default_permissions = user.inherit_default_permissions
1055 1058
1056 1059 log.debug('Computing PERMISSION tree for scope %s' % (scope, ))
1057 1060 compute = caches.conditional_cache(
1058 1061 'short_term', 'cache_desc',
1059 1062 condition=cache, func=_cached_perms_data)
1060 1063 result = compute(user_id, scope, user_is_admin,
1061 1064 user_inherit_default_permissions, explicit, algo,
1062 1065 calculate_super_admin)
1063 1066
1064 1067 result_repr = []
1065 1068 for k in result:
1066 1069 result_repr.append((k, len(result[k])))
1067 1070
1068 1071 log.debug('PERMISSION tree computed %s' % (result_repr,))
1069 1072 return result
1070 1073
1071 1074 @property
1072 1075 def is_default(self):
1073 1076 return self.username == User.DEFAULT_USER
1074 1077
1075 1078 @property
1076 1079 def is_admin(self):
1077 1080 return self.admin
1078 1081
1079 1082 @property
1080 1083 def is_user_object(self):
1081 1084 return self.user_id is not None
1082 1085
1083 1086 @property
1084 1087 def repositories_admin(self):
1085 1088 """
1086 1089 Returns list of repositories you're an admin of
1087 1090 """
1088 1091 return [
1089 1092 x[0] for x in self.permissions['repositories'].iteritems()
1090 1093 if x[1] == 'repository.admin']
1091 1094
1092 1095 @property
1093 1096 def repository_groups_admin(self):
1094 1097 """
1095 1098 Returns list of repository groups you're an admin of
1096 1099 """
1097 1100 return [
1098 1101 x[0] for x in self.permissions['repositories_groups'].iteritems()
1099 1102 if x[1] == 'group.admin']
1100 1103
1101 1104 @property
1102 1105 def user_groups_admin(self):
1103 1106 """
1104 1107 Returns list of user groups you're an admin of
1105 1108 """
1106 1109 return [
1107 1110 x[0] for x in self.permissions['user_groups'].iteritems()
1108 1111 if x[1] == 'usergroup.admin']
1109 1112
1110 1113 def repo_acl_ids(self, perms=None, name_filter=None, cache=False):
1111 1114 """
1112 1115 Returns list of repository ids that user have access to based on given
1113 1116 perms. The cache flag should be only used in cases that are used for
1114 1117 display purposes, NOT IN ANY CASE for permission checks.
1115 1118 """
1116 1119 from rhodecode.model.scm import RepoList
1117 1120 if not perms:
1118 1121 perms = [
1119 1122 'repository.read', 'repository.write', 'repository.admin']
1120 1123
1121 1124 def _cached_repo_acl(user_id, perm_def, name_filter):
1122 1125 qry = Repository.query()
1123 1126 if name_filter:
1124 1127 ilike_expression = u'%{}%'.format(safe_unicode(name_filter))
1125 1128 qry = qry.filter(
1126 1129 Repository.repo_name.ilike(ilike_expression))
1127 1130
1128 1131 return [x.repo_id for x in
1129 1132 RepoList(qry, perm_set=perm_def)]
1130 1133
1131 1134 compute = caches.conditional_cache(
1132 1135 'long_term', 'repo_acl_ids',
1133 1136 condition=cache, func=_cached_repo_acl)
1134 1137 return compute(self.user_id, perms, name_filter)
1135 1138
1136 1139 def repo_group_acl_ids(self, perms=None, name_filter=None, cache=False):
1137 1140 """
1138 1141 Returns list of repository group ids that user have access to based on given
1139 1142 perms. The cache flag should be only used in cases that are used for
1140 1143 display purposes, NOT IN ANY CASE for permission checks.
1141 1144 """
1142 1145 from rhodecode.model.scm import RepoGroupList
1143 1146 if not perms:
1144 1147 perms = [
1145 1148 'group.read', 'group.write', 'group.admin']
1146 1149
1147 1150 def _cached_repo_group_acl(user_id, perm_def, name_filter):
1148 1151 qry = RepoGroup.query()
1149 1152 if name_filter:
1150 1153 ilike_expression = u'%{}%'.format(safe_unicode(name_filter))
1151 1154 qry = qry.filter(
1152 1155 RepoGroup.group_name.ilike(ilike_expression))
1153 1156
1154 1157 return [x.group_id for x in
1155 1158 RepoGroupList(qry, perm_set=perm_def)]
1156 1159
1157 1160 compute = caches.conditional_cache(
1158 1161 'long_term', 'repo_group_acl_ids',
1159 1162 condition=cache, func=_cached_repo_group_acl)
1160 1163 return compute(self.user_id, perms, name_filter)
1161 1164
1162 1165 def user_group_acl_ids(self, perms=None, name_filter=None, cache=False):
1163 1166 """
1164 1167 Returns list of user group ids that user have access to based on given
1165 1168 perms. The cache flag should be only used in cases that are used for
1166 1169 display purposes, NOT IN ANY CASE for permission checks.
1167 1170 """
1168 1171 from rhodecode.model.scm import UserGroupList
1169 1172 if not perms:
1170 1173 perms = [
1171 1174 'usergroup.read', 'usergroup.write', 'usergroup.admin']
1172 1175
1173 1176 def _cached_user_group_acl(user_id, perm_def, name_filter):
1174 1177 qry = UserGroup.query()
1175 1178 if name_filter:
1176 1179 ilike_expression = u'%{}%'.format(safe_unicode(name_filter))
1177 1180 qry = qry.filter(
1178 1181 UserGroup.users_group_name.ilike(ilike_expression))
1179 1182
1180 1183 return [x.users_group_id for x in
1181 1184 UserGroupList(qry, perm_set=perm_def)]
1182 1185
1183 1186 compute = caches.conditional_cache(
1184 1187 'long_term', 'user_group_acl_ids',
1185 1188 condition=cache, func=_cached_user_group_acl)
1186 1189 return compute(self.user_id, perms, name_filter)
1187 1190
1188 1191 @property
1189 1192 def ip_allowed(self):
1190 1193 """
1191 1194 Checks if ip_addr used in constructor is allowed from defined list of
1192 1195 allowed ip_addresses for user
1193 1196
1194 1197 :returns: boolean, True if ip is in allowed ip range
1195 1198 """
1196 1199 # check IP
1197 1200 inherit = self.inherit_default_permissions
1198 1201 return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
1199 1202 inherit_from_default=inherit)
1200 1203 @property
1201 1204 def personal_repo_group(self):
1202 1205 return RepoGroup.get_user_personal_repo_group(self.user_id)
1203 1206
1204 1207 @classmethod
1205 1208 def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
1206 1209 allowed_ips = AuthUser.get_allowed_ips(
1207 1210 user_id, cache=True, inherit_from_default=inherit_from_default)
1208 1211 if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
1209 1212 log.debug('IP:%s is in range of %s' % (ip_addr, allowed_ips))
1210 1213 return True
1211 1214 else:
1212 1215 log.info('Access for IP:%s forbidden, '
1213 1216 'not in %s' % (ip_addr, allowed_ips))
1214 1217 return False
1215 1218
1216 1219 def __repr__(self):
1217 1220 return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
1218 1221 % (self.user_id, self.username, self.ip_addr, self.is_authenticated)
1219 1222
1220 1223 def set_authenticated(self, authenticated=True):
1221 1224 if self.user_id != self.anonymous_user.user_id:
1222 1225 self.is_authenticated = authenticated
1223 1226
1224 1227 def get_cookie_store(self):
1225 1228 return {
1226 1229 'username': self.username,
1227 1230 'password': md5(self.password),
1228 1231 'user_id': self.user_id,
1229 1232 'is_authenticated': self.is_authenticated
1230 1233 }
1231 1234
1232 1235 @classmethod
1233 1236 def from_cookie_store(cls, cookie_store):
1234 1237 """
1235 1238 Creates AuthUser from a cookie store
1236 1239
1237 1240 :param cls:
1238 1241 :param cookie_store:
1239 1242 """
1240 1243 user_id = cookie_store.get('user_id')
1241 1244 username = cookie_store.get('username')
1242 1245 api_key = cookie_store.get('api_key')
1243 1246 return AuthUser(user_id, api_key, username)
1244 1247
1245 1248 @classmethod
1246 1249 def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
1247 1250 _set = set()
1248 1251
1249 1252 if inherit_from_default:
1250 1253 default_ips = UserIpMap.query().filter(
1251 1254 UserIpMap.user == User.get_default_user(cache=True))
1252 1255 if cache:
1253 1256 default_ips = default_ips.options(
1254 1257 FromCache("sql_cache_short", "get_user_ips_default"))
1255 1258
1256 1259 # populate from default user
1257 1260 for ip in default_ips:
1258 1261 try:
1259 1262 _set.add(ip.ip_addr)
1260 1263 except ObjectDeletedError:
1261 1264 # since we use heavy caching sometimes it happens that
1262 1265 # we get deleted objects here, we just skip them
1263 1266 pass
1264 1267
1265 1268 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
1266 1269 if cache:
1267 1270 user_ips = user_ips.options(
1268 1271 FromCache("sql_cache_short", "get_user_ips_%s" % user_id))
1269 1272
1270 1273 for ip in user_ips:
1271 1274 try:
1272 1275 _set.add(ip.ip_addr)
1273 1276 except ObjectDeletedError:
1274 1277 # since we use heavy caching sometimes it happens that we get
1275 1278 # deleted objects here, we just skip them
1276 1279 pass
1277 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 1286 permission given in db. We don't want to check each time from db for new
1284 1287 permissions since adding a new permission also requires application restart
1285 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 1294 try:
1292 1295 sa = meta.Session
1293 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 1300 except Exception:
1296 log.error(traceback.format_exc())
1297 finally:
1298 meta.Session.remove()
1301 log.exception('Failed to fetch permissions from the database.')
1302 raise
1299 1303
1300 1304
1301 1305 def get_csrf_token(session, force_new=False, save_if_missing=True):
1302 1306 """
1303 1307 Return the current authentication token, creating one if one doesn't
1304 1308 already exist and the save_if_missing flag is present.
1305 1309
1306 1310 :param session: pass in the pylons session, else we use the global ones
1307 1311 :param force_new: force to re-generate the token and store it in session
1308 1312 :param save_if_missing: save the newly generated token if it's missing in
1309 1313 session
1310 1314 """
1311 1315 # NOTE(marcink): probably should be replaced with below one from pyramid 1.9
1312 1316 # from pyramid.csrf import get_csrf_token
1313 1317
1314 1318 if (csrf_token_key not in session and save_if_missing) or force_new:
1315 1319 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
1316 1320 session[csrf_token_key] = token
1317 1321 if hasattr(session, 'save'):
1318 1322 session.save()
1319 1323 return session.get(csrf_token_key)
1320 1324
1321 1325
1322 1326 def get_request(perm_class_instance):
1323 1327 from pyramid.threadlocal import get_current_request
1324 1328 pyramid_request = get_current_request()
1325 1329 if not pyramid_request:
1326 1330 # return global request of pylons in case pyramid isn't available
1327 1331 # NOTE(marcink): this should be removed after migration to pyramid
1328 1332 from pylons import request
1329 1333 return request
1330 1334 return pyramid_request
1331 1335
1332 1336
1333 1337 # CHECK DECORATORS
1334 1338 class CSRFRequired(object):
1335 1339 """
1336 1340 Decorator for authenticating a form
1337 1341
1338 1342 This decorator uses an authorization token stored in the client's
1339 1343 session for prevention of certain Cross-site request forgery (CSRF)
1340 1344 attacks (See
1341 1345 http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
1342 1346 information).
1343 1347
1344 1348 For use with the ``webhelpers.secure_form`` helper functions.
1345 1349
1346 1350 """
1347 1351 def __init__(self, token=csrf_token_key, header='X-CSRF-Token',
1348 1352 except_methods=None):
1349 1353 self.token = token
1350 1354 self.header = header
1351 1355 self.except_methods = except_methods or []
1352 1356
1353 1357 def __call__(self, func):
1354 1358 return get_cython_compat_decorator(self.__wrapper, func)
1355 1359
1356 1360 def _get_csrf(self, _request):
1357 1361 return _request.POST.get(self.token, _request.headers.get(self.header))
1358 1362
1359 1363 def check_csrf(self, _request, cur_token):
1360 1364 supplied_token = self._get_csrf(_request)
1361 1365 return supplied_token and supplied_token == cur_token
1362 1366
1363 1367 def _get_request(self):
1364 1368 return get_request(self)
1365 1369
1366 1370 def __wrapper(self, func, *fargs, **fkwargs):
1367 1371 request = self._get_request()
1368 1372
1369 1373 if request.method in self.except_methods:
1370 1374 return func(*fargs, **fkwargs)
1371 1375
1372 1376 cur_token = get_csrf_token(request.session, save_if_missing=False)
1373 1377 if self.check_csrf(request, cur_token):
1374 1378 if request.POST.get(self.token):
1375 1379 del request.POST[self.token]
1376 1380 return func(*fargs, **fkwargs)
1377 1381 else:
1378 1382 reason = 'token-missing'
1379 1383 supplied_token = self._get_csrf(request)
1380 1384 if supplied_token and cur_token != supplied_token:
1381 1385 reason = 'token-mismatch [%s:%s]' % (
1382 1386 cur_token or ''[:6], supplied_token or ''[:6])
1383 1387
1384 1388 csrf_message = \
1385 1389 ("Cross-site request forgery detected, request denied. See "
1386 1390 "http://en.wikipedia.org/wiki/Cross-site_request_forgery for "
1387 1391 "more information.")
1388 1392 log.warn('Cross-site request forgery detected, request %r DENIED: %s '
1389 1393 'REMOTE_ADDR:%s, HEADERS:%s' % (
1390 1394 request, reason, request.remote_addr, request.headers))
1391 1395
1392 1396 raise HTTPForbidden(explanation=csrf_message)
1393 1397
1394 1398
1395 1399 class LoginRequired(object):
1396 1400 """
1397 1401 Must be logged in to execute this function else
1398 1402 redirect to login page
1399 1403
1400 1404 :param api_access: if enabled this checks only for valid auth token
1401 1405 and grants access based on valid token
1402 1406 """
1403 1407 def __init__(self, auth_token_access=None):
1404 1408 self.auth_token_access = auth_token_access
1405 1409
1406 1410 def __call__(self, func):
1407 1411 return get_cython_compat_decorator(self.__wrapper, func)
1408 1412
1409 1413 def _get_request(self):
1410 1414 return get_request(self)
1411 1415
1412 1416 def __wrapper(self, func, *fargs, **fkwargs):
1413 1417 from rhodecode.lib import helpers as h
1414 1418 cls = fargs[0]
1415 1419 user = cls._rhodecode_user
1416 1420 request = self._get_request()
1417 1421
1418 1422 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1419 1423 log.debug('Starting login restriction checks for user: %s' % (user,))
1420 1424 # check if our IP is allowed
1421 1425 ip_access_valid = True
1422 1426 if not user.ip_allowed:
1423 1427 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1424 1428 category='warning')
1425 1429 ip_access_valid = False
1426 1430
1427 1431 # check if we used an APIKEY and it's a valid one
1428 1432 # defined white-list of controllers which API access will be enabled
1429 1433 _auth_token = request.GET.get(
1430 1434 'auth_token', '') or request.GET.get('api_key', '')
1431 1435 auth_token_access_valid = allowed_auth_token_access(
1432 1436 loc, auth_token=_auth_token)
1433 1437
1434 1438 # explicit controller is enabled or API is in our whitelist
1435 1439 if self.auth_token_access or auth_token_access_valid:
1436 1440 log.debug('Checking AUTH TOKEN access for %s' % (cls,))
1437 1441 db_user = user.get_instance()
1438 1442
1439 1443 if db_user:
1440 1444 if self.auth_token_access:
1441 1445 roles = self.auth_token_access
1442 1446 else:
1443 1447 roles = [UserApiKeys.ROLE_HTTP]
1444 1448 token_match = db_user.authenticate_by_token(
1445 1449 _auth_token, roles=roles)
1446 1450 else:
1447 1451 log.debug('Unable to fetch db instance for auth user: %s', user)
1448 1452 token_match = False
1449 1453
1450 1454 if _auth_token and token_match:
1451 1455 auth_token_access_valid = True
1452 1456 log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],))
1453 1457 else:
1454 1458 auth_token_access_valid = False
1455 1459 if not _auth_token:
1456 1460 log.debug("AUTH TOKEN *NOT* present in request")
1457 1461 else:
1458 1462 log.warning(
1459 1463 "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:])
1460 1464
1461 1465 log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
1462 1466 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1463 1467 else 'AUTH_TOKEN_AUTH'
1464 1468
1465 1469 if ip_access_valid and (
1466 1470 user.is_authenticated or auth_token_access_valid):
1467 1471 log.info(
1468 1472 'user %s authenticating with:%s IS authenticated on func %s'
1469 1473 % (user, reason, loc))
1470 1474
1471 1475 # update user data to check last activity
1472 1476 user.update_lastactivity()
1473 1477 Session().commit()
1474 1478 return func(*fargs, **fkwargs)
1475 1479 else:
1476 1480 log.warning(
1477 1481 'user %s authenticating with:%s NOT authenticated on '
1478 1482 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s'
1479 1483 % (user, reason, loc, ip_access_valid,
1480 1484 auth_token_access_valid))
1481 1485 # we preserve the get PARAM
1482 1486 came_from = get_came_from(request)
1483 1487
1484 1488 log.debug('redirecting to login page with %s' % (came_from,))
1485 1489 raise HTTPFound(
1486 1490 h.route_path('login', _query={'came_from': came_from}))
1487 1491
1488 1492
1489 1493 class NotAnonymous(object):
1490 1494 """
1491 1495 Must be logged in to execute this function else
1492 1496 redirect to login page
1493 1497 """
1494 1498
1495 1499 def __call__(self, func):
1496 1500 return get_cython_compat_decorator(self.__wrapper, func)
1497 1501
1498 1502 def _get_request(self):
1499 1503 return get_request(self)
1500 1504
1501 1505 def __wrapper(self, func, *fargs, **fkwargs):
1502 1506 import rhodecode.lib.helpers as h
1503 1507 cls = fargs[0]
1504 1508 self.user = cls._rhodecode_user
1505 1509 request = self._get_request()
1506 1510
1507 1511 log.debug('Checking if user is not anonymous @%s' % cls)
1508 1512
1509 1513 anonymous = self.user.username == User.DEFAULT_USER
1510 1514
1511 1515 if anonymous:
1512 1516 came_from = get_came_from(request)
1513 1517 h.flash(_('You need to be a registered user to '
1514 1518 'perform this action'),
1515 1519 category='warning')
1516 1520 raise HTTPFound(
1517 1521 h.route_path('login', _query={'came_from': came_from}))
1518 1522 else:
1519 1523 return func(*fargs, **fkwargs)
1520 1524
1521 1525
1522 1526 class PermsDecorator(object):
1523 1527 """
1524 1528 Base class for controller decorators, we extract the current user from
1525 1529 the class itself, which has it stored in base controllers
1526 1530 """
1527 1531
1528 1532 def __init__(self, *required_perms):
1529 1533 self.required_perms = set(required_perms)
1530 1534
1531 1535 def __call__(self, func):
1532 1536 return get_cython_compat_decorator(self.__wrapper, func)
1533 1537
1534 1538 def _get_request(self):
1535 1539 return get_request(self)
1536 1540
1537 1541 def __wrapper(self, func, *fargs, **fkwargs):
1538 1542 import rhodecode.lib.helpers as h
1539 1543 cls = fargs[0]
1540 1544 _user = cls._rhodecode_user
1541 1545
1542 1546 log.debug('checking %s permissions %s for %s %s',
1543 1547 self.__class__.__name__, self.required_perms, cls, _user)
1544 1548
1545 1549 if self.check_permissions(_user):
1546 1550 log.debug('Permission granted for %s %s', cls, _user)
1547 1551 return func(*fargs, **fkwargs)
1548 1552
1549 1553 else:
1550 1554 log.debug('Permission denied for %s %s', cls, _user)
1551 1555 anonymous = _user.username == User.DEFAULT_USER
1552 1556
1553 1557 if anonymous:
1554 1558 came_from = get_came_from(self._get_request())
1555 1559 h.flash(_('You need to be signed in to view this page'),
1556 1560 category='warning')
1557 1561 raise HTTPFound(
1558 1562 h.route_path('login', _query={'came_from': came_from}))
1559 1563
1560 1564 else:
1561 1565 # redirect with 404 to prevent resource discovery
1562 1566 raise HTTPNotFound()
1563 1567
1564 1568 def check_permissions(self, user):
1565 1569 """Dummy function for overriding"""
1566 1570 raise NotImplementedError(
1567 1571 'You have to write this function in child class')
1568 1572
1569 1573
1570 1574 class HasPermissionAllDecorator(PermsDecorator):
1571 1575 """
1572 1576 Checks for access permission for all given predicates. All of them
1573 1577 have to be meet in order to fulfill the request
1574 1578 """
1575 1579
1576 1580 def check_permissions(self, user):
1577 1581 perms = user.permissions_with_scope({})
1578 1582 if self.required_perms.issubset(perms['global']):
1579 1583 return True
1580 1584 return False
1581 1585
1582 1586
1583 1587 class HasPermissionAnyDecorator(PermsDecorator):
1584 1588 """
1585 1589 Checks for access permission for any of given predicates. In order to
1586 1590 fulfill the request any of predicates must be meet
1587 1591 """
1588 1592
1589 1593 def check_permissions(self, user):
1590 1594 perms = user.permissions_with_scope({})
1591 1595 if self.required_perms.intersection(perms['global']):
1592 1596 return True
1593 1597 return False
1594 1598
1595 1599
1596 1600 class HasRepoPermissionAllDecorator(PermsDecorator):
1597 1601 """
1598 1602 Checks for access permission for all given predicates for specific
1599 1603 repository. All of them have to be meet in order to fulfill the request
1600 1604 """
1601 1605 def _get_repo_name(self):
1602 1606 _request = self._get_request()
1603 1607 return get_repo_slug(_request)
1604 1608
1605 1609 def check_permissions(self, user):
1606 1610 perms = user.permissions
1607 1611 repo_name = self._get_repo_name()
1608 1612
1609 1613 try:
1610 1614 user_perms = set([perms['repositories'][repo_name]])
1611 1615 except KeyError:
1612 1616 log.debug('cannot locate repo with name: `%s` in permissions defs',
1613 1617 repo_name)
1614 1618 return False
1615 1619
1616 1620 log.debug('checking `%s` permissions for repo `%s`',
1617 1621 user_perms, repo_name)
1618 1622 if self.required_perms.issubset(user_perms):
1619 1623 return True
1620 1624 return False
1621 1625
1622 1626
1623 1627 class HasRepoPermissionAnyDecorator(PermsDecorator):
1624 1628 """
1625 1629 Checks for access permission for any of given predicates for specific
1626 1630 repository. In order to fulfill the request any of predicates must be meet
1627 1631 """
1628 1632 def _get_repo_name(self):
1629 1633 _request = self._get_request()
1630 1634 return get_repo_slug(_request)
1631 1635
1632 1636 def check_permissions(self, user):
1633 1637 perms = user.permissions
1634 1638 repo_name = self._get_repo_name()
1635 1639
1636 1640 try:
1637 1641 user_perms = set([perms['repositories'][repo_name]])
1638 1642 except KeyError:
1639 1643 log.debug(
1640 1644 'cannot locate repo with name: `%s` in permissions defs',
1641 1645 repo_name)
1642 1646 return False
1643 1647
1644 1648 log.debug('checking `%s` permissions for repo `%s`',
1645 1649 user_perms, repo_name)
1646 1650 if self.required_perms.intersection(user_perms):
1647 1651 return True
1648 1652 return False
1649 1653
1650 1654
1651 1655 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1652 1656 """
1653 1657 Checks for access permission for all given predicates for specific
1654 1658 repository group. All of them have to be meet in order to
1655 1659 fulfill the request
1656 1660 """
1657 1661 def _get_repo_group_name(self):
1658 1662 _request = self._get_request()
1659 1663 return get_repo_group_slug(_request)
1660 1664
1661 1665 def check_permissions(self, user):
1662 1666 perms = user.permissions
1663 1667 group_name = self._get_repo_group_name()
1664 1668 try:
1665 1669 user_perms = set([perms['repositories_groups'][group_name]])
1666 1670 except KeyError:
1667 1671 log.debug(
1668 1672 'cannot locate repo group with name: `%s` in permissions defs',
1669 1673 group_name)
1670 1674 return False
1671 1675
1672 1676 log.debug('checking `%s` permissions for repo group `%s`',
1673 1677 user_perms, group_name)
1674 1678 if self.required_perms.issubset(user_perms):
1675 1679 return True
1676 1680 return False
1677 1681
1678 1682
1679 1683 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1680 1684 """
1681 1685 Checks for access permission for any of given predicates for specific
1682 1686 repository group. In order to fulfill the request any
1683 1687 of predicates must be met
1684 1688 """
1685 1689 def _get_repo_group_name(self):
1686 1690 _request = self._get_request()
1687 1691 return get_repo_group_slug(_request)
1688 1692
1689 1693 def check_permissions(self, user):
1690 1694 perms = user.permissions
1691 1695 group_name = self._get_repo_group_name()
1692 1696
1693 1697 try:
1694 1698 user_perms = set([perms['repositories_groups'][group_name]])
1695 1699 except KeyError:
1696 1700 log.debug(
1697 1701 'cannot locate repo group with name: `%s` in permissions defs',
1698 1702 group_name)
1699 1703 return False
1700 1704
1701 1705 log.debug('checking `%s` permissions for repo group `%s`',
1702 1706 user_perms, group_name)
1703 1707 if self.required_perms.intersection(user_perms):
1704 1708 return True
1705 1709 return False
1706 1710
1707 1711
1708 1712 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1709 1713 """
1710 1714 Checks for access permission for all given predicates for specific
1711 1715 user group. All of them have to be meet in order to fulfill the request
1712 1716 """
1713 1717 def _get_user_group_name(self):
1714 1718 _request = self._get_request()
1715 1719 return get_user_group_slug(_request)
1716 1720
1717 1721 def check_permissions(self, user):
1718 1722 perms = user.permissions
1719 1723 group_name = self._get_user_group_name()
1720 1724 try:
1721 1725 user_perms = set([perms['user_groups'][group_name]])
1722 1726 except KeyError:
1723 1727 return False
1724 1728
1725 1729 if self.required_perms.issubset(user_perms):
1726 1730 return True
1727 1731 return False
1728 1732
1729 1733
1730 1734 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1731 1735 """
1732 1736 Checks for access permission for any of given predicates for specific
1733 1737 user group. In order to fulfill the request any of predicates must be meet
1734 1738 """
1735 1739 def _get_user_group_name(self):
1736 1740 _request = self._get_request()
1737 1741 return get_user_group_slug(_request)
1738 1742
1739 1743 def check_permissions(self, user):
1740 1744 perms = user.permissions
1741 1745 group_name = self._get_user_group_name()
1742 1746 try:
1743 1747 user_perms = set([perms['user_groups'][group_name]])
1744 1748 except KeyError:
1745 1749 return False
1746 1750
1747 1751 if self.required_perms.intersection(user_perms):
1748 1752 return True
1749 1753 return False
1750 1754
1751 1755
1752 1756 # CHECK FUNCTIONS
1753 1757 class PermsFunction(object):
1754 1758 """Base function for other check functions"""
1755 1759
1756 1760 def __init__(self, *perms):
1757 1761 self.required_perms = set(perms)
1758 1762 self.repo_name = None
1759 1763 self.repo_group_name = None
1760 1764 self.user_group_name = None
1761 1765
1762 1766 def __bool__(self):
1763 1767 frame = inspect.currentframe()
1764 1768 stack_trace = traceback.format_stack(frame)
1765 1769 log.error('Checking bool value on a class instance of perm '
1766 1770 'function is not allowed: %s' % ''.join(stack_trace))
1767 1771 # rather than throwing errors, here we always return False so if by
1768 1772 # accident someone checks truth for just an instance it will always end
1769 1773 # up in returning False
1770 1774 return False
1771 1775 __nonzero__ = __bool__
1772 1776
1773 1777 def __call__(self, check_location='', user=None):
1774 1778 if not user:
1775 1779 log.debug('Using user attribute from global request')
1776 1780 # TODO: remove this someday,put as user as attribute here
1777 1781 request = self._get_request()
1778 1782 user = request.user
1779 1783
1780 1784 # init auth user if not already given
1781 1785 if not isinstance(user, AuthUser):
1782 1786 log.debug('Wrapping user %s into AuthUser', user)
1783 1787 user = AuthUser(user.user_id)
1784 1788
1785 1789 cls_name = self.__class__.__name__
1786 1790 check_scope = self._get_check_scope(cls_name)
1787 1791 check_location = check_location or 'unspecified location'
1788 1792
1789 1793 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1790 1794 self.required_perms, user, check_scope, check_location)
1791 1795 if not user:
1792 1796 log.warning('Empty user given for permission check')
1793 1797 return False
1794 1798
1795 1799 if self.check_permissions(user):
1796 1800 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1797 1801 check_scope, user, check_location)
1798 1802 return True
1799 1803
1800 1804 else:
1801 1805 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1802 1806 check_scope, user, check_location)
1803 1807 return False
1804 1808
1805 1809 def _get_request(self):
1806 1810 return get_request(self)
1807 1811
1808 1812 def _get_check_scope(self, cls_name):
1809 1813 return {
1810 1814 'HasPermissionAll': 'GLOBAL',
1811 1815 'HasPermissionAny': 'GLOBAL',
1812 1816 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
1813 1817 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
1814 1818 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
1815 1819 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
1816 1820 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
1817 1821 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
1818 1822 }.get(cls_name, '?:%s' % cls_name)
1819 1823
1820 1824 def check_permissions(self, user):
1821 1825 """Dummy function for overriding"""
1822 1826 raise Exception('You have to write this function in child class')
1823 1827
1824 1828
1825 1829 class HasPermissionAll(PermsFunction):
1826 1830 def check_permissions(self, user):
1827 1831 perms = user.permissions_with_scope({})
1828 1832 if self.required_perms.issubset(perms.get('global')):
1829 1833 return True
1830 1834 return False
1831 1835
1832 1836
1833 1837 class HasPermissionAny(PermsFunction):
1834 1838 def check_permissions(self, user):
1835 1839 perms = user.permissions_with_scope({})
1836 1840 if self.required_perms.intersection(perms.get('global')):
1837 1841 return True
1838 1842 return False
1839 1843
1840 1844
1841 1845 class HasRepoPermissionAll(PermsFunction):
1842 1846 def __call__(self, repo_name=None, check_location='', user=None):
1843 1847 self.repo_name = repo_name
1844 1848 return super(HasRepoPermissionAll, self).__call__(check_location, user)
1845 1849
1846 1850 def _get_repo_name(self):
1847 1851 if not self.repo_name:
1848 1852 _request = self._get_request()
1849 1853 self.repo_name = get_repo_slug(_request)
1850 1854 return self.repo_name
1851 1855
1852 1856 def check_permissions(self, user):
1853 1857 self.repo_name = self._get_repo_name()
1854 1858 perms = user.permissions
1855 1859 try:
1856 1860 user_perms = set([perms['repositories'][self.repo_name]])
1857 1861 except KeyError:
1858 1862 return False
1859 1863 if self.required_perms.issubset(user_perms):
1860 1864 return True
1861 1865 return False
1862 1866
1863 1867
1864 1868 class HasRepoPermissionAny(PermsFunction):
1865 1869 def __call__(self, repo_name=None, check_location='', user=None):
1866 1870 self.repo_name = repo_name
1867 1871 return super(HasRepoPermissionAny, self).__call__(check_location, user)
1868 1872
1869 1873 def _get_repo_name(self):
1870 1874 if not self.repo_name:
1871 1875 _request = self._get_request()
1872 1876 self.repo_name = get_repo_slug(_request)
1873 1877 return self.repo_name
1874 1878
1875 1879 def check_permissions(self, user):
1876 1880 self.repo_name = self._get_repo_name()
1877 1881 perms = user.permissions
1878 1882 try:
1879 1883 user_perms = set([perms['repositories'][self.repo_name]])
1880 1884 except KeyError:
1881 1885 return False
1882 1886 if self.required_perms.intersection(user_perms):
1883 1887 return True
1884 1888 return False
1885 1889
1886 1890
1887 1891 class HasRepoGroupPermissionAny(PermsFunction):
1888 1892 def __call__(self, group_name=None, check_location='', user=None):
1889 1893 self.repo_group_name = group_name
1890 1894 return super(HasRepoGroupPermissionAny, self).__call__(
1891 1895 check_location, user)
1892 1896
1893 1897 def check_permissions(self, user):
1894 1898 perms = user.permissions
1895 1899 try:
1896 1900 user_perms = set(
1897 1901 [perms['repositories_groups'][self.repo_group_name]])
1898 1902 except KeyError:
1899 1903 return False
1900 1904 if self.required_perms.intersection(user_perms):
1901 1905 return True
1902 1906 return False
1903 1907
1904 1908
1905 1909 class HasRepoGroupPermissionAll(PermsFunction):
1906 1910 def __call__(self, group_name=None, check_location='', user=None):
1907 1911 self.repo_group_name = group_name
1908 1912 return super(HasRepoGroupPermissionAll, self).__call__(
1909 1913 check_location, user)
1910 1914
1911 1915 def check_permissions(self, user):
1912 1916 perms = user.permissions
1913 1917 try:
1914 1918 user_perms = set(
1915 1919 [perms['repositories_groups'][self.repo_group_name]])
1916 1920 except KeyError:
1917 1921 return False
1918 1922 if self.required_perms.issubset(user_perms):
1919 1923 return True
1920 1924 return False
1921 1925
1922 1926
1923 1927 class HasUserGroupPermissionAny(PermsFunction):
1924 1928 def __call__(self, user_group_name=None, check_location='', user=None):
1925 1929 self.user_group_name = user_group_name
1926 1930 return super(HasUserGroupPermissionAny, self).__call__(
1927 1931 check_location, user)
1928 1932
1929 1933 def check_permissions(self, user):
1930 1934 perms = user.permissions
1931 1935 try:
1932 1936 user_perms = set([perms['user_groups'][self.user_group_name]])
1933 1937 except KeyError:
1934 1938 return False
1935 1939 if self.required_perms.intersection(user_perms):
1936 1940 return True
1937 1941 return False
1938 1942
1939 1943
1940 1944 class HasUserGroupPermissionAll(PermsFunction):
1941 1945 def __call__(self, user_group_name=None, check_location='', user=None):
1942 1946 self.user_group_name = user_group_name
1943 1947 return super(HasUserGroupPermissionAll, self).__call__(
1944 1948 check_location, user)
1945 1949
1946 1950 def check_permissions(self, user):
1947 1951 perms = user.permissions
1948 1952 try:
1949 1953 user_perms = set([perms['user_groups'][self.user_group_name]])
1950 1954 except KeyError:
1951 1955 return False
1952 1956 if self.required_perms.issubset(user_perms):
1953 1957 return True
1954 1958 return False
1955 1959
1956 1960
1957 1961 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
1958 1962 class HasPermissionAnyMiddleware(object):
1959 1963 def __init__(self, *perms):
1960 1964 self.required_perms = set(perms)
1961 1965
1962 1966 def __call__(self, user, repo_name):
1963 1967 # repo_name MUST be unicode, since we handle keys in permission
1964 1968 # dict by unicode
1965 1969 repo_name = safe_unicode(repo_name)
1966 1970 user = AuthUser(user.user_id)
1967 1971 log.debug(
1968 1972 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
1969 1973 self.required_perms, user, repo_name)
1970 1974
1971 1975 if self.check_permissions(user, repo_name):
1972 1976 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
1973 1977 repo_name, user, 'PermissionMiddleware')
1974 1978 return True
1975 1979
1976 1980 else:
1977 1981 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
1978 1982 repo_name, user, 'PermissionMiddleware')
1979 1983 return False
1980 1984
1981 1985 def check_permissions(self, user, repo_name):
1982 1986 perms = user.permissions_with_scope({'repo_name': repo_name})
1983 1987
1984 1988 try:
1985 1989 user_perms = set([perms['repositories'][repo_name]])
1986 1990 except Exception:
1987 1991 log.exception('Error while accessing user permissions')
1988 1992 return False
1989 1993
1990 1994 if self.required_perms.intersection(user_perms):
1991 1995 return True
1992 1996 return False
1993 1997
1994 1998
1995 1999 # SPECIAL VERSION TO HANDLE API AUTH
1996 2000 class _BaseApiPerm(object):
1997 2001 def __init__(self, *perms):
1998 2002 self.required_perms = set(perms)
1999 2003
2000 2004 def __call__(self, check_location=None, user=None, repo_name=None,
2001 2005 group_name=None, user_group_name=None):
2002 2006 cls_name = self.__class__.__name__
2003 2007 check_scope = 'global:%s' % (self.required_perms,)
2004 2008 if repo_name:
2005 2009 check_scope += ', repo_name:%s' % (repo_name,)
2006 2010
2007 2011 if group_name:
2008 2012 check_scope += ', repo_group_name:%s' % (group_name,)
2009 2013
2010 2014 if user_group_name:
2011 2015 check_scope += ', user_group_name:%s' % (user_group_name,)
2012 2016
2013 2017 log.debug(
2014 2018 'checking cls:%s %s %s @ %s'
2015 2019 % (cls_name, self.required_perms, check_scope, check_location))
2016 2020 if not user:
2017 2021 log.debug('Empty User passed into arguments')
2018 2022 return False
2019 2023
2020 2024 # process user
2021 2025 if not isinstance(user, AuthUser):
2022 2026 user = AuthUser(user.user_id)
2023 2027 if not check_location:
2024 2028 check_location = 'unspecified'
2025 2029 if self.check_permissions(user.permissions, repo_name, group_name,
2026 2030 user_group_name):
2027 2031 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
2028 2032 check_scope, user, check_location)
2029 2033 return True
2030 2034
2031 2035 else:
2032 2036 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
2033 2037 check_scope, user, check_location)
2034 2038 return False
2035 2039
2036 2040 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2037 2041 user_group_name=None):
2038 2042 """
2039 2043 implement in child class should return True if permissions are ok,
2040 2044 False otherwise
2041 2045
2042 2046 :param perm_defs: dict with permission definitions
2043 2047 :param repo_name: repo name
2044 2048 """
2045 2049 raise NotImplementedError()
2046 2050
2047 2051
2048 2052 class HasPermissionAllApi(_BaseApiPerm):
2049 2053 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2050 2054 user_group_name=None):
2051 2055 if self.required_perms.issubset(perm_defs.get('global')):
2052 2056 return True
2053 2057 return False
2054 2058
2055 2059
2056 2060 class HasPermissionAnyApi(_BaseApiPerm):
2057 2061 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2058 2062 user_group_name=None):
2059 2063 if self.required_perms.intersection(perm_defs.get('global')):
2060 2064 return True
2061 2065 return False
2062 2066
2063 2067
2064 2068 class HasRepoPermissionAllApi(_BaseApiPerm):
2065 2069 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2066 2070 user_group_name=None):
2067 2071 try:
2068 2072 _user_perms = set([perm_defs['repositories'][repo_name]])
2069 2073 except KeyError:
2070 2074 log.warning(traceback.format_exc())
2071 2075 return False
2072 2076 if self.required_perms.issubset(_user_perms):
2073 2077 return True
2074 2078 return False
2075 2079
2076 2080
2077 2081 class HasRepoPermissionAnyApi(_BaseApiPerm):
2078 2082 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2079 2083 user_group_name=None):
2080 2084 try:
2081 2085 _user_perms = set([perm_defs['repositories'][repo_name]])
2082 2086 except KeyError:
2083 2087 log.warning(traceback.format_exc())
2084 2088 return False
2085 2089 if self.required_perms.intersection(_user_perms):
2086 2090 return True
2087 2091 return False
2088 2092
2089 2093
2090 2094 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
2091 2095 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2092 2096 user_group_name=None):
2093 2097 try:
2094 2098 _user_perms = set([perm_defs['repositories_groups'][group_name]])
2095 2099 except KeyError:
2096 2100 log.warning(traceback.format_exc())
2097 2101 return False
2098 2102 if self.required_perms.intersection(_user_perms):
2099 2103 return True
2100 2104 return False
2101 2105
2102 2106
2103 2107 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
2104 2108 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2105 2109 user_group_name=None):
2106 2110 try:
2107 2111 _user_perms = set([perm_defs['repositories_groups'][group_name]])
2108 2112 except KeyError:
2109 2113 log.warning(traceback.format_exc())
2110 2114 return False
2111 2115 if self.required_perms.issubset(_user_perms):
2112 2116 return True
2113 2117 return False
2114 2118
2115 2119
2116 2120 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
2117 2121 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2118 2122 user_group_name=None):
2119 2123 try:
2120 2124 _user_perms = set([perm_defs['user_groups'][user_group_name]])
2121 2125 except KeyError:
2122 2126 log.warning(traceback.format_exc())
2123 2127 return False
2124 2128 if self.required_perms.intersection(_user_perms):
2125 2129 return True
2126 2130 return False
2127 2131
2128 2132
2129 2133 def check_ip_access(source_ip, allowed_ips=None):
2130 2134 """
2131 2135 Checks if source_ip is a subnet of any of allowed_ips.
2132 2136
2133 2137 :param source_ip:
2134 2138 :param allowed_ips: list of allowed ips together with mask
2135 2139 """
2136 2140 log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips))
2137 2141 source_ip_address = ipaddress.ip_address(safe_unicode(source_ip))
2138 2142 if isinstance(allowed_ips, (tuple, list, set)):
2139 2143 for ip in allowed_ips:
2140 2144 ip = safe_unicode(ip)
2141 2145 try:
2142 2146 network_address = ipaddress.ip_network(ip, strict=False)
2143 2147 if source_ip_address in network_address:
2144 2148 log.debug('IP %s is network %s' %
2145 2149 (source_ip_address, network_address))
2146 2150 return True
2147 2151 # for any case we cannot determine the IP, don't crash just
2148 2152 # skip it and log as error, we want to say forbidden still when
2149 2153 # sending bad IP
2150 2154 except Exception:
2151 2155 log.error(traceback.format_exc())
2152 2156 continue
2153 2157 return False
2154 2158
2155 2159
2156 2160 def get_cython_compat_decorator(wrapper, func):
2157 2161 """
2158 2162 Creates a cython compatible decorator. The previously used
2159 2163 decorator.decorator() function seems to be incompatible with cython.
2160 2164
2161 2165 :param wrapper: __wrapper method of the decorator class
2162 2166 :param func: decorated function
2163 2167 """
2164 2168 @wraps(func)
2165 2169 def local_wrapper(*args, **kwds):
2166 2170 return wrapper(func, *args, **kwds)
2167 2171 local_wrapper.__wrapped__ = func
2168 2172 return local_wrapper
2169 2173
2170 2174
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,635 +1,641 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2011-2017 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import logging
22 22 import traceback
23 23
24 24 from rhodecode.lib.utils2 import safe_str, safe_unicode
25 25 from rhodecode.lib.exceptions import (
26 26 UserGroupAssignedException, RepoGroupAssignmentError)
27 27 from rhodecode.lib.utils2 import (
28 28 get_current_rhodecode_user, action_logger_generic)
29 29 from rhodecode.model import BaseModel
30 30 from rhodecode.model.scm import UserGroupList
31 31 from rhodecode.model.db import (
32 32 true, func, User, UserGroupMember, UserGroup,
33 33 UserGroupRepoToPerm, Permission, UserGroupToPerm, UserUserGroupToPerm,
34 34 UserGroupUserGroupToPerm, UserGroupRepoGroupToPerm)
35 35
36 36
37 37 log = logging.getLogger(__name__)
38 38
39 39
40 40 class UserGroupModel(BaseModel):
41 41
42 42 cls = UserGroup
43 43
44 44 def _get_user_group(self, user_group):
45 45 return self._get_instance(UserGroup, user_group,
46 46 callback=UserGroup.get_by_group_name)
47 47
48 48 def _create_default_perms(self, user_group):
49 49 # create default permission
50 50 default_perm = 'usergroup.read'
51 51 def_user = User.get_default_user()
52 52 for p in def_user.user_perms:
53 53 if p.permission.permission_name.startswith('usergroup.'):
54 54 default_perm = p.permission.permission_name
55 55 break
56 56
57 57 user_group_to_perm = UserUserGroupToPerm()
58 58 user_group_to_perm.permission = Permission.get_by_key(default_perm)
59 59
60 60 user_group_to_perm.user_group = user_group
61 61 user_group_to_perm.user_id = def_user.user_id
62 62 return user_group_to_perm
63 63
64 64 def update_permissions(
65 65 self, user_group, perm_additions=None, perm_updates=None,
66 66 perm_deletions=None, check_perms=True, cur_user=None):
67 67
68 68 from rhodecode.lib.auth import HasUserGroupPermissionAny
69 69 if not perm_additions:
70 70 perm_additions = []
71 71 if not perm_updates:
72 72 perm_updates = []
73 73 if not perm_deletions:
74 74 perm_deletions = []
75 75
76 76 req_perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin')
77 77
78 78 changes = {
79 79 'added': [],
80 80 'updated': [],
81 81 'deleted': []
82 82 }
83 83 # update permissions
84 84 for member_id, perm, member_type in perm_updates:
85 85 member_id = int(member_id)
86 86 if member_type == 'user':
87 87 member_name = User.get(member_id).username
88 88 # this updates existing one
89 89 self.grant_user_permission(
90 90 user_group=user_group, user=member_id, perm=perm
91 91 )
92 92 else:
93 93 # check if we have permissions to alter this usergroup
94 94 member_name = UserGroup.get(member_id).users_group_name
95 95 if not check_perms or HasUserGroupPermissionAny(
96 96 *req_perms)(member_name, user=cur_user):
97 97 self.grant_user_group_permission(
98 98 target_user_group=user_group, user_group=member_id, perm=perm)
99 99
100 100 changes['updated'].append({'type': member_type, 'id': member_id,
101 101 'name': member_name, 'new_perm': perm})
102 102
103 103 # set new permissions
104 104 for member_id, perm, member_type in perm_additions:
105 105 member_id = int(member_id)
106 106 if member_type == 'user':
107 107 member_name = User.get(member_id).username
108 108 self.grant_user_permission(
109 109 user_group=user_group, user=member_id, perm=perm)
110 110 else:
111 111 # check if we have permissions to alter this usergroup
112 112 member_name = UserGroup.get(member_id).users_group_name
113 113 if not check_perms or HasUserGroupPermissionAny(
114 114 *req_perms)(member_name, user=cur_user):
115 115 self.grant_user_group_permission(
116 116 target_user_group=user_group, user_group=member_id, perm=perm)
117 117
118 118 changes['added'].append({'type': member_type, 'id': member_id,
119 119 'name': member_name, 'new_perm': perm})
120 120
121 121 # delete permissions
122 122 for member_id, perm, member_type in perm_deletions:
123 123 member_id = int(member_id)
124 124 if member_type == 'user':
125 125 member_name = User.get(member_id).username
126 126 self.revoke_user_permission(user_group=user_group, user=member_id)
127 127 else:
128 128 # check if we have permissions to alter this usergroup
129 129 member_name = UserGroup.get(member_id).users_group_name
130 130 if not check_perms or HasUserGroupPermissionAny(
131 131 *req_perms)(member_name, user=cur_user):
132 132 self.revoke_user_group_permission(
133 133 target_user_group=user_group, user_group=member_id)
134 134
135 135 changes['deleted'].append({'type': member_type, 'id': member_id,
136 136 'name': member_name, 'new_perm': perm})
137 137 return changes
138 138
139 139 def get(self, user_group_id, cache=False):
140 140 return UserGroup.get(user_group_id)
141 141
142 142 def get_group(self, user_group):
143 143 return self._get_user_group(user_group)
144 144
145 145 def get_by_name(self, name, cache=False, case_insensitive=False):
146 146 return UserGroup.get_by_group_name(name, cache, case_insensitive)
147 147
148 148 def create(self, name, description, owner, active=True, group_data=None):
149 149 try:
150 150 new_user_group = UserGroup()
151 151 new_user_group.user = self._get_user(owner)
152 152 new_user_group.users_group_name = name
153 153 new_user_group.user_group_description = description
154 154 new_user_group.users_group_active = active
155 155 if group_data:
156 156 new_user_group.group_data = group_data
157 157 self.sa.add(new_user_group)
158 158 perm_obj = self._create_default_perms(new_user_group)
159 159 self.sa.add(perm_obj)
160 160
161 161 self.grant_user_permission(user_group=new_user_group,
162 162 user=owner, perm='usergroup.admin')
163 163
164 164 return new_user_group
165 165 except Exception:
166 166 log.error(traceback.format_exc())
167 167 raise
168 168
169 169 def _get_memberships_for_user_ids(self, user_group, user_id_list):
170 170 members = []
171 171 for user_id in user_id_list:
172 172 member = self._get_membership(user_group.users_group_id, user_id)
173 173 members.append(member)
174 174 return members
175 175
176 176 def _get_added_and_removed_user_ids(self, user_group, user_id_list):
177 177 current_members = user_group.members or []
178 178 current_members_ids = [m.user.user_id for m in current_members]
179 179
180 180 added_members = [
181 181 user_id for user_id in user_id_list
182 182 if user_id not in current_members_ids]
183 183 if user_id_list == []:
184 184 # all members were deleted
185 185 deleted_members = current_members_ids
186 186 else:
187 187 deleted_members = [
188 188 user_id for user_id in current_members_ids
189 189 if user_id not in user_id_list]
190 190
191 191 return added_members, deleted_members
192 192
193 193 def _set_users_as_members(self, user_group, user_ids):
194 194 user_group.members = []
195 195 self.sa.flush()
196 196 members = self._get_memberships_for_user_ids(
197 197 user_group, user_ids)
198 198 user_group.members = members
199 199 self.sa.add(user_group)
200 200
201 201 def _update_members_from_user_ids(self, user_group, user_ids):
202 202 added, removed = self._get_added_and_removed_user_ids(
203 203 user_group, user_ids)
204 204 self._set_users_as_members(user_group, user_ids)
205 205 self._log_user_changes('added to', user_group, added)
206 206 self._log_user_changes('removed from', user_group, removed)
207 207 return added, removed
208 208
209 209 def _clean_members_data(self, members_data):
210 210 if not members_data:
211 211 members_data = []
212 212
213 213 members = []
214 214 for user in members_data:
215 215 uid = int(user['member_user_id'])
216 216 if uid not in members and user['type'] in ['new', 'existing']:
217 217 members.append(uid)
218 218 return members
219 219
220 220 def update(self, user_group, form_data):
221 221 user_group = self._get_user_group(user_group)
222 222 if 'users_group_name' in form_data:
223 223 user_group.users_group_name = form_data['users_group_name']
224 224 if 'users_group_active' in form_data:
225 225 user_group.users_group_active = form_data['users_group_active']
226 226 if 'user_group_description' in form_data:
227 227 user_group.user_group_description = form_data[
228 228 'user_group_description']
229 229
230 230 # handle owner change
231 231 if 'user' in form_data:
232 232 owner = form_data['user']
233 233 if isinstance(owner, basestring):
234 234 owner = User.get_by_username(form_data['user'])
235 235
236 236 if not isinstance(owner, User):
237 237 raise ValueError(
238 238 'invalid owner for user group: %s' % form_data['user'])
239 239
240 240 user_group.user = owner
241 241
242 242 added_user_ids = []
243 243 removed_user_ids = []
244 244 if 'users_group_members' in form_data:
245 245 members_id_list = self._clean_members_data(
246 246 form_data['users_group_members'])
247 247 added_user_ids, removed_user_ids = \
248 248 self._update_members_from_user_ids(user_group, members_id_list)
249 249
250 250 self.sa.add(user_group)
251 251 return user_group, added_user_ids, removed_user_ids
252 252
253 253 def delete(self, user_group, force=False):
254 254 """
255 255 Deletes repository group, unless force flag is used
256 256 raises exception if there are members in that group, else deletes
257 257 group and users
258 258
259 259 :param user_group:
260 260 :param force:
261 261 """
262 262 user_group = self._get_user_group(user_group)
263 263 if not user_group:
264 264 return
265 265
266 266 try:
267 267 # check if this group is not assigned to repo
268 268 assigned_to_repo = [x.repository for x in UserGroupRepoToPerm.query()\
269 269 .filter(UserGroupRepoToPerm.users_group == user_group).all()]
270 270 # check if this group is not assigned to repo
271 271 assigned_to_repo_group = [x.group for x in UserGroupRepoGroupToPerm.query()\
272 272 .filter(UserGroupRepoGroupToPerm.users_group == user_group).all()]
273 273
274 274 if (assigned_to_repo or assigned_to_repo_group) and not force:
275 275 assigned = ','.join(map(safe_str,
276 276 assigned_to_repo+assigned_to_repo_group))
277 277
278 278 raise UserGroupAssignedException(
279 279 'UserGroup assigned to %s' % (assigned,))
280 280 self.sa.delete(user_group)
281 281 except Exception:
282 282 log.error(traceback.format_exc())
283 283 raise
284 284
285 285 def _log_user_changes(self, action, user_group, user_or_users):
286 286 users = user_or_users
287 287 if not isinstance(users, (list, tuple)):
288 288 users = [users]
289 289
290 290 group_name = user_group.users_group_name
291 291
292 292 for user_or_user_id in users:
293 293 user = self._get_user(user_or_user_id)
294 294 log_text = 'User {user} {action} {group}'.format(
295 295 action=action, user=user.username, group=group_name)
296 296 action_logger_generic(log_text)
297 297
298 298 def _find_user_in_group(self, user, user_group):
299 299 user_group_member = None
300 300 for m in user_group.members:
301 301 if m.user_id == user.user_id:
302 302 # Found this user's membership row
303 303 user_group_member = m
304 304 break
305 305
306 306 return user_group_member
307 307
308 308 def _get_membership(self, user_group_id, user_id):
309 309 user_group_member = UserGroupMember(user_group_id, user_id)
310 310 return user_group_member
311 311
312 312 def add_user_to_group(self, user_group, user):
313 313 user_group = self._get_user_group(user_group)
314 314 user = self._get_user(user)
315 315 user_member = self._find_user_in_group(user, user_group)
316 316 if user_member:
317 317 # user already in the group, skip
318 318 return True
319 319
320 320 member = self._get_membership(
321 321 user_group.users_group_id, user.user_id)
322 322 user_group.members.append(member)
323 323
324 324 try:
325 325 self.sa.add(member)
326 326 except Exception:
327 327 # what could go wrong here?
328 328 log.error(traceback.format_exc())
329 329 raise
330 330
331 331 self._log_user_changes('added to', user_group, user)
332 332 return member
333 333
334 334 def remove_user_from_group(self, user_group, user):
335 335 user_group = self._get_user_group(user_group)
336 336 user = self._get_user(user)
337 337 user_group_member = self._find_user_in_group(user, user_group)
338 338
339 339 if not user_group_member:
340 340 # User isn't in that group
341 341 return False
342 342
343 343 try:
344 344 self.sa.delete(user_group_member)
345 345 except Exception:
346 346 log.error(traceback.format_exc())
347 347 raise
348 348
349 349 self._log_user_changes('removed from', user_group, user)
350 350 return True
351 351
352 352 def has_perm(self, user_group, perm):
353 353 user_group = self._get_user_group(user_group)
354 354 perm = self._get_perm(perm)
355 355
356 356 return UserGroupToPerm.query()\
357 357 .filter(UserGroupToPerm.users_group == user_group)\
358 358 .filter(UserGroupToPerm.permission == perm).scalar() is not None
359 359
360 360 def grant_perm(self, user_group, perm):
361 361 user_group = self._get_user_group(user_group)
362 362 perm = self._get_perm(perm)
363 363
364 364 # if this permission is already granted skip it
365 365 _perm = UserGroupToPerm.query()\
366 366 .filter(UserGroupToPerm.users_group == user_group)\
367 367 .filter(UserGroupToPerm.permission == perm)\
368 368 .scalar()
369 369 if _perm:
370 370 return
371 371
372 372 new = UserGroupToPerm()
373 373 new.users_group = user_group
374 374 new.permission = perm
375 375 self.sa.add(new)
376 376 return new
377 377
378 378 def revoke_perm(self, user_group, perm):
379 379 user_group = self._get_user_group(user_group)
380 380 perm = self._get_perm(perm)
381 381
382 382 obj = UserGroupToPerm.query()\
383 383 .filter(UserGroupToPerm.users_group == user_group)\
384 384 .filter(UserGroupToPerm.permission == perm).scalar()
385 385 if obj:
386 386 self.sa.delete(obj)
387 387
388 388 def grant_user_permission(self, user_group, user, perm):
389 389 """
390 390 Grant permission for user on given user group, or update
391 391 existing one if found
392 392
393 393 :param user_group: Instance of UserGroup, users_group_id,
394 394 or users_group_name
395 395 :param user: Instance of User, user_id or username
396 396 :param perm: Instance of Permission, or permission_name
397 397 """
398 398
399 399 user_group = self._get_user_group(user_group)
400 400 user = self._get_user(user)
401 401 permission = self._get_perm(perm)
402 402
403 403 # check if we have that permission already
404 404 obj = self.sa.query(UserUserGroupToPerm)\
405 405 .filter(UserUserGroupToPerm.user == user)\
406 406 .filter(UserUserGroupToPerm.user_group == user_group)\
407 407 .scalar()
408 408 if obj is None:
409 409 # create new !
410 410 obj = UserUserGroupToPerm()
411 411 obj.user_group = user_group
412 412 obj.user = user
413 413 obj.permission = permission
414 414 self.sa.add(obj)
415 415 log.debug('Granted perm %s to %s on %s', perm, user, user_group)
416 416 action_logger_generic(
417 417 'granted permission: {} to user: {} on usergroup: {}'.format(
418 418 perm, user, user_group), namespace='security.usergroup')
419 419
420 420 return obj
421 421
422 422 def revoke_user_permission(self, user_group, user):
423 423 """
424 424 Revoke permission for user on given user group
425 425
426 426 :param user_group: Instance of UserGroup, users_group_id,
427 427 or users_group name
428 428 :param user: Instance of User, user_id or username
429 429 """
430 430
431 431 user_group = self._get_user_group(user_group)
432 432 user = self._get_user(user)
433 433
434 434 obj = self.sa.query(UserUserGroupToPerm)\
435 435 .filter(UserUserGroupToPerm.user == user)\
436 436 .filter(UserUserGroupToPerm.user_group == user_group)\
437 437 .scalar()
438 438 if obj:
439 439 self.sa.delete(obj)
440 440 log.debug('Revoked perm on %s on %s', user_group, user)
441 441 action_logger_generic(
442 442 'revoked permission from user: {} on usergroup: {}'.format(
443 443 user, user_group), namespace='security.usergroup')
444 444
445 445 def grant_user_group_permission(self, target_user_group, user_group, perm):
446 446 """
447 447 Grant user group permission for given target_user_group
448 448
449 449 :param target_user_group:
450 450 :param user_group:
451 451 :param perm:
452 452 """
453 453 target_user_group = self._get_user_group(target_user_group)
454 454 user_group = self._get_user_group(user_group)
455 455 permission = self._get_perm(perm)
456 456 # forbid assigning same user group to itself
457 457 if target_user_group == user_group:
458 458 raise RepoGroupAssignmentError('target repo:%s cannot be '
459 459 'assigned to itself' % target_user_group)
460 460
461 461 # check if we have that permission already
462 462 obj = self.sa.query(UserGroupUserGroupToPerm)\
463 463 .filter(UserGroupUserGroupToPerm.target_user_group == target_user_group)\
464 464 .filter(UserGroupUserGroupToPerm.user_group == user_group)\
465 465 .scalar()
466 466 if obj is None:
467 467 # create new !
468 468 obj = UserGroupUserGroupToPerm()
469 469 obj.user_group = user_group
470 470 obj.target_user_group = target_user_group
471 471 obj.permission = permission
472 472 self.sa.add(obj)
473 473 log.debug(
474 474 'Granted perm %s to %s on %s', perm, target_user_group, user_group)
475 475 action_logger_generic(
476 476 'granted permission: {} to usergroup: {} on usergroup: {}'.format(
477 477 perm, user_group, target_user_group),
478 478 namespace='security.usergroup')
479 479
480 480 return obj
481 481
482 482 def revoke_user_group_permission(self, target_user_group, user_group):
483 483 """
484 484 Revoke user group permission for given target_user_group
485 485
486 486 :param target_user_group:
487 487 :param user_group:
488 488 """
489 489 target_user_group = self._get_user_group(target_user_group)
490 490 user_group = self._get_user_group(user_group)
491 491
492 492 obj = self.sa.query(UserGroupUserGroupToPerm)\
493 493 .filter(UserGroupUserGroupToPerm.target_user_group == target_user_group)\
494 494 .filter(UserGroupUserGroupToPerm.user_group == user_group)\
495 495 .scalar()
496 496 if obj:
497 497 self.sa.delete(obj)
498 498 log.debug(
499 499 'Revoked perm on %s on %s', target_user_group, user_group)
500 500 action_logger_generic(
501 501 'revoked permission from usergroup: {} on usergroup: {}'.format(
502 502 user_group, target_user_group),
503 503 namespace='security.repogroup')
504 504
505 505 def enforce_groups(self, user, groups, extern_type=None):
506 506 user = self._get_user(user)
507 507 log.debug('Enforcing groups %s on user %s', groups, user)
508 508 current_groups = user.group_member
509 509 # find the external created groups
510 510 externals = [x.users_group for x in current_groups
511 511 if 'extern_type' in x.users_group.group_data]
512 512
513 513 # calculate from what groups user should be removed
514 514 # externals that are not in groups
515 515 for gr in externals:
516 516 if gr.users_group_name not in groups:
517 517 log.debug('Removing user %s from user group %s', user, gr)
518 518 self.remove_user_from_group(gr, user)
519 519
520 520 # now we calculate in which groups user should be == groups params
521 521 owner = User.get_first_super_admin().username
522 522 for gr in set(groups):
523 523 existing_group = UserGroup.get_by_group_name(gr)
524 524 if not existing_group:
525 525 desc = 'Automatically created from plugin:%s' % extern_type
526 526 # we use first admin account to set the owner of the group
527 527 existing_group = UserGroupModel().create(
528 528 gr, desc, owner, group_data={'extern_type': extern_type})
529 529
530 530 # we can only add users to special groups created via plugins
531 531 managed = 'extern_type' in existing_group.group_data
532 532 if managed:
533 533 log.debug('Adding user %s to user group %s', user, gr)
534 534 UserGroupModel().add_user_to_group(existing_group, user)
535 535 else:
536 536 log.debug('Skipping addition to group %s since it is '
537 537 'not set to be automatically synchronized' % gr)
538 538
539 539 def change_groups(self, user, groups):
540 540 """
541 541 This method changes user group assignment
542 542 :param user: User
543 543 :param groups: array of UserGroupModel
544 544 """
545 545 user = self._get_user(user)
546 546 log.debug('Changing user(%s) assignment to groups(%s)', user, groups)
547 547 current_groups = user.group_member
548 548 current_groups = [x.users_group for x in current_groups]
549 549
550 550 # calculate from what groups user should be removed/add
551 551 groups = set(groups)
552 552 current_groups = set(current_groups)
553 553
554 554 groups_to_remove = current_groups - groups
555 555 groups_to_add = groups - current_groups
556 556
557 removed_from_groups = []
558 added_to_groups = []
557 559 for gr in groups_to_remove:
558 560 log.debug('Removing user %s from user group %s',
559 561 user.username, gr.users_group_name)
562 removed_from_groups.append(gr.users_group_id)
560 563 self.remove_user_from_group(gr.users_group_name, user.username)
561 564 for gr in groups_to_add:
562 565 log.debug('Adding user %s to user group %s',
563 566 user.username, gr.users_group_name)
567 added_to_groups.append(gr.users_group_id)
564 568 UserGroupModel().add_user_to_group(
565 569 gr.users_group_name, user.username)
566 570
571 return added_to_groups, removed_from_groups
572
567 573 def _serialize_user_group(self, user_group):
568 574 import rhodecode.lib.helpers as h
569 575 return {
570 576 'id': user_group.users_group_id,
571 577 # TODO: marcink figure out a way to generate the url for the
572 578 # icon
573 579 'icon_link': '',
574 580 'value_display': 'Group: %s (%d members)' % (
575 581 user_group.users_group_name, len(user_group.members),),
576 582 'value': user_group.users_group_name,
577 583 'description': user_group.user_group_description,
578 584 'owner': user_group.user.username,
579 585
580 586 'owner_icon': h.gravatar_url(user_group.user.email, 30),
581 587 'value_display_owner': h.person(user_group.user.email),
582 588
583 589 'value_type': 'user_group',
584 590 'active': user_group.users_group_active,
585 591 }
586 592
587 593 def get_user_groups(self, name_contains=None, limit=20, only_active=True,
588 594 expand_groups=False):
589 595 query = self.sa.query(UserGroup)
590 596 if only_active:
591 597 query = query.filter(UserGroup.users_group_active == true())
592 598
593 599 if name_contains:
594 600 ilike_expression = u'%{}%'.format(safe_unicode(name_contains))
595 601 query = query.filter(
596 602 UserGroup.users_group_name.ilike(ilike_expression))\
597 603 .order_by(func.length(UserGroup.users_group_name))\
598 604 .order_by(UserGroup.users_group_name)
599 605
600 606 query = query.limit(limit)
601 607 user_groups = query.all()
602 608 perm_set = ['usergroup.read', 'usergroup.write', 'usergroup.admin']
603 609 user_groups = UserGroupList(user_groups, perm_set=perm_set)
604 610
605 611 # store same serialize method to extract data from User
606 612 from rhodecode.model.user import UserModel
607 613 serialize_user = UserModel()._serialize_user
608 614
609 615 _groups = []
610 616 for group in user_groups:
611 617 entry = self._serialize_user_group(group)
612 618 if expand_groups:
613 619 expanded_members = []
614 620 for member in group.members:
615 621 expanded_members.append(serialize_user(member.user))
616 622 entry['members'] = expanded_members
617 623 _groups.append(entry)
618 624 return _groups
619 625
620 626 @staticmethod
621 627 def get_user_groups_as_dict(user_group):
622 628 import rhodecode.lib.helpers as h
623 629
624 630 data = {
625 631 'users_group_id': user_group.users_group_id,
626 632 'group_name': user_group.users_group_name,
627 633 'group_description': user_group.user_group_description,
628 634 'active': user_group.users_group_active,
629 635 "owner": user_group.user.username,
630 636 'owner_icon': h.gravatar_url(user_group.user.email, 30),
631 637 "owner_data": {
632 638 'owner': user_group.user.username,
633 639 'owner_icon': h.gravatar_url(user_group.user.email, 30)}
634 640 }
635 641 return data
@@ -1,274 +1,283 b''
1 1
2 2 /******************************************************************************
3 3 * *
4 4 * DO NOT CHANGE THIS FILE MANUALLY *
5 5 * *
6 6 * *
7 7 * This file is automatically generated when the app starts up with *
8 8 * generate_js_files = true *
9 9 * *
10 10 * To add a route here pass jsroute=True to the route definition in the app *
11 11 * *
12 12 ******************************************************************************/
13 13 function registerRCRoutes() {
14 14 // routes registration
15 pyroutes.register('edit_user', '/_admin/users/%(user_id)s/edit', ['user_id']);
16 15 pyroutes.register('favicon', '/favicon.ico', []);
17 16 pyroutes.register('robots', '/robots.txt', []);
18 17 pyroutes.register('auth_home', '/_admin/auth*traverse', []);
19 18 pyroutes.register('global_integrations_new', '/_admin/integrations/new', []);
20 19 pyroutes.register('global_integrations_home', '/_admin/integrations', []);
21 20 pyroutes.register('global_integrations_list', '/_admin/integrations/%(integration)s', ['integration']);
22 21 pyroutes.register('global_integrations_create', '/_admin/integrations/%(integration)s/new', ['integration']);
23 22 pyroutes.register('global_integrations_edit', '/_admin/integrations/%(integration)s/%(integration_id)s', ['integration', 'integration_id']);
24 23 pyroutes.register('repo_group_integrations_home', '/%(repo_group_name)s/settings/integrations', ['repo_group_name']);
25 24 pyroutes.register('repo_group_integrations_new', '/%(repo_group_name)s/settings/integrations/new', ['repo_group_name']);
26 25 pyroutes.register('repo_group_integrations_list', '/%(repo_group_name)s/settings/integrations/%(integration)s', ['repo_group_name', 'integration']);
27 26 pyroutes.register('repo_group_integrations_create', '/%(repo_group_name)s/settings/integrations/%(integration)s/new', ['repo_group_name', 'integration']);
28 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 28 pyroutes.register('repo_integrations_home', '/%(repo_name)s/settings/integrations', ['repo_name']);
30 29 pyroutes.register('repo_integrations_new', '/%(repo_name)s/settings/integrations/new', ['repo_name']);
31 30 pyroutes.register('repo_integrations_list', '/%(repo_name)s/settings/integrations/%(integration)s', ['repo_name', 'integration']);
32 31 pyroutes.register('repo_integrations_create', '/%(repo_name)s/settings/integrations/%(integration)s/new', ['repo_name', 'integration']);
33 32 pyroutes.register('repo_integrations_edit', '/%(repo_name)s/settings/integrations/%(integration)s/%(integration_id)s', ['repo_name', 'integration', 'integration_id']);
34 33 pyroutes.register('ops_ping', '/_admin/ops/ping', []);
35 34 pyroutes.register('ops_error_test', '/_admin/ops/error', []);
36 35 pyroutes.register('ops_redirect_test', '/_admin/ops/redirect', []);
37 36 pyroutes.register('ops_ping_legacy', '/_admin/ping', []);
38 37 pyroutes.register('ops_error_test_legacy', '/_admin/error_test', []);
39 38 pyroutes.register('admin_home', '/_admin', []);
40 39 pyroutes.register('admin_audit_logs', '/_admin/audit_logs', []);
41 40 pyroutes.register('admin_audit_log_entry', '/_admin/audit_logs/%(audit_log_id)s', ['audit_log_id']);
42 41 pyroutes.register('pull_requests_global_0', '/_admin/pull_requests/%(pull_request_id)s', ['pull_request_id']);
43 42 pyroutes.register('pull_requests_global_1', '/_admin/pull-requests/%(pull_request_id)s', ['pull_request_id']);
44 43 pyroutes.register('pull_requests_global', '/_admin/pull-request/%(pull_request_id)s', ['pull_request_id']);
45 44 pyroutes.register('admin_settings_open_source', '/_admin/settings/open_source', []);
46 45 pyroutes.register('admin_settings_vcs_svn_generate_cfg', '/_admin/settings/vcs/svn_generate_cfg', []);
47 46 pyroutes.register('admin_settings_system', '/_admin/settings/system', []);
48 47 pyroutes.register('admin_settings_system_update', '/_admin/settings/system/updates', []);
49 48 pyroutes.register('admin_settings_sessions', '/_admin/settings/sessions', []);
50 49 pyroutes.register('admin_settings_sessions_cleanup', '/_admin/settings/sessions/cleanup', []);
51 50 pyroutes.register('admin_settings_process_management', '/_admin/settings/process_management', []);
52 51 pyroutes.register('admin_settings_process_management_signal', '/_admin/settings/process_management/signal', []);
53 52 pyroutes.register('admin_defaults_repositories', '/_admin/defaults/repositories', []);
54 53 pyroutes.register('admin_defaults_repositories_update', '/_admin/defaults/repositories/update', []);
55 54 pyroutes.register('admin_permissions_application', '/_admin/permissions/application', []);
56 55 pyroutes.register('admin_permissions_application_update', '/_admin/permissions/application/update', []);
57 56 pyroutes.register('admin_permissions_global', '/_admin/permissions/global', []);
58 57 pyroutes.register('admin_permissions_global_update', '/_admin/permissions/global/update', []);
59 58 pyroutes.register('admin_permissions_object', '/_admin/permissions/object', []);
60 59 pyroutes.register('admin_permissions_object_update', '/_admin/permissions/object/update', []);
61 60 pyroutes.register('admin_permissions_ips', '/_admin/permissions/ips', []);
62 61 pyroutes.register('admin_permissions_overview', '/_admin/permissions/overview', []);
63 62 pyroutes.register('admin_permissions_auth_token_access', '/_admin/permissions/auth_token_access', []);
64 63 pyroutes.register('admin_permissions_ssh_keys', '/_admin/permissions/ssh_keys', []);
65 64 pyroutes.register('admin_permissions_ssh_keys_data', '/_admin/permissions/ssh_keys/data', []);
66 65 pyroutes.register('admin_permissions_ssh_keys_update', '/_admin/permissions/ssh_keys/update', []);
67 66 pyroutes.register('users', '/_admin/users', []);
68 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 78 pyroutes.register('edit_user_auth_tokens', '/_admin/users/%(user_id)s/edit/auth_tokens', ['user_id']);
70 79 pyroutes.register('edit_user_auth_tokens_add', '/_admin/users/%(user_id)s/edit/auth_tokens/new', ['user_id']);
71 80 pyroutes.register('edit_user_auth_tokens_delete', '/_admin/users/%(user_id)s/edit/auth_tokens/delete', ['user_id']);
72 81 pyroutes.register('edit_user_ssh_keys', '/_admin/users/%(user_id)s/edit/ssh_keys', ['user_id']);
73 82 pyroutes.register('edit_user_ssh_keys_generate_keypair', '/_admin/users/%(user_id)s/edit/ssh_keys/generate', ['user_id']);
74 83 pyroutes.register('edit_user_ssh_keys_add', '/_admin/users/%(user_id)s/edit/ssh_keys/new', ['user_id']);
75 84 pyroutes.register('edit_user_ssh_keys_delete', '/_admin/users/%(user_id)s/edit/ssh_keys/delete', ['user_id']);
76 85 pyroutes.register('edit_user_emails', '/_admin/users/%(user_id)s/edit/emails', ['user_id']);
77 86 pyroutes.register('edit_user_emails_add', '/_admin/users/%(user_id)s/edit/emails/new', ['user_id']);
78 87 pyroutes.register('edit_user_emails_delete', '/_admin/users/%(user_id)s/edit/emails/delete', ['user_id']);
79 88 pyroutes.register('edit_user_ips', '/_admin/users/%(user_id)s/edit/ips', ['user_id']);
80 89 pyroutes.register('edit_user_ips_add', '/_admin/users/%(user_id)s/edit/ips/new', ['user_id']);
81 90 pyroutes.register('edit_user_ips_delete', '/_admin/users/%(user_id)s/edit/ips/delete', ['user_id']);
82 91 pyroutes.register('edit_user_perms_summary', '/_admin/users/%(user_id)s/edit/permissions_summary', ['user_id']);
83 92 pyroutes.register('edit_user_perms_summary_json', '/_admin/users/%(user_id)s/edit/permissions_summary/json', ['user_id']);
84 93 pyroutes.register('edit_user_groups_management', '/_admin/users/%(user_id)s/edit/groups_management', ['user_id']);
85 94 pyroutes.register('edit_user_groups_management_updates', '/_admin/users/%(user_id)s/edit/edit_user_groups_management/updates', ['user_id']);
86 95 pyroutes.register('edit_user_audit_logs', '/_admin/users/%(user_id)s/edit/audit', ['user_id']);
87 96 pyroutes.register('user_groups', '/_admin/user_groups', []);
88 97 pyroutes.register('user_groups_data', '/_admin/user_groups_data', []);
89 98 pyroutes.register('user_groups_new', '/_admin/user_groups/new', []);
90 99 pyroutes.register('user_groups_create', '/_admin/user_groups/create', []);
91 100 pyroutes.register('repos', '/_admin/repos', []);
92 101 pyroutes.register('repo_new', '/_admin/repos/new', []);
93 102 pyroutes.register('repo_create', '/_admin/repos/create', []);
94 103 pyroutes.register('channelstream_connect', '/_admin/channelstream/connect', []);
95 104 pyroutes.register('channelstream_subscribe', '/_admin/channelstream/subscribe', []);
96 105 pyroutes.register('channelstream_proxy', '/_channelstream', []);
97 106 pyroutes.register('login', '/_admin/login', []);
98 107 pyroutes.register('logout', '/_admin/logout', []);
99 108 pyroutes.register('register', '/_admin/register', []);
100 109 pyroutes.register('reset_password', '/_admin/password_reset', []);
101 110 pyroutes.register('reset_password_confirmation', '/_admin/password_reset_confirmation', []);
102 111 pyroutes.register('home', '/', []);
103 112 pyroutes.register('user_autocomplete_data', '/_users', []);
104 113 pyroutes.register('user_group_autocomplete_data', '/_user_groups', []);
105 114 pyroutes.register('repo_list_data', '/_repos', []);
106 115 pyroutes.register('goto_switcher_data', '/_goto_data', []);
107 116 pyroutes.register('journal', '/_admin/journal', []);
108 117 pyroutes.register('journal_rss', '/_admin/journal/rss', []);
109 118 pyroutes.register('journal_atom', '/_admin/journal/atom', []);
110 119 pyroutes.register('journal_public', '/_admin/public_journal', []);
111 120 pyroutes.register('journal_public_atom', '/_admin/public_journal/atom', []);
112 121 pyroutes.register('journal_public_atom_old', '/_admin/public_journal_atom', []);
113 122 pyroutes.register('journal_public_rss', '/_admin/public_journal/rss', []);
114 123 pyroutes.register('journal_public_rss_old', '/_admin/public_journal_rss', []);
115 124 pyroutes.register('toggle_following', '/_admin/toggle_following', []);
116 125 pyroutes.register('repo_creating', '/%(repo_name)s/repo_creating', ['repo_name']);
117 126 pyroutes.register('repo_creating_check', '/%(repo_name)s/repo_creating_check', ['repo_name']);
118 127 pyroutes.register('repo_summary_explicit', '/%(repo_name)s/summary', ['repo_name']);
119 128 pyroutes.register('repo_summary_commits', '/%(repo_name)s/summary-commits', ['repo_name']);
120 129 pyroutes.register('repo_commit', '/%(repo_name)s/changeset/%(commit_id)s', ['repo_name', 'commit_id']);
121 130 pyroutes.register('repo_commit_children', '/%(repo_name)s/changeset_children/%(commit_id)s', ['repo_name', 'commit_id']);
122 131 pyroutes.register('repo_commit_parents', '/%(repo_name)s/changeset_parents/%(commit_id)s', ['repo_name', 'commit_id']);
123 132 pyroutes.register('repo_commit_raw', '/%(repo_name)s/changeset-diff/%(commit_id)s', ['repo_name', 'commit_id']);
124 133 pyroutes.register('repo_commit_patch', '/%(repo_name)s/changeset-patch/%(commit_id)s', ['repo_name', 'commit_id']);
125 134 pyroutes.register('repo_commit_download', '/%(repo_name)s/changeset-download/%(commit_id)s', ['repo_name', 'commit_id']);
126 135 pyroutes.register('repo_commit_data', '/%(repo_name)s/changeset-data/%(commit_id)s', ['repo_name', 'commit_id']);
127 136 pyroutes.register('repo_commit_comment_create', '/%(repo_name)s/changeset/%(commit_id)s/comment/create', ['repo_name', 'commit_id']);
128 137 pyroutes.register('repo_commit_comment_preview', '/%(repo_name)s/changeset/%(commit_id)s/comment/preview', ['repo_name', 'commit_id']);
129 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 139 pyroutes.register('repo_commit_raw_deprecated', '/%(repo_name)s/raw-changeset/%(commit_id)s', ['repo_name', 'commit_id']);
131 140 pyroutes.register('repo_archivefile', '/%(repo_name)s/archive/%(fname)s', ['repo_name', 'fname']);
132 141 pyroutes.register('repo_files_diff', '/%(repo_name)s/diff/%(f_path)s', ['repo_name', 'f_path']);
133 142 pyroutes.register('repo_files_diff_2way_redirect', '/%(repo_name)s/diff-2way/%(f_path)s', ['repo_name', 'f_path']);
134 143 pyroutes.register('repo_files', '/%(repo_name)s/files/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
135 144 pyroutes.register('repo_files:default_path', '/%(repo_name)s/files/%(commit_id)s/', ['repo_name', 'commit_id']);
136 145 pyroutes.register('repo_files:default_commit', '/%(repo_name)s/files', ['repo_name']);
137 146 pyroutes.register('repo_files:rendered', '/%(repo_name)s/render/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
138 147 pyroutes.register('repo_files:annotated', '/%(repo_name)s/annotate/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
139 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 149 pyroutes.register('repo_nodetree_full', '/%(repo_name)s/nodetree_full/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
141 150 pyroutes.register('repo_nodetree_full:default_path', '/%(repo_name)s/nodetree_full/%(commit_id)s/', ['repo_name', 'commit_id']);
142 151 pyroutes.register('repo_files_nodelist', '/%(repo_name)s/nodelist/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
143 152 pyroutes.register('repo_file_raw', '/%(repo_name)s/raw/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
144 153 pyroutes.register('repo_file_download', '/%(repo_name)s/download/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
145 154 pyroutes.register('repo_file_download:legacy', '/%(repo_name)s/rawfile/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
146 155 pyroutes.register('repo_file_history', '/%(repo_name)s/history/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
147 156 pyroutes.register('repo_file_authors', '/%(repo_name)s/authors/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
148 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 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 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 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 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 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 163 pyroutes.register('repo_refs_data', '/%(repo_name)s/refs-data', ['repo_name']);
155 164 pyroutes.register('repo_refs_changelog_data', '/%(repo_name)s/refs-data-changelog', ['repo_name']);
156 165 pyroutes.register('repo_stats', '/%(repo_name)s/repo_stats/%(commit_id)s', ['repo_name', 'commit_id']);
157 166 pyroutes.register('repo_changelog', '/%(repo_name)s/changelog', ['repo_name']);
158 167 pyroutes.register('repo_changelog_file', '/%(repo_name)s/changelog/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
159 168 pyroutes.register('repo_changelog_elements', '/%(repo_name)s/changelog_elements', ['repo_name']);
160 169 pyroutes.register('repo_compare_select', '/%(repo_name)s/compare', ['repo_name']);
161 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 171 pyroutes.register('tags_home', '/%(repo_name)s/tags', ['repo_name']);
163 172 pyroutes.register('branches_home', '/%(repo_name)s/branches', ['repo_name']);
164 173 pyroutes.register('bookmarks_home', '/%(repo_name)s/bookmarks', ['repo_name']);
165 174 pyroutes.register('repo_fork_new', '/%(repo_name)s/fork', ['repo_name']);
166 175 pyroutes.register('repo_fork_create', '/%(repo_name)s/fork/create', ['repo_name']);
167 176 pyroutes.register('repo_forks_show_all', '/%(repo_name)s/forks', ['repo_name']);
168 177 pyroutes.register('repo_forks_data', '/%(repo_name)s/forks/data', ['repo_name']);
169 178 pyroutes.register('pullrequest_show', '/%(repo_name)s/pull-request/%(pull_request_id)s', ['repo_name', 'pull_request_id']);
170 179 pyroutes.register('pullrequest_show_all', '/%(repo_name)s/pull-request', ['repo_name']);
171 180 pyroutes.register('pullrequest_show_all_data', '/%(repo_name)s/pull-request-data', ['repo_name']);
172 181 pyroutes.register('pullrequest_repo_refs', '/%(repo_name)s/pull-request/refs/%(target_repo_name)s', ['repo_name', 'target_repo_name']);
173 182 pyroutes.register('pullrequest_repo_destinations', '/%(repo_name)s/pull-request/repo-destinations', ['repo_name']);
174 183 pyroutes.register('pullrequest_new', '/%(repo_name)s/pull-request/new', ['repo_name']);
175 184 pyroutes.register('pullrequest_create', '/%(repo_name)s/pull-request/create', ['repo_name']);
176 185 pyroutes.register('pullrequest_update', '/%(repo_name)s/pull-request/%(pull_request_id)s/update', ['repo_name', 'pull_request_id']);
177 186 pyroutes.register('pullrequest_merge', '/%(repo_name)s/pull-request/%(pull_request_id)s/merge', ['repo_name', 'pull_request_id']);
178 187 pyroutes.register('pullrequest_delete', '/%(repo_name)s/pull-request/%(pull_request_id)s/delete', ['repo_name', 'pull_request_id']);
179 188 pyroutes.register('pullrequest_comment_create', '/%(repo_name)s/pull-request/%(pull_request_id)s/comment', ['repo_name', 'pull_request_id']);
180 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 190 pyroutes.register('edit_repo', '/%(repo_name)s/settings', ['repo_name']);
182 191 pyroutes.register('edit_repo_advanced', '/%(repo_name)s/settings/advanced', ['repo_name']);
183 192 pyroutes.register('edit_repo_advanced_delete', '/%(repo_name)s/settings/advanced/delete', ['repo_name']);
184 193 pyroutes.register('edit_repo_advanced_locking', '/%(repo_name)s/settings/advanced/locking', ['repo_name']);
185 194 pyroutes.register('edit_repo_advanced_journal', '/%(repo_name)s/settings/advanced/journal', ['repo_name']);
186 195 pyroutes.register('edit_repo_advanced_fork', '/%(repo_name)s/settings/advanced/fork', ['repo_name']);
187 196 pyroutes.register('edit_repo_caches', '/%(repo_name)s/settings/caches', ['repo_name']);
188 197 pyroutes.register('edit_repo_perms', '/%(repo_name)s/settings/permissions', ['repo_name']);
189 198 pyroutes.register('edit_repo_maintenance', '/%(repo_name)s/settings/maintenance', ['repo_name']);
190 199 pyroutes.register('edit_repo_maintenance_execute', '/%(repo_name)s/settings/maintenance/execute', ['repo_name']);
191 200 pyroutes.register('edit_repo_fields', '/%(repo_name)s/settings/fields', ['repo_name']);
192 201 pyroutes.register('edit_repo_fields_create', '/%(repo_name)s/settings/fields/create', ['repo_name']);
193 202 pyroutes.register('edit_repo_fields_delete', '/%(repo_name)s/settings/fields/%(field_id)s/delete', ['repo_name', 'field_id']);
194 203 pyroutes.register('repo_edit_toggle_locking', '/%(repo_name)s/settings/toggle_locking', ['repo_name']);
195 204 pyroutes.register('edit_repo_remote', '/%(repo_name)s/settings/remote', ['repo_name']);
196 205 pyroutes.register('edit_repo_remote_pull', '/%(repo_name)s/settings/remote/pull', ['repo_name']);
197 206 pyroutes.register('edit_repo_statistics', '/%(repo_name)s/settings/statistics', ['repo_name']);
198 207 pyroutes.register('edit_repo_statistics_reset', '/%(repo_name)s/settings/statistics/update', ['repo_name']);
199 208 pyroutes.register('edit_repo_issuetracker', '/%(repo_name)s/settings/issue_trackers', ['repo_name']);
200 209 pyroutes.register('edit_repo_issuetracker_test', '/%(repo_name)s/settings/issue_trackers/test', ['repo_name']);
201 210 pyroutes.register('edit_repo_issuetracker_delete', '/%(repo_name)s/settings/issue_trackers/delete', ['repo_name']);
202 211 pyroutes.register('edit_repo_issuetracker_update', '/%(repo_name)s/settings/issue_trackers/update', ['repo_name']);
203 212 pyroutes.register('edit_repo_vcs', '/%(repo_name)s/settings/vcs', ['repo_name']);
204 213 pyroutes.register('edit_repo_vcs_update', '/%(repo_name)s/settings/vcs/update', ['repo_name']);
205 214 pyroutes.register('edit_repo_vcs_svn_pattern_delete', '/%(repo_name)s/settings/vcs/svn_pattern/delete', ['repo_name']);
206 215 pyroutes.register('repo_reviewers', '/%(repo_name)s/settings/review/rules', ['repo_name']);
207 216 pyroutes.register('repo_default_reviewers_data', '/%(repo_name)s/settings/review/default-reviewers', ['repo_name']);
208 217 pyroutes.register('edit_repo_strip', '/%(repo_name)s/settings/strip', ['repo_name']);
209 218 pyroutes.register('strip_check', '/%(repo_name)s/settings/strip_check', ['repo_name']);
210 219 pyroutes.register('strip_execute', '/%(repo_name)s/settings/strip_execute', ['repo_name']);
211 220 pyroutes.register('rss_feed_home', '/%(repo_name)s/feed/rss', ['repo_name']);
212 221 pyroutes.register('atom_feed_home', '/%(repo_name)s/feed/atom', ['repo_name']);
213 222 pyroutes.register('repo_summary', '/%(repo_name)s', ['repo_name']);
214 223 pyroutes.register('repo_summary_slash', '/%(repo_name)s/', ['repo_name']);
215 224 pyroutes.register('repo_group_home', '/%(repo_group_name)s', ['repo_group_name']);
216 225 pyroutes.register('repo_group_home_slash', '/%(repo_group_name)s/', ['repo_group_name']);
217 226 pyroutes.register('user_group_members_data', '/_admin/user_groups/%(user_group_id)s/members', ['user_group_id']);
218 227 pyroutes.register('edit_user_group_perms_summary', '/_admin/user_groups/%(user_group_id)s/edit/permissions_summary', ['user_group_id']);
219 228 pyroutes.register('edit_user_group_perms_summary_json', '/_admin/user_groups/%(user_group_id)s/edit/permissions_summary/json', ['user_group_id']);
220 229 pyroutes.register('edit_user_group', '/_admin/user_groups/%(user_group_id)s/edit', ['user_group_id']);
221 230 pyroutes.register('user_groups_update', '/_admin/user_groups/%(user_group_id)s/update', ['user_group_id']);
222 231 pyroutes.register('edit_user_group_global_perms', '/_admin/user_groups/%(user_group_id)s/edit/global_permissions', ['user_group_id']);
223 232 pyroutes.register('edit_user_group_global_perms_update', '/_admin/user_groups/%(user_group_id)s/edit/global_permissions/update', ['user_group_id']);
224 233 pyroutes.register('edit_user_group_perms', '/_admin/user_groups/%(user_group_id)s/edit/permissions', ['user_group_id']);
225 234 pyroutes.register('edit_user_group_perms_update', '/_admin/user_groups/%(user_group_id)s/edit/permissions/update', ['user_group_id']);
226 235 pyroutes.register('edit_user_group_advanced', '/_admin/user_groups/%(user_group_id)s/edit/advanced', ['user_group_id']);
227 236 pyroutes.register('edit_user_group_advanced_sync', '/_admin/user_groups/%(user_group_id)s/edit/advanced/sync', ['user_group_id']);
228 237 pyroutes.register('user_groups_delete', '/_admin/user_groups/%(user_group_id)s/delete', ['user_group_id']);
229 238 pyroutes.register('search', '/_admin/search', []);
230 239 pyroutes.register('search_repo', '/%(repo_name)s/search', ['repo_name']);
231 240 pyroutes.register('user_profile', '/_profiles/%(username)s', ['username']);
232 241 pyroutes.register('my_account_profile', '/_admin/my_account/profile', []);
233 242 pyroutes.register('my_account_edit', '/_admin/my_account/edit', []);
234 243 pyroutes.register('my_account_update', '/_admin/my_account/update', []);
235 244 pyroutes.register('my_account_password', '/_admin/my_account/password', []);
236 245 pyroutes.register('my_account_password_update', '/_admin/my_account/password/update', []);
237 246 pyroutes.register('my_account_auth_tokens', '/_admin/my_account/auth_tokens', []);
238 247 pyroutes.register('my_account_auth_tokens_add', '/_admin/my_account/auth_tokens/new', []);
239 248 pyroutes.register('my_account_auth_tokens_delete', '/_admin/my_account/auth_tokens/delete', []);
240 249 pyroutes.register('my_account_ssh_keys', '/_admin/my_account/ssh_keys', []);
241 250 pyroutes.register('my_account_ssh_keys_generate', '/_admin/my_account/ssh_keys/generate', []);
242 251 pyroutes.register('my_account_ssh_keys_add', '/_admin/my_account/ssh_keys/new', []);
243 252 pyroutes.register('my_account_ssh_keys_delete', '/_admin/my_account/ssh_keys/delete', []);
244 253 pyroutes.register('my_account_emails', '/_admin/my_account/emails', []);
245 254 pyroutes.register('my_account_emails_add', '/_admin/my_account/emails/new', []);
246 255 pyroutes.register('my_account_emails_delete', '/_admin/my_account/emails/delete', []);
247 256 pyroutes.register('my_account_repos', '/_admin/my_account/repos', []);
248 257 pyroutes.register('my_account_watched', '/_admin/my_account/watched', []);
249 258 pyroutes.register('my_account_perms', '/_admin/my_account/perms', []);
250 259 pyroutes.register('my_account_notifications', '/_admin/my_account/notifications', []);
251 260 pyroutes.register('my_account_notifications_toggle_visibility', '/_admin/my_account/toggle_visibility', []);
252 261 pyroutes.register('my_account_pullrequests', '/_admin/my_account/pull_requests', []);
253 262 pyroutes.register('my_account_pullrequests_data', '/_admin/my_account/pull_requests/data', []);
254 263 pyroutes.register('notifications_show_all', '/_admin/notifications', []);
255 264 pyroutes.register('notifications_mark_all_read', '/_admin/notifications/mark_all_read', []);
256 265 pyroutes.register('notifications_show', '/_admin/notifications/%(notification_id)s', ['notification_id']);
257 266 pyroutes.register('notifications_update', '/_admin/notifications/%(notification_id)s/update', ['notification_id']);
258 267 pyroutes.register('notifications_delete', '/_admin/notifications/%(notification_id)s/delete', ['notification_id']);
259 268 pyroutes.register('my_account_notifications_test_channelstream', '/_admin/my_account/test_channelstream', []);
260 269 pyroutes.register('gists_show', '/_admin/gists', []);
261 270 pyroutes.register('gists_new', '/_admin/gists/new', []);
262 271 pyroutes.register('gists_create', '/_admin/gists/create', []);
263 272 pyroutes.register('gist_show', '/_admin/gists/%(gist_id)s', ['gist_id']);
264 273 pyroutes.register('gist_delete', '/_admin/gists/%(gist_id)s/delete', ['gist_id']);
265 274 pyroutes.register('gist_edit', '/_admin/gists/%(gist_id)s/edit', ['gist_id']);
266 275 pyroutes.register('gist_edit_check_revision', '/_admin/gists/%(gist_id)s/edit/check_revision', ['gist_id']);
267 276 pyroutes.register('gist_update', '/_admin/gists/%(gist_id)s/update', ['gist_id']);
268 277 pyroutes.register('gist_show_rev', '/_admin/gists/%(gist_id)s/%(revision)s', ['gist_id', 'revision']);
269 278 pyroutes.register('gist_show_formatted', '/_admin/gists/%(gist_id)s/%(revision)s/%(format)s', ['gist_id', 'revision', 'format']);
270 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 280 pyroutes.register('debug_style_home', '/_admin/debug_style', []);
272 281 pyroutes.register('debug_style_template', '/_admin/debug_style/t/%(t_path)s', ['t_path']);
273 282 pyroutes.register('apiv2', '/_admin/api', []);
274 283 }
@@ -1,332 +1,339 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20 import io
21 21 import re
22 22 import datetime
23 23 import logging
24 24 import pylons
25 25 import Queue
26 26 import subprocess32
27 27 import os
28 28
29 29 from pyramid.i18n import get_localizer
30 30 from pyramid.threadlocal import get_current_request
31 31 from pyramid.interfaces import IRoutesMapper
32 32 from pyramid.settings import asbool
33 33 from pyramid.path import AssetResolver
34 34 from threading import Thread
35 35
36 36 from rhodecode.translation import _ as tsf
37 37 from rhodecode.config.jsroutes import generate_jsroutes_content
38 from rhodecode.lib import auth
38 39
39 40 import rhodecode
40 41
41 42 from pylons.i18n.translation import _get_translator
42 43 from pylons.util import ContextObj
43 44 from routes.util import URLGenerator
44 45
45 46 from rhodecode.lib.base import attach_context_attributes, get_auth_user
46 47
47 48 log = logging.getLogger(__name__)
48 49
49 50
50 51 def add_renderer_globals(event):
51 52 from rhodecode.lib import helpers
52 53
53 54 # NOTE(marcink):
54 55 # Put pylons stuff into the context. This will be removed as soon as
55 56 # migration to pyramid is finished.
56 57 event['c'] = pylons.tmpl_context
57 58
58 59 # TODO: When executed in pyramid view context the request is not available
59 60 # in the event. Find a better solution to get the request.
60 61 request = event['request'] or get_current_request()
61 62
62 63 # Add Pyramid translation as '_' to context
63 64 event['_'] = request.translate
64 65 event['_ungettext'] = request.plularize
65 66 event['h'] = helpers
66 67
67 68
68 69 def add_localizer(event):
69 70 request = event.request
70 71 localizer = get_localizer(request)
71 72
72 73 def auto_translate(*args, **kwargs):
73 74 return localizer.translate(tsf(*args, **kwargs))
74 75
75 76 request.localizer = localizer
76 77 request.translate = auto_translate
77 78 request.plularize = localizer.pluralize
78 79
79 80
80 81 def set_user_lang(event):
81 82 request = event.request
82 83 cur_user = getattr(request, 'user', None)
83 84
84 85 if cur_user:
85 86 user_lang = cur_user.get_instance().user_data.get('language')
86 87 if user_lang:
87 88 log.debug('lang: setting current user:%s language to: %s', cur_user, user_lang)
88 89 event.request._LOCALE_ = user_lang
89 90
90 91
91 92 def add_request_user_context(event):
92 93 """
93 94 Adds auth user into request context
94 95 """
95 96 request = event.request
96 97
97 98 if hasattr(request, 'vcs_call'):
98 99 # skip vcs calls
99 100 return
100 101
101 102 if hasattr(request, 'rpc_method'):
102 103 # skip api calls
103 104 return
104 105
105 106 auth_user = get_auth_user(request)
106 107 request.user = auth_user
107 108 request.environ['rc_auth_user'] = auth_user
108 109
109 110
110 111 def add_pylons_context(event):
111 112 request = event.request
112 113
113 114 config = rhodecode.CONFIG
114 115 environ = request.environ
115 116 session = request.session
116 117
117 118 if hasattr(request, 'vcs_call'):
118 119 # skip vcs calls
119 120 return
120 121
121 122 # Setup pylons globals.
122 123 pylons.config._push_object(config)
123 124 pylons.request._push_object(request)
124 125 pylons.session._push_object(session)
125 126 pylons.translator._push_object(_get_translator(config.get('lang')))
126 127
127 128 pylons.url._push_object(URLGenerator(config['routes.map'], environ))
128 129 session_key = (
129 130 config['pylons.environ_config'].get('session', 'beaker.session'))
130 131 environ[session_key] = session
131 132
132 133 if hasattr(request, 'rpc_method'):
133 134 # skip api calls
134 135 return
135 136
136 137 # Setup the pylons context object ('c')
137 138 context = ContextObj()
138 139 context.rhodecode_user = request.user
139 140 attach_context_attributes(context, request, request.user.user_id)
140 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 150 def scan_repositories_if_enabled(event):
144 151 """
145 152 This is subscribed to the `pyramid.events.ApplicationCreated` event. It
146 153 does a repository scan if enabled in the settings.
147 154 """
148 155 settings = event.app.registry.settings
149 156 vcs_server_enabled = settings['vcs.server.enable']
150 157 import_on_startup = settings['startup.import_repos']
151 158 if vcs_server_enabled and import_on_startup:
152 159 from rhodecode.model.scm import ScmModel
153 160 from rhodecode.lib.utils import repo2db_mapper, get_rhodecode_base_path
154 161 repositories = ScmModel().repo_scan(get_rhodecode_base_path())
155 162 repo2db_mapper(repositories, remove_obsolete=False)
156 163
157 164
158 165 def write_metadata_if_needed(event):
159 166 """
160 167 Writes upgrade metadata
161 168 """
162 169 import rhodecode
163 170 from rhodecode.lib import system_info
164 171 from rhodecode.lib import ext_json
165 172
166 173 def write():
167 174 fname = '.rcmetadata.json'
168 175 ini_loc = os.path.dirname(rhodecode.CONFIG.get('__file__'))
169 176 metadata_destination = os.path.join(ini_loc, fname)
170 177
171 178 configuration = system_info.SysInfo(
172 179 system_info.rhodecode_config)()['value']
173 180 license_token = configuration['config']['license_token']
174 181 dbinfo = system_info.SysInfo(system_info.database_info)()['value']
175 182 del dbinfo['url']
176 183 metadata = dict(
177 184 desc='upgrade metadata info',
178 185 license_token=license_token,
179 186 created_on=datetime.datetime.utcnow().isoformat(),
180 187 usage=system_info.SysInfo(system_info.usage_info)()['value'],
181 188 platform=system_info.SysInfo(system_info.platform_type)()['value'],
182 189 database=dbinfo,
183 190 cpu=system_info.SysInfo(system_info.cpu)()['value'],
184 191 memory=system_info.SysInfo(system_info.memory)()['value'],
185 192 )
186 193
187 194 with open(metadata_destination, 'wb') as f:
188 195 f.write(ext_json.json.dumps(metadata))
189 196
190 197 settings = event.app.registry.settings
191 198 if settings.get('metadata.skip'):
192 199 return
193 200
194 201 try:
195 202 write()
196 203 except Exception:
197 204 pass
198 205
199 206
200 207 def write_js_routes_if_enabled(event):
201 208 registry = event.app.registry
202 209
203 210 mapper = registry.queryUtility(IRoutesMapper)
204 211 _argument_prog = re.compile('\{(.*?)\}|:\((.*)\)')
205 212
206 213 def _extract_route_information(route):
207 214 """
208 215 Convert a route into tuple(name, path, args), eg:
209 216 ('show_user', '/profile/%(username)s', ['username'])
210 217 """
211 218
212 219 routepath = route.pattern
213 220 pattern = route.pattern
214 221
215 222 def replace(matchobj):
216 223 if matchobj.group(1):
217 224 return "%%(%s)s" % matchobj.group(1).split(':')[0]
218 225 else:
219 226 return "%%(%s)s" % matchobj.group(2)
220 227
221 228 routepath = _argument_prog.sub(replace, routepath)
222 229
223 230 if not routepath.startswith('/'):
224 231 routepath = '/'+routepath
225 232
226 233 return (
227 234 route.name,
228 235 routepath,
229 236 [(arg[0].split(':')[0] if arg[0] != '' else arg[1])
230 237 for arg in _argument_prog.findall(pattern)]
231 238 )
232 239
233 240 def get_routes():
234 241 # pylons routes
235 242 # TODO(marcink): remove when pyramid migration is finished
236 243 if 'routes.map' in rhodecode.CONFIG:
237 244 for route in rhodecode.CONFIG['routes.map'].jsroutes():
238 245 yield route
239 246
240 247 # pyramid routes
241 248 for route in mapper.get_routes():
242 249 if not route.name.startswith('__'):
243 250 yield _extract_route_information(route)
244 251
245 252 if asbool(registry.settings.get('generate_js_files', 'false')):
246 253 static_path = AssetResolver().resolve('rhodecode:public').abspath()
247 254 jsroutes = get_routes()
248 255 jsroutes_file_content = generate_jsroutes_content(jsroutes)
249 256 jsroutes_file_path = os.path.join(
250 257 static_path, 'js', 'rhodecode', 'routes.js')
251 258
252 259 with io.open(jsroutes_file_path, 'w', encoding='utf-8') as f:
253 260 f.write(jsroutes_file_content)
254 261
255 262
256 263 class Subscriber(object):
257 264 """
258 265 Base class for subscribers to the pyramid event system.
259 266 """
260 267 def __call__(self, event):
261 268 self.run(event)
262 269
263 270 def run(self, event):
264 271 raise NotImplementedError('Subclass has to implement this.')
265 272
266 273
267 274 class AsyncSubscriber(Subscriber):
268 275 """
269 276 Subscriber that handles the execution of events in a separate task to not
270 277 block the execution of the code which triggers the event. It puts the
271 278 received events into a queue from which the worker process takes them in
272 279 order.
273 280 """
274 281 def __init__(self):
275 282 self._stop = False
276 283 self._eventq = Queue.Queue()
277 284 self._worker = self.create_worker()
278 285 self._worker.start()
279 286
280 287 def __call__(self, event):
281 288 self._eventq.put(event)
282 289
283 290 def create_worker(self):
284 291 worker = Thread(target=self.do_work)
285 292 worker.daemon = True
286 293 return worker
287 294
288 295 def stop_worker(self):
289 296 self._stop = False
290 297 self._eventq.put(None)
291 298 self._worker.join()
292 299
293 300 def do_work(self):
294 301 while not self._stop:
295 302 event = self._eventq.get()
296 303 if event is not None:
297 304 self.run(event)
298 305
299 306
300 307 class AsyncSubprocessSubscriber(AsyncSubscriber):
301 308 """
302 309 Subscriber that uses the subprocess32 module to execute a command if an
303 310 event is received. Events are handled asynchronously.
304 311 """
305 312
306 313 def __init__(self, cmd, timeout=None):
307 314 super(AsyncSubprocessSubscriber, self).__init__()
308 315 self._cmd = cmd
309 316 self._timeout = timeout
310 317
311 318 def run(self, event):
312 319 cmd = self._cmd
313 320 timeout = self._timeout
314 321 log.debug('Executing command %s.', cmd)
315 322
316 323 try:
317 324 output = subprocess32.check_output(
318 325 cmd, timeout=timeout, stderr=subprocess32.STDOUT)
319 326 log.debug('Command finished %s', cmd)
320 327 if output:
321 328 log.debug('Command output: %s', output)
322 329 except subprocess32.TimeoutExpired as e:
323 330 log.exception('Timeout while executing command.')
324 331 if e.output:
325 332 log.error('Command output: %s', e.output)
326 333 except subprocess32.CalledProcessError as e:
327 334 log.exception('Error while executing command.')
328 335 if e.output:
329 336 log.error('Command output: %s', e.output)
330 337 except:
331 338 log.exception(
332 339 'Exception while executing command %s.', cmd)
@@ -1,180 +1,179 b''
1 1 <div class="panel panel-default">
2 2 <div class="panel-heading">
3 3 <h3 class="panel-title">${_('Authentication Tokens')}</h3>
4 4 </div>
5 5 <div class="panel-body">
6 6 <div class="apikeys_wrap">
7 7 <p>
8 8 ${_('Each token can have a role. Token with a role can be used only in given context, '
9 9 'e.g. VCS tokens can be used together with the authtoken auth plugin for git/hg/svn operations only.')}
10 10 </p>
11 11 <table class="rctable auth_tokens">
12 12 <tr>
13 13 <th>${_('Token')}</th>
14 14 <th>${_('Scope')}</th>
15 15 <th>${_('Description')}</th>
16 16 <th>${_('Role')}</th>
17 17 <th>${_('Expiration')}</th>
18 18 <th>${_('Action')}</th>
19 19 </tr>
20 20 %if c.user_auth_tokens:
21 21 %for auth_token in c.user_auth_tokens:
22 22 <tr class="${'expired' if auth_token.expired else ''}">
23 23 <td class="truncate-wrap td-authtoken">
24 24 <div class="user_auth_tokens truncate autoexpand">
25 25 <code>${auth_token.api_key}</code>
26 26 </div>
27 27 </td>
28 28 <td class="td">${auth_token.scope_humanized}</td>
29 29 <td class="td-wrap">${auth_token.description}</td>
30 30 <td class="td-tags">
31 31 <span class="tag disabled">${auth_token.role_humanized}</span>
32 32 </td>
33 33 <td class="td-exp">
34 34 %if auth_token.expires == -1:
35 35 ${_('never')}
36 36 %else:
37 37 %if auth_token.expired:
38 38 <span style="text-decoration: line-through">${h.age_component(h.time_to_utcdatetime(auth_token.expires))}</span>
39 39 %else:
40 40 ${h.age_component(h.time_to_utcdatetime(auth_token.expires))}
41 41 %endif
42 42 %endif
43 43 </td>
44 44 <td class="td-action">
45 45 ${h.secure_form(h.route_path('my_account_auth_tokens_delete'), request=request)}
46 46 ${h.hidden('del_auth_token', auth_token.user_api_key_id)}
47 47 <button class="btn btn-link btn-danger" type="submit"
48 48 onclick="return confirm('${_('Confirm to remove this auth token: %s') % auth_token.token_obfuscated}');">
49 49 ${_('Delete')}
50 50 </button>
51 51 ${h.end_form()}
52 52 </td>
53 53 </tr>
54 54 %endfor
55 55 %else:
56 56 <tr><td><div class="ip">${_('No additional auth tokens specified')}</div></td></tr>
57 57 %endif
58 58 </table>
59 59 </div>
60 60
61 61 <div class="user_auth_tokens">
62 62 ${h.secure_form(h.route_path('my_account_auth_tokens_add'), request=request)}
63 63 <div class="form form-vertical">
64 64 <!-- fields -->
65 65 <div class="fields">
66 66 <div class="field">
67 67 <div class="label">
68 68 <label for="new_email">${_('New authentication token')}:</label>
69 69 </div>
70 70 <div class="input">
71 71 ${h.text('description', class_='medium', placeholder=_('Description'))}
72 72 ${h.hidden('lifetime')}
73 73 ${h.select('role', '', c.role_options)}
74 74
75 75 % if c.allow_scoped_tokens:
76 76 ${h.hidden('scope_repo_id')}
77 77 % else:
78 78 ${h.select('scope_repo_id_disabled', '', ['Scopes available in EE edition'], disabled='disabled')}
79 79 % endif
80 80 </div>
81 81 <p class="help-block">
82 82 ${_('Repository scope works only with tokens with VCS type.')}
83 83 </p>
84 84 </div>
85 85 <div class="buttons">
86 86 ${h.submit('save',_('Add'),class_="btn")}
87 87 ${h.reset('reset',_('Reset'),class_="btn")}
88 88 </div>
89 89 </div>
90 90 </div>
91 91 ${h.end_form()}
92 92 </div>
93 93 </div>
94 94 </div>
95 95 <script>
96 96 $(document).ready(function(){
97 97
98 98 var select2Options = {
99 99 'containerCssClass': "drop-menu",
100 100 'dropdownCssClass': "drop-menu-dropdown",
101 101 'dropdownAutoWidth': true
102 102 };
103 103 $("#role").select2(select2Options);
104 104
105
106 105 var preloadData = {
107 106 results: [
108 107 % for entry in c.lifetime_values:
109 108 {id:${entry[0]}, text:"${entry[1]}"}${'' if loop.last else ','}
110 109 % endfor
111 110 ]
112 111 };
113 112
114 113 $("#lifetime").select2({
115 114 containerCssClass: "drop-menu",
116 115 dropdownCssClass: "drop-menu-dropdown",
117 116 dropdownAutoWidth: true,
118 117 data: preloadData,
119 118 placeholder: "${_('Select or enter expiration date')}",
120 119 query: function(query) {
121 120 feedLifetimeOptions(query, preloadData);
122 121 }
123 122 });
124 123
125 124
126 125 var repoFilter = function(data) {
127 126 var results = [];
128 127
129 128 if (!data.results[0]) {
130 129 return data
131 130 }
132 131
133 132 $.each(data.results[0].children, function() {
134 133 // replace name to ID for submision
135 134 this.id = this.obj.repo_id;
136 135 results.push(this);
137 136 });
138 137
139 138 data.results[0].children = results;
140 139 return data;
141 140 };
142 141
143 142 $("#scope_repo_id_disabled").select2(select2Options);
144 143
145 144 $("#scope_repo_id").select2({
146 145 cachedDataSource: {},
147 146 minimumInputLength: 2,
148 147 placeholder: "${_('repository scope')}",
149 148 dropdownAutoWidth: true,
150 149 containerCssClass: "drop-menu",
151 150 dropdownCssClass: "drop-menu-dropdown",
152 151 formatResult: formatResult,
153 152 query: $.debounce(250, function(query){
154 153 self = this;
155 154 var cacheKey = query.term;
156 155 var cachedData = self.cachedDataSource[cacheKey];
157 156
158 157 if (cachedData) {
159 158 query.callback({results: cachedData.results});
160 159 } else {
161 160 $.ajax({
162 161 url: pyroutes.url('repo_list_data'),
163 162 data: {'query': query.term},
164 163 dataType: 'json',
165 164 type: 'GET',
166 165 success: function(data) {
167 166 data = repoFilter(data);
168 167 self.cachedDataSource[cacheKey] = data;
169 168 query.callback({results: data.results});
170 169 },
171 170 error: function(data, textStatus, errorThrown) {
172 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 179 </script>
@@ -1,186 +1,186 b''
1 1 ## -*- coding: utf-8 -*-
2 2 <%namespace name="base" file="/base/base.mako"/>
3 3
4 4 <div class="panel panel-default">
5 5 <div class="panel-heading">
6 6 <h3 class="panel-title">${_('User Group: %s') % c.user_group.users_group_name}</h3>
7 7 </div>
8 8 <div class="panel-body">
9 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 10 <div class="form">
11 11 <!-- fields -->
12 12 <div class="fields">
13 13 <div class="field">
14 14 <div class="label">
15 15 <label for="users_group_name">${_('Group name')}:</label>
16 16 </div>
17 17 <div class="input">
18 18 ${h.text('users_group_name',class_='medium')}
19 19 </div>
20 20 </div>
21 21
22 22 <div class="field badged-field">
23 23 <div class="label">
24 24 <label for="user">${_('Owner')}:</label>
25 25 </div>
26 26 <div class="input">
27 27 <div class="badge-input-container">
28 28 <div class="user-badge">
29 29 ${base.gravatar_with_user(c.user_group.user.email, show_disabled=not c.user_group.user.active)}
30 30 </div>
31 31 <div class="badge-input-wrap">
32 32 ${h.text('user', class_="medium", autocomplete="off")}
33 33 </div>
34 34 </div>
35 35 <form:error name="user"/>
36 36 <p class="help-block">${_('Change owner of this user group.')}</p>
37 37 </div>
38 38 </div>
39 39
40 40 <div class="field">
41 41 <div class="label label-textarea">
42 42 <label for="user_group_description">${_('Description')}:</label>
43 43 </div>
44 44 <div class="textarea textarea-small editor">
45 45 ${h.textarea('user_group_description',cols=23,rows=5,class_="medium")}
46 46 <span class="help-block">${_('Short, optional description for this user group.')}</span>
47 47 </div>
48 48 </div>
49 49 <div class="field">
50 50 <div class="label label-checkbox">
51 51 <label for="users_group_active">${_('Active')}:</label>
52 52 </div>
53 53 <div class="checkboxes">
54 54 ${h.checkbox('users_group_active',value=True)}
55 55 </div>
56 56 </div>
57 57
58 58 <div class="field">
59 59 <div class="label label-checkbox">
60 60 <label for="users_group_active">${_('Add members')}:</label>
61 61 </div>
62 62 <div class="input">
63 63 ${h.text('user_group_add_members', placeholder="user/usergroup", class_="medium")}
64 64 </div>
65 65 </div>
66 66
67 67 <input type="hidden" name="__start__" value="user_group_members:sequence"/>
68 68 <table id="group_members_placeholder" class="rctable group_members">
69 69 <tr>
70 70 <th>${_('Username')}</th>
71 71 <th>${_('Action')}</th>
72 72 </tr>
73 73
74 74 % if c.group_members_obj:
75 75 % for user in c.group_members_obj:
76 76 <tr>
77 77 <td id="member_user_${user.user_id}" class="td-author">
78 78 <div class="group_member">
79 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 81 <input type="hidden" name="__start__" value="member:mapping">
82 82 <input type="hidden" name="member_user_id" value="${user.user_id}">
83 83 <input type="hidden" name="type" value="existing" id="member_${user.user_id}">
84 84 <input type="hidden" name="__end__" value="member:mapping">
85 85 </div>
86 86 </td>
87 87 <td class="">
88 88 <div class="usergroup_member_remove action_button" onclick="removeUserGroupMember(${user.user_id}, true)" style="visibility: visible;">
89 89 <i class="icon-remove-sign"></i>
90 90 </div>
91 91 </td>
92 92 </tr>
93 93 % endfor
94 94
95 95 % else:
96 96 <tr><td colspan="2">${_('No members yet')}</td></tr>
97 97 % endif
98 98 </table>
99 99 <input type="hidden" name="__end__" value="user_group_members:sequence"/>
100 100
101 101 <div class="buttons">
102 102 ${h.submit('Save',_('Save'),class_="btn")}
103 103 </div>
104 104 </div>
105 105 </div>
106 106 ${h.end_form()}
107 107 </div>
108 108 </div>
109 109 <script>
110 110 $(document).ready(function(){
111 111 $("#group_parent_id").select2({
112 112 'containerCssClass': "drop-menu",
113 113 'dropdownCssClass': "drop-menu-dropdown",
114 114 'dropdownAutoWidth': true
115 115 });
116 116
117 117 removeUserGroupMember = function(userId){
118 118 $('#member_'+userId).val('remove');
119 119 $('#member_user_'+userId).addClass('to-delete');
120 120 };
121 121
122 122 $('#user_group_add_members').autocomplete({
123 123 serviceUrl: pyroutes.url('user_autocomplete_data'),
124 124 minChars:2,
125 125 maxHeight:400,
126 126 width:300,
127 127 deferRequestBy: 300, //miliseconds
128 128 showNoSuggestionNotice: true,
129 129 params: { user_groups:true },
130 130 formatResult: autocompleteFormatResult,
131 131 lookupFilter: autocompleteFilterResult,
132 132 onSelect: function(element, suggestion){
133 133
134 134 function addMember(user, fromUserGroup) {
135 135 var gravatar = user.icon_link;
136 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 138 var uid = user.id;
139 139
140 140 if (fromUserGroup) {
141 141 username = username +" "+ _gettext('(from usergroup {0})'.format(fromUserGroup))
142 142 }
143 143
144 144 var elem = $(
145 145 ('<tr>'+
146 146 '<td id="member_user_{6}" class="td-author td-author-new-entry">'+
147 147 '<div class="group_member">'+
148 148 '<img class="gravatar" src="{0}" height="16" width="16">'+
149 149 '<span class="username user"><a href="{1}">{2}</a></span>'+
150 150 '<input type="hidden" name="__start__" value="member:mapping">'+
151 151 '<input type="hidden" name="member_user_id" value="{3}">'+
152 152 '<input type="hidden" name="type" value="new" id="member_{4}">'+
153 153 '<input type="hidden" name="__end__" value="member:mapping">'+
154 154 '</div>'+
155 155 '</td>'+
156 156 '<td class="td-author-new-entry">'+
157 157 '<div class="usergroup_member_remove action_button" onclick="removeUserGroupMember({5}, true)" style="visibility: visible;">'+
158 158 '<i class="icon-remove-sign"></i>'+
159 159 '</div>'+
160 160 '</td>'+
161 161 '</tr>').format(gravatar, userLink, username,
162 162 uid, uid, uid, uid)
163 163 );
164 164 $('#group_members_placeholder').append(elem)
165 165 }
166 166
167 167 if (suggestion.value_type == 'user_group') {
168 168 $.getJSON(
169 169 pyroutes.url('user_group_members_data',
170 170 {'user_group_id': suggestion.id}),
171 171 function(data) {
172 172 $.each(data.members, function(idx, user) {
173 173 addMember(user, suggestion.value)
174 174 });
175 175 }
176 176 );
177 177 } else if (suggestion.value_type == 'user') {
178 178 addMember(suggestion, null);
179 179 }
180 180 }
181 181 });
182 182
183 183
184 184 UsersAutoComplete('user', '${c.rhodecode_user.user_id}');
185 185 })
186 186 </script>
@@ -1,147 +1,147 b''
1 1 ## -*- coding: utf-8 -*-
2 2 <%inherit file="/base/base.mako"/>
3 3
4 4 <%def name="title()">
5 5 ${_('Add user')}
6 6 %if c.rhodecode_name:
7 7 &middot; ${h.branding(c.rhodecode_name)}
8 8 %endif
9 9 </%def>
10 10 <%def name="breadcrumbs_links()">
11 11 ${h.link_to(_('Admin'),h.route_path('admin_home'))}
12 12 &raquo;
13 13 ${h.link_to(_('Users'),h.route_path('users'))}
14 14 &raquo;
15 15 ${_('Add User')}
16 16 </%def>
17 17
18 18 <%def name="menu_bar_nav()">
19 19 ${self.menu_items(active='admin')}
20 20 </%def>
21 21
22 22 <%def name="main()">
23 23 <div class="box">
24 24 <!-- box / title -->
25 25 <div class="title">
26 26 ${self.breadcrumbs()}
27 27 </div>
28 28 <!-- end box / title -->
29 ${h.secure_form(h.url('users'))}
29 ${h.secure_form(h.route_path('users_create'), request=request)}
30 30 <div class="form">
31 31 <!-- fields -->
32 32 <div class="fields">
33 33 <div class="field">
34 34 <div class="label">
35 35 <label for="username">${_('Username')}:</label>
36 36 </div>
37 37 <div class="input">
38 38 ${h.text('username', class_='medium')}
39 39 </div>
40 40 </div>
41 41
42 42 <div class="field">
43 43 <div class="label">
44 44 <label for="password">${_('Password')}:</label>
45 45 </div>
46 46 <div class="input">
47 47 ${h.password('password', class_='medium')}
48 48 </div>
49 49 </div>
50 50
51 51 <div class="field">
52 52 <div class="label">
53 53 <label for="password_confirmation">${_('Password confirmation')}:</label>
54 54 </div>
55 55 <div class="input">
56 56 ${h.password('password_confirmation',autocomplete="off", class_='medium')}
57 57 <div class="info-block">
58 58 <a id="generate_password" href="#">
59 59 <i class="icon-lock"></i> ${_('Generate password')}
60 60 </a>
61 61 <span id="generate_password_preview"></span>
62 62 </div>
63 63 </div>
64 64 </div>
65 65
66 66 <div class="field">
67 67 <div class="label">
68 68 <label for="firstname">${_('First Name')}:</label>
69 69 </div>
70 70 <div class="input">
71 71 ${h.text('firstname', class_='medium')}
72 72 </div>
73 73 </div>
74 74
75 75 <div class="field">
76 76 <div class="label">
77 77 <label for="lastname">${_('Last Name')}:</label>
78 78 </div>
79 79 <div class="input">
80 80 ${h.text('lastname', class_='medium')}
81 81 </div>
82 82 </div>
83 83
84 84 <div class="field">
85 85 <div class="label">
86 86 <label for="email">${_('Email')}:</label>
87 87 </div>
88 88 <div class="input">
89 89 ${h.text('email', class_='medium')}
90 90 ${h.hidden('extern_name', c.default_extern_type)}
91 91 ${h.hidden('extern_type', c.default_extern_type)}
92 92 </div>
93 93 </div>
94 94
95 95 <div class="field">
96 96 <div class="label label-checkbox">
97 97 <label for="active">${_('Active')}:</label>
98 98 </div>
99 99 <div class="checkboxes">
100 100 ${h.checkbox('active',value=True,checked='checked')}
101 101 </div>
102 102 </div>
103 103
104 104 <div class="field">
105 105 <div class="label label-checkbox">
106 106 <label for="password_change">${_('Password change')}:</label>
107 107 </div>
108 108 <div class="checkboxes">
109 109 ${h.checkbox('password_change',value=True)}
110 110 <span class="help-block">${_('Force user to change his password on the next login')}</span>
111 111 </div>
112 112 </div>
113 113
114 114 <div class="field">
115 115 <div class="label label-checkbox">
116 116 <label for="create_repo_group">${_('Add personal repository group')}:</label>
117 117 </div>
118 118 <div class="checkboxes">
119 119 ${h.checkbox('create_repo_group',value=True, checked=c.default_create_repo_group)}
120 120 <span class="help-block">
121 121 ${_('New group will be created at: `/%(path)s`') % {'path': c.personal_repo_group_name}}<br/>
122 122 ${_('User will be automatically set as this group owner.')}
123 123 </span>
124 124 </div>
125 125 </div>
126 126
127 127 <div class="buttons">
128 128 ${h.submit('save',_('Save'),class_="btn")}
129 129 </div>
130 130 </div>
131 131 </div>
132 132 ${h.end_form()}
133 133 </div>
134 134 <script>
135 135 $(document).ready(function(){
136 136 $('#username').focus();
137 137
138 138 $('#generate_password').on('click', function(e){
139 139 var tmpl = "(${_('generated password:')} {0})";
140 140 var new_passwd = generatePassword(12);
141 141 $('#generate_password_preview').html(tmpl.format(new_passwd));
142 142 $('#password').val(new_passwd);
143 143 $('#password_confirmation').val(new_passwd);
144 144 })
145 145 })
146 146 </script>
147 147 </%def>
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now