##// END OF EJS Templates
branch permissions: added logic to define in UI branch permissions....
marcink -
r2975:2d612d18 default
parent child Browse files
Show More

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

@@ -0,0 +1,45 b''
1 # -*- coding: utf-8 -*-
2
3 # Copyright (C) 2011-2018 RhodeCode GmbH
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
21 import logging
22
23 from pyramid.view import view_config
24
25 from rhodecode.apps._base import RepoAppView
26 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
27
28 log = logging.getLogger(__name__)
29
30
31 class RepoSettingsBranchPermissionsView(RepoAppView):
32
33 def load_default_context(self):
34 c = self._get_local_tmpl_context()
35 return c
36
37 @LoginRequired()
38 @HasRepoPermissionAnyDecorator('repository.admin')
39 @view_config(
40 route_name='edit_repo_perms_branch', request_method='GET',
41 renderer='rhodecode:templates/admin/repos/repo_edit.mako')
42 def branch_permissions(self):
43 c = self.load_default_context()
44 c.active = 'permissions_branch'
45 return self._get_template_context(c)
This diff has been collapsed as it changes many lines, (4587 lines changed) Show them Hide them
@@ -0,0 +1,4587 b''
1 # -*- coding: utf-8 -*-
2
3 # Copyright (C) 2010-2018 RhodeCode GmbH
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
21 """
22 Database Models for RhodeCode Enterprise
23 """
24
25 import re
26 import os
27 import time
28 import hashlib
29 import logging
30 import datetime
31 import warnings
32 import ipaddress
33 import functools
34 import traceback
35 import collections
36
37 from sqlalchemy import (
38 or_, and_, not_, func, TypeDecorator, event,
39 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
40 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
41 Text, Float, PickleType)
42 from sqlalchemy.sql.expression import true, false
43 from sqlalchemy.sql.functions import coalesce, count # noqa
44 from sqlalchemy.orm import (
45 relationship, joinedload, class_mapper, validates, aliased)
46 from sqlalchemy.ext.declarative import declared_attr
47 from sqlalchemy.ext.hybrid import hybrid_property
48 from sqlalchemy.exc import IntegrityError # noqa
49 from sqlalchemy.dialects.mysql import LONGTEXT
50 from beaker.cache import cache_region
51 from zope.cachedescriptors.property import Lazy as LazyProperty
52
53 from pyramid.threadlocal import get_current_request
54
55 from rhodecode.translation import _
56 from rhodecode.lib.vcs import get_vcs_instance
57 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
58 from rhodecode.lib.utils2 import (
59 str2bool, safe_str, get_commit_safe, safe_unicode, md5_safe,
60 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
61 glob2re, StrictAttributeDict, cleaned_uri)
62 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
63 JsonRaw
64 from rhodecode.lib.ext_json import json
65 from rhodecode.lib.caching_query import FromCache
66 from rhodecode.lib.encrypt import AESCipher
67
68 from rhodecode.model.meta import Base, Session
69
70 URL_SEP = '/'
71 log = logging.getLogger(__name__)
72
73 # =============================================================================
74 # BASE CLASSES
75 # =============================================================================
76
77 # this is propagated from .ini file rhodecode.encrypted_values.secret or
78 # beaker.session.secret if first is not set.
79 # and initialized at environment.py
80 ENCRYPTION_KEY = None
81
82 # used to sort permissions by types, '#' used here is not allowed to be in
83 # usernames, and it's very early in sorted string.printable table.
84 PERMISSION_TYPE_SORT = {
85 'admin': '####',
86 'write': '###',
87 'read': '##',
88 'none': '#',
89 }
90
91
92 def display_user_sort(obj):
93 """
94 Sort function used to sort permissions in .permissions() function of
95 Repository, RepoGroup, UserGroup. Also it put the default user in front
96 of all other resources
97 """
98
99 if obj.username == User.DEFAULT_USER:
100 return '#####'
101 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
102 return prefix + obj.username
103
104
105 def display_user_group_sort(obj):
106 """
107 Sort function used to sort permissions in .permissions() function of
108 Repository, RepoGroup, UserGroup. Also it put the default user in front
109 of all other resources
110 """
111
112 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
113 return prefix + obj.users_group_name
114
115
116 def _hash_key(k):
117 return md5_safe(k)
118
119
120 def in_filter_generator(qry, items, limit=500):
121 """
122 Splits IN() into multiple with OR
123 e.g.::
124 cnt = Repository.query().filter(
125 or_(
126 *in_filter_generator(Repository.repo_id, range(100000))
127 )).count()
128 """
129 if not items:
130 # empty list will cause empty query which might cause security issues
131 # this can lead to hidden unpleasant results
132 items = [-1]
133
134 parts = []
135 for chunk in xrange(0, len(items), limit):
136 parts.append(
137 qry.in_(items[chunk: chunk + limit])
138 )
139
140 return parts
141
142
143 class EncryptedTextValue(TypeDecorator):
144 """
145 Special column for encrypted long text data, use like::
146
147 value = Column("encrypted_value", EncryptedValue(), nullable=False)
148
149 This column is intelligent so if value is in unencrypted form it return
150 unencrypted form, but on save it always encrypts
151 """
152 impl = Text
153
154 def process_bind_param(self, value, dialect):
155 if not value:
156 return value
157 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
158 # protect against double encrypting if someone manually starts
159 # doing
160 raise ValueError('value needs to be in unencrypted format, ie. '
161 'not starting with enc$aes')
162 return 'enc$aes_hmac$%s' % AESCipher(
163 ENCRYPTION_KEY, hmac=True).encrypt(value)
164
165 def process_result_value(self, value, dialect):
166 import rhodecode
167
168 if not value:
169 return value
170
171 parts = value.split('$', 3)
172 if not len(parts) == 3:
173 # probably not encrypted values
174 return value
175 else:
176 if parts[0] != 'enc':
177 # parts ok but without our header ?
178 return value
179 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
180 'rhodecode.encrypted_values.strict') or True)
181 # at that stage we know it's our encryption
182 if parts[1] == 'aes':
183 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
184 elif parts[1] == 'aes_hmac':
185 decrypted_data = AESCipher(
186 ENCRYPTION_KEY, hmac=True,
187 strict_verification=enc_strict_mode).decrypt(parts[2])
188 else:
189 raise ValueError(
190 'Encryption type part is wrong, must be `aes` '
191 'or `aes_hmac`, got `%s` instead' % (parts[1]))
192 return decrypted_data
193
194
195 class BaseModel(object):
196 """
197 Base Model for all classes
198 """
199
200 @classmethod
201 def _get_keys(cls):
202 """return column names for this model """
203 return class_mapper(cls).c.keys()
204
205 def get_dict(self):
206 """
207 return dict with keys and values corresponding
208 to this model data """
209
210 d = {}
211 for k in self._get_keys():
212 d[k] = getattr(self, k)
213
214 # also use __json__() if present to get additional fields
215 _json_attr = getattr(self, '__json__', None)
216 if _json_attr:
217 # update with attributes from __json__
218 if callable(_json_attr):
219 _json_attr = _json_attr()
220 for k, val in _json_attr.iteritems():
221 d[k] = val
222 return d
223
224 def get_appstruct(self):
225 """return list with keys and values tuples corresponding
226 to this model data """
227
228 lst = []
229 for k in self._get_keys():
230 lst.append((k, getattr(self, k),))
231 return lst
232
233 def populate_obj(self, populate_dict):
234 """populate model with data from given populate_dict"""
235
236 for k in self._get_keys():
237 if k in populate_dict:
238 setattr(self, k, populate_dict[k])
239
240 @classmethod
241 def query(cls):
242 return Session().query(cls)
243
244 @classmethod
245 def get(cls, id_):
246 if id_:
247 return cls.query().get(id_)
248
249 @classmethod
250 def get_or_404(cls, id_):
251 from pyramid.httpexceptions import HTTPNotFound
252
253 try:
254 id_ = int(id_)
255 except (TypeError, ValueError):
256 raise HTTPNotFound()
257
258 res = cls.query().get(id_)
259 if not res:
260 raise HTTPNotFound()
261 return res
262
263 @classmethod
264 def getAll(cls):
265 # deprecated and left for backward compatibility
266 return cls.get_all()
267
268 @classmethod
269 def get_all(cls):
270 return cls.query().all()
271
272 @classmethod
273 def delete(cls, id_):
274 obj = cls.query().get(id_)
275 Session().delete(obj)
276
277 @classmethod
278 def identity_cache(cls, session, attr_name, value):
279 exist_in_session = []
280 for (item_cls, pkey), instance in session.identity_map.items():
281 if cls == item_cls and getattr(instance, attr_name) == value:
282 exist_in_session.append(instance)
283 if exist_in_session:
284 if len(exist_in_session) == 1:
285 return exist_in_session[0]
286 log.exception(
287 'multiple objects with attr %s and '
288 'value %s found with same name: %r',
289 attr_name, value, exist_in_session)
290
291 def __repr__(self):
292 if hasattr(self, '__unicode__'):
293 # python repr needs to return str
294 try:
295 return safe_str(self.__unicode__())
296 except UnicodeDecodeError:
297 pass
298 return '<DB:%s>' % (self.__class__.__name__)
299
300
301 class RhodeCodeSetting(Base, BaseModel):
302 __tablename__ = 'rhodecode_settings'
303 __table_args__ = (
304 UniqueConstraint('app_settings_name'),
305 {'extend_existing': True, 'mysql_engine': 'InnoDB',
306 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
307 )
308
309 SETTINGS_TYPES = {
310 'str': safe_str,
311 'int': safe_int,
312 'unicode': safe_unicode,
313 'bool': str2bool,
314 'list': functools.partial(aslist, sep=',')
315 }
316 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
317 GLOBAL_CONF_KEY = 'app_settings'
318
319 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
320 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
321 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
322 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
323
324 def __init__(self, key='', val='', type='unicode'):
325 self.app_settings_name = key
326 self.app_settings_type = type
327 self.app_settings_value = val
328
329 @validates('_app_settings_value')
330 def validate_settings_value(self, key, val):
331 assert type(val) == unicode
332 return val
333
334 @hybrid_property
335 def app_settings_value(self):
336 v = self._app_settings_value
337 _type = self.app_settings_type
338 if _type:
339 _type = self.app_settings_type.split('.')[0]
340 # decode the encrypted value
341 if 'encrypted' in self.app_settings_type:
342 cipher = EncryptedTextValue()
343 v = safe_unicode(cipher.process_result_value(v, None))
344
345 converter = self.SETTINGS_TYPES.get(_type) or \
346 self.SETTINGS_TYPES['unicode']
347 return converter(v)
348
349 @app_settings_value.setter
350 def app_settings_value(self, val):
351 """
352 Setter that will always make sure we use unicode in app_settings_value
353
354 :param val:
355 """
356 val = safe_unicode(val)
357 # encode the encrypted value
358 if 'encrypted' in self.app_settings_type:
359 cipher = EncryptedTextValue()
360 val = safe_unicode(cipher.process_bind_param(val, None))
361 self._app_settings_value = val
362
363 @hybrid_property
364 def app_settings_type(self):
365 return self._app_settings_type
366
367 @app_settings_type.setter
368 def app_settings_type(self, val):
369 if val.split('.')[0] not in self.SETTINGS_TYPES:
370 raise Exception('type must be one of %s got %s'
371 % (self.SETTINGS_TYPES.keys(), val))
372 self._app_settings_type = val
373
374 def __unicode__(self):
375 return u"<%s('%s:%s[%s]')>" % (
376 self.__class__.__name__,
377 self.app_settings_name, self.app_settings_value,
378 self.app_settings_type
379 )
380
381
382 class RhodeCodeUi(Base, BaseModel):
383 __tablename__ = 'rhodecode_ui'
384 __table_args__ = (
385 UniqueConstraint('ui_key'),
386 {'extend_existing': True, 'mysql_engine': 'InnoDB',
387 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
388 )
389
390 HOOK_REPO_SIZE = 'changegroup.repo_size'
391 # HG
392 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
393 HOOK_PULL = 'outgoing.pull_logger'
394 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
395 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
396 HOOK_PUSH = 'changegroup.push_logger'
397 HOOK_PUSH_KEY = 'pushkey.key_push'
398
399 # TODO: johbo: Unify way how hooks are configured for git and hg,
400 # git part is currently hardcoded.
401
402 # SVN PATTERNS
403 SVN_BRANCH_ID = 'vcs_svn_branch'
404 SVN_TAG_ID = 'vcs_svn_tag'
405
406 ui_id = Column(
407 "ui_id", Integer(), nullable=False, unique=True, default=None,
408 primary_key=True)
409 ui_section = Column(
410 "ui_section", String(255), nullable=True, unique=None, default=None)
411 ui_key = Column(
412 "ui_key", String(255), nullable=True, unique=None, default=None)
413 ui_value = Column(
414 "ui_value", String(255), nullable=True, unique=None, default=None)
415 ui_active = Column(
416 "ui_active", Boolean(), nullable=True, unique=None, default=True)
417
418 def __repr__(self):
419 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
420 self.ui_key, self.ui_value)
421
422
423 class RepoRhodeCodeSetting(Base, BaseModel):
424 __tablename__ = 'repo_rhodecode_settings'
425 __table_args__ = (
426 UniqueConstraint(
427 'app_settings_name', 'repository_id',
428 name='uq_repo_rhodecode_setting_name_repo_id'),
429 {'extend_existing': True, 'mysql_engine': 'InnoDB',
430 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
431 )
432
433 repository_id = Column(
434 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
435 nullable=False)
436 app_settings_id = Column(
437 "app_settings_id", Integer(), nullable=False, unique=True,
438 default=None, primary_key=True)
439 app_settings_name = Column(
440 "app_settings_name", String(255), nullable=True, unique=None,
441 default=None)
442 _app_settings_value = Column(
443 "app_settings_value", String(4096), nullable=True, unique=None,
444 default=None)
445 _app_settings_type = Column(
446 "app_settings_type", String(255), nullable=True, unique=None,
447 default=None)
448
449 repository = relationship('Repository')
450
451 def __init__(self, repository_id, key='', val='', type='unicode'):
452 self.repository_id = repository_id
453 self.app_settings_name = key
454 self.app_settings_type = type
455 self.app_settings_value = val
456
457 @validates('_app_settings_value')
458 def validate_settings_value(self, key, val):
459 assert type(val) == unicode
460 return val
461
462 @hybrid_property
463 def app_settings_value(self):
464 v = self._app_settings_value
465 type_ = self.app_settings_type
466 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
467 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
468 return converter(v)
469
470 @app_settings_value.setter
471 def app_settings_value(self, val):
472 """
473 Setter that will always make sure we use unicode in app_settings_value
474
475 :param val:
476 """
477 self._app_settings_value = safe_unicode(val)
478
479 @hybrid_property
480 def app_settings_type(self):
481 return self._app_settings_type
482
483 @app_settings_type.setter
484 def app_settings_type(self, val):
485 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
486 if val not in SETTINGS_TYPES:
487 raise Exception('type must be one of %s got %s'
488 % (SETTINGS_TYPES.keys(), val))
489 self._app_settings_type = val
490
491 def __unicode__(self):
492 return u"<%s('%s:%s:%s[%s]')>" % (
493 self.__class__.__name__, self.repository.repo_name,
494 self.app_settings_name, self.app_settings_value,
495 self.app_settings_type
496 )
497
498
499 class RepoRhodeCodeUi(Base, BaseModel):
500 __tablename__ = 'repo_rhodecode_ui'
501 __table_args__ = (
502 UniqueConstraint(
503 'repository_id', 'ui_section', 'ui_key',
504 name='uq_repo_rhodecode_ui_repository_id_section_key'),
505 {'extend_existing': True, 'mysql_engine': 'InnoDB',
506 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
507 )
508
509 repository_id = Column(
510 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
511 nullable=False)
512 ui_id = Column(
513 "ui_id", Integer(), nullable=False, unique=True, default=None,
514 primary_key=True)
515 ui_section = Column(
516 "ui_section", String(255), nullable=True, unique=None, default=None)
517 ui_key = Column(
518 "ui_key", String(255), nullable=True, unique=None, default=None)
519 ui_value = Column(
520 "ui_value", String(255), nullable=True, unique=None, default=None)
521 ui_active = Column(
522 "ui_active", Boolean(), nullable=True, unique=None, default=True)
523
524 repository = relationship('Repository')
525
526 def __repr__(self):
527 return '<%s[%s:%s]%s=>%s]>' % (
528 self.__class__.__name__, self.repository.repo_name,
529 self.ui_section, self.ui_key, self.ui_value)
530
531
532 class User(Base, BaseModel):
533 __tablename__ = 'users'
534 __table_args__ = (
535 UniqueConstraint('username'), UniqueConstraint('email'),
536 Index('u_username_idx', 'username'),
537 Index('u_email_idx', 'email'),
538 {'extend_existing': True, 'mysql_engine': 'InnoDB',
539 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
540 )
541 DEFAULT_USER = 'default'
542 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
543 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
544
545 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
546 username = Column("username", String(255), nullable=True, unique=None, default=None)
547 password = Column("password", String(255), nullable=True, unique=None, default=None)
548 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
549 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
550 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
551 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
552 _email = Column("email", String(255), nullable=True, unique=None, default=None)
553 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
554 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
555
556 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
557 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
558 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
559 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
560 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
561 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
562
563 user_log = relationship('UserLog')
564 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
565
566 repositories = relationship('Repository')
567 repository_groups = relationship('RepoGroup')
568 user_groups = relationship('UserGroup')
569
570 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
571 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
572
573 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
574 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
575 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
576
577 group_member = relationship('UserGroupMember', cascade='all')
578
579 notifications = relationship('UserNotification', cascade='all')
580 # notifications assigned to this user
581 user_created_notifications = relationship('Notification', cascade='all')
582 # comments created by this user
583 user_comments = relationship('ChangesetComment', cascade='all')
584 # user profile extra info
585 user_emails = relationship('UserEmailMap', cascade='all')
586 user_ip_map = relationship('UserIpMap', cascade='all')
587 user_auth_tokens = relationship('UserApiKeys', cascade='all')
588 user_ssh_keys = relationship('UserSshKeys', cascade='all')
589
590 # gists
591 user_gists = relationship('Gist', cascade='all')
592 # user pull requests
593 user_pull_requests = relationship('PullRequest', cascade='all')
594 # external identities
595 extenal_identities = relationship(
596 'ExternalIdentity',
597 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
598 cascade='all')
599 # review rules
600 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
601
602 def __unicode__(self):
603 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
604 self.user_id, self.username)
605
606 @hybrid_property
607 def email(self):
608 return self._email
609
610 @email.setter
611 def email(self, val):
612 self._email = val.lower() if val else None
613
614 @hybrid_property
615 def first_name(self):
616 from rhodecode.lib import helpers as h
617 if self.name:
618 return h.escape(self.name)
619 return self.name
620
621 @hybrid_property
622 def last_name(self):
623 from rhodecode.lib import helpers as h
624 if self.lastname:
625 return h.escape(self.lastname)
626 return self.lastname
627
628 @hybrid_property
629 def api_key(self):
630 """
631 Fetch if exist an auth-token with role ALL connected to this user
632 """
633 user_auth_token = UserApiKeys.query()\
634 .filter(UserApiKeys.user_id == self.user_id)\
635 .filter(or_(UserApiKeys.expires == -1,
636 UserApiKeys.expires >= time.time()))\
637 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
638 if user_auth_token:
639 user_auth_token = user_auth_token.api_key
640
641 return user_auth_token
642
643 @api_key.setter
644 def api_key(self, val):
645 # don't allow to set API key this is deprecated for now
646 self._api_key = None
647
648 @property
649 def reviewer_pull_requests(self):
650 return PullRequestReviewers.query() \
651 .options(joinedload(PullRequestReviewers.pull_request)) \
652 .filter(PullRequestReviewers.user_id == self.user_id) \
653 .all()
654
655 @property
656 def firstname(self):
657 # alias for future
658 return self.name
659
660 @property
661 def emails(self):
662 other = UserEmailMap.query()\
663 .filter(UserEmailMap.user == self) \
664 .order_by(UserEmailMap.email_id.asc()) \
665 .all()
666 return [self.email] + [x.email for x in other]
667
668 @property
669 def auth_tokens(self):
670 auth_tokens = self.get_auth_tokens()
671 return [x.api_key for x in auth_tokens]
672
673 def get_auth_tokens(self):
674 return UserApiKeys.query()\
675 .filter(UserApiKeys.user == self)\
676 .order_by(UserApiKeys.user_api_key_id.asc())\
677 .all()
678
679 @LazyProperty
680 def feed_token(self):
681 return self.get_feed_token()
682
683 def get_feed_token(self, cache=True):
684 feed_tokens = UserApiKeys.query()\
685 .filter(UserApiKeys.user == self)\
686 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
687 if cache:
688 feed_tokens = feed_tokens.options(
689 FromCache("long_term", "get_user_feed_token_%s" % self.user_id))
690
691 feed_tokens = feed_tokens.all()
692 if feed_tokens:
693 return feed_tokens[0].api_key
694 return 'NO_FEED_TOKEN_AVAILABLE'
695
696 @classmethod
697 def get(cls, user_id, cache=False):
698 if not user_id:
699 return
700
701 user = cls.query()
702 if cache:
703 user = user.options(
704 FromCache("sql_cache_short", "get_users_%s" % user_id))
705 return user.get(user_id)
706
707 @classmethod
708 def extra_valid_auth_tokens(cls, user, role=None):
709 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
710 .filter(or_(UserApiKeys.expires == -1,
711 UserApiKeys.expires >= time.time()))
712 if role:
713 tokens = tokens.filter(or_(UserApiKeys.role == role,
714 UserApiKeys.role == UserApiKeys.ROLE_ALL))
715 return tokens.all()
716
717 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
718 from rhodecode.lib import auth
719
720 log.debug('Trying to authenticate user: %s via auth-token, '
721 'and roles: %s', self, roles)
722
723 if not auth_token:
724 return False
725
726 crypto_backend = auth.crypto_backend()
727
728 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
729 tokens_q = UserApiKeys.query()\
730 .filter(UserApiKeys.user_id == self.user_id)\
731 .filter(or_(UserApiKeys.expires == -1,
732 UserApiKeys.expires >= time.time()))
733
734 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
735
736 plain_tokens = []
737 hash_tokens = []
738
739 for token in tokens_q.all():
740 # verify scope first
741 if token.repo_id:
742 # token has a scope, we need to verify it
743 if scope_repo_id != token.repo_id:
744 log.debug(
745 'Scope mismatch: token has a set repo scope: %s, '
746 'and calling scope is:%s, skipping further checks',
747 token.repo, scope_repo_id)
748 # token has a scope, and it doesn't match, skip token
749 continue
750
751 if token.api_key.startswith(crypto_backend.ENC_PREF):
752 hash_tokens.append(token.api_key)
753 else:
754 plain_tokens.append(token.api_key)
755
756 is_plain_match = auth_token in plain_tokens
757 if is_plain_match:
758 return True
759
760 for hashed in hash_tokens:
761 # TODO(marcink): this is expensive to calculate, but most secure
762 match = crypto_backend.hash_check(auth_token, hashed)
763 if match:
764 return True
765
766 return False
767
768 @property
769 def ip_addresses(self):
770 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
771 return [x.ip_addr for x in ret]
772
773 @property
774 def username_and_name(self):
775 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
776
777 @property
778 def username_or_name_or_email(self):
779 full_name = self.full_name if self.full_name is not ' ' else None
780 return self.username or full_name or self.email
781
782 @property
783 def full_name(self):
784 return '%s %s' % (self.first_name, self.last_name)
785
786 @property
787 def full_name_or_username(self):
788 return ('%s %s' % (self.first_name, self.last_name)
789 if (self.first_name and self.last_name) else self.username)
790
791 @property
792 def full_contact(self):
793 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
794
795 @property
796 def short_contact(self):
797 return '%s %s' % (self.first_name, self.last_name)
798
799 @property
800 def is_admin(self):
801 return self.admin
802
803 def AuthUser(self, **kwargs):
804 """
805 Returns instance of AuthUser for this user
806 """
807 from rhodecode.lib.auth import AuthUser
808 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
809
810 @hybrid_property
811 def user_data(self):
812 if not self._user_data:
813 return {}
814
815 try:
816 return json.loads(self._user_data)
817 except TypeError:
818 return {}
819
820 @user_data.setter
821 def user_data(self, val):
822 if not isinstance(val, dict):
823 raise Exception('user_data must be dict, got %s' % type(val))
824 try:
825 self._user_data = json.dumps(val)
826 except Exception:
827 log.error(traceback.format_exc())
828
829 @classmethod
830 def get_by_username(cls, username, case_insensitive=False,
831 cache=False, identity_cache=False):
832 session = Session()
833
834 if case_insensitive:
835 q = cls.query().filter(
836 func.lower(cls.username) == func.lower(username))
837 else:
838 q = cls.query().filter(cls.username == username)
839
840 if cache:
841 if identity_cache:
842 val = cls.identity_cache(session, 'username', username)
843 if val:
844 return val
845 else:
846 cache_key = "get_user_by_name_%s" % _hash_key(username)
847 q = q.options(
848 FromCache("sql_cache_short", cache_key))
849
850 return q.scalar()
851
852 @classmethod
853 def get_by_auth_token(cls, auth_token, cache=False):
854 q = UserApiKeys.query()\
855 .filter(UserApiKeys.api_key == auth_token)\
856 .filter(or_(UserApiKeys.expires == -1,
857 UserApiKeys.expires >= time.time()))
858 if cache:
859 q = q.options(
860 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
861
862 match = q.first()
863 if match:
864 return match.user
865
866 @classmethod
867 def get_by_email(cls, email, case_insensitive=False, cache=False):
868
869 if case_insensitive:
870 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
871
872 else:
873 q = cls.query().filter(cls.email == email)
874
875 email_key = _hash_key(email)
876 if cache:
877 q = q.options(
878 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
879
880 ret = q.scalar()
881 if ret is None:
882 q = UserEmailMap.query()
883 # try fetching in alternate email map
884 if case_insensitive:
885 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
886 else:
887 q = q.filter(UserEmailMap.email == email)
888 q = q.options(joinedload(UserEmailMap.user))
889 if cache:
890 q = q.options(
891 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
892 ret = getattr(q.scalar(), 'user', None)
893
894 return ret
895
896 @classmethod
897 def get_from_cs_author(cls, author):
898 """
899 Tries to get User objects out of commit author string
900
901 :param author:
902 """
903 from rhodecode.lib.helpers import email, author_name
904 # Valid email in the attribute passed, see if they're in the system
905 _email = email(author)
906 if _email:
907 user = cls.get_by_email(_email, case_insensitive=True)
908 if user:
909 return user
910 # Maybe we can match by username?
911 _author = author_name(author)
912 user = cls.get_by_username(_author, case_insensitive=True)
913 if user:
914 return user
915
916 def update_userdata(self, **kwargs):
917 usr = self
918 old = usr.user_data
919 old.update(**kwargs)
920 usr.user_data = old
921 Session().add(usr)
922 log.debug('updated userdata with ', kwargs)
923
924 def update_lastlogin(self):
925 """Update user lastlogin"""
926 self.last_login = datetime.datetime.now()
927 Session().add(self)
928 log.debug('updated user %s lastlogin', self.username)
929
930 def update_lastactivity(self):
931 """Update user lastactivity"""
932 self.last_activity = datetime.datetime.now()
933 Session().add(self)
934 log.debug('updated user `%s` last activity', self.username)
935
936 def update_password(self, new_password):
937 from rhodecode.lib.auth import get_crypt_password
938
939 self.password = get_crypt_password(new_password)
940 Session().add(self)
941
942 @classmethod
943 def get_first_super_admin(cls):
944 user = User.query().filter(User.admin == true()).first()
945 if user is None:
946 raise Exception('FATAL: Missing administrative account!')
947 return user
948
949 @classmethod
950 def get_all_super_admins(cls):
951 """
952 Returns all admin accounts sorted by username
953 """
954 return User.query().filter(User.admin == true())\
955 .order_by(User.username.asc()).all()
956
957 @classmethod
958 def get_default_user(cls, cache=False, refresh=False):
959 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
960 if user is None:
961 raise Exception('FATAL: Missing default account!')
962 if refresh:
963 # The default user might be based on outdated state which
964 # has been loaded from the cache.
965 # A call to refresh() ensures that the
966 # latest state from the database is used.
967 Session().refresh(user)
968 return user
969
970 def _get_default_perms(self, user, suffix=''):
971 from rhodecode.model.permission import PermissionModel
972 return PermissionModel().get_default_perms(user.user_perms, suffix)
973
974 def get_default_perms(self, suffix=''):
975 return self._get_default_perms(self, suffix)
976
977 def get_api_data(self, include_secrets=False, details='full'):
978 """
979 Common function for generating user related data for API
980
981 :param include_secrets: By default secrets in the API data will be replaced
982 by a placeholder value to prevent exposing this data by accident. In case
983 this data shall be exposed, set this flag to ``True``.
984
985 :param details: details can be 'basic|full' basic gives only a subset of
986 the available user information that includes user_id, name and emails.
987 """
988 user = self
989 user_data = self.user_data
990 data = {
991 'user_id': user.user_id,
992 'username': user.username,
993 'firstname': user.name,
994 'lastname': user.lastname,
995 'email': user.email,
996 'emails': user.emails,
997 }
998 if details == 'basic':
999 return data
1000
1001 auth_token_length = 40
1002 auth_token_replacement = '*' * auth_token_length
1003
1004 extras = {
1005 'auth_tokens': [auth_token_replacement],
1006 'active': user.active,
1007 'admin': user.admin,
1008 'extern_type': user.extern_type,
1009 'extern_name': user.extern_name,
1010 'last_login': user.last_login,
1011 'last_activity': user.last_activity,
1012 'ip_addresses': user.ip_addresses,
1013 'language': user_data.get('language')
1014 }
1015 data.update(extras)
1016
1017 if include_secrets:
1018 data['auth_tokens'] = user.auth_tokens
1019 return data
1020
1021 def __json__(self):
1022 data = {
1023 'full_name': self.full_name,
1024 'full_name_or_username': self.full_name_or_username,
1025 'short_contact': self.short_contact,
1026 'full_contact': self.full_contact,
1027 }
1028 data.update(self.get_api_data())
1029 return data
1030
1031
1032 class UserApiKeys(Base, BaseModel):
1033 __tablename__ = 'user_api_keys'
1034 __table_args__ = (
1035 Index('uak_api_key_idx', 'api_key', unique=True),
1036 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1037 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1038 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1039 )
1040 __mapper_args__ = {}
1041
1042 # ApiKey role
1043 ROLE_ALL = 'token_role_all'
1044 ROLE_HTTP = 'token_role_http'
1045 ROLE_VCS = 'token_role_vcs'
1046 ROLE_API = 'token_role_api'
1047 ROLE_FEED = 'token_role_feed'
1048 ROLE_PASSWORD_RESET = 'token_password_reset'
1049
1050 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
1051
1052 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1053 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1054 api_key = Column("api_key", String(255), nullable=False, unique=True)
1055 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1056 expires = Column('expires', Float(53), nullable=False)
1057 role = Column('role', String(255), nullable=True)
1058 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1059
1060 # scope columns
1061 repo_id = Column(
1062 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1063 nullable=True, unique=None, default=None)
1064 repo = relationship('Repository', lazy='joined')
1065
1066 repo_group_id = Column(
1067 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1068 nullable=True, unique=None, default=None)
1069 repo_group = relationship('RepoGroup', lazy='joined')
1070
1071 user = relationship('User', lazy='joined')
1072
1073 def __unicode__(self):
1074 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1075
1076 def __json__(self):
1077 data = {
1078 'auth_token': self.api_key,
1079 'role': self.role,
1080 'scope': self.scope_humanized,
1081 'expired': self.expired
1082 }
1083 return data
1084
1085 def get_api_data(self, include_secrets=False):
1086 data = self.__json__()
1087 if include_secrets:
1088 return data
1089 else:
1090 data['auth_token'] = self.token_obfuscated
1091 return data
1092
1093 @hybrid_property
1094 def description_safe(self):
1095 from rhodecode.lib import helpers as h
1096 return h.escape(self.description)
1097
1098 @property
1099 def expired(self):
1100 if self.expires == -1:
1101 return False
1102 return time.time() > self.expires
1103
1104 @classmethod
1105 def _get_role_name(cls, role):
1106 return {
1107 cls.ROLE_ALL: _('all'),
1108 cls.ROLE_HTTP: _('http/web interface'),
1109 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1110 cls.ROLE_API: _('api calls'),
1111 cls.ROLE_FEED: _('feed access'),
1112 }.get(role, role)
1113
1114 @property
1115 def role_humanized(self):
1116 return self._get_role_name(self.role)
1117
1118 def _get_scope(self):
1119 if self.repo:
1120 return repr(self.repo)
1121 if self.repo_group:
1122 return repr(self.repo_group) + ' (recursive)'
1123 return 'global'
1124
1125 @property
1126 def scope_humanized(self):
1127 return self._get_scope()
1128
1129 @property
1130 def token_obfuscated(self):
1131 if self.api_key:
1132 return self.api_key[:4] + "****"
1133
1134
1135 class UserEmailMap(Base, BaseModel):
1136 __tablename__ = 'user_email_map'
1137 __table_args__ = (
1138 Index('uem_email_idx', 'email'),
1139 UniqueConstraint('email'),
1140 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1141 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1142 )
1143 __mapper_args__ = {}
1144
1145 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1146 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1147 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1148 user = relationship('User', lazy='joined')
1149
1150 @validates('_email')
1151 def validate_email(self, key, email):
1152 # check if this email is not main one
1153 main_email = Session().query(User).filter(User.email == email).scalar()
1154 if main_email is not None:
1155 raise AttributeError('email %s is present is user table' % email)
1156 return email
1157
1158 @hybrid_property
1159 def email(self):
1160 return self._email
1161
1162 @email.setter
1163 def email(self, val):
1164 self._email = val.lower() if val else None
1165
1166
1167 class UserIpMap(Base, BaseModel):
1168 __tablename__ = 'user_ip_map'
1169 __table_args__ = (
1170 UniqueConstraint('user_id', 'ip_addr'),
1171 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1172 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1173 )
1174 __mapper_args__ = {}
1175
1176 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1177 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1178 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1179 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1180 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1181 user = relationship('User', lazy='joined')
1182
1183 @hybrid_property
1184 def description_safe(self):
1185 from rhodecode.lib import helpers as h
1186 return h.escape(self.description)
1187
1188 @classmethod
1189 def _get_ip_range(cls, ip_addr):
1190 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1191 return [str(net.network_address), str(net.broadcast_address)]
1192
1193 def __json__(self):
1194 return {
1195 'ip_addr': self.ip_addr,
1196 'ip_range': self._get_ip_range(self.ip_addr),
1197 }
1198
1199 def __unicode__(self):
1200 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1201 self.user_id, self.ip_addr)
1202
1203
1204 class UserSshKeys(Base, BaseModel):
1205 __tablename__ = 'user_ssh_keys'
1206 __table_args__ = (
1207 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1208
1209 UniqueConstraint('ssh_key_fingerprint'),
1210
1211 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1212 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1213 )
1214 __mapper_args__ = {}
1215
1216 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1217 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1218 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1219
1220 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1221
1222 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1223 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1224 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1225
1226 user = relationship('User', lazy='joined')
1227
1228 def __json__(self):
1229 data = {
1230 'ssh_fingerprint': self.ssh_key_fingerprint,
1231 'description': self.description,
1232 'created_on': self.created_on
1233 }
1234 return data
1235
1236 def get_api_data(self):
1237 data = self.__json__()
1238 return data
1239
1240
1241 class UserLog(Base, BaseModel):
1242 __tablename__ = 'user_logs'
1243 __table_args__ = (
1244 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1245 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1246 )
1247 VERSION_1 = 'v1'
1248 VERSION_2 = 'v2'
1249 VERSIONS = [VERSION_1, VERSION_2]
1250
1251 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1252 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1253 username = Column("username", String(255), nullable=True, unique=None, default=None)
1254 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1255 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1256 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1257 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1258 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1259
1260 version = Column("version", String(255), nullable=True, default=VERSION_1)
1261 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1262 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1263
1264 def __unicode__(self):
1265 return u"<%s('id:%s:%s')>" % (
1266 self.__class__.__name__, self.repository_name, self.action)
1267
1268 def __json__(self):
1269 return {
1270 'user_id': self.user_id,
1271 'username': self.username,
1272 'repository_id': self.repository_id,
1273 'repository_name': self.repository_name,
1274 'user_ip': self.user_ip,
1275 'action_date': self.action_date,
1276 'action': self.action,
1277 }
1278
1279 @hybrid_property
1280 def entry_id(self):
1281 return self.user_log_id
1282
1283 @property
1284 def action_as_day(self):
1285 return datetime.date(*self.action_date.timetuple()[:3])
1286
1287 user = relationship('User')
1288 repository = relationship('Repository', cascade='')
1289
1290
1291 class UserGroup(Base, BaseModel):
1292 __tablename__ = 'users_groups'
1293 __table_args__ = (
1294 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1295 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1296 )
1297
1298 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1299 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1300 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1301 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1302 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1303 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1304 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1305 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1306
1307 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1308 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1309 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1310 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1311 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1312 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1313
1314 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1315 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1316
1317 @classmethod
1318 def _load_group_data(cls, column):
1319 if not column:
1320 return {}
1321
1322 try:
1323 return json.loads(column) or {}
1324 except TypeError:
1325 return {}
1326
1327 @hybrid_property
1328 def description_safe(self):
1329 from rhodecode.lib import helpers as h
1330 return h.escape(self.user_group_description)
1331
1332 @hybrid_property
1333 def group_data(self):
1334 return self._load_group_data(self._group_data)
1335
1336 @group_data.expression
1337 def group_data(self, **kwargs):
1338 return self._group_data
1339
1340 @group_data.setter
1341 def group_data(self, val):
1342 try:
1343 self._group_data = json.dumps(val)
1344 except Exception:
1345 log.error(traceback.format_exc())
1346
1347 @classmethod
1348 def _load_sync(cls, group_data):
1349 if group_data:
1350 return group_data.get('extern_type')
1351
1352 @property
1353 def sync(self):
1354 return self._load_sync(self.group_data)
1355
1356 def __unicode__(self):
1357 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1358 self.users_group_id,
1359 self.users_group_name)
1360
1361 @classmethod
1362 def get_by_group_name(cls, group_name, cache=False,
1363 case_insensitive=False):
1364 if case_insensitive:
1365 q = cls.query().filter(func.lower(cls.users_group_name) ==
1366 func.lower(group_name))
1367
1368 else:
1369 q = cls.query().filter(cls.users_group_name == group_name)
1370 if cache:
1371 q = q.options(
1372 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1373 return q.scalar()
1374
1375 @classmethod
1376 def get(cls, user_group_id, cache=False):
1377 if not user_group_id:
1378 return
1379
1380 user_group = cls.query()
1381 if cache:
1382 user_group = user_group.options(
1383 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1384 return user_group.get(user_group_id)
1385
1386 def permissions(self, with_admins=True, with_owner=True):
1387 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1388 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1389 joinedload(UserUserGroupToPerm.user),
1390 joinedload(UserUserGroupToPerm.permission),)
1391
1392 # get owners and admins and permissions. We do a trick of re-writing
1393 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1394 # has a global reference and changing one object propagates to all
1395 # others. This means if admin is also an owner admin_row that change
1396 # would propagate to both objects
1397 perm_rows = []
1398 for _usr in q.all():
1399 usr = AttributeDict(_usr.user.get_dict())
1400 usr.permission = _usr.permission.permission_name
1401 perm_rows.append(usr)
1402
1403 # filter the perm rows by 'default' first and then sort them by
1404 # admin,write,read,none permissions sorted again alphabetically in
1405 # each group
1406 perm_rows = sorted(perm_rows, key=display_user_sort)
1407
1408 _admin_perm = 'usergroup.admin'
1409 owner_row = []
1410 if with_owner:
1411 usr = AttributeDict(self.user.get_dict())
1412 usr.owner_row = True
1413 usr.permission = _admin_perm
1414 owner_row.append(usr)
1415
1416 super_admin_rows = []
1417 if with_admins:
1418 for usr in User.get_all_super_admins():
1419 # if this admin is also owner, don't double the record
1420 if usr.user_id == owner_row[0].user_id:
1421 owner_row[0].admin_row = True
1422 else:
1423 usr = AttributeDict(usr.get_dict())
1424 usr.admin_row = True
1425 usr.permission = _admin_perm
1426 super_admin_rows.append(usr)
1427
1428 return super_admin_rows + owner_row + perm_rows
1429
1430 def permission_user_groups(self):
1431 q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self)
1432 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1433 joinedload(UserGroupUserGroupToPerm.target_user_group),
1434 joinedload(UserGroupUserGroupToPerm.permission),)
1435
1436 perm_rows = []
1437 for _user_group in q.all():
1438 usr = AttributeDict(_user_group.user_group.get_dict())
1439 usr.permission = _user_group.permission.permission_name
1440 perm_rows.append(usr)
1441
1442 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1443 return perm_rows
1444
1445 def _get_default_perms(self, user_group, suffix=''):
1446 from rhodecode.model.permission import PermissionModel
1447 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1448
1449 def get_default_perms(self, suffix=''):
1450 return self._get_default_perms(self, suffix)
1451
1452 def get_api_data(self, with_group_members=True, include_secrets=False):
1453 """
1454 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1455 basically forwarded.
1456
1457 """
1458 user_group = self
1459 data = {
1460 'users_group_id': user_group.users_group_id,
1461 'group_name': user_group.users_group_name,
1462 'group_description': user_group.user_group_description,
1463 'active': user_group.users_group_active,
1464 'owner': user_group.user.username,
1465 'sync': user_group.sync,
1466 'owner_email': user_group.user.email,
1467 }
1468
1469 if with_group_members:
1470 users = []
1471 for user in user_group.members:
1472 user = user.user
1473 users.append(user.get_api_data(include_secrets=include_secrets))
1474 data['users'] = users
1475
1476 return data
1477
1478
1479 class UserGroupMember(Base, BaseModel):
1480 __tablename__ = 'users_groups_members'
1481 __table_args__ = (
1482 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1483 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1484 )
1485
1486 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1487 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1488 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1489
1490 user = relationship('User', lazy='joined')
1491 users_group = relationship('UserGroup')
1492
1493 def __init__(self, gr_id='', u_id=''):
1494 self.users_group_id = gr_id
1495 self.user_id = u_id
1496
1497
1498 class RepositoryField(Base, BaseModel):
1499 __tablename__ = 'repositories_fields'
1500 __table_args__ = (
1501 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1502 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1503 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1504 )
1505 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1506
1507 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1508 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1509 field_key = Column("field_key", String(250))
1510 field_label = Column("field_label", String(1024), nullable=False)
1511 field_value = Column("field_value", String(10000), nullable=False)
1512 field_desc = Column("field_desc", String(1024), nullable=False)
1513 field_type = Column("field_type", String(255), nullable=False, unique=None)
1514 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1515
1516 repository = relationship('Repository')
1517
1518 @property
1519 def field_key_prefixed(self):
1520 return 'ex_%s' % self.field_key
1521
1522 @classmethod
1523 def un_prefix_key(cls, key):
1524 if key.startswith(cls.PREFIX):
1525 return key[len(cls.PREFIX):]
1526 return key
1527
1528 @classmethod
1529 def get_by_key_name(cls, key, repo):
1530 row = cls.query()\
1531 .filter(cls.repository == repo)\
1532 .filter(cls.field_key == key).scalar()
1533 return row
1534
1535
1536 class Repository(Base, BaseModel):
1537 __tablename__ = 'repositories'
1538 __table_args__ = (
1539 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1540 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1541 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1542 )
1543 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1544 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1545 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1546
1547 STATE_CREATED = 'repo_state_created'
1548 STATE_PENDING = 'repo_state_pending'
1549 STATE_ERROR = 'repo_state_error'
1550
1551 LOCK_AUTOMATIC = 'lock_auto'
1552 LOCK_API = 'lock_api'
1553 LOCK_WEB = 'lock_web'
1554 LOCK_PULL = 'lock_pull'
1555
1556 NAME_SEP = URL_SEP
1557
1558 repo_id = Column(
1559 "repo_id", Integer(), nullable=False, unique=True, default=None,
1560 primary_key=True)
1561 _repo_name = Column(
1562 "repo_name", Text(), nullable=False, default=None)
1563 _repo_name_hash = Column(
1564 "repo_name_hash", String(255), nullable=False, unique=True)
1565 repo_state = Column("repo_state", String(255), nullable=True)
1566
1567 clone_uri = Column(
1568 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1569 default=None)
1570 push_uri = Column(
1571 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1572 default=None)
1573 repo_type = Column(
1574 "repo_type", String(255), nullable=False, unique=False, default=None)
1575 user_id = Column(
1576 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1577 unique=False, default=None)
1578 private = Column(
1579 "private", Boolean(), nullable=True, unique=None, default=None)
1580 enable_statistics = Column(
1581 "statistics", Boolean(), nullable=True, unique=None, default=True)
1582 enable_downloads = Column(
1583 "downloads", Boolean(), nullable=True, unique=None, default=True)
1584 description = Column(
1585 "description", String(10000), nullable=True, unique=None, default=None)
1586 created_on = Column(
1587 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1588 default=datetime.datetime.now)
1589 updated_on = Column(
1590 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1591 default=datetime.datetime.now)
1592 _landing_revision = Column(
1593 "landing_revision", String(255), nullable=False, unique=False,
1594 default=None)
1595 enable_locking = Column(
1596 "enable_locking", Boolean(), nullable=False, unique=None,
1597 default=False)
1598 _locked = Column(
1599 "locked", String(255), nullable=True, unique=False, default=None)
1600 _changeset_cache = Column(
1601 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1602
1603 fork_id = Column(
1604 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1605 nullable=True, unique=False, default=None)
1606 group_id = Column(
1607 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1608 unique=False, default=None)
1609
1610 user = relationship('User', lazy='joined')
1611 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1612 group = relationship('RepoGroup', lazy='joined')
1613 repo_to_perm = relationship(
1614 'UserRepoToPerm', cascade='all',
1615 order_by='UserRepoToPerm.repo_to_perm_id')
1616 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1617 stats = relationship('Statistics', cascade='all', uselist=False)
1618
1619 followers = relationship(
1620 'UserFollowing',
1621 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1622 cascade='all')
1623 extra_fields = relationship(
1624 'RepositoryField', cascade="all, delete, delete-orphan")
1625 logs = relationship('UserLog')
1626 comments = relationship(
1627 'ChangesetComment', cascade="all, delete, delete-orphan")
1628 pull_requests_source = relationship(
1629 'PullRequest',
1630 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1631 cascade="all, delete, delete-orphan")
1632 pull_requests_target = relationship(
1633 'PullRequest',
1634 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1635 cascade="all, delete, delete-orphan")
1636 ui = relationship('RepoRhodeCodeUi', cascade="all")
1637 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1638 integrations = relationship('Integration',
1639 cascade="all, delete, delete-orphan")
1640
1641 scoped_tokens = relationship('UserApiKeys', cascade="all")
1642
1643 def __unicode__(self):
1644 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1645 safe_unicode(self.repo_name))
1646
1647 @hybrid_property
1648 def description_safe(self):
1649 from rhodecode.lib import helpers as h
1650 return h.escape(self.description)
1651
1652 @hybrid_property
1653 def landing_rev(self):
1654 # always should return [rev_type, rev]
1655 if self._landing_revision:
1656 _rev_info = self._landing_revision.split(':')
1657 if len(_rev_info) < 2:
1658 _rev_info.insert(0, 'rev')
1659 return [_rev_info[0], _rev_info[1]]
1660 return [None, None]
1661
1662 @landing_rev.setter
1663 def landing_rev(self, val):
1664 if ':' not in val:
1665 raise ValueError('value must be delimited with `:` and consist '
1666 'of <rev_type>:<rev>, got %s instead' % val)
1667 self._landing_revision = val
1668
1669 @hybrid_property
1670 def locked(self):
1671 if self._locked:
1672 user_id, timelocked, reason = self._locked.split(':')
1673 lock_values = int(user_id), timelocked, reason
1674 else:
1675 lock_values = [None, None, None]
1676 return lock_values
1677
1678 @locked.setter
1679 def locked(self, val):
1680 if val and isinstance(val, (list, tuple)):
1681 self._locked = ':'.join(map(str, val))
1682 else:
1683 self._locked = None
1684
1685 @hybrid_property
1686 def changeset_cache(self):
1687 from rhodecode.lib.vcs.backends.base import EmptyCommit
1688 dummy = EmptyCommit().__json__()
1689 if not self._changeset_cache:
1690 return dummy
1691 try:
1692 return json.loads(self._changeset_cache)
1693 except TypeError:
1694 return dummy
1695 except Exception:
1696 log.error(traceback.format_exc())
1697 return dummy
1698
1699 @changeset_cache.setter
1700 def changeset_cache(self, val):
1701 try:
1702 self._changeset_cache = json.dumps(val)
1703 except Exception:
1704 log.error(traceback.format_exc())
1705
1706 @hybrid_property
1707 def repo_name(self):
1708 return self._repo_name
1709
1710 @repo_name.setter
1711 def repo_name(self, value):
1712 self._repo_name = value
1713 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1714
1715 @classmethod
1716 def normalize_repo_name(cls, repo_name):
1717 """
1718 Normalizes os specific repo_name to the format internally stored inside
1719 database using URL_SEP
1720
1721 :param cls:
1722 :param repo_name:
1723 """
1724 return cls.NAME_SEP.join(repo_name.split(os.sep))
1725
1726 @classmethod
1727 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1728 session = Session()
1729 q = session.query(cls).filter(cls.repo_name == repo_name)
1730
1731 if cache:
1732 if identity_cache:
1733 val = cls.identity_cache(session, 'repo_name', repo_name)
1734 if val:
1735 return val
1736 else:
1737 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1738 q = q.options(
1739 FromCache("sql_cache_short", cache_key))
1740
1741 return q.scalar()
1742
1743 @classmethod
1744 def get_by_id_or_repo_name(cls, repoid):
1745 if isinstance(repoid, (int, long)):
1746 try:
1747 repo = cls.get(repoid)
1748 except ValueError:
1749 repo = None
1750 else:
1751 repo = cls.get_by_repo_name(repoid)
1752 return repo
1753
1754 @classmethod
1755 def get_by_full_path(cls, repo_full_path):
1756 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1757 repo_name = cls.normalize_repo_name(repo_name)
1758 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1759
1760 @classmethod
1761 def get_repo_forks(cls, repo_id):
1762 return cls.query().filter(Repository.fork_id == repo_id)
1763
1764 @classmethod
1765 def base_path(cls):
1766 """
1767 Returns base path when all repos are stored
1768
1769 :param cls:
1770 """
1771 q = Session().query(RhodeCodeUi)\
1772 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1773 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1774 return q.one().ui_value
1775
1776 @classmethod
1777 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1778 case_insensitive=True):
1779 q = Repository.query()
1780
1781 if not isinstance(user_id, Optional):
1782 q = q.filter(Repository.user_id == user_id)
1783
1784 if not isinstance(group_id, Optional):
1785 q = q.filter(Repository.group_id == group_id)
1786
1787 if case_insensitive:
1788 q = q.order_by(func.lower(Repository.repo_name))
1789 else:
1790 q = q.order_by(Repository.repo_name)
1791 return q.all()
1792
1793 @property
1794 def forks(self):
1795 """
1796 Return forks of this repo
1797 """
1798 return Repository.get_repo_forks(self.repo_id)
1799
1800 @property
1801 def parent(self):
1802 """
1803 Returns fork parent
1804 """
1805 return self.fork
1806
1807 @property
1808 def just_name(self):
1809 return self.repo_name.split(self.NAME_SEP)[-1]
1810
1811 @property
1812 def groups_with_parents(self):
1813 groups = []
1814 if self.group is None:
1815 return groups
1816
1817 cur_gr = self.group
1818 groups.insert(0, cur_gr)
1819 while 1:
1820 gr = getattr(cur_gr, 'parent_group', None)
1821 cur_gr = cur_gr.parent_group
1822 if gr is None:
1823 break
1824 groups.insert(0, gr)
1825
1826 return groups
1827
1828 @property
1829 def groups_and_repo(self):
1830 return self.groups_with_parents, self
1831
1832 @LazyProperty
1833 def repo_path(self):
1834 """
1835 Returns base full path for that repository means where it actually
1836 exists on a filesystem
1837 """
1838 q = Session().query(RhodeCodeUi).filter(
1839 RhodeCodeUi.ui_key == self.NAME_SEP)
1840 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1841 return q.one().ui_value
1842
1843 @property
1844 def repo_full_path(self):
1845 p = [self.repo_path]
1846 # we need to split the name by / since this is how we store the
1847 # names in the database, but that eventually needs to be converted
1848 # into a valid system path
1849 p += self.repo_name.split(self.NAME_SEP)
1850 return os.path.join(*map(safe_unicode, p))
1851
1852 @property
1853 def cache_keys(self):
1854 """
1855 Returns associated cache keys for that repo
1856 """
1857 return CacheKey.query()\
1858 .filter(CacheKey.cache_args == self.repo_name)\
1859 .order_by(CacheKey.cache_key)\
1860 .all()
1861
1862 @property
1863 def cached_diffs_relative_dir(self):
1864 """
1865 Return a relative to the repository store path of cached diffs
1866 used for safe display for users, who shouldn't know the absolute store
1867 path
1868 """
1869 return os.path.join(
1870 os.path.dirname(self.repo_name),
1871 self.cached_diffs_dir.split(os.path.sep)[-1])
1872
1873 @property
1874 def cached_diffs_dir(self):
1875 path = self.repo_full_path
1876 return os.path.join(
1877 os.path.dirname(path),
1878 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
1879
1880 def cached_diffs(self):
1881 diff_cache_dir = self.cached_diffs_dir
1882 if os.path.isdir(diff_cache_dir):
1883 return os.listdir(diff_cache_dir)
1884 return []
1885
1886 def get_new_name(self, repo_name):
1887 """
1888 returns new full repository name based on assigned group and new new
1889
1890 :param group_name:
1891 """
1892 path_prefix = self.group.full_path_splitted if self.group else []
1893 return self.NAME_SEP.join(path_prefix + [repo_name])
1894
1895 @property
1896 def _config(self):
1897 """
1898 Returns db based config object.
1899 """
1900 from rhodecode.lib.utils import make_db_config
1901 return make_db_config(clear_session=False, repo=self)
1902
1903 def permissions(self, with_admins=True, with_owner=True):
1904 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1905 q = q.options(joinedload(UserRepoToPerm.repository),
1906 joinedload(UserRepoToPerm.user),
1907 joinedload(UserRepoToPerm.permission),)
1908
1909 # get owners and admins and permissions. We do a trick of re-writing
1910 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1911 # has a global reference and changing one object propagates to all
1912 # others. This means if admin is also an owner admin_row that change
1913 # would propagate to both objects
1914 perm_rows = []
1915 for _usr in q.all():
1916 usr = AttributeDict(_usr.user.get_dict())
1917 usr.permission = _usr.permission.permission_name
1918 usr.permission_id = _usr.repo_to_perm_id
1919 perm_rows.append(usr)
1920
1921 # filter the perm rows by 'default' first and then sort them by
1922 # admin,write,read,none permissions sorted again alphabetically in
1923 # each group
1924 perm_rows = sorted(perm_rows, key=display_user_sort)
1925
1926 _admin_perm = 'repository.admin'
1927 owner_row = []
1928 if with_owner:
1929 usr = AttributeDict(self.user.get_dict())
1930 usr.owner_row = True
1931 usr.permission = _admin_perm
1932 usr.permission_id = None
1933 owner_row.append(usr)
1934
1935 super_admin_rows = []
1936 if with_admins:
1937 for usr in User.get_all_super_admins():
1938 # if this admin is also owner, don't double the record
1939 if usr.user_id == owner_row[0].user_id:
1940 owner_row[0].admin_row = True
1941 else:
1942 usr = AttributeDict(usr.get_dict())
1943 usr.admin_row = True
1944 usr.permission = _admin_perm
1945 usr.permission_id = None
1946 super_admin_rows.append(usr)
1947
1948 return super_admin_rows + owner_row + perm_rows
1949
1950 def permission_user_groups(self):
1951 q = UserGroupRepoToPerm.query().filter(
1952 UserGroupRepoToPerm.repository == self)
1953 q = q.options(joinedload(UserGroupRepoToPerm.repository),
1954 joinedload(UserGroupRepoToPerm.users_group),
1955 joinedload(UserGroupRepoToPerm.permission),)
1956
1957 perm_rows = []
1958 for _user_group in q.all():
1959 usr = AttributeDict(_user_group.users_group.get_dict())
1960 usr.permission = _user_group.permission.permission_name
1961 perm_rows.append(usr)
1962
1963 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1964 return perm_rows
1965
1966 def get_api_data(self, include_secrets=False):
1967 """
1968 Common function for generating repo api data
1969
1970 :param include_secrets: See :meth:`User.get_api_data`.
1971
1972 """
1973 # TODO: mikhail: Here there is an anti-pattern, we probably need to
1974 # move this methods on models level.
1975 from rhodecode.model.settings import SettingsModel
1976 from rhodecode.model.repo import RepoModel
1977
1978 repo = self
1979 _user_id, _time, _reason = self.locked
1980
1981 data = {
1982 'repo_id': repo.repo_id,
1983 'repo_name': repo.repo_name,
1984 'repo_type': repo.repo_type,
1985 'clone_uri': repo.clone_uri or '',
1986 'push_uri': repo.push_uri or '',
1987 'url': RepoModel().get_url(self),
1988 'private': repo.private,
1989 'created_on': repo.created_on,
1990 'description': repo.description_safe,
1991 'landing_rev': repo.landing_rev,
1992 'owner': repo.user.username,
1993 'fork_of': repo.fork.repo_name if repo.fork else None,
1994 'fork_of_id': repo.fork.repo_id if repo.fork else None,
1995 'enable_statistics': repo.enable_statistics,
1996 'enable_locking': repo.enable_locking,
1997 'enable_downloads': repo.enable_downloads,
1998 'last_changeset': repo.changeset_cache,
1999 'locked_by': User.get(_user_id).get_api_data(
2000 include_secrets=include_secrets) if _user_id else None,
2001 'locked_date': time_to_datetime(_time) if _time else None,
2002 'lock_reason': _reason if _reason else None,
2003 }
2004
2005 # TODO: mikhail: should be per-repo settings here
2006 rc_config = SettingsModel().get_all_settings()
2007 repository_fields = str2bool(
2008 rc_config.get('rhodecode_repository_fields'))
2009 if repository_fields:
2010 for f in self.extra_fields:
2011 data[f.field_key_prefixed] = f.field_value
2012
2013 return data
2014
2015 @classmethod
2016 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2017 if not lock_time:
2018 lock_time = time.time()
2019 if not lock_reason:
2020 lock_reason = cls.LOCK_AUTOMATIC
2021 repo.locked = [user_id, lock_time, lock_reason]
2022 Session().add(repo)
2023 Session().commit()
2024
2025 @classmethod
2026 def unlock(cls, repo):
2027 repo.locked = None
2028 Session().add(repo)
2029 Session().commit()
2030
2031 @classmethod
2032 def getlock(cls, repo):
2033 return repo.locked
2034
2035 def is_user_lock(self, user_id):
2036 if self.lock[0]:
2037 lock_user_id = safe_int(self.lock[0])
2038 user_id = safe_int(user_id)
2039 # both are ints, and they are equal
2040 return all([lock_user_id, user_id]) and lock_user_id == user_id
2041
2042 return False
2043
2044 def get_locking_state(self, action, user_id, only_when_enabled=True):
2045 """
2046 Checks locking on this repository, if locking is enabled and lock is
2047 present returns a tuple of make_lock, locked, locked_by.
2048 make_lock can have 3 states None (do nothing) True, make lock
2049 False release lock, This value is later propagated to hooks, which
2050 do the locking. Think about this as signals passed to hooks what to do.
2051
2052 """
2053 # TODO: johbo: This is part of the business logic and should be moved
2054 # into the RepositoryModel.
2055
2056 if action not in ('push', 'pull'):
2057 raise ValueError("Invalid action value: %s" % repr(action))
2058
2059 # defines if locked error should be thrown to user
2060 currently_locked = False
2061 # defines if new lock should be made, tri-state
2062 make_lock = None
2063 repo = self
2064 user = User.get(user_id)
2065
2066 lock_info = repo.locked
2067
2068 if repo and (repo.enable_locking or not only_when_enabled):
2069 if action == 'push':
2070 # check if it's already locked !, if it is compare users
2071 locked_by_user_id = lock_info[0]
2072 if user.user_id == locked_by_user_id:
2073 log.debug(
2074 'Got `push` action from user %s, now unlocking', user)
2075 # unlock if we have push from user who locked
2076 make_lock = False
2077 else:
2078 # we're not the same user who locked, ban with
2079 # code defined in settings (default is 423 HTTP Locked) !
2080 log.debug('Repo %s is currently locked by %s', repo, user)
2081 currently_locked = True
2082 elif action == 'pull':
2083 # [0] user [1] date
2084 if lock_info[0] and lock_info[1]:
2085 log.debug('Repo %s is currently locked by %s', repo, user)
2086 currently_locked = True
2087 else:
2088 log.debug('Setting lock on repo %s by %s', repo, user)
2089 make_lock = True
2090
2091 else:
2092 log.debug('Repository %s do not have locking enabled', repo)
2093
2094 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2095 make_lock, currently_locked, lock_info)
2096
2097 from rhodecode.lib.auth import HasRepoPermissionAny
2098 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2099 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2100 # if we don't have at least write permission we cannot make a lock
2101 log.debug('lock state reset back to FALSE due to lack '
2102 'of at least read permission')
2103 make_lock = False
2104
2105 return make_lock, currently_locked, lock_info
2106
2107 @property
2108 def last_db_change(self):
2109 return self.updated_on
2110
2111 @property
2112 def clone_uri_hidden(self):
2113 clone_uri = self.clone_uri
2114 if clone_uri:
2115 import urlobject
2116 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2117 if url_obj.password:
2118 clone_uri = url_obj.with_password('*****')
2119 return clone_uri
2120
2121 @property
2122 def push_uri_hidden(self):
2123 push_uri = self.push_uri
2124 if push_uri:
2125 import urlobject
2126 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2127 if url_obj.password:
2128 push_uri = url_obj.with_password('*****')
2129 return push_uri
2130
2131 def clone_url(self, **override):
2132 from rhodecode.model.settings import SettingsModel
2133
2134 uri_tmpl = None
2135 if 'with_id' in override:
2136 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2137 del override['with_id']
2138
2139 if 'uri_tmpl' in override:
2140 uri_tmpl = override['uri_tmpl']
2141 del override['uri_tmpl']
2142
2143 ssh = False
2144 if 'ssh' in override:
2145 ssh = True
2146 del override['ssh']
2147
2148 # we didn't override our tmpl from **overrides
2149 if not uri_tmpl:
2150 rc_config = SettingsModel().get_all_settings(cache=True)
2151 if ssh:
2152 uri_tmpl = rc_config.get(
2153 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2154 else:
2155 uri_tmpl = rc_config.get(
2156 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2157
2158 request = get_current_request()
2159 return get_clone_url(request=request,
2160 uri_tmpl=uri_tmpl,
2161 repo_name=self.repo_name,
2162 repo_id=self.repo_id, **override)
2163
2164 def set_state(self, state):
2165 self.repo_state = state
2166 Session().add(self)
2167 #==========================================================================
2168 # SCM PROPERTIES
2169 #==========================================================================
2170
2171 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2172 return get_commit_safe(
2173 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2174
2175 def get_changeset(self, rev=None, pre_load=None):
2176 warnings.warn("Use get_commit", DeprecationWarning)
2177 commit_id = None
2178 commit_idx = None
2179 if isinstance(rev, basestring):
2180 commit_id = rev
2181 else:
2182 commit_idx = rev
2183 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2184 pre_load=pre_load)
2185
2186 def get_landing_commit(self):
2187 """
2188 Returns landing commit, or if that doesn't exist returns the tip
2189 """
2190 _rev_type, _rev = self.landing_rev
2191 commit = self.get_commit(_rev)
2192 if isinstance(commit, EmptyCommit):
2193 return self.get_commit()
2194 return commit
2195
2196 def update_commit_cache(self, cs_cache=None, config=None):
2197 """
2198 Update cache of last changeset for repository, keys should be::
2199
2200 short_id
2201 raw_id
2202 revision
2203 parents
2204 message
2205 date
2206 author
2207
2208 :param cs_cache:
2209 """
2210 from rhodecode.lib.vcs.backends.base import BaseChangeset
2211 if cs_cache is None:
2212 # use no-cache version here
2213 scm_repo = self.scm_instance(cache=False, config=config)
2214 if scm_repo:
2215 cs_cache = scm_repo.get_commit(
2216 pre_load=["author", "date", "message", "parents"])
2217 else:
2218 cs_cache = EmptyCommit()
2219
2220 if isinstance(cs_cache, BaseChangeset):
2221 cs_cache = cs_cache.__json__()
2222
2223 def is_outdated(new_cs_cache):
2224 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2225 new_cs_cache['revision'] != self.changeset_cache['revision']):
2226 return True
2227 return False
2228
2229 # check if we have maybe already latest cached revision
2230 if is_outdated(cs_cache) or not self.changeset_cache:
2231 _default = datetime.datetime.fromtimestamp(0)
2232 last_change = cs_cache.get('date') or _default
2233 log.debug('updated repo %s with new cs cache %s',
2234 self.repo_name, cs_cache)
2235 self.updated_on = last_change
2236 self.changeset_cache = cs_cache
2237 Session().add(self)
2238 Session().commit()
2239 else:
2240 log.debug('Skipping update_commit_cache for repo:`%s` '
2241 'commit already with latest changes', self.repo_name)
2242
2243 @property
2244 def tip(self):
2245 return self.get_commit('tip')
2246
2247 @property
2248 def author(self):
2249 return self.tip.author
2250
2251 @property
2252 def last_change(self):
2253 return self.scm_instance().last_change
2254
2255 def get_comments(self, revisions=None):
2256 """
2257 Returns comments for this repository grouped by revisions
2258
2259 :param revisions: filter query by revisions only
2260 """
2261 cmts = ChangesetComment.query()\
2262 .filter(ChangesetComment.repo == self)
2263 if revisions:
2264 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2265 grouped = collections.defaultdict(list)
2266 for cmt in cmts.all():
2267 grouped[cmt.revision].append(cmt)
2268 return grouped
2269
2270 def statuses(self, revisions=None):
2271 """
2272 Returns statuses for this repository
2273
2274 :param revisions: list of revisions to get statuses for
2275 """
2276 statuses = ChangesetStatus.query()\
2277 .filter(ChangesetStatus.repo == self)\
2278 .filter(ChangesetStatus.version == 0)
2279
2280 if revisions:
2281 # Try doing the filtering in chunks to avoid hitting limits
2282 size = 500
2283 status_results = []
2284 for chunk in xrange(0, len(revisions), size):
2285 status_results += statuses.filter(
2286 ChangesetStatus.revision.in_(
2287 revisions[chunk: chunk+size])
2288 ).all()
2289 else:
2290 status_results = statuses.all()
2291
2292 grouped = {}
2293
2294 # maybe we have open new pullrequest without a status?
2295 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2296 status_lbl = ChangesetStatus.get_status_lbl(stat)
2297 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2298 for rev in pr.revisions:
2299 pr_id = pr.pull_request_id
2300 pr_repo = pr.target_repo.repo_name
2301 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2302
2303 for stat in status_results:
2304 pr_id = pr_repo = None
2305 if stat.pull_request:
2306 pr_id = stat.pull_request.pull_request_id
2307 pr_repo = stat.pull_request.target_repo.repo_name
2308 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2309 pr_id, pr_repo]
2310 return grouped
2311
2312 # ==========================================================================
2313 # SCM CACHE INSTANCE
2314 # ==========================================================================
2315
2316 def scm_instance(self, **kwargs):
2317 import rhodecode
2318
2319 # Passing a config will not hit the cache currently only used
2320 # for repo2dbmapper
2321 config = kwargs.pop('config', None)
2322 cache = kwargs.pop('cache', None)
2323 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2324 # if cache is NOT defined use default global, else we have a full
2325 # control over cache behaviour
2326 if cache is None and full_cache and not config:
2327 return self._get_instance_cached()
2328 return self._get_instance(cache=bool(cache), config=config)
2329
2330 def _get_instance_cached(self):
2331 return self._get_instance()
2332
2333 def _get_instance(self, cache=True, config=None):
2334 config = config or self._config
2335 custom_wire = {
2336 'cache': cache # controls the vcs.remote cache
2337 }
2338 repo = get_vcs_instance(
2339 repo_path=safe_str(self.repo_full_path),
2340 config=config,
2341 with_wire=custom_wire,
2342 create=False,
2343 _vcs_alias=self.repo_type)
2344
2345 return repo
2346
2347 def __json__(self):
2348 return {'landing_rev': self.landing_rev}
2349
2350 def get_dict(self):
2351
2352 # Since we transformed `repo_name` to a hybrid property, we need to
2353 # keep compatibility with the code which uses `repo_name` field.
2354
2355 result = super(Repository, self).get_dict()
2356 result['repo_name'] = result.pop('_repo_name', None)
2357 return result
2358
2359
2360 class RepoGroup(Base, BaseModel):
2361 __tablename__ = 'groups'
2362 __table_args__ = (
2363 UniqueConstraint('group_name', 'group_parent_id'),
2364 CheckConstraint('group_id != group_parent_id'),
2365 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2366 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2367 )
2368 __mapper_args__ = {'order_by': 'group_name'}
2369
2370 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2371
2372 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2373 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2374 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2375 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2376 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2377 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2378 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2379 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2380 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2381
2382 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2383 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2384 parent_group = relationship('RepoGroup', remote_side=group_id)
2385 user = relationship('User')
2386 integrations = relationship('Integration',
2387 cascade="all, delete, delete-orphan")
2388
2389 def __init__(self, group_name='', parent_group=None):
2390 self.group_name = group_name
2391 self.parent_group = parent_group
2392
2393 def __unicode__(self):
2394 return u"<%s('id:%s:%s')>" % (
2395 self.__class__.__name__, self.group_id, self.group_name)
2396
2397 @hybrid_property
2398 def description_safe(self):
2399 from rhodecode.lib import helpers as h
2400 return h.escape(self.group_description)
2401
2402 @classmethod
2403 def _generate_choice(cls, repo_group):
2404 from webhelpers.html import literal as _literal
2405 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2406 return repo_group.group_id, _name(repo_group.full_path_splitted)
2407
2408 @classmethod
2409 def groups_choices(cls, groups=None, show_empty_group=True):
2410 if not groups:
2411 groups = cls.query().all()
2412
2413 repo_groups = []
2414 if show_empty_group:
2415 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2416
2417 repo_groups.extend([cls._generate_choice(x) for x in groups])
2418
2419 repo_groups = sorted(
2420 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2421 return repo_groups
2422
2423 @classmethod
2424 def url_sep(cls):
2425 return URL_SEP
2426
2427 @classmethod
2428 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2429 if case_insensitive:
2430 gr = cls.query().filter(func.lower(cls.group_name)
2431 == func.lower(group_name))
2432 else:
2433 gr = cls.query().filter(cls.group_name == group_name)
2434 if cache:
2435 name_key = _hash_key(group_name)
2436 gr = gr.options(
2437 FromCache("sql_cache_short", "get_group_%s" % name_key))
2438 return gr.scalar()
2439
2440 @classmethod
2441 def get_user_personal_repo_group(cls, user_id):
2442 user = User.get(user_id)
2443 if user.username == User.DEFAULT_USER:
2444 return None
2445
2446 return cls.query()\
2447 .filter(cls.personal == true()) \
2448 .filter(cls.user == user).scalar()
2449
2450 @classmethod
2451 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2452 case_insensitive=True):
2453 q = RepoGroup.query()
2454
2455 if not isinstance(user_id, Optional):
2456 q = q.filter(RepoGroup.user_id == user_id)
2457
2458 if not isinstance(group_id, Optional):
2459 q = q.filter(RepoGroup.group_parent_id == group_id)
2460
2461 if case_insensitive:
2462 q = q.order_by(func.lower(RepoGroup.group_name))
2463 else:
2464 q = q.order_by(RepoGroup.group_name)
2465 return q.all()
2466
2467 @property
2468 def parents(self):
2469 parents_recursion_limit = 10
2470 groups = []
2471 if self.parent_group is None:
2472 return groups
2473 cur_gr = self.parent_group
2474 groups.insert(0, cur_gr)
2475 cnt = 0
2476 while 1:
2477 cnt += 1
2478 gr = getattr(cur_gr, 'parent_group', None)
2479 cur_gr = cur_gr.parent_group
2480 if gr is None:
2481 break
2482 if cnt == parents_recursion_limit:
2483 # this will prevent accidental infinit loops
2484 log.error(('more than %s parents found for group %s, stopping '
2485 'recursive parent fetching' % (parents_recursion_limit, self)))
2486 break
2487
2488 groups.insert(0, gr)
2489 return groups
2490
2491 @property
2492 def last_db_change(self):
2493 return self.updated_on
2494
2495 @property
2496 def children(self):
2497 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2498
2499 @property
2500 def name(self):
2501 return self.group_name.split(RepoGroup.url_sep())[-1]
2502
2503 @property
2504 def full_path(self):
2505 return self.group_name
2506
2507 @property
2508 def full_path_splitted(self):
2509 return self.group_name.split(RepoGroup.url_sep())
2510
2511 @property
2512 def repositories(self):
2513 return Repository.query()\
2514 .filter(Repository.group == self)\
2515 .order_by(Repository.repo_name)
2516
2517 @property
2518 def repositories_recursive_count(self):
2519 cnt = self.repositories.count()
2520
2521 def children_count(group):
2522 cnt = 0
2523 for child in group.children:
2524 cnt += child.repositories.count()
2525 cnt += children_count(child)
2526 return cnt
2527
2528 return cnt + children_count(self)
2529
2530 def _recursive_objects(self, include_repos=True):
2531 all_ = []
2532
2533 def _get_members(root_gr):
2534 if include_repos:
2535 for r in root_gr.repositories:
2536 all_.append(r)
2537 childs = root_gr.children.all()
2538 if childs:
2539 for gr in childs:
2540 all_.append(gr)
2541 _get_members(gr)
2542
2543 _get_members(self)
2544 return [self] + all_
2545
2546 def recursive_groups_and_repos(self):
2547 """
2548 Recursive return all groups, with repositories in those groups
2549 """
2550 return self._recursive_objects()
2551
2552 def recursive_groups(self):
2553 """
2554 Returns all children groups for this group including children of children
2555 """
2556 return self._recursive_objects(include_repos=False)
2557
2558 def get_new_name(self, group_name):
2559 """
2560 returns new full group name based on parent and new name
2561
2562 :param group_name:
2563 """
2564 path_prefix = (self.parent_group.full_path_splitted if
2565 self.parent_group else [])
2566 return RepoGroup.url_sep().join(path_prefix + [group_name])
2567
2568 def permissions(self, with_admins=True, with_owner=True):
2569 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2570 q = q.options(joinedload(UserRepoGroupToPerm.group),
2571 joinedload(UserRepoGroupToPerm.user),
2572 joinedload(UserRepoGroupToPerm.permission),)
2573
2574 # get owners and admins and permissions. We do a trick of re-writing
2575 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2576 # has a global reference and changing one object propagates to all
2577 # others. This means if admin is also an owner admin_row that change
2578 # would propagate to both objects
2579 perm_rows = []
2580 for _usr in q.all():
2581 usr = AttributeDict(_usr.user.get_dict())
2582 usr.permission = _usr.permission.permission_name
2583 perm_rows.append(usr)
2584
2585 # filter the perm rows by 'default' first and then sort them by
2586 # admin,write,read,none permissions sorted again alphabetically in
2587 # each group
2588 perm_rows = sorted(perm_rows, key=display_user_sort)
2589
2590 _admin_perm = 'group.admin'
2591 owner_row = []
2592 if with_owner:
2593 usr = AttributeDict(self.user.get_dict())
2594 usr.owner_row = True
2595 usr.permission = _admin_perm
2596 owner_row.append(usr)
2597
2598 super_admin_rows = []
2599 if with_admins:
2600 for usr in User.get_all_super_admins():
2601 # if this admin is also owner, don't double the record
2602 if usr.user_id == owner_row[0].user_id:
2603 owner_row[0].admin_row = True
2604 else:
2605 usr = AttributeDict(usr.get_dict())
2606 usr.admin_row = True
2607 usr.permission = _admin_perm
2608 super_admin_rows.append(usr)
2609
2610 return super_admin_rows + owner_row + perm_rows
2611
2612 def permission_user_groups(self):
2613 q = UserGroupRepoGroupToPerm.query().filter(UserGroupRepoGroupToPerm.group == self)
2614 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2615 joinedload(UserGroupRepoGroupToPerm.users_group),
2616 joinedload(UserGroupRepoGroupToPerm.permission),)
2617
2618 perm_rows = []
2619 for _user_group in q.all():
2620 usr = AttributeDict(_user_group.users_group.get_dict())
2621 usr.permission = _user_group.permission.permission_name
2622 perm_rows.append(usr)
2623
2624 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2625 return perm_rows
2626
2627 def get_api_data(self):
2628 """
2629 Common function for generating api data
2630
2631 """
2632 group = self
2633 data = {
2634 'group_id': group.group_id,
2635 'group_name': group.group_name,
2636 'group_description': group.description_safe,
2637 'parent_group': group.parent_group.group_name if group.parent_group else None,
2638 'repositories': [x.repo_name for x in group.repositories],
2639 'owner': group.user.username,
2640 }
2641 return data
2642
2643
2644 class Permission(Base, BaseModel):
2645 __tablename__ = 'permissions'
2646 __table_args__ = (
2647 Index('p_perm_name_idx', 'permission_name'),
2648 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2649 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2650 )
2651 PERMS = [
2652 ('hg.admin', _('RhodeCode Super Administrator')),
2653
2654 ('repository.none', _('Repository no access')),
2655 ('repository.read', _('Repository read access')),
2656 ('repository.write', _('Repository write access')),
2657 ('repository.admin', _('Repository admin access')),
2658
2659 ('group.none', _('Repository group no access')),
2660 ('group.read', _('Repository group read access')),
2661 ('group.write', _('Repository group write access')),
2662 ('group.admin', _('Repository group admin access')),
2663
2664 ('usergroup.none', _('User group no access')),
2665 ('usergroup.read', _('User group read access')),
2666 ('usergroup.write', _('User group write access')),
2667 ('usergroup.admin', _('User group admin access')),
2668
2669 ('branch.none', _('Branch no permissions')),
2670 ('branch.merge', _('Branch access by web merge')),
2671 ('branch.push', _('Branch access by push')),
2672 ('branch.push_force', _('Branch access by push with force')),
2673
2674 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2675 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2676
2677 ('hg.usergroup.create.false', _('User Group creation disabled')),
2678 ('hg.usergroup.create.true', _('User Group creation enabled')),
2679
2680 ('hg.create.none', _('Repository creation disabled')),
2681 ('hg.create.repository', _('Repository creation enabled')),
2682 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2683 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2684
2685 ('hg.fork.none', _('Repository forking disabled')),
2686 ('hg.fork.repository', _('Repository forking enabled')),
2687
2688 ('hg.register.none', _('Registration disabled')),
2689 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2690 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2691
2692 ('hg.password_reset.enabled', _('Password reset enabled')),
2693 ('hg.password_reset.hidden', _('Password reset hidden')),
2694 ('hg.password_reset.disabled', _('Password reset disabled')),
2695
2696 ('hg.extern_activate.manual', _('Manual activation of external account')),
2697 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2698
2699 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2700 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2701 ]
2702
2703 # definition of system default permissions for DEFAULT user, created on
2704 # system setup
2705 DEFAULT_USER_PERMISSIONS = [
2706 # object perms
2707 'repository.read',
2708 'group.read',
2709 'usergroup.read',
2710 # branch
2711 'branch.push',
2712 # global
2713 'hg.create.repository',
2714 'hg.repogroup.create.false',
2715 'hg.usergroup.create.false',
2716 'hg.create.write_on_repogroup.true',
2717 'hg.fork.repository',
2718 'hg.register.manual_activate',
2719 'hg.password_reset.enabled',
2720 'hg.extern_activate.auto',
2721 'hg.inherit_default_perms.true',
2722 ]
2723
2724 # defines which permissions are more important higher the more important
2725 # Weight defines which permissions are more important.
2726 # The higher number the more important.
2727 PERM_WEIGHTS = {
2728 'repository.none': 0,
2729 'repository.read': 1,
2730 'repository.write': 3,
2731 'repository.admin': 4,
2732
2733 'group.none': 0,
2734 'group.read': 1,
2735 'group.write': 3,
2736 'group.admin': 4,
2737
2738 'usergroup.none': 0,
2739 'usergroup.read': 1,
2740 'usergroup.write': 3,
2741 'usergroup.admin': 4,
2742
2743 'branch.none': 0,
2744 'branch.merge': 1,
2745 'branch.push': 3,
2746 'branch.push_force': 4,
2747
2748 'hg.repogroup.create.false': 0,
2749 'hg.repogroup.create.true': 1,
2750
2751 'hg.usergroup.create.false': 0,
2752 'hg.usergroup.create.true': 1,
2753
2754 'hg.fork.none': 0,
2755 'hg.fork.repository': 1,
2756 'hg.create.none': 0,
2757 'hg.create.repository': 1
2758 }
2759
2760 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2761 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2762 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2763
2764 def __unicode__(self):
2765 return u"<%s('%s:%s')>" % (
2766 self.__class__.__name__, self.permission_id, self.permission_name
2767 )
2768
2769 @classmethod
2770 def get_by_key(cls, key):
2771 return cls.query().filter(cls.permission_name == key).scalar()
2772
2773 @classmethod
2774 def get_default_repo_perms(cls, user_id, repo_id=None):
2775 q = Session().query(UserRepoToPerm, Repository, Permission)\
2776 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2777 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2778 .filter(UserRepoToPerm.user_id == user_id)
2779 if repo_id:
2780 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2781 return q.all()
2782
2783 @classmethod
2784 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2785 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2786 .join(
2787 Permission,
2788 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2789 .join(
2790 Repository,
2791 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2792 .join(
2793 UserGroup,
2794 UserGroupRepoToPerm.users_group_id ==
2795 UserGroup.users_group_id)\
2796 .join(
2797 UserGroupMember,
2798 UserGroupRepoToPerm.users_group_id ==
2799 UserGroupMember.users_group_id)\
2800 .filter(
2801 UserGroupMember.user_id == user_id,
2802 UserGroup.users_group_active == true())
2803 if repo_id:
2804 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2805 return q.all()
2806
2807 @classmethod
2808 def get_default_group_perms(cls, user_id, repo_group_id=None):
2809 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2810 .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\
2811 .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
2812 .filter(UserRepoGroupToPerm.user_id == user_id)
2813 if repo_group_id:
2814 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2815 return q.all()
2816
2817 @classmethod
2818 def get_default_group_perms_from_user_group(
2819 cls, user_id, repo_group_id=None):
2820 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2821 .join(
2822 Permission,
2823 UserGroupRepoGroupToPerm.permission_id ==
2824 Permission.permission_id)\
2825 .join(
2826 RepoGroup,
2827 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2828 .join(
2829 UserGroup,
2830 UserGroupRepoGroupToPerm.users_group_id ==
2831 UserGroup.users_group_id)\
2832 .join(
2833 UserGroupMember,
2834 UserGroupRepoGroupToPerm.users_group_id ==
2835 UserGroupMember.users_group_id)\
2836 .filter(
2837 UserGroupMember.user_id == user_id,
2838 UserGroup.users_group_active == true())
2839 if repo_group_id:
2840 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
2841 return q.all()
2842
2843 @classmethod
2844 def get_default_user_group_perms(cls, user_id, user_group_id=None):
2845 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
2846 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
2847 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
2848 .filter(UserUserGroupToPerm.user_id == user_id)
2849 if user_group_id:
2850 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
2851 return q.all()
2852
2853 @classmethod
2854 def get_default_user_group_perms_from_user_group(
2855 cls, user_id, user_group_id=None):
2856 TargetUserGroup = aliased(UserGroup, name='target_user_group')
2857 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
2858 .join(
2859 Permission,
2860 UserGroupUserGroupToPerm.permission_id ==
2861 Permission.permission_id)\
2862 .join(
2863 TargetUserGroup,
2864 UserGroupUserGroupToPerm.target_user_group_id ==
2865 TargetUserGroup.users_group_id)\
2866 .join(
2867 UserGroup,
2868 UserGroupUserGroupToPerm.user_group_id ==
2869 UserGroup.users_group_id)\
2870 .join(
2871 UserGroupMember,
2872 UserGroupUserGroupToPerm.user_group_id ==
2873 UserGroupMember.users_group_id)\
2874 .filter(
2875 UserGroupMember.user_id == user_id,
2876 UserGroup.users_group_active == true())
2877 if user_group_id:
2878 q = q.filter(
2879 UserGroupUserGroupToPerm.user_group_id == user_group_id)
2880
2881 return q.all()
2882
2883
2884 class UserRepoToPerm(Base, BaseModel):
2885 __tablename__ = 'repo_to_perm'
2886 __table_args__ = (
2887 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
2888 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2889 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2890 )
2891 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2892 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2893 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2894 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2895
2896 user = relationship('User')
2897 repository = relationship('Repository')
2898 permission = relationship('Permission')
2899
2900 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete, delete-orphan", lazy='joined')
2901
2902 @classmethod
2903 def create(cls, user, repository, permission):
2904 n = cls()
2905 n.user = user
2906 n.repository = repository
2907 n.permission = permission
2908 Session().add(n)
2909 return n
2910
2911 def __unicode__(self):
2912 return u'<%s => %s >' % (self.user, self.repository)
2913
2914
2915 class UserUserGroupToPerm(Base, BaseModel):
2916 __tablename__ = 'user_user_group_to_perm'
2917 __table_args__ = (
2918 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
2919 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2920 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2921 )
2922 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2923 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2924 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2925 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2926
2927 user = relationship('User')
2928 user_group = relationship('UserGroup')
2929 permission = relationship('Permission')
2930
2931 @classmethod
2932 def create(cls, user, user_group, permission):
2933 n = cls()
2934 n.user = user
2935 n.user_group = user_group
2936 n.permission = permission
2937 Session().add(n)
2938 return n
2939
2940 def __unicode__(self):
2941 return u'<%s => %s >' % (self.user, self.user_group)
2942
2943
2944 class UserToPerm(Base, BaseModel):
2945 __tablename__ = 'user_to_perm'
2946 __table_args__ = (
2947 UniqueConstraint('user_id', 'permission_id'),
2948 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2949 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2950 )
2951 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2952 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2953 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2954
2955 user = relationship('User')
2956 permission = relationship('Permission', lazy='joined')
2957
2958 def __unicode__(self):
2959 return u'<%s => %s >' % (self.user, self.permission)
2960
2961
2962 class UserGroupRepoToPerm(Base, BaseModel):
2963 __tablename__ = 'users_group_repo_to_perm'
2964 __table_args__ = (
2965 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
2966 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2967 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2968 )
2969 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2970 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2971 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2972 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2973
2974 users_group = relationship('UserGroup')
2975 permission = relationship('Permission')
2976 repository = relationship('Repository')
2977
2978 @classmethod
2979 def create(cls, users_group, repository, permission):
2980 n = cls()
2981 n.users_group = users_group
2982 n.repository = repository
2983 n.permission = permission
2984 Session().add(n)
2985 return n
2986
2987 def __unicode__(self):
2988 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
2989
2990
2991 class UserGroupUserGroupToPerm(Base, BaseModel):
2992 __tablename__ = 'user_group_user_group_to_perm'
2993 __table_args__ = (
2994 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
2995 CheckConstraint('target_user_group_id != user_group_id'),
2996 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2997 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2998 )
2999 user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3000 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3001 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3002 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3003
3004 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3005 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3006 permission = relationship('Permission')
3007
3008 @classmethod
3009 def create(cls, target_user_group, user_group, permission):
3010 n = cls()
3011 n.target_user_group = target_user_group
3012 n.user_group = user_group
3013 n.permission = permission
3014 Session().add(n)
3015 return n
3016
3017 def __unicode__(self):
3018 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3019
3020
3021 class UserGroupToPerm(Base, BaseModel):
3022 __tablename__ = 'users_group_to_perm'
3023 __table_args__ = (
3024 UniqueConstraint('users_group_id', 'permission_id',),
3025 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3026 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3027 )
3028 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3029 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3030 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3031
3032 users_group = relationship('UserGroup')
3033 permission = relationship('Permission')
3034
3035
3036 class UserRepoGroupToPerm(Base, BaseModel):
3037 __tablename__ = 'user_repo_group_to_perm'
3038 __table_args__ = (
3039 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3040 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3041 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3042 )
3043
3044 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3045 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3046 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3047 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3048
3049 user = relationship('User')
3050 group = relationship('RepoGroup')
3051 permission = relationship('Permission')
3052
3053 @classmethod
3054 def create(cls, user, repository_group, permission):
3055 n = cls()
3056 n.user = user
3057 n.group = repository_group
3058 n.permission = permission
3059 Session().add(n)
3060 return n
3061
3062
3063 class UserGroupRepoGroupToPerm(Base, BaseModel):
3064 __tablename__ = 'users_group_repo_group_to_perm'
3065 __table_args__ = (
3066 UniqueConstraint('users_group_id', 'group_id'),
3067 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3068 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3069 )
3070
3071 users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3072 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3073 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3074 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3075
3076 users_group = relationship('UserGroup')
3077 permission = relationship('Permission')
3078 group = relationship('RepoGroup')
3079
3080 @classmethod
3081 def create(cls, user_group, repository_group, permission):
3082 n = cls()
3083 n.users_group = user_group
3084 n.group = repository_group
3085 n.permission = permission
3086 Session().add(n)
3087 return n
3088
3089 def __unicode__(self):
3090 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3091
3092
3093 class Statistics(Base, BaseModel):
3094 __tablename__ = 'statistics'
3095 __table_args__ = (
3096 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3097 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3098 )
3099 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3100 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3101 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3102 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3103 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3104 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3105
3106 repository = relationship('Repository', single_parent=True)
3107
3108
3109 class UserFollowing(Base, BaseModel):
3110 __tablename__ = 'user_followings'
3111 __table_args__ = (
3112 UniqueConstraint('user_id', 'follows_repository_id'),
3113 UniqueConstraint('user_id', 'follows_user_id'),
3114 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3115 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3116 )
3117
3118 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3119 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3120 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3121 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3122 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3123
3124 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3125
3126 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3127 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3128
3129 @classmethod
3130 def get_repo_followers(cls, repo_id):
3131 return cls.query().filter(cls.follows_repo_id == repo_id)
3132
3133
3134 class CacheKey(Base, BaseModel):
3135 __tablename__ = 'cache_invalidation'
3136 __table_args__ = (
3137 UniqueConstraint('cache_key'),
3138 Index('key_idx', 'cache_key'),
3139 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3140 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3141 )
3142 CACHE_TYPE_ATOM = 'ATOM'
3143 CACHE_TYPE_RSS = 'RSS'
3144 CACHE_TYPE_README = 'README'
3145
3146 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3147 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3148 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3149 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3150
3151 def __init__(self, cache_key, cache_args=''):
3152 self.cache_key = cache_key
3153 self.cache_args = cache_args
3154 self.cache_active = False
3155
3156 def __unicode__(self):
3157 return u"<%s('%s:%s[%s]')>" % (
3158 self.__class__.__name__,
3159 self.cache_id, self.cache_key, self.cache_active)
3160
3161 def _cache_key_partition(self):
3162 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3163 return prefix, repo_name, suffix
3164
3165 def get_prefix(self):
3166 """
3167 Try to extract prefix from existing cache key. The key could consist
3168 of prefix, repo_name, suffix
3169 """
3170 # this returns prefix, repo_name, suffix
3171 return self._cache_key_partition()[0]
3172
3173 def get_suffix(self):
3174 """
3175 get suffix that might have been used in _get_cache_key to
3176 generate self.cache_key. Only used for informational purposes
3177 in repo_edit.mako.
3178 """
3179 # prefix, repo_name, suffix
3180 return self._cache_key_partition()[2]
3181
3182 @classmethod
3183 def delete_all_cache(cls):
3184 """
3185 Delete all cache keys from database.
3186 Should only be run when all instances are down and all entries
3187 thus stale.
3188 """
3189 cls.query().delete()
3190 Session().commit()
3191
3192 @classmethod
3193 def get_cache_key(cls, repo_name, cache_type):
3194 """
3195
3196 Generate a cache key for this process of RhodeCode instance.
3197 Prefix most likely will be process id or maybe explicitly set
3198 instance_id from .ini file.
3199 """
3200 import rhodecode
3201 prefix = safe_unicode(rhodecode.CONFIG.get('instance_id') or '')
3202
3203 repo_as_unicode = safe_unicode(repo_name)
3204 key = u'{}_{}'.format(repo_as_unicode, cache_type) \
3205 if cache_type else repo_as_unicode
3206
3207 return u'{}{}'.format(prefix, key)
3208
3209 @classmethod
3210 def set_invalidate(cls, repo_name, delete=False):
3211 """
3212 Mark all caches of a repo as invalid in the database.
3213 """
3214
3215 try:
3216 qry = Session().query(cls).filter(cls.cache_args == repo_name)
3217 if delete:
3218 log.debug('cache objects deleted for repo %s',
3219 safe_str(repo_name))
3220 qry.delete()
3221 else:
3222 log.debug('cache objects marked as invalid for repo %s',
3223 safe_str(repo_name))
3224 qry.update({"cache_active": False})
3225
3226 Session().commit()
3227 except Exception:
3228 log.exception(
3229 'Cache key invalidation failed for repository %s',
3230 safe_str(repo_name))
3231 Session().rollback()
3232
3233 @classmethod
3234 def get_active_cache(cls, cache_key):
3235 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3236 if inv_obj:
3237 return inv_obj
3238 return None
3239
3240
3241 class ChangesetComment(Base, BaseModel):
3242 __tablename__ = 'changeset_comments'
3243 __table_args__ = (
3244 Index('cc_revision_idx', 'revision'),
3245 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3246 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3247 )
3248
3249 COMMENT_OUTDATED = u'comment_outdated'
3250 COMMENT_TYPE_NOTE = u'note'
3251 COMMENT_TYPE_TODO = u'todo'
3252 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3253
3254 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3255 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3256 revision = Column('revision', String(40), nullable=True)
3257 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3258 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3259 line_no = Column('line_no', Unicode(10), nullable=True)
3260 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3261 f_path = Column('f_path', Unicode(1000), nullable=True)
3262 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3263 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3264 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3265 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3266 renderer = Column('renderer', Unicode(64), nullable=True)
3267 display_state = Column('display_state', Unicode(128), nullable=True)
3268
3269 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3270 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3271 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, backref='resolved_by')
3272 author = relationship('User', lazy='joined')
3273 repo = relationship('Repository')
3274 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3275 pull_request = relationship('PullRequest', lazy='joined')
3276 pull_request_version = relationship('PullRequestVersion')
3277
3278 @classmethod
3279 def get_users(cls, revision=None, pull_request_id=None):
3280 """
3281 Returns user associated with this ChangesetComment. ie those
3282 who actually commented
3283
3284 :param cls:
3285 :param revision:
3286 """
3287 q = Session().query(User)\
3288 .join(ChangesetComment.author)
3289 if revision:
3290 q = q.filter(cls.revision == revision)
3291 elif pull_request_id:
3292 q = q.filter(cls.pull_request_id == pull_request_id)
3293 return q.all()
3294
3295 @classmethod
3296 def get_index_from_version(cls, pr_version, versions):
3297 num_versions = [x.pull_request_version_id for x in versions]
3298 try:
3299 return num_versions.index(pr_version) +1
3300 except (IndexError, ValueError):
3301 return
3302
3303 @property
3304 def outdated(self):
3305 return self.display_state == self.COMMENT_OUTDATED
3306
3307 def outdated_at_version(self, version):
3308 """
3309 Checks if comment is outdated for given pull request version
3310 """
3311 return self.outdated and self.pull_request_version_id != version
3312
3313 def older_than_version(self, version):
3314 """
3315 Checks if comment is made from previous version than given
3316 """
3317 if version is None:
3318 return self.pull_request_version_id is not None
3319
3320 return self.pull_request_version_id < version
3321
3322 @property
3323 def resolved(self):
3324 return self.resolved_by[0] if self.resolved_by else None
3325
3326 @property
3327 def is_todo(self):
3328 return self.comment_type == self.COMMENT_TYPE_TODO
3329
3330 @property
3331 def is_inline(self):
3332 return self.line_no and self.f_path
3333
3334 def get_index_version(self, versions):
3335 return self.get_index_from_version(
3336 self.pull_request_version_id, versions)
3337
3338 def __repr__(self):
3339 if self.comment_id:
3340 return '<DB:Comment #%s>' % self.comment_id
3341 else:
3342 return '<DB:Comment at %#x>' % id(self)
3343
3344 def get_api_data(self):
3345 comment = self
3346 data = {
3347 'comment_id': comment.comment_id,
3348 'comment_type': comment.comment_type,
3349 'comment_text': comment.text,
3350 'comment_status': comment.status_change,
3351 'comment_f_path': comment.f_path,
3352 'comment_lineno': comment.line_no,
3353 'comment_author': comment.author,
3354 'comment_created_on': comment.created_on
3355 }
3356 return data
3357
3358 def __json__(self):
3359 data = dict()
3360 data.update(self.get_api_data())
3361 return data
3362
3363
3364 class ChangesetStatus(Base, BaseModel):
3365 __tablename__ = 'changeset_statuses'
3366 __table_args__ = (
3367 Index('cs_revision_idx', 'revision'),
3368 Index('cs_version_idx', 'version'),
3369 UniqueConstraint('repo_id', 'revision', 'version'),
3370 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3371 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3372 )
3373 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3374 STATUS_APPROVED = 'approved'
3375 STATUS_REJECTED = 'rejected'
3376 STATUS_UNDER_REVIEW = 'under_review'
3377
3378 STATUSES = [
3379 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3380 (STATUS_APPROVED, _("Approved")),
3381 (STATUS_REJECTED, _("Rejected")),
3382 (STATUS_UNDER_REVIEW, _("Under Review")),
3383 ]
3384
3385 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3386 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3387 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3388 revision = Column('revision', String(40), nullable=False)
3389 status = Column('status', String(128), nullable=False, default=DEFAULT)
3390 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3391 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3392 version = Column('version', Integer(), nullable=False, default=0)
3393 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3394
3395 author = relationship('User', lazy='joined')
3396 repo = relationship('Repository')
3397 comment = relationship('ChangesetComment', lazy='joined')
3398 pull_request = relationship('PullRequest', lazy='joined')
3399
3400 def __unicode__(self):
3401 return u"<%s('%s[v%s]:%s')>" % (
3402 self.__class__.__name__,
3403 self.status, self.version, self.author
3404 )
3405
3406 @classmethod
3407 def get_status_lbl(cls, value):
3408 return dict(cls.STATUSES).get(value)
3409
3410 @property
3411 def status_lbl(self):
3412 return ChangesetStatus.get_status_lbl(self.status)
3413
3414 def get_api_data(self):
3415 status = self
3416 data = {
3417 'status_id': status.changeset_status_id,
3418 'status': status.status,
3419 }
3420 return data
3421
3422 def __json__(self):
3423 data = dict()
3424 data.update(self.get_api_data())
3425 return data
3426
3427
3428 class _PullRequestBase(BaseModel):
3429 """
3430 Common attributes of pull request and version entries.
3431 """
3432
3433 # .status values
3434 STATUS_NEW = u'new'
3435 STATUS_OPEN = u'open'
3436 STATUS_CLOSED = u'closed'
3437
3438 title = Column('title', Unicode(255), nullable=True)
3439 description = Column(
3440 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3441 nullable=True)
3442 # new/open/closed status of pull request (not approve/reject/etc)
3443 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3444 created_on = Column(
3445 'created_on', DateTime(timezone=False), nullable=False,
3446 default=datetime.datetime.now)
3447 updated_on = Column(
3448 'updated_on', DateTime(timezone=False), nullable=False,
3449 default=datetime.datetime.now)
3450
3451 @declared_attr
3452 def user_id(cls):
3453 return Column(
3454 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3455 unique=None)
3456
3457 # 500 revisions max
3458 _revisions = Column(
3459 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3460
3461 @declared_attr
3462 def source_repo_id(cls):
3463 # TODO: dan: rename column to source_repo_id
3464 return Column(
3465 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3466 nullable=False)
3467
3468 source_ref = Column('org_ref', Unicode(255), nullable=False)
3469
3470 @declared_attr
3471 def target_repo_id(cls):
3472 # TODO: dan: rename column to target_repo_id
3473 return Column(
3474 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3475 nullable=False)
3476
3477 target_ref = Column('other_ref', Unicode(255), nullable=False)
3478 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3479
3480 # TODO: dan: rename column to last_merge_source_rev
3481 _last_merge_source_rev = Column(
3482 'last_merge_org_rev', String(40), nullable=True)
3483 # TODO: dan: rename column to last_merge_target_rev
3484 _last_merge_target_rev = Column(
3485 'last_merge_other_rev', String(40), nullable=True)
3486 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3487 merge_rev = Column('merge_rev', String(40), nullable=True)
3488
3489 reviewer_data = Column(
3490 'reviewer_data_json', MutationObj.as_mutable(
3491 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3492
3493 @property
3494 def reviewer_data_json(self):
3495 return json.dumps(self.reviewer_data)
3496
3497 @hybrid_property
3498 def description_safe(self):
3499 from rhodecode.lib import helpers as h
3500 return h.escape(self.description)
3501
3502 @hybrid_property
3503 def revisions(self):
3504 return self._revisions.split(':') if self._revisions else []
3505
3506 @revisions.setter
3507 def revisions(self, val):
3508 self._revisions = ':'.join(val)
3509
3510 @hybrid_property
3511 def last_merge_status(self):
3512 return safe_int(self._last_merge_status)
3513
3514 @last_merge_status.setter
3515 def last_merge_status(self, val):
3516 self._last_merge_status = val
3517
3518 @declared_attr
3519 def author(cls):
3520 return relationship('User', lazy='joined')
3521
3522 @declared_attr
3523 def source_repo(cls):
3524 return relationship(
3525 'Repository',
3526 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3527
3528 @property
3529 def source_ref_parts(self):
3530 return self.unicode_to_reference(self.source_ref)
3531
3532 @declared_attr
3533 def target_repo(cls):
3534 return relationship(
3535 'Repository',
3536 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3537
3538 @property
3539 def target_ref_parts(self):
3540 return self.unicode_to_reference(self.target_ref)
3541
3542 @property
3543 def shadow_merge_ref(self):
3544 return self.unicode_to_reference(self._shadow_merge_ref)
3545
3546 @shadow_merge_ref.setter
3547 def shadow_merge_ref(self, ref):
3548 self._shadow_merge_ref = self.reference_to_unicode(ref)
3549
3550 def unicode_to_reference(self, raw):
3551 """
3552 Convert a unicode (or string) to a reference object.
3553 If unicode evaluates to False it returns None.
3554 """
3555 if raw:
3556 refs = raw.split(':')
3557 return Reference(*refs)
3558 else:
3559 return None
3560
3561 def reference_to_unicode(self, ref):
3562 """
3563 Convert a reference object to unicode.
3564 If reference is None it returns None.
3565 """
3566 if ref:
3567 return u':'.join(ref)
3568 else:
3569 return None
3570
3571 def get_api_data(self, with_merge_state=True):
3572 from rhodecode.model.pull_request import PullRequestModel
3573
3574 pull_request = self
3575 if with_merge_state:
3576 merge_status = PullRequestModel().merge_status(pull_request)
3577 merge_state = {
3578 'status': merge_status[0],
3579 'message': safe_unicode(merge_status[1]),
3580 }
3581 else:
3582 merge_state = {'status': 'not_available',
3583 'message': 'not_available'}
3584
3585 merge_data = {
3586 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3587 'reference': (
3588 pull_request.shadow_merge_ref._asdict()
3589 if pull_request.shadow_merge_ref else None),
3590 }
3591
3592 data = {
3593 'pull_request_id': pull_request.pull_request_id,
3594 'url': PullRequestModel().get_url(pull_request),
3595 'title': pull_request.title,
3596 'description': pull_request.description,
3597 'status': pull_request.status,
3598 'created_on': pull_request.created_on,
3599 'updated_on': pull_request.updated_on,
3600 'commit_ids': pull_request.revisions,
3601 'review_status': pull_request.calculated_review_status(),
3602 'mergeable': merge_state,
3603 'source': {
3604 'clone_url': pull_request.source_repo.clone_url(),
3605 'repository': pull_request.source_repo.repo_name,
3606 'reference': {
3607 'name': pull_request.source_ref_parts.name,
3608 'type': pull_request.source_ref_parts.type,
3609 'commit_id': pull_request.source_ref_parts.commit_id,
3610 },
3611 },
3612 'target': {
3613 'clone_url': pull_request.target_repo.clone_url(),
3614 'repository': pull_request.target_repo.repo_name,
3615 'reference': {
3616 'name': pull_request.target_ref_parts.name,
3617 'type': pull_request.target_ref_parts.type,
3618 'commit_id': pull_request.target_ref_parts.commit_id,
3619 },
3620 },
3621 'merge': merge_data,
3622 'author': pull_request.author.get_api_data(include_secrets=False,
3623 details='basic'),
3624 'reviewers': [
3625 {
3626 'user': reviewer.get_api_data(include_secrets=False,
3627 details='basic'),
3628 'reasons': reasons,
3629 'review_status': st[0][1].status if st else 'not_reviewed',
3630 }
3631 for obj, reviewer, reasons, mandatory, st in
3632 pull_request.reviewers_statuses()
3633 ]
3634 }
3635
3636 return data
3637
3638
3639 class PullRequest(Base, _PullRequestBase):
3640 __tablename__ = 'pull_requests'
3641 __table_args__ = (
3642 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3643 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3644 )
3645
3646 pull_request_id = Column(
3647 'pull_request_id', Integer(), nullable=False, primary_key=True)
3648
3649 def __repr__(self):
3650 if self.pull_request_id:
3651 return '<DB:PullRequest #%s>' % self.pull_request_id
3652 else:
3653 return '<DB:PullRequest at %#x>' % id(self)
3654
3655 reviewers = relationship('PullRequestReviewers',
3656 cascade="all, delete, delete-orphan")
3657 statuses = relationship('ChangesetStatus',
3658 cascade="all, delete, delete-orphan")
3659 comments = relationship('ChangesetComment',
3660 cascade="all, delete, delete-orphan")
3661 versions = relationship('PullRequestVersion',
3662 cascade="all, delete, delete-orphan",
3663 lazy='dynamic')
3664
3665 @classmethod
3666 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3667 internal_methods=None):
3668
3669 class PullRequestDisplay(object):
3670 """
3671 Special object wrapper for showing PullRequest data via Versions
3672 It mimics PR object as close as possible. This is read only object
3673 just for display
3674 """
3675
3676 def __init__(self, attrs, internal=None):
3677 self.attrs = attrs
3678 # internal have priority over the given ones via attrs
3679 self.internal = internal or ['versions']
3680
3681 def __getattr__(self, item):
3682 if item in self.internal:
3683 return getattr(self, item)
3684 try:
3685 return self.attrs[item]
3686 except KeyError:
3687 raise AttributeError(
3688 '%s object has no attribute %s' % (self, item))
3689
3690 def __repr__(self):
3691 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3692
3693 def versions(self):
3694 return pull_request_obj.versions.order_by(
3695 PullRequestVersion.pull_request_version_id).all()
3696
3697 def is_closed(self):
3698 return pull_request_obj.is_closed()
3699
3700 @property
3701 def pull_request_version_id(self):
3702 return getattr(pull_request_obj, 'pull_request_version_id', None)
3703
3704 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3705
3706 attrs.author = StrictAttributeDict(
3707 pull_request_obj.author.get_api_data())
3708 if pull_request_obj.target_repo:
3709 attrs.target_repo = StrictAttributeDict(
3710 pull_request_obj.target_repo.get_api_data())
3711 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3712
3713 if pull_request_obj.source_repo:
3714 attrs.source_repo = StrictAttributeDict(
3715 pull_request_obj.source_repo.get_api_data())
3716 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3717
3718 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3719 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3720 attrs.revisions = pull_request_obj.revisions
3721
3722 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3723 attrs.reviewer_data = org_pull_request_obj.reviewer_data
3724 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
3725
3726 return PullRequestDisplay(attrs, internal=internal_methods)
3727
3728 def is_closed(self):
3729 return self.status == self.STATUS_CLOSED
3730
3731 def __json__(self):
3732 return {
3733 'revisions': self.revisions,
3734 }
3735
3736 def calculated_review_status(self):
3737 from rhodecode.model.changeset_status import ChangesetStatusModel
3738 return ChangesetStatusModel().calculated_review_status(self)
3739
3740 def reviewers_statuses(self):
3741 from rhodecode.model.changeset_status import ChangesetStatusModel
3742 return ChangesetStatusModel().reviewers_statuses(self)
3743
3744 @property
3745 def workspace_id(self):
3746 from rhodecode.model.pull_request import PullRequestModel
3747 return PullRequestModel()._workspace_id(self)
3748
3749 def get_shadow_repo(self):
3750 workspace_id = self.workspace_id
3751 vcs_obj = self.target_repo.scm_instance()
3752 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3753 workspace_id)
3754 return vcs_obj._get_shadow_instance(shadow_repository_path)
3755
3756
3757 class PullRequestVersion(Base, _PullRequestBase):
3758 __tablename__ = 'pull_request_versions'
3759 __table_args__ = (
3760 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3761 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3762 )
3763
3764 pull_request_version_id = Column(
3765 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3766 pull_request_id = Column(
3767 'pull_request_id', Integer(),
3768 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3769 pull_request = relationship('PullRequest')
3770
3771 def __repr__(self):
3772 if self.pull_request_version_id:
3773 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3774 else:
3775 return '<DB:PullRequestVersion at %#x>' % id(self)
3776
3777 @property
3778 def reviewers(self):
3779 return self.pull_request.reviewers
3780
3781 @property
3782 def versions(self):
3783 return self.pull_request.versions
3784
3785 def is_closed(self):
3786 # calculate from original
3787 return self.pull_request.status == self.STATUS_CLOSED
3788
3789 def calculated_review_status(self):
3790 return self.pull_request.calculated_review_status()
3791
3792 def reviewers_statuses(self):
3793 return self.pull_request.reviewers_statuses()
3794
3795
3796 class PullRequestReviewers(Base, BaseModel):
3797 __tablename__ = 'pull_request_reviewers'
3798 __table_args__ = (
3799 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3800 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3801 )
3802
3803 @hybrid_property
3804 def reasons(self):
3805 if not self._reasons:
3806 return []
3807 return self._reasons
3808
3809 @reasons.setter
3810 def reasons(self, val):
3811 val = val or []
3812 if any(not isinstance(x, basestring) for x in val):
3813 raise Exception('invalid reasons type, must be list of strings')
3814 self._reasons = val
3815
3816 pull_requests_reviewers_id = Column(
3817 'pull_requests_reviewers_id', Integer(), nullable=False,
3818 primary_key=True)
3819 pull_request_id = Column(
3820 "pull_request_id", Integer(),
3821 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3822 user_id = Column(
3823 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3824 _reasons = Column(
3825 'reason', MutationList.as_mutable(
3826 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
3827
3828 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
3829 user = relationship('User')
3830 pull_request = relationship('PullRequest')
3831
3832 rule_data = Column(
3833 'rule_data_json',
3834 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
3835
3836 def rule_user_group_data(self):
3837 """
3838 Returns the voting user group rule data for this reviewer
3839 """
3840
3841 if self.rule_data and 'vote_rule' in self.rule_data:
3842 user_group_data = {}
3843 if 'rule_user_group_entry_id' in self.rule_data:
3844 # means a group with voting rules !
3845 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
3846 user_group_data['name'] = self.rule_data['rule_name']
3847 user_group_data['vote_rule'] = self.rule_data['vote_rule']
3848
3849 return user_group_data
3850
3851 def __unicode__(self):
3852 return u"<%s('id:%s')>" % (self.__class__.__name__,
3853 self.pull_requests_reviewers_id)
3854
3855
3856 class Notification(Base, BaseModel):
3857 __tablename__ = 'notifications'
3858 __table_args__ = (
3859 Index('notification_type_idx', 'type'),
3860 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3861 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3862 )
3863
3864 TYPE_CHANGESET_COMMENT = u'cs_comment'
3865 TYPE_MESSAGE = u'message'
3866 TYPE_MENTION = u'mention'
3867 TYPE_REGISTRATION = u'registration'
3868 TYPE_PULL_REQUEST = u'pull_request'
3869 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
3870
3871 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
3872 subject = Column('subject', Unicode(512), nullable=True)
3873 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
3874 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
3875 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3876 type_ = Column('type', Unicode(255))
3877
3878 created_by_user = relationship('User')
3879 notifications_to_users = relationship('UserNotification', lazy='joined',
3880 cascade="all, delete, delete-orphan")
3881
3882 @property
3883 def recipients(self):
3884 return [x.user for x in UserNotification.query()\
3885 .filter(UserNotification.notification == self)\
3886 .order_by(UserNotification.user_id.asc()).all()]
3887
3888 @classmethod
3889 def create(cls, created_by, subject, body, recipients, type_=None):
3890 if type_ is None:
3891 type_ = Notification.TYPE_MESSAGE
3892
3893 notification = cls()
3894 notification.created_by_user = created_by
3895 notification.subject = subject
3896 notification.body = body
3897 notification.type_ = type_
3898 notification.created_on = datetime.datetime.now()
3899
3900 for u in recipients:
3901 assoc = UserNotification()
3902 assoc.notification = notification
3903
3904 # if created_by is inside recipients mark his notification
3905 # as read
3906 if u.user_id == created_by.user_id:
3907 assoc.read = True
3908
3909 u.notifications.append(assoc)
3910 Session().add(notification)
3911
3912 return notification
3913
3914
3915 class UserNotification(Base, BaseModel):
3916 __tablename__ = 'user_to_notification'
3917 __table_args__ = (
3918 UniqueConstraint('user_id', 'notification_id'),
3919 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3920 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3921 )
3922 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
3923 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
3924 read = Column('read', Boolean, default=False)
3925 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
3926
3927 user = relationship('User', lazy="joined")
3928 notification = relationship('Notification', lazy="joined",
3929 order_by=lambda: Notification.created_on.desc(),)
3930
3931 def mark_as_read(self):
3932 self.read = True
3933 Session().add(self)
3934
3935
3936 class Gist(Base, BaseModel):
3937 __tablename__ = 'gists'
3938 __table_args__ = (
3939 Index('g_gist_access_id_idx', 'gist_access_id'),
3940 Index('g_created_on_idx', 'created_on'),
3941 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3942 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3943 )
3944 GIST_PUBLIC = u'public'
3945 GIST_PRIVATE = u'private'
3946 DEFAULT_FILENAME = u'gistfile1.txt'
3947
3948 ACL_LEVEL_PUBLIC = u'acl_public'
3949 ACL_LEVEL_PRIVATE = u'acl_private'
3950
3951 gist_id = Column('gist_id', Integer(), primary_key=True)
3952 gist_access_id = Column('gist_access_id', Unicode(250))
3953 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
3954 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
3955 gist_expires = Column('gist_expires', Float(53), nullable=False)
3956 gist_type = Column('gist_type', Unicode(128), nullable=False)
3957 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3958 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3959 acl_level = Column('acl_level', Unicode(128), nullable=True)
3960
3961 owner = relationship('User')
3962
3963 def __repr__(self):
3964 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
3965
3966 @hybrid_property
3967 def description_safe(self):
3968 from rhodecode.lib import helpers as h
3969 return h.escape(self.gist_description)
3970
3971 @classmethod
3972 def get_or_404(cls, id_):
3973 from pyramid.httpexceptions import HTTPNotFound
3974
3975 res = cls.query().filter(cls.gist_access_id == id_).scalar()
3976 if not res:
3977 raise HTTPNotFound()
3978 return res
3979
3980 @classmethod
3981 def get_by_access_id(cls, gist_access_id):
3982 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
3983
3984 def gist_url(self):
3985 from rhodecode.model.gist import GistModel
3986 return GistModel().get_url(self)
3987
3988 @classmethod
3989 def base_path(cls):
3990 """
3991 Returns base path when all gists are stored
3992
3993 :param cls:
3994 """
3995 from rhodecode.model.gist import GIST_STORE_LOC
3996 q = Session().query(RhodeCodeUi)\
3997 .filter(RhodeCodeUi.ui_key == URL_SEP)
3998 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
3999 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4000
4001 def get_api_data(self):
4002 """
4003 Common function for generating gist related data for API
4004 """
4005 gist = self
4006 data = {
4007 'gist_id': gist.gist_id,
4008 'type': gist.gist_type,
4009 'access_id': gist.gist_access_id,
4010 'description': gist.gist_description,
4011 'url': gist.gist_url(),
4012 'expires': gist.gist_expires,
4013 'created_on': gist.created_on,
4014 'modified_at': gist.modified_at,
4015 'content': None,
4016 'acl_level': gist.acl_level,
4017 }
4018 return data
4019
4020 def __json__(self):
4021 data = dict(
4022 )
4023 data.update(self.get_api_data())
4024 return data
4025 # SCM functions
4026
4027 def scm_instance(self, **kwargs):
4028 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4029 return get_vcs_instance(
4030 repo_path=safe_str(full_repo_path), create=False)
4031
4032
4033 class ExternalIdentity(Base, BaseModel):
4034 __tablename__ = 'external_identities'
4035 __table_args__ = (
4036 Index('local_user_id_idx', 'local_user_id'),
4037 Index('external_id_idx', 'external_id'),
4038 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4039 'mysql_charset': 'utf8'})
4040
4041 external_id = Column('external_id', Unicode(255), default=u'',
4042 primary_key=True)
4043 external_username = Column('external_username', Unicode(1024), default=u'')
4044 local_user_id = Column('local_user_id', Integer(),
4045 ForeignKey('users.user_id'), primary_key=True)
4046 provider_name = Column('provider_name', Unicode(255), default=u'',
4047 primary_key=True)
4048 access_token = Column('access_token', String(1024), default=u'')
4049 alt_token = Column('alt_token', String(1024), default=u'')
4050 token_secret = Column('token_secret', String(1024), default=u'')
4051
4052 @classmethod
4053 def by_external_id_and_provider(cls, external_id, provider_name,
4054 local_user_id=None):
4055 """
4056 Returns ExternalIdentity instance based on search params
4057
4058 :param external_id:
4059 :param provider_name:
4060 :return: ExternalIdentity
4061 """
4062 query = cls.query()
4063 query = query.filter(cls.external_id == external_id)
4064 query = query.filter(cls.provider_name == provider_name)
4065 if local_user_id:
4066 query = query.filter(cls.local_user_id == local_user_id)
4067 return query.first()
4068
4069 @classmethod
4070 def user_by_external_id_and_provider(cls, external_id, provider_name):
4071 """
4072 Returns User instance based on search params
4073
4074 :param external_id:
4075 :param provider_name:
4076 :return: User
4077 """
4078 query = User.query()
4079 query = query.filter(cls.external_id == external_id)
4080 query = query.filter(cls.provider_name == provider_name)
4081 query = query.filter(User.user_id == cls.local_user_id)
4082 return query.first()
4083
4084 @classmethod
4085 def by_local_user_id(cls, local_user_id):
4086 """
4087 Returns all tokens for user
4088
4089 :param local_user_id:
4090 :return: ExternalIdentity
4091 """
4092 query = cls.query()
4093 query = query.filter(cls.local_user_id == local_user_id)
4094 return query
4095
4096
4097 class Integration(Base, BaseModel):
4098 __tablename__ = 'integrations'
4099 __table_args__ = (
4100 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4101 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
4102 )
4103
4104 integration_id = Column('integration_id', Integer(), primary_key=True)
4105 integration_type = Column('integration_type', String(255))
4106 enabled = Column('enabled', Boolean(), nullable=False)
4107 name = Column('name', String(255), nullable=False)
4108 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4109 default=False)
4110
4111 settings = Column(
4112 'settings_json', MutationObj.as_mutable(
4113 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4114 repo_id = Column(
4115 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4116 nullable=True, unique=None, default=None)
4117 repo = relationship('Repository', lazy='joined')
4118
4119 repo_group_id = Column(
4120 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4121 nullable=True, unique=None, default=None)
4122 repo_group = relationship('RepoGroup', lazy='joined')
4123
4124 @property
4125 def scope(self):
4126 if self.repo:
4127 return repr(self.repo)
4128 if self.repo_group:
4129 if self.child_repos_only:
4130 return repr(self.repo_group) + ' (child repos only)'
4131 else:
4132 return repr(self.repo_group) + ' (recursive)'
4133 if self.child_repos_only:
4134 return 'root_repos'
4135 return 'global'
4136
4137 def __repr__(self):
4138 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4139
4140
4141 class RepoReviewRuleUser(Base, BaseModel):
4142 __tablename__ = 'repo_review_rules_users'
4143 __table_args__ = (
4144 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4145 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4146 )
4147
4148 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4149 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4150 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4151 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4152 user = relationship('User')
4153
4154 def rule_data(self):
4155 return {
4156 'mandatory': self.mandatory
4157 }
4158
4159
4160 class RepoReviewRuleUserGroup(Base, BaseModel):
4161 __tablename__ = 'repo_review_rules_users_groups'
4162 __table_args__ = (
4163 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4164 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4165 )
4166 VOTE_RULE_ALL = -1
4167
4168 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4169 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4170 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4171 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4172 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4173 users_group = relationship('UserGroup')
4174
4175 def rule_data(self):
4176 return {
4177 'mandatory': self.mandatory,
4178 'vote_rule': self.vote_rule
4179 }
4180
4181 @property
4182 def vote_rule_label(self):
4183 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4184 return 'all must vote'
4185 else:
4186 return 'min. vote {}'.format(self.vote_rule)
4187
4188
4189 class RepoReviewRule(Base, BaseModel):
4190 __tablename__ = 'repo_review_rules'
4191 __table_args__ = (
4192 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4193 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4194 )
4195
4196 repo_review_rule_id = Column(
4197 'repo_review_rule_id', Integer(), primary_key=True)
4198 repo_id = Column(
4199 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4200 repo = relationship('Repository', backref='review_rules')
4201
4202 review_rule_name = Column('review_rule_name', String(255))
4203 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4204 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4205 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4206
4207 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4208 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4209 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4210 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4211
4212 rule_users = relationship('RepoReviewRuleUser')
4213 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4214
4215 def _validate_glob(self, value):
4216 re.compile('^' + glob2re(value) + '$')
4217
4218 @hybrid_property
4219 def source_branch_pattern(self):
4220 return self._branch_pattern or '*'
4221
4222 @source_branch_pattern.setter
4223 def source_branch_pattern(self, value):
4224 self._validate_glob(value)
4225 self._branch_pattern = value or '*'
4226
4227 @hybrid_property
4228 def target_branch_pattern(self):
4229 return self._target_branch_pattern or '*'
4230
4231 @target_branch_pattern.setter
4232 def target_branch_pattern(self, value):
4233 self._validate_glob(value)
4234 self._target_branch_pattern = value or '*'
4235
4236 @hybrid_property
4237 def file_pattern(self):
4238 return self._file_pattern or '*'
4239
4240 @file_pattern.setter
4241 def file_pattern(self, value):
4242 self._validate_glob(value)
4243 self._file_pattern = value or '*'
4244
4245 def matches(self, source_branch, target_branch, files_changed):
4246 """
4247 Check if this review rule matches a branch/files in a pull request
4248
4249 :param source_branch: source branch name for the commit
4250 :param target_branch: target branch name for the commit
4251 :param files_changed: list of file paths changed in the pull request
4252 """
4253
4254 source_branch = source_branch or ''
4255 target_branch = target_branch or ''
4256 files_changed = files_changed or []
4257
4258 branch_matches = True
4259 if source_branch or target_branch:
4260 if self.source_branch_pattern == '*':
4261 source_branch_match = True
4262 else:
4263 source_branch_regex = re.compile(
4264 '^' + glob2re(self.source_branch_pattern) + '$')
4265 source_branch_match = bool(source_branch_regex.search(source_branch))
4266 if self.target_branch_pattern == '*':
4267 target_branch_match = True
4268 else:
4269 target_branch_regex = re.compile(
4270 '^' + glob2re(self.target_branch_pattern) + '$')
4271 target_branch_match = bool(target_branch_regex.search(target_branch))
4272
4273 branch_matches = source_branch_match and target_branch_match
4274
4275 files_matches = True
4276 if self.file_pattern != '*':
4277 files_matches = False
4278 file_regex = re.compile(glob2re(self.file_pattern))
4279 for filename in files_changed:
4280 if file_regex.search(filename):
4281 files_matches = True
4282 break
4283
4284 return branch_matches and files_matches
4285
4286 @property
4287 def review_users(self):
4288 """ Returns the users which this rule applies to """
4289
4290 users = collections.OrderedDict()
4291
4292 for rule_user in self.rule_users:
4293 if rule_user.user.active:
4294 if rule_user.user not in users:
4295 users[rule_user.user.username] = {
4296 'user': rule_user.user,
4297 'source': 'user',
4298 'source_data': {},
4299 'data': rule_user.rule_data()
4300 }
4301
4302 for rule_user_group in self.rule_user_groups:
4303 source_data = {
4304 'user_group_id': rule_user_group.users_group.users_group_id,
4305 'name': rule_user_group.users_group.users_group_name,
4306 'members': len(rule_user_group.users_group.members)
4307 }
4308 for member in rule_user_group.users_group.members:
4309 if member.user.active:
4310 key = member.user.username
4311 if key in users:
4312 # skip this member as we have him already
4313 # this prevents from override the "first" matched
4314 # users with duplicates in multiple groups
4315 continue
4316
4317 users[key] = {
4318 'user': member.user,
4319 'source': 'user_group',
4320 'source_data': source_data,
4321 'data': rule_user_group.rule_data()
4322 }
4323
4324 return users
4325
4326 def user_group_vote_rule(self):
4327 rules = []
4328 if self.rule_user_groups:
4329 for user_group in self.rule_user_groups:
4330 rules.append(user_group)
4331 return rules
4332
4333 def __repr__(self):
4334 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4335 self.repo_review_rule_id, self.repo)
4336
4337
4338 class ScheduleEntry(Base, BaseModel):
4339 __tablename__ = 'schedule_entries'
4340 __table_args__ = (
4341 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4342 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4343 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4344 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
4345 )
4346 schedule_types = ['crontab', 'timedelta', 'integer']
4347 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4348
4349 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4350 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4351 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4352
4353 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4354 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4355
4356 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4357 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4358
4359 # task
4360 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4361 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4362 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4363 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4364
4365 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4366 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4367
4368 @hybrid_property
4369 def schedule_type(self):
4370 return self._schedule_type
4371
4372 @schedule_type.setter
4373 def schedule_type(self, val):
4374 if val not in self.schedule_types:
4375 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4376 val, self.schedule_type))
4377
4378 self._schedule_type = val
4379
4380 @classmethod
4381 def get_uid(cls, obj):
4382 args = obj.task_args
4383 kwargs = obj.task_kwargs
4384 if isinstance(args, JsonRaw):
4385 try:
4386 args = json.loads(args)
4387 except ValueError:
4388 args = tuple()
4389
4390 if isinstance(kwargs, JsonRaw):
4391 try:
4392 kwargs = json.loads(kwargs)
4393 except ValueError:
4394 kwargs = dict()
4395
4396 dot_notation = obj.task_dot_notation
4397 val = '.'.join(map(safe_str, [
4398 sorted(dot_notation), args, sorted(kwargs.items())]))
4399 return hashlib.sha1(val).hexdigest()
4400
4401 @classmethod
4402 def get_by_schedule_name(cls, schedule_name):
4403 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4404
4405 @classmethod
4406 def get_by_schedule_id(cls, schedule_id):
4407 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4408
4409 @property
4410 def task(self):
4411 return self.task_dot_notation
4412
4413 @property
4414 def schedule(self):
4415 from rhodecode.lib.celerylib.utils import raw_2_schedule
4416 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4417 return schedule
4418
4419 @property
4420 def args(self):
4421 try:
4422 return list(self.task_args or [])
4423 except ValueError:
4424 return list()
4425
4426 @property
4427 def kwargs(self):
4428 try:
4429 return dict(self.task_kwargs or {})
4430 except ValueError:
4431 return dict()
4432
4433 def _as_raw(self, val):
4434 if hasattr(val, 'de_coerce'):
4435 val = val.de_coerce()
4436 if val:
4437 val = json.dumps(val)
4438
4439 return val
4440
4441 @property
4442 def schedule_definition_raw(self):
4443 return self._as_raw(self.schedule_definition)
4444
4445 @property
4446 def args_raw(self):
4447 return self._as_raw(self.task_args)
4448
4449 @property
4450 def kwargs_raw(self):
4451 return self._as_raw(self.task_kwargs)
4452
4453 def __repr__(self):
4454 return '<DB:ScheduleEntry({}:{})>'.format(
4455 self.schedule_entry_id, self.schedule_name)
4456
4457
4458 @event.listens_for(ScheduleEntry, 'before_update')
4459 def update_task_uid(mapper, connection, target):
4460 target.task_uid = ScheduleEntry.get_uid(target)
4461
4462
4463 @event.listens_for(ScheduleEntry, 'before_insert')
4464 def set_task_uid(mapper, connection, target):
4465 target.task_uid = ScheduleEntry.get_uid(target)
4466
4467
4468 class _BaseBranchPerms(BaseModel):
4469 @classmethod
4470 def compute_hash(cls, value):
4471 return md5_safe(value)
4472
4473 @hybrid_property
4474 def branch_pattern(self):
4475 return self._branch_pattern or '*'
4476
4477 @hybrid_property
4478 def branch_hash(self):
4479 return self._branch_hash
4480
4481 def _validate_glob(self, value):
4482 re.compile('^' + glob2re(value) + '$')
4483
4484 @branch_pattern.setter
4485 def branch_pattern(self, value):
4486 self._validate_glob(value)
4487 self._branch_pattern = value or '*'
4488 # set the Hash when setting the branch pattern
4489 self._branch_hash = self.compute_hash(self._branch_pattern)
4490
4491 def matches(self, branch):
4492 """
4493 Check if this the branch matches entry
4494
4495 :param branch: branch name for the commit
4496 """
4497
4498 branch = branch or ''
4499
4500 branch_matches = True
4501 if branch:
4502 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
4503 branch_matches = bool(branch_regex.search(branch))
4504
4505 return branch_matches
4506
4507
4508 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
4509 __tablename__ = 'user_to_repo_branch_permissions'
4510 __table_args__ = (
4511 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4512 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4513 )
4514
4515 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4516
4517 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4518 repo = relationship('Repository', backref='user_branch_perms')
4519
4520 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4521 permission = relationship('Permission')
4522
4523 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
4524 user_repo_to_perm = relationship('UserRepoToPerm')
4525
4526 rule_order = Column('rule_order', Integer(), nullable=False)
4527 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4528 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4529
4530 def __unicode__(self):
4531 return u'<UserBranchPermission(%s => %r)>' % (
4532 self.user_repo_to_perm, self.branch_pattern)
4533
4534
4535 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
4536 __tablename__ = 'user_group_to_repo_branch_permissions'
4537 __table_args__ = (
4538 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4539 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4540 )
4541
4542 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4543
4544 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4545 repo = relationship('Repository', backref='user_group_branch_perms')
4546
4547 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4548 permission = relationship('Permission')
4549
4550 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('users_group_repo_to_perm.users_group_to_perm_id'), nullable=False, unique=None, default=None)
4551 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
4552
4553 rule_order = Column('rule_order', Integer(), nullable=False)
4554 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4555 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4556
4557 def __unicode__(self):
4558 return u'<UserBranchPermission(%s => %r)>' % (
4559 self.user_group_repo_to_perm, self.branch_pattern)
4560
4561
4562 class DbMigrateVersion(Base, BaseModel):
4563 __tablename__ = 'db_migrate_version'
4564 __table_args__ = (
4565 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4566 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
4567 )
4568 repository_id = Column('repository_id', String(250), primary_key=True)
4569 repository_path = Column('repository_path', Text)
4570 version = Column('version', Integer)
4571
4572
4573 class DbSession(Base, BaseModel):
4574 __tablename__ = 'db_session'
4575 __table_args__ = (
4576 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4577 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
4578 )
4579
4580 def __repr__(self):
4581 return '<DB:DbSession({})>'.format(self.id)
4582
4583 id = Column('id', Integer())
4584 namespace = Column('namespace', String(255), primary_key=True)
4585 accessed = Column('accessed', DateTime, nullable=False)
4586 created = Column('created', DateTime, nullable=False)
4587 data = Column('data', PickleType, nullable=False)
@@ -0,0 +1,46 b''
1 import logging
2
3 from sqlalchemy import *
4 from sqlalchemy.engine import reflection
5 from sqlalchemy.dialects.mysql import LONGTEXT
6
7 from alembic.migration import MigrationContext
8 from alembic.operations import Operations
9
10 from rhodecode.lib.dbmigrate.utils import create_default_permissions, \
11 create_default_object_permission
12 from rhodecode.model import meta
13 from rhodecode.lib.dbmigrate.versions import _reset_base, notify
14
15 log = logging.getLogger(__name__)
16
17
18 def upgrade(migrate_engine):
19 """
20 Upgrade operations go here.
21 Don't create your own engine; bind migrate_engine to your metadata
22 """
23 _reset_base(migrate_engine)
24 from rhodecode.lib.dbmigrate.schema import db_4_13_0_0 as db
25
26 # issue fixups
27 fixups(db, meta.Session)
28
29
30 def downgrade(migrate_engine):
31 meta = MetaData()
32 meta.bind = migrate_engine
33
34
35 def fixups(models, _SESSION):
36 # create default permissions
37 create_default_permissions(_SESSION, models)
38 log.info('created default global permissions definitions')
39 _SESSION().commit()
40
41 # # fix default object permissions
42 # create_default_object_permission(_SESSION, models)
43
44 log.info('created default permission')
45 _SESSION().commit()
46
@@ -0,0 +1,39 b''
1 import logging
2
3 from sqlalchemy import *
4 from sqlalchemy.engine import reflection
5 from sqlalchemy.dialects.mysql import LONGTEXT
6
7 from alembic.migration import MigrationContext
8 from alembic.operations import Operations
9
10 from rhodecode.model import meta
11 from rhodecode.lib.dbmigrate.versions import _reset_base, notify
12
13 log = logging.getLogger(__name__)
14
15
16 def upgrade(migrate_engine):
17 """
18 Upgrade operations go here.
19 Don't create your own engine; bind migrate_engine to your metadata
20 """
21 _reset_base(migrate_engine)
22 from rhodecode.lib.dbmigrate.schema import db_4_13_0_0 as db
23
24 db.UserToRepoBranchPermission.__table__.create()
25 db.UserGroupToRepoBranchPermission.__table__.create()
26
27 # issue fixups
28 fixups(db, meta.Session)
29
30
31 def downgrade(migrate_engine):
32 meta = MetaData()
33 meta.bind = migrate_engine
34
35
36 def fixups(models, _SESSION):
37 pass
38
39
@@ -0,0 +1,43 b''
1 import logging
2
3 from sqlalchemy import *
4
5 from rhodecode.lib.dbmigrate.utils import (
6 create_default_object_permission, create_default_permissions)
7
8 from rhodecode.model import meta
9 from rhodecode.lib.dbmigrate.versions import _reset_base, notify
10
11 log = logging.getLogger(__name__)
12
13
14 def upgrade(migrate_engine):
15 """
16 Upgrade operations go here.
17 Don't create your own engine; bind migrate_engine to your metadata
18 """
19 _reset_base(migrate_engine)
20 from rhodecode.lib.dbmigrate.schema import db_4_13_0_0 as db
21
22 # issue fixups
23 fixups(db, meta.Session)
24
25
26 def downgrade(migrate_engine):
27 meta = MetaData()
28 meta.bind = migrate_engine
29
30
31 def fixups(models, _SESSION):
32 # create default permissions
33 create_default_permissions(_SESSION, models)
34 log.info('created default global permissions definitions')
35 _SESSION().commit()
36
37 # fix default object permissions
38 create_default_object_permission(_SESSION, models)
39
40 log.info('created default permission')
41 _SESSION().commit()
42
43
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,63 +1,63 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2018 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
23 23 RhodeCode, a web based repository management software
24 24 versioning implementation: http://www.python.org/dev/peps/pep-0386/
25 25 """
26 26
27 27 import os
28 28 import sys
29 29 import platform
30 30
31 31 VERSION = tuple(open(os.path.join(
32 32 os.path.dirname(__file__), 'VERSION')).read().split('.'))
33 33
34 34 BACKENDS = {
35 35 'hg': 'Mercurial repository',
36 36 'git': 'Git repository',
37 37 'svn': 'Subversion repository',
38 38 }
39 39
40 40 CELERY_ENABLED = False
41 41 CELERY_EAGER = False
42 42
43 43 # link to config for pyramid
44 44 CONFIG = {}
45 45
46 46 # Populated with the settings dictionary from application init in
47 47 # rhodecode.conf.environment.load_pyramid_environment
48 48 PYRAMID_SETTINGS = {}
49 49
50 50 # Linked module for extensions
51 51 EXTENSIONS = {}
52 52
53 53 __version__ = ('.'.join((str(each) for each in VERSION[:3])))
54 __dbversion__ = 87 # defines current db version for migrations
54 __dbversion__ = 90 # defines current db version for migrations
55 55 __platform__ = platform.system()
56 56 __license__ = 'AGPLv3, and Commercial License'
57 57 __author__ = 'RhodeCode GmbH'
58 58 __url__ = 'https://code.rhodecode.com'
59 59
60 60 is_windows = __platform__ in ['Windows']
61 61 is_unix = not is_windows
62 62 is_test = False
63 63 disable_error_handler = False
@@ -1,439 +1,444 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2016-2018 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._base import ADMIN_PREFIX
23 23
24 24
25 25 def admin_routes(config):
26 26 """
27 27 Admin prefixed routes
28 28 """
29 29
30 30 config.add_route(
31 31 name='admin_audit_logs',
32 32 pattern='/audit_logs')
33 33
34 34 config.add_route(
35 35 name='admin_audit_log_entry',
36 36 pattern='/audit_logs/{audit_log_id}')
37 37
38 38 config.add_route(
39 39 name='pull_requests_global_0', # backward compat
40 40 pattern='/pull_requests/{pull_request_id:\d+}')
41 41 config.add_route(
42 42 name='pull_requests_global_1', # backward compat
43 43 pattern='/pull-requests/{pull_request_id:\d+}')
44 44 config.add_route(
45 45 name='pull_requests_global',
46 46 pattern='/pull-request/{pull_request_id:\d+}')
47 47
48 48 config.add_route(
49 49 name='admin_settings_open_source',
50 50 pattern='/settings/open_source')
51 51 config.add_route(
52 52 name='admin_settings_vcs_svn_generate_cfg',
53 53 pattern='/settings/vcs/svn_generate_cfg')
54 54
55 55 config.add_route(
56 56 name='admin_settings_system',
57 57 pattern='/settings/system')
58 58 config.add_route(
59 59 name='admin_settings_system_update',
60 60 pattern='/settings/system/updates')
61 61
62 62 config.add_route(
63 63 name='admin_settings_exception_tracker',
64 64 pattern='/settings/exceptions')
65 65 config.add_route(
66 66 name='admin_settings_exception_tracker_delete_all',
67 67 pattern='/settings/exceptions/delete')
68 68 config.add_route(
69 69 name='admin_settings_exception_tracker_show',
70 70 pattern='/settings/exceptions/{exception_id}')
71 71 config.add_route(
72 72 name='admin_settings_exception_tracker_delete',
73 73 pattern='/settings/exceptions/{exception_id}/delete')
74 74
75 75 config.add_route(
76 76 name='admin_settings_sessions',
77 77 pattern='/settings/sessions')
78 78 config.add_route(
79 79 name='admin_settings_sessions_cleanup',
80 80 pattern='/settings/sessions/cleanup')
81 81
82 82 config.add_route(
83 83 name='admin_settings_process_management',
84 84 pattern='/settings/process_management')
85 85 config.add_route(
86 86 name='admin_settings_process_management_data',
87 87 pattern='/settings/process_management/data')
88 88 config.add_route(
89 89 name='admin_settings_process_management_signal',
90 90 pattern='/settings/process_management/signal')
91 91 config.add_route(
92 92 name='admin_settings_process_management_master_signal',
93 93 pattern='/settings/process_management/master_signal')
94 94
95 95 # default settings
96 96 config.add_route(
97 97 name='admin_defaults_repositories',
98 98 pattern='/defaults/repositories')
99 99 config.add_route(
100 100 name='admin_defaults_repositories_update',
101 101 pattern='/defaults/repositories/update')
102 102
103 103 # admin settings
104 104
105 105 config.add_route(
106 106 name='admin_settings',
107 107 pattern='/settings')
108 108 config.add_route(
109 109 name='admin_settings_update',
110 110 pattern='/settings/update')
111 111
112 112 config.add_route(
113 113 name='admin_settings_global',
114 114 pattern='/settings/global')
115 115 config.add_route(
116 116 name='admin_settings_global_update',
117 117 pattern='/settings/global/update')
118 118
119 119 config.add_route(
120 120 name='admin_settings_vcs',
121 121 pattern='/settings/vcs')
122 122 config.add_route(
123 123 name='admin_settings_vcs_update',
124 124 pattern='/settings/vcs/update')
125 125 config.add_route(
126 126 name='admin_settings_vcs_svn_pattern_delete',
127 127 pattern='/settings/vcs/svn_pattern_delete')
128 128
129 129 config.add_route(
130 130 name='admin_settings_mapping',
131 131 pattern='/settings/mapping')
132 132 config.add_route(
133 133 name='admin_settings_mapping_update',
134 134 pattern='/settings/mapping/update')
135 135
136 136 config.add_route(
137 137 name='admin_settings_visual',
138 138 pattern='/settings/visual')
139 139 config.add_route(
140 140 name='admin_settings_visual_update',
141 141 pattern='/settings/visual/update')
142 142
143 143
144 144 config.add_route(
145 145 name='admin_settings_issuetracker',
146 146 pattern='/settings/issue-tracker')
147 147 config.add_route(
148 148 name='admin_settings_issuetracker_update',
149 149 pattern='/settings/issue-tracker/update')
150 150 config.add_route(
151 151 name='admin_settings_issuetracker_test',
152 152 pattern='/settings/issue-tracker/test')
153 153 config.add_route(
154 154 name='admin_settings_issuetracker_delete',
155 155 pattern='/settings/issue-tracker/delete')
156 156
157 157 config.add_route(
158 158 name='admin_settings_email',
159 159 pattern='/settings/email')
160 160 config.add_route(
161 161 name='admin_settings_email_update',
162 162 pattern='/settings/email/update')
163 163
164 164 config.add_route(
165 165 name='admin_settings_hooks',
166 166 pattern='/settings/hooks')
167 167 config.add_route(
168 168 name='admin_settings_hooks_update',
169 169 pattern='/settings/hooks/update')
170 170 config.add_route(
171 171 name='admin_settings_hooks_delete',
172 172 pattern='/settings/hooks/delete')
173 173
174 174 config.add_route(
175 175 name='admin_settings_search',
176 176 pattern='/settings/search')
177 177
178 178 config.add_route(
179 179 name='admin_settings_labs',
180 180 pattern='/settings/labs')
181 181 config.add_route(
182 182 name='admin_settings_labs_update',
183 183 pattern='/settings/labs/update')
184 184
185 185 # Automation EE feature
186 186 config.add_route(
187 187 'admin_settings_automation',
188 188 pattern=ADMIN_PREFIX + '/settings/automation')
189 189
190 190 # global permissions
191 191
192 192 config.add_route(
193 193 name='admin_permissions_application',
194 194 pattern='/permissions/application')
195 195 config.add_route(
196 196 name='admin_permissions_application_update',
197 197 pattern='/permissions/application/update')
198 198
199 199 config.add_route(
200 200 name='admin_permissions_global',
201 201 pattern='/permissions/global')
202 202 config.add_route(
203 203 name='admin_permissions_global_update',
204 204 pattern='/permissions/global/update')
205 205
206 206 config.add_route(
207 207 name='admin_permissions_object',
208 208 pattern='/permissions/object')
209 209 config.add_route(
210 210 name='admin_permissions_object_update',
211 211 pattern='/permissions/object/update')
212 212
213 # Branch perms EE feature
214 config.add_route(
215 name='admin_permissions_branch',
216 pattern='/permissions/branch')
217
213 218 config.add_route(
214 219 name='admin_permissions_ips',
215 220 pattern='/permissions/ips')
216 221
217 222 config.add_route(
218 223 name='admin_permissions_overview',
219 224 pattern='/permissions/overview')
220 225
221 226 config.add_route(
222 227 name='admin_permissions_auth_token_access',
223 228 pattern='/permissions/auth_token_access')
224 229
225 230 config.add_route(
226 231 name='admin_permissions_ssh_keys',
227 232 pattern='/permissions/ssh_keys')
228 233 config.add_route(
229 234 name='admin_permissions_ssh_keys_data',
230 235 pattern='/permissions/ssh_keys/data')
231 236 config.add_route(
232 237 name='admin_permissions_ssh_keys_update',
233 238 pattern='/permissions/ssh_keys/update')
234 239
235 240 # users admin
236 241 config.add_route(
237 242 name='users',
238 243 pattern='/users')
239 244
240 245 config.add_route(
241 246 name='users_data',
242 247 pattern='/users_data')
243 248
244 249 config.add_route(
245 250 name='users_create',
246 251 pattern='/users/create')
247 252
248 253 config.add_route(
249 254 name='users_new',
250 255 pattern='/users/new')
251 256
252 257 # user management
253 258 config.add_route(
254 259 name='user_edit',
255 260 pattern='/users/{user_id:\d+}/edit',
256 261 user_route=True)
257 262 config.add_route(
258 263 name='user_edit_advanced',
259 264 pattern='/users/{user_id:\d+}/edit/advanced',
260 265 user_route=True)
261 266 config.add_route(
262 267 name='user_edit_global_perms',
263 268 pattern='/users/{user_id:\d+}/edit/global_permissions',
264 269 user_route=True)
265 270 config.add_route(
266 271 name='user_edit_global_perms_update',
267 272 pattern='/users/{user_id:\d+}/edit/global_permissions/update',
268 273 user_route=True)
269 274 config.add_route(
270 275 name='user_update',
271 276 pattern='/users/{user_id:\d+}/update',
272 277 user_route=True)
273 278 config.add_route(
274 279 name='user_delete',
275 280 pattern='/users/{user_id:\d+}/delete',
276 281 user_route=True)
277 282 config.add_route(
278 283 name='user_force_password_reset',
279 284 pattern='/users/{user_id:\d+}/password_reset',
280 285 user_route=True)
281 286 config.add_route(
282 287 name='user_create_personal_repo_group',
283 288 pattern='/users/{user_id:\d+}/create_repo_group',
284 289 user_route=True)
285 290
286 291 # user auth tokens
287 292 config.add_route(
288 293 name='edit_user_auth_tokens',
289 294 pattern='/users/{user_id:\d+}/edit/auth_tokens',
290 295 user_route=True)
291 296 config.add_route(
292 297 name='edit_user_auth_tokens_add',
293 298 pattern='/users/{user_id:\d+}/edit/auth_tokens/new',
294 299 user_route=True)
295 300 config.add_route(
296 301 name='edit_user_auth_tokens_delete',
297 302 pattern='/users/{user_id:\d+}/edit/auth_tokens/delete',
298 303 user_route=True)
299 304
300 305 # user ssh keys
301 306 config.add_route(
302 307 name='edit_user_ssh_keys',
303 308 pattern='/users/{user_id:\d+}/edit/ssh_keys',
304 309 user_route=True)
305 310 config.add_route(
306 311 name='edit_user_ssh_keys_generate_keypair',
307 312 pattern='/users/{user_id:\d+}/edit/ssh_keys/generate',
308 313 user_route=True)
309 314 config.add_route(
310 315 name='edit_user_ssh_keys_add',
311 316 pattern='/users/{user_id:\d+}/edit/ssh_keys/new',
312 317 user_route=True)
313 318 config.add_route(
314 319 name='edit_user_ssh_keys_delete',
315 320 pattern='/users/{user_id:\d+}/edit/ssh_keys/delete',
316 321 user_route=True)
317 322
318 323 # user emails
319 324 config.add_route(
320 325 name='edit_user_emails',
321 326 pattern='/users/{user_id:\d+}/edit/emails',
322 327 user_route=True)
323 328 config.add_route(
324 329 name='edit_user_emails_add',
325 330 pattern='/users/{user_id:\d+}/edit/emails/new',
326 331 user_route=True)
327 332 config.add_route(
328 333 name='edit_user_emails_delete',
329 334 pattern='/users/{user_id:\d+}/edit/emails/delete',
330 335 user_route=True)
331 336
332 337 # user IPs
333 338 config.add_route(
334 339 name='edit_user_ips',
335 340 pattern='/users/{user_id:\d+}/edit/ips',
336 341 user_route=True)
337 342 config.add_route(
338 343 name='edit_user_ips_add',
339 344 pattern='/users/{user_id:\d+}/edit/ips/new',
340 345 user_route_with_default=True) # enabled for default user too
341 346 config.add_route(
342 347 name='edit_user_ips_delete',
343 348 pattern='/users/{user_id:\d+}/edit/ips/delete',
344 349 user_route_with_default=True) # enabled for default user too
345 350
346 351 # user perms
347 352 config.add_route(
348 353 name='edit_user_perms_summary',
349 354 pattern='/users/{user_id:\d+}/edit/permissions_summary',
350 355 user_route=True)
351 356 config.add_route(
352 357 name='edit_user_perms_summary_json',
353 358 pattern='/users/{user_id:\d+}/edit/permissions_summary/json',
354 359 user_route=True)
355 360
356 361 # user user groups management
357 362 config.add_route(
358 363 name='edit_user_groups_management',
359 364 pattern='/users/{user_id:\d+}/edit/groups_management',
360 365 user_route=True)
361 366
362 367 config.add_route(
363 368 name='edit_user_groups_management_updates',
364 369 pattern='/users/{user_id:\d+}/edit/edit_user_groups_management/updates',
365 370 user_route=True)
366 371
367 372 # user audit logs
368 373 config.add_route(
369 374 name='edit_user_audit_logs',
370 375 pattern='/users/{user_id:\d+}/edit/audit', user_route=True)
371 376
372 377 # user caches
373 378 config.add_route(
374 379 name='edit_user_caches',
375 380 pattern='/users/{user_id:\d+}/edit/caches',
376 381 user_route=True)
377 382 config.add_route(
378 383 name='edit_user_caches_update',
379 384 pattern='/users/{user_id:\d+}/edit/caches/update',
380 385 user_route=True)
381 386
382 387 # user-groups admin
383 388 config.add_route(
384 389 name='user_groups',
385 390 pattern='/user_groups')
386 391
387 392 config.add_route(
388 393 name='user_groups_data',
389 394 pattern='/user_groups_data')
390 395
391 396 config.add_route(
392 397 name='user_groups_new',
393 398 pattern='/user_groups/new')
394 399
395 400 config.add_route(
396 401 name='user_groups_create',
397 402 pattern='/user_groups/create')
398 403
399 404 # repos admin
400 405 config.add_route(
401 406 name='repos',
402 407 pattern='/repos')
403 408
404 409 config.add_route(
405 410 name='repo_new',
406 411 pattern='/repos/new')
407 412
408 413 config.add_route(
409 414 name='repo_create',
410 415 pattern='/repos/create')
411 416
412 417 # repo groups admin
413 418 config.add_route(
414 419 name='repo_groups',
415 420 pattern='/repo_groups')
416 421
417 422 config.add_route(
418 423 name='repo_group_new',
419 424 pattern='/repo_group/new')
420 425
421 426 config.add_route(
422 427 name='repo_group_create',
423 428 pattern='/repo_group/create')
424 429
425 430
426 431 def includeme(config):
427 432 from rhodecode.apps.admin.navigation import includeme as nav_includeme
428 433
429 434 # Create admin navigation registry and add it to the pyramid registry.
430 435 nav_includeme(config)
431 436
432 437 # main admin routes
433 438 config.add_route(name='admin_home', pattern=ADMIN_PREFIX)
434 439 config.include(admin_routes, route_prefix=ADMIN_PREFIX)
435 440
436 441 config.include('.subscribers')
437 442
438 443 # Scan module for configuration decorators.
439 444 config.scan('.views', ignore='.tests')
@@ -1,484 +1,509 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2016-2018 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 re
22 22 import logging
23 23 import formencode
24 24 import formencode.htmlfill
25 25 import datetime
26 26 from pyramid.interfaces import IRoutesMapper
27 27
28 28 from pyramid.view import view_config
29 29 from pyramid.httpexceptions import HTTPFound
30 30 from pyramid.renderers import render
31 31 from pyramid.response import Response
32 32
33 33 from rhodecode.apps._base import BaseAppView, DataGridAppView
34 34 from rhodecode.apps.ssh_support import SshKeyFileChangeEvent
35 35 from rhodecode.events import trigger
36 36
37 37 from rhodecode.lib import helpers as h
38 38 from rhodecode.lib.auth import (
39 39 LoginRequired, HasPermissionAllDecorator, CSRFRequired)
40 40 from rhodecode.lib.utils2 import aslist, safe_unicode
41 41 from rhodecode.model.db import (
42 42 or_, coalesce, User, UserIpMap, UserSshKeys)
43 43 from rhodecode.model.forms import (
44 44 ApplicationPermissionsForm, ObjectPermissionsForm, UserPermissionsForm)
45 45 from rhodecode.model.meta import Session
46 46 from rhodecode.model.permission import PermissionModel
47 47 from rhodecode.model.settings import SettingsModel
48 48
49 49
50 50 log = logging.getLogger(__name__)
51 51
52 52
53 53 class AdminPermissionsView(BaseAppView, DataGridAppView):
54 54 def load_default_context(self):
55 55 c = self._get_local_tmpl_context()
56 56 PermissionModel().set_global_permission_choices(
57 57 c, gettext_translator=self.request.translate)
58 58 return c
59 59
60 60 @LoginRequired()
61 61 @HasPermissionAllDecorator('hg.admin')
62 62 @view_config(
63 63 route_name='admin_permissions_application', request_method='GET',
64 64 renderer='rhodecode:templates/admin/permissions/permissions.mako')
65 65 def permissions_application(self):
66 66 c = self.load_default_context()
67 67 c.active = 'application'
68 68
69 69 c.user = User.get_default_user(refresh=True)
70 70
71 71 app_settings = SettingsModel().get_all_settings()
72 72 defaults = {
73 73 'anonymous': c.user.active,
74 74 'default_register_message': app_settings.get(
75 75 'rhodecode_register_message')
76 76 }
77 77 defaults.update(c.user.get_default_perms())
78 78
79 79 data = render('rhodecode:templates/admin/permissions/permissions.mako',
80 80 self._get_template_context(c), self.request)
81 81 html = formencode.htmlfill.render(
82 82 data,
83 83 defaults=defaults,
84 84 encoding="UTF-8",
85 85 force_defaults=False
86 86 )
87 87 return Response(html)
88 88
89 89 @LoginRequired()
90 90 @HasPermissionAllDecorator('hg.admin')
91 91 @CSRFRequired()
92 92 @view_config(
93 93 route_name='admin_permissions_application_update', request_method='POST',
94 94 renderer='rhodecode:templates/admin/permissions/permissions.mako')
95 95 def permissions_application_update(self):
96 96 _ = self.request.translate
97 97 c = self.load_default_context()
98 98 c.active = 'application'
99 99
100 100 _form = ApplicationPermissionsForm(
101 101 self.request.translate,
102 102 [x[0] for x in c.register_choices],
103 103 [x[0] for x in c.password_reset_choices],
104 104 [x[0] for x in c.extern_activate_choices])()
105 105
106 106 try:
107 107 form_result = _form.to_python(dict(self.request.POST))
108 108 form_result.update({'perm_user_name': User.DEFAULT_USER})
109 109 PermissionModel().update_application_permissions(form_result)
110 110
111 111 settings = [
112 112 ('register_message', 'default_register_message'),
113 113 ]
114 114 for setting, form_key in settings:
115 115 sett = SettingsModel().create_or_update_setting(
116 116 setting, form_result[form_key])
117 117 Session().add(sett)
118 118
119 119 Session().commit()
120 120 h.flash(_('Application permissions updated successfully'),
121 121 category='success')
122 122
123 123 except formencode.Invalid as errors:
124 124 defaults = errors.value
125 125
126 126 data = render(
127 127 'rhodecode:templates/admin/permissions/permissions.mako',
128 128 self._get_template_context(c), self.request)
129 129 html = formencode.htmlfill.render(
130 130 data,
131 131 defaults=defaults,
132 132 errors=errors.error_dict or {},
133 133 prefix_error=False,
134 134 encoding="UTF-8",
135 135 force_defaults=False
136 136 )
137 137 return Response(html)
138 138
139 139 except Exception:
140 140 log.exception("Exception during update of permissions")
141 141 h.flash(_('Error occurred during update of permissions'),
142 142 category='error')
143 143
144 144 raise HTTPFound(h.route_path('admin_permissions_application'))
145 145
146 146 @LoginRequired()
147 147 @HasPermissionAllDecorator('hg.admin')
148 148 @view_config(
149 149 route_name='admin_permissions_object', request_method='GET',
150 150 renderer='rhodecode:templates/admin/permissions/permissions.mako')
151 151 def permissions_objects(self):
152 152 c = self.load_default_context()
153 153 c.active = 'objects'
154 154
155 155 c.user = User.get_default_user(refresh=True)
156 156 defaults = {}
157 157 defaults.update(c.user.get_default_perms())
158 158
159 159 data = render(
160 160 'rhodecode:templates/admin/permissions/permissions.mako',
161 161 self._get_template_context(c), self.request)
162 162 html = formencode.htmlfill.render(
163 163 data,
164 164 defaults=defaults,
165 165 encoding="UTF-8",
166 166 force_defaults=False
167 167 )
168 168 return Response(html)
169 169
170 170 @LoginRequired()
171 171 @HasPermissionAllDecorator('hg.admin')
172 172 @CSRFRequired()
173 173 @view_config(
174 174 route_name='admin_permissions_object_update', request_method='POST',
175 175 renderer='rhodecode:templates/admin/permissions/permissions.mako')
176 176 def permissions_objects_update(self):
177 177 _ = self.request.translate
178 178 c = self.load_default_context()
179 179 c.active = 'objects'
180 180
181 181 _form = ObjectPermissionsForm(
182 182 self.request.translate,
183 183 [x[0] for x in c.repo_perms_choices],
184 184 [x[0] for x in c.group_perms_choices],
185 [x[0] for x in c.user_group_perms_choices])()
185 [x[0] for x in c.user_group_perms_choices],
186 )()
186 187
187 188 try:
188 189 form_result = _form.to_python(dict(self.request.POST))
189 190 form_result.update({'perm_user_name': User.DEFAULT_USER})
190 191 PermissionModel().update_object_permissions(form_result)
191 192
192 193 Session().commit()
193 194 h.flash(_('Object permissions updated successfully'),
194 195 category='success')
195 196
196 197 except formencode.Invalid as errors:
197 198 defaults = errors.value
198 199
199 200 data = render(
200 201 'rhodecode:templates/admin/permissions/permissions.mako',
201 202 self._get_template_context(c), self.request)
202 203 html = formencode.htmlfill.render(
203 204 data,
204 205 defaults=defaults,
205 206 errors=errors.error_dict or {},
206 207 prefix_error=False,
207 208 encoding="UTF-8",
208 209 force_defaults=False
209 210 )
210 211 return Response(html)
211 212 except Exception:
212 213 log.exception("Exception during update of permissions")
213 214 h.flash(_('Error occurred during update of permissions'),
214 215 category='error')
215 216
216 217 raise HTTPFound(h.route_path('admin_permissions_object'))
217 218
218 219 @LoginRequired()
219 220 @HasPermissionAllDecorator('hg.admin')
220 221 @view_config(
222 route_name='admin_permissions_branch', request_method='GET',
223 renderer='rhodecode:templates/admin/permissions/permissions.mako')
224 def permissions_branch(self):
225 c = self.load_default_context()
226 c.active = 'branch'
227
228 c.user = User.get_default_user(refresh=True)
229 defaults = {}
230 defaults.update(c.user.get_default_perms())
231
232 data = render(
233 'rhodecode:templates/admin/permissions/permissions.mako',
234 self._get_template_context(c), self.request)
235 html = formencode.htmlfill.render(
236 data,
237 defaults=defaults,
238 encoding="UTF-8",
239 force_defaults=False
240 )
241 return Response(html)
242
243 @LoginRequired()
244 @HasPermissionAllDecorator('hg.admin')
245 @view_config(
221 246 route_name='admin_permissions_global', request_method='GET',
222 247 renderer='rhodecode:templates/admin/permissions/permissions.mako')
223 248 def permissions_global(self):
224 249 c = self.load_default_context()
225 250 c.active = 'global'
226 251
227 252 c.user = User.get_default_user(refresh=True)
228 253 defaults = {}
229 254 defaults.update(c.user.get_default_perms())
230 255
231 256 data = render(
232 257 'rhodecode:templates/admin/permissions/permissions.mako',
233 258 self._get_template_context(c), self.request)
234 259 html = formencode.htmlfill.render(
235 260 data,
236 261 defaults=defaults,
237 262 encoding="UTF-8",
238 263 force_defaults=False
239 264 )
240 265 return Response(html)
241 266
242 267 @LoginRequired()
243 268 @HasPermissionAllDecorator('hg.admin')
244 269 @CSRFRequired()
245 270 @view_config(
246 271 route_name='admin_permissions_global_update', request_method='POST',
247 272 renderer='rhodecode:templates/admin/permissions/permissions.mako')
248 273 def permissions_global_update(self):
249 274 _ = self.request.translate
250 275 c = self.load_default_context()
251 276 c.active = 'global'
252 277
253 278 _form = UserPermissionsForm(
254 279 self.request.translate,
255 280 [x[0] for x in c.repo_create_choices],
256 281 [x[0] for x in c.repo_create_on_write_choices],
257 282 [x[0] for x in c.repo_group_create_choices],
258 283 [x[0] for x in c.user_group_create_choices],
259 284 [x[0] for x in c.fork_choices],
260 285 [x[0] for x in c.inherit_default_permission_choices])()
261 286
262 287 try:
263 288 form_result = _form.to_python(dict(self.request.POST))
264 289 form_result.update({'perm_user_name': User.DEFAULT_USER})
265 290 PermissionModel().update_user_permissions(form_result)
266 291
267 292 Session().commit()
268 293 h.flash(_('Global permissions updated successfully'),
269 294 category='success')
270 295
271 296 except formencode.Invalid as errors:
272 297 defaults = errors.value
273 298
274 299 data = render(
275 300 'rhodecode:templates/admin/permissions/permissions.mako',
276 301 self._get_template_context(c), self.request)
277 302 html = formencode.htmlfill.render(
278 303 data,
279 304 defaults=defaults,
280 305 errors=errors.error_dict or {},
281 306 prefix_error=False,
282 307 encoding="UTF-8",
283 308 force_defaults=False
284 309 )
285 310 return Response(html)
286 311 except Exception:
287 312 log.exception("Exception during update of permissions")
288 313 h.flash(_('Error occurred during update of permissions'),
289 314 category='error')
290 315
291 316 raise HTTPFound(h.route_path('admin_permissions_global'))
292 317
293 318 @LoginRequired()
294 319 @HasPermissionAllDecorator('hg.admin')
295 320 @view_config(
296 321 route_name='admin_permissions_ips', request_method='GET',
297 322 renderer='rhodecode:templates/admin/permissions/permissions.mako')
298 323 def permissions_ips(self):
299 324 c = self.load_default_context()
300 325 c.active = 'ips'
301 326
302 327 c.user = User.get_default_user(refresh=True)
303 328 c.user_ip_map = (
304 329 UserIpMap.query().filter(UserIpMap.user == c.user).all())
305 330
306 331 return self._get_template_context(c)
307 332
308 333 @LoginRequired()
309 334 @HasPermissionAllDecorator('hg.admin')
310 335 @view_config(
311 336 route_name='admin_permissions_overview', request_method='GET',
312 337 renderer='rhodecode:templates/admin/permissions/permissions.mako')
313 338 def permissions_overview(self):
314 339 c = self.load_default_context()
315 340 c.active = 'perms'
316 341
317 342 c.user = User.get_default_user(refresh=True)
318 343 c.perm_user = c.user.AuthUser()
319 344 return self._get_template_context(c)
320 345
321 346 @LoginRequired()
322 347 @HasPermissionAllDecorator('hg.admin')
323 348 @view_config(
324 349 route_name='admin_permissions_auth_token_access', request_method='GET',
325 350 renderer='rhodecode:templates/admin/permissions/permissions.mako')
326 351 def auth_token_access(self):
327 352 from rhodecode import CONFIG
328 353
329 354 c = self.load_default_context()
330 355 c.active = 'auth_token_access'
331 356
332 357 c.user = User.get_default_user(refresh=True)
333 358 c.perm_user = c.user.AuthUser()
334 359
335 360 mapper = self.request.registry.queryUtility(IRoutesMapper)
336 361 c.view_data = []
337 362
338 363 _argument_prog = re.compile('\{(.*?)\}|:\((.*)\)')
339 364 introspector = self.request.registry.introspector
340 365
341 366 view_intr = {}
342 367 for view_data in introspector.get_category('views'):
343 368 intr = view_data['introspectable']
344 369
345 370 if 'route_name' in intr and intr['attr']:
346 371 view_intr[intr['route_name']] = '{}:{}'.format(
347 372 str(intr['derived_callable'].func_name), intr['attr']
348 373 )
349 374
350 375 c.whitelist_key = 'api_access_controllers_whitelist'
351 376 c.whitelist_file = CONFIG.get('__file__')
352 377 whitelist_views = aslist(
353 378 CONFIG.get(c.whitelist_key), sep=',')
354 379
355 380 for route_info in mapper.get_routes():
356 381 if not route_info.name.startswith('__'):
357 382 routepath = route_info.pattern
358 383
359 384 def replace(matchobj):
360 385 if matchobj.group(1):
361 386 return "{%s}" % matchobj.group(1).split(':')[0]
362 387 else:
363 388 return "{%s}" % matchobj.group(2)
364 389
365 390 routepath = _argument_prog.sub(replace, routepath)
366 391
367 392 if not routepath.startswith('/'):
368 393 routepath = '/' + routepath
369 394
370 395 view_fqn = view_intr.get(route_info.name, 'NOT AVAILABLE')
371 396 active = view_fqn in whitelist_views
372 397 c.view_data.append((route_info.name, view_fqn, routepath, active))
373 398
374 399 c.whitelist_views = whitelist_views
375 400 return self._get_template_context(c)
376 401
377 402 def ssh_enabled(self):
378 403 return self.request.registry.settings.get(
379 404 'ssh.generate_authorized_keyfile')
380 405
381 406 @LoginRequired()
382 407 @HasPermissionAllDecorator('hg.admin')
383 408 @view_config(
384 409 route_name='admin_permissions_ssh_keys', request_method='GET',
385 410 renderer='rhodecode:templates/admin/permissions/permissions.mako')
386 411 def ssh_keys(self):
387 412 c = self.load_default_context()
388 413 c.active = 'ssh_keys'
389 414 c.ssh_enabled = self.ssh_enabled()
390 415 return self._get_template_context(c)
391 416
392 417 @LoginRequired()
393 418 @HasPermissionAllDecorator('hg.admin')
394 419 @view_config(
395 420 route_name='admin_permissions_ssh_keys_data', request_method='GET',
396 421 renderer='json_ext', xhr=True)
397 422 def ssh_keys_data(self):
398 423 _ = self.request.translate
399 424 self.load_default_context()
400 425 column_map = {
401 426 'fingerprint': 'ssh_key_fingerprint',
402 427 'username': User.username
403 428 }
404 429 draw, start, limit = self._extract_chunk(self.request)
405 430 search_q, order_by, order_dir = self._extract_ordering(
406 431 self.request, column_map=column_map)
407 432
408 433 ssh_keys_data_total_count = UserSshKeys.query()\
409 434 .count()
410 435
411 436 # json generate
412 437 base_q = UserSshKeys.query().join(UserSshKeys.user)
413 438
414 439 if search_q:
415 440 like_expression = u'%{}%'.format(safe_unicode(search_q))
416 441 base_q = base_q.filter(or_(
417 442 User.username.ilike(like_expression),
418 443 UserSshKeys.ssh_key_fingerprint.ilike(like_expression),
419 444 ))
420 445
421 446 users_data_total_filtered_count = base_q.count()
422 447
423 448 sort_col = self._get_order_col(order_by, UserSshKeys)
424 449 if sort_col:
425 450 if order_dir == 'asc':
426 451 # handle null values properly to order by NULL last
427 452 if order_by in ['created_on']:
428 453 sort_col = coalesce(sort_col, datetime.date.max)
429 454 sort_col = sort_col.asc()
430 455 else:
431 456 # handle null values properly to order by NULL last
432 457 if order_by in ['created_on']:
433 458 sort_col = coalesce(sort_col, datetime.date.min)
434 459 sort_col = sort_col.desc()
435 460
436 461 base_q = base_q.order_by(sort_col)
437 462 base_q = base_q.offset(start).limit(limit)
438 463
439 464 ssh_keys = base_q.all()
440 465
441 466 ssh_keys_data = []
442 467 for ssh_key in ssh_keys:
443 468 ssh_keys_data.append({
444 469 "username": h.gravatar_with_user(self.request, ssh_key.user.username),
445 470 "fingerprint": ssh_key.ssh_key_fingerprint,
446 471 "description": ssh_key.description,
447 472 "created_on": h.format_date(ssh_key.created_on),
448 473 "accessed_on": h.format_date(ssh_key.accessed_on),
449 474 "action": h.link_to(
450 475 _('Edit'), h.route_path('edit_user_ssh_keys',
451 476 user_id=ssh_key.user.user_id))
452 477 })
453 478
454 479 data = ({
455 480 'draw': draw,
456 481 'data': ssh_keys_data,
457 482 'recordsTotal': ssh_keys_data_total_count,
458 483 'recordsFiltered': users_data_total_filtered_count,
459 484 })
460 485
461 486 return data
462 487
463 488 @LoginRequired()
464 489 @HasPermissionAllDecorator('hg.admin')
465 490 @CSRFRequired()
466 491 @view_config(
467 492 route_name='admin_permissions_ssh_keys_update', request_method='POST',
468 493 renderer='rhodecode:templates/admin/permissions/permissions.mako')
469 494 def ssh_keys_update(self):
470 495 _ = self.request.translate
471 496 self.load_default_context()
472 497
473 498 ssh_enabled = self.ssh_enabled()
474 499 key_file = self.request.registry.settings.get(
475 500 'ssh.authorized_keys_file_path')
476 501 if ssh_enabled:
477 502 trigger(SshKeyFileChangeEvent(), self.request.registry)
478 503 h.flash(_('Updated SSH keys file: {}').format(key_file),
479 504 category='success')
480 505 else:
481 506 h.flash(_('SSH key support is disabled in .ini file'),
482 507 category='warning')
483 508
484 509 raise HTTPFound(h.route_path('admin_permissions_ssh_keys'))
@@ -1,467 +1,476 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2016-2018 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 from rhodecode.apps._base import add_route_with_slash
21 21
22 22
23 23 def includeme(config):
24 24
25 25 # repo creating checks, special cases that aren't repo routes
26 26 config.add_route(
27 27 name='repo_creating',
28 28 pattern='/{repo_name:.*?[^/]}/repo_creating')
29 29
30 30 config.add_route(
31 31 name='repo_creating_check',
32 32 pattern='/{repo_name:.*?[^/]}/repo_creating_check')
33 33
34 34 # Summary
35 35 # NOTE(marcink): one additional route is defined in very bottom, catch
36 36 # all pattern
37 37 config.add_route(
38 38 name='repo_summary_explicit',
39 39 pattern='/{repo_name:.*?[^/]}/summary', repo_route=True)
40 40 config.add_route(
41 41 name='repo_summary_commits',
42 42 pattern='/{repo_name:.*?[^/]}/summary-commits', repo_route=True)
43 43
44 44 # Commits
45 45 config.add_route(
46 46 name='repo_commit',
47 47 pattern='/{repo_name:.*?[^/]}/changeset/{commit_id}', repo_route=True)
48 48
49 49 config.add_route(
50 50 name='repo_commit_children',
51 51 pattern='/{repo_name:.*?[^/]}/changeset_children/{commit_id}', repo_route=True)
52 52
53 53 config.add_route(
54 54 name='repo_commit_parents',
55 55 pattern='/{repo_name:.*?[^/]}/changeset_parents/{commit_id}', repo_route=True)
56 56
57 57 config.add_route(
58 58 name='repo_commit_raw',
59 59 pattern='/{repo_name:.*?[^/]}/changeset-diff/{commit_id}', repo_route=True)
60 60
61 61 config.add_route(
62 62 name='repo_commit_patch',
63 63 pattern='/{repo_name:.*?[^/]}/changeset-patch/{commit_id}', repo_route=True)
64 64
65 65 config.add_route(
66 66 name='repo_commit_download',
67 67 pattern='/{repo_name:.*?[^/]}/changeset-download/{commit_id}', repo_route=True)
68 68
69 69 config.add_route(
70 70 name='repo_commit_data',
71 71 pattern='/{repo_name:.*?[^/]}/changeset-data/{commit_id}', repo_route=True)
72 72
73 73 config.add_route(
74 74 name='repo_commit_comment_create',
75 75 pattern='/{repo_name:.*?[^/]}/changeset/{commit_id}/comment/create', repo_route=True)
76 76
77 77 config.add_route(
78 78 name='repo_commit_comment_preview',
79 79 pattern='/{repo_name:.*?[^/]}/changeset/{commit_id}/comment/preview', repo_route=True)
80 80
81 81 config.add_route(
82 82 name='repo_commit_comment_delete',
83 83 pattern='/{repo_name:.*?[^/]}/changeset/{commit_id}/comment/{comment_id}/delete', repo_route=True)
84 84
85 85 # still working url for backward compat.
86 86 config.add_route(
87 87 name='repo_commit_raw_deprecated',
88 88 pattern='/{repo_name:.*?[^/]}/raw-changeset/{commit_id}', repo_route=True)
89 89
90 90 # Files
91 91 config.add_route(
92 92 name='repo_archivefile',
93 93 pattern='/{repo_name:.*?[^/]}/archive/{fname}', repo_route=True)
94 94
95 95 config.add_route(
96 96 name='repo_files_diff',
97 97 pattern='/{repo_name:.*?[^/]}/diff/{f_path:.*}', repo_route=True)
98 98 config.add_route( # legacy route to make old links work
99 99 name='repo_files_diff_2way_redirect',
100 100 pattern='/{repo_name:.*?[^/]}/diff-2way/{f_path:.*}', repo_route=True)
101 101
102 102 config.add_route(
103 103 name='repo_files',
104 104 pattern='/{repo_name:.*?[^/]}/files/{commit_id}/{f_path:.*}', repo_route=True)
105 105 config.add_route(
106 106 name='repo_files:default_path',
107 107 pattern='/{repo_name:.*?[^/]}/files/{commit_id}/', repo_route=True)
108 108 config.add_route(
109 109 name='repo_files:default_commit',
110 110 pattern='/{repo_name:.*?[^/]}/files', repo_route=True)
111 111
112 112 config.add_route(
113 113 name='repo_files:rendered',
114 114 pattern='/{repo_name:.*?[^/]}/render/{commit_id}/{f_path:.*}', repo_route=True)
115 115
116 116 config.add_route(
117 117 name='repo_files:annotated',
118 118 pattern='/{repo_name:.*?[^/]}/annotate/{commit_id}/{f_path:.*}', repo_route=True)
119 119 config.add_route(
120 120 name='repo_files:annotated_previous',
121 121 pattern='/{repo_name:.*?[^/]}/annotate-previous/{commit_id}/{f_path:.*}', repo_route=True)
122 122
123 123 config.add_route(
124 124 name='repo_nodetree_full',
125 125 pattern='/{repo_name:.*?[^/]}/nodetree_full/{commit_id}/{f_path:.*}', repo_route=True)
126 126 config.add_route(
127 127 name='repo_nodetree_full:default_path',
128 128 pattern='/{repo_name:.*?[^/]}/nodetree_full/{commit_id}/', repo_route=True)
129 129
130 130 config.add_route(
131 131 name='repo_files_nodelist',
132 132 pattern='/{repo_name:.*?[^/]}/nodelist/{commit_id}/{f_path:.*}', repo_route=True)
133 133
134 134 config.add_route(
135 135 name='repo_file_raw',
136 136 pattern='/{repo_name:.*?[^/]}/raw/{commit_id}/{f_path:.*}', repo_route=True)
137 137
138 138 config.add_route(
139 139 name='repo_file_download',
140 140 pattern='/{repo_name:.*?[^/]}/download/{commit_id}/{f_path:.*}', repo_route=True)
141 141 config.add_route( # backward compat to keep old links working
142 142 name='repo_file_download:legacy',
143 143 pattern='/{repo_name:.*?[^/]}/rawfile/{commit_id}/{f_path:.*}',
144 144 repo_route=True)
145 145
146 146 config.add_route(
147 147 name='repo_file_history',
148 148 pattern='/{repo_name:.*?[^/]}/history/{commit_id}/{f_path:.*}', repo_route=True)
149 149
150 150 config.add_route(
151 151 name='repo_file_authors',
152 152 pattern='/{repo_name:.*?[^/]}/authors/{commit_id}/{f_path:.*}', repo_route=True)
153 153
154 154 config.add_route(
155 155 name='repo_files_remove_file',
156 156 pattern='/{repo_name:.*?[^/]}/remove_file/{commit_id}/{f_path:.*}',
157 157 repo_route=True)
158 158 config.add_route(
159 159 name='repo_files_delete_file',
160 160 pattern='/{repo_name:.*?[^/]}/delete_file/{commit_id}/{f_path:.*}',
161 161 repo_route=True)
162 162 config.add_route(
163 163 name='repo_files_edit_file',
164 164 pattern='/{repo_name:.*?[^/]}/edit_file/{commit_id}/{f_path:.*}',
165 165 repo_route=True)
166 166 config.add_route(
167 167 name='repo_files_update_file',
168 168 pattern='/{repo_name:.*?[^/]}/update_file/{commit_id}/{f_path:.*}',
169 169 repo_route=True)
170 170 config.add_route(
171 171 name='repo_files_add_file',
172 172 pattern='/{repo_name:.*?[^/]}/add_file/{commit_id}/{f_path:.*}',
173 173 repo_route=True)
174 174 config.add_route(
175 175 name='repo_files_create_file',
176 176 pattern='/{repo_name:.*?[^/]}/create_file/{commit_id}/{f_path:.*}',
177 177 repo_route=True)
178 178
179 179 # Refs data
180 180 config.add_route(
181 181 name='repo_refs_data',
182 182 pattern='/{repo_name:.*?[^/]}/refs-data', repo_route=True)
183 183
184 184 config.add_route(
185 185 name='repo_refs_changelog_data',
186 186 pattern='/{repo_name:.*?[^/]}/refs-data-changelog', repo_route=True)
187 187
188 188 config.add_route(
189 189 name='repo_stats',
190 190 pattern='/{repo_name:.*?[^/]}/repo_stats/{commit_id}', repo_route=True)
191 191
192 192 # Changelog
193 193 config.add_route(
194 194 name='repo_changelog',
195 195 pattern='/{repo_name:.*?[^/]}/changelog', repo_route=True)
196 196 config.add_route(
197 197 name='repo_changelog_file',
198 198 pattern='/{repo_name:.*?[^/]}/changelog/{commit_id}/{f_path:.*}', repo_route=True)
199 199 config.add_route(
200 200 name='repo_changelog_elements',
201 201 pattern='/{repo_name:.*?[^/]}/changelog_elements', repo_route=True)
202 202 config.add_route(
203 203 name='repo_changelog_elements_file',
204 204 pattern='/{repo_name:.*?[^/]}/changelog_elements/{commit_id}/{f_path:.*}', repo_route=True)
205 205
206 206 # Compare
207 207 config.add_route(
208 208 name='repo_compare_select',
209 209 pattern='/{repo_name:.*?[^/]}/compare', repo_route=True)
210 210
211 211 config.add_route(
212 212 name='repo_compare',
213 213 pattern='/{repo_name:.*?[^/]}/compare/{source_ref_type}@{source_ref:.*?}...{target_ref_type}@{target_ref:.*?}', repo_route=True)
214 214
215 215 # Tags
216 216 config.add_route(
217 217 name='tags_home',
218 218 pattern='/{repo_name:.*?[^/]}/tags', repo_route=True)
219 219
220 220 # Branches
221 221 config.add_route(
222 222 name='branches_home',
223 223 pattern='/{repo_name:.*?[^/]}/branches', repo_route=True)
224 224
225 225 # Bookmarks
226 226 config.add_route(
227 227 name='bookmarks_home',
228 228 pattern='/{repo_name:.*?[^/]}/bookmarks', repo_route=True)
229 229
230 230 # Forks
231 231 config.add_route(
232 232 name='repo_fork_new',
233 233 pattern='/{repo_name:.*?[^/]}/fork', repo_route=True,
234 234 repo_accepted_types=['hg', 'git'])
235 235
236 236 config.add_route(
237 237 name='repo_fork_create',
238 238 pattern='/{repo_name:.*?[^/]}/fork/create', repo_route=True,
239 239 repo_accepted_types=['hg', 'git'])
240 240
241 241 config.add_route(
242 242 name='repo_forks_show_all',
243 243 pattern='/{repo_name:.*?[^/]}/forks', repo_route=True,
244 244 repo_accepted_types=['hg', 'git'])
245 245 config.add_route(
246 246 name='repo_forks_data',
247 247 pattern='/{repo_name:.*?[^/]}/forks/data', repo_route=True,
248 248 repo_accepted_types=['hg', 'git'])
249 249
250 250 # Pull Requests
251 251 config.add_route(
252 252 name='pullrequest_show',
253 253 pattern='/{repo_name:.*?[^/]}/pull-request/{pull_request_id:\d+}',
254 254 repo_route=True)
255 255
256 256 config.add_route(
257 257 name='pullrequest_show_all',
258 258 pattern='/{repo_name:.*?[^/]}/pull-request',
259 259 repo_route=True, repo_accepted_types=['hg', 'git'])
260 260
261 261 config.add_route(
262 262 name='pullrequest_show_all_data',
263 263 pattern='/{repo_name:.*?[^/]}/pull-request-data',
264 264 repo_route=True, repo_accepted_types=['hg', 'git'])
265 265
266 266 config.add_route(
267 267 name='pullrequest_repo_refs',
268 268 pattern='/{repo_name:.*?[^/]}/pull-request/refs/{target_repo_name:.*?[^/]}',
269 269 repo_route=True)
270 270
271 271 config.add_route(
272 272 name='pullrequest_repo_destinations',
273 273 pattern='/{repo_name:.*?[^/]}/pull-request/repo-destinations',
274 274 repo_route=True)
275 275
276 276 config.add_route(
277 277 name='pullrequest_new',
278 278 pattern='/{repo_name:.*?[^/]}/pull-request/new',
279 279 repo_route=True, repo_accepted_types=['hg', 'git'])
280 280
281 281 config.add_route(
282 282 name='pullrequest_create',
283 283 pattern='/{repo_name:.*?[^/]}/pull-request/create',
284 284 repo_route=True, repo_accepted_types=['hg', 'git'])
285 285
286 286 config.add_route(
287 287 name='pullrequest_update',
288 288 pattern='/{repo_name:.*?[^/]}/pull-request/{pull_request_id:\d+}/update',
289 289 repo_route=True)
290 290
291 291 config.add_route(
292 292 name='pullrequest_merge',
293 293 pattern='/{repo_name:.*?[^/]}/pull-request/{pull_request_id:\d+}/merge',
294 294 repo_route=True)
295 295
296 296 config.add_route(
297 297 name='pullrequest_delete',
298 298 pattern='/{repo_name:.*?[^/]}/pull-request/{pull_request_id:\d+}/delete',
299 299 repo_route=True)
300 300
301 301 config.add_route(
302 302 name='pullrequest_comment_create',
303 303 pattern='/{repo_name:.*?[^/]}/pull-request/{pull_request_id:\d+}/comment',
304 304 repo_route=True)
305 305
306 306 config.add_route(
307 307 name='pullrequest_comment_delete',
308 308 pattern='/{repo_name:.*?[^/]}/pull-request/{pull_request_id:\d+}/comment/{comment_id}/delete',
309 309 repo_route=True, repo_accepted_types=['hg', 'git'])
310 310
311 311 # Settings
312 312 config.add_route(
313 313 name='edit_repo',
314 314 pattern='/{repo_name:.*?[^/]}/settings', repo_route=True)
315 315 # update is POST on edit_repo
316 316
317 317 # Settings advanced
318 318 config.add_route(
319 319 name='edit_repo_advanced',
320 320 pattern='/{repo_name:.*?[^/]}/settings/advanced', repo_route=True)
321 321 config.add_route(
322 322 name='edit_repo_advanced_delete',
323 323 pattern='/{repo_name:.*?[^/]}/settings/advanced/delete', repo_route=True)
324 324 config.add_route(
325 325 name='edit_repo_advanced_locking',
326 326 pattern='/{repo_name:.*?[^/]}/settings/advanced/locking', repo_route=True)
327 327 config.add_route(
328 328 name='edit_repo_advanced_journal',
329 329 pattern='/{repo_name:.*?[^/]}/settings/advanced/journal', repo_route=True)
330 330 config.add_route(
331 331 name='edit_repo_advanced_fork',
332 332 pattern='/{repo_name:.*?[^/]}/settings/advanced/fork', repo_route=True)
333 333
334 334 config.add_route(
335 335 name='edit_repo_advanced_hooks',
336 336 pattern='/{repo_name:.*?[^/]}/settings/advanced/hooks', repo_route=True)
337 337
338 338 # Caches
339 339 config.add_route(
340 340 name='edit_repo_caches',
341 341 pattern='/{repo_name:.*?[^/]}/settings/caches', repo_route=True)
342 342
343 343 # Permissions
344 344 config.add_route(
345 345 name='edit_repo_perms',
346 346 pattern='/{repo_name:.*?[^/]}/settings/permissions', repo_route=True)
347 347
348 # Permissions Branch (EE feature)
349 config.add_route(
350 name='edit_repo_perms_branch',
351 pattern='/{repo_name:.*?[^/]}/settings/branch_permissions', repo_route=True)
352 config.add_route(
353 name='edit_repo_perms_branch_delete',
354 pattern='/{repo_name:.*?[^/]}/settings/branch_permissions/{rule_id}/delete',
355 repo_route=True)
356
348 357 # Maintenance
349 358 config.add_route(
350 359 name='edit_repo_maintenance',
351 360 pattern='/{repo_name:.*?[^/]}/settings/maintenance', repo_route=True)
352 361
353 362 config.add_route(
354 363 name='edit_repo_maintenance_execute',
355 364 pattern='/{repo_name:.*?[^/]}/settings/maintenance/execute', repo_route=True)
356 365
357 366 # Fields
358 367 config.add_route(
359 368 name='edit_repo_fields',
360 369 pattern='/{repo_name:.*?[^/]}/settings/fields', repo_route=True)
361 370 config.add_route(
362 371 name='edit_repo_fields_create',
363 372 pattern='/{repo_name:.*?[^/]}/settings/fields/create', repo_route=True)
364 373 config.add_route(
365 374 name='edit_repo_fields_delete',
366 375 pattern='/{repo_name:.*?[^/]}/settings/fields/{field_id}/delete', repo_route=True)
367 376
368 377 # Locking
369 378 config.add_route(
370 379 name='repo_edit_toggle_locking',
371 380 pattern='/{repo_name:.*?[^/]}/settings/toggle_locking', repo_route=True)
372 381
373 382 # Remote
374 383 config.add_route(
375 384 name='edit_repo_remote',
376 385 pattern='/{repo_name:.*?[^/]}/settings/remote', repo_route=True)
377 386 config.add_route(
378 387 name='edit_repo_remote_pull',
379 388 pattern='/{repo_name:.*?[^/]}/settings/remote/pull', repo_route=True)
380 389 config.add_route(
381 390 name='edit_repo_remote_push',
382 391 pattern='/{repo_name:.*?[^/]}/settings/remote/push', repo_route=True)
383 392
384 393 # Statistics
385 394 config.add_route(
386 395 name='edit_repo_statistics',
387 396 pattern='/{repo_name:.*?[^/]}/settings/statistics', repo_route=True)
388 397 config.add_route(
389 398 name='edit_repo_statistics_reset',
390 399 pattern='/{repo_name:.*?[^/]}/settings/statistics/update', repo_route=True)
391 400
392 401 # Issue trackers
393 402 config.add_route(
394 403 name='edit_repo_issuetracker',
395 404 pattern='/{repo_name:.*?[^/]}/settings/issue_trackers', repo_route=True)
396 405 config.add_route(
397 406 name='edit_repo_issuetracker_test',
398 407 pattern='/{repo_name:.*?[^/]}/settings/issue_trackers/test', repo_route=True)
399 408 config.add_route(
400 409 name='edit_repo_issuetracker_delete',
401 410 pattern='/{repo_name:.*?[^/]}/settings/issue_trackers/delete', repo_route=True)
402 411 config.add_route(
403 412 name='edit_repo_issuetracker_update',
404 413 pattern='/{repo_name:.*?[^/]}/settings/issue_trackers/update', repo_route=True)
405 414
406 415 # VCS Settings
407 416 config.add_route(
408 417 name='edit_repo_vcs',
409 418 pattern='/{repo_name:.*?[^/]}/settings/vcs', repo_route=True)
410 419 config.add_route(
411 420 name='edit_repo_vcs_update',
412 421 pattern='/{repo_name:.*?[^/]}/settings/vcs/update', repo_route=True)
413 422
414 423 # svn pattern
415 424 config.add_route(
416 425 name='edit_repo_vcs_svn_pattern_delete',
417 426 pattern='/{repo_name:.*?[^/]}/settings/vcs/svn_pattern/delete', repo_route=True)
418 427
419 428 # Repo Review Rules (EE feature)
420 429 config.add_route(
421 430 name='repo_reviewers',
422 431 pattern='/{repo_name:.*?[^/]}/settings/review/rules', repo_route=True)
423 432
424 433 config.add_route(
425 434 name='repo_default_reviewers_data',
426 435 pattern='/{repo_name:.*?[^/]}/settings/review/default-reviewers', repo_route=True)
427 436
428 437 # Repo Automation (EE feature)
429 438 config.add_route(
430 439 name='repo_automation',
431 440 pattern='/{repo_name:.*?[^/]}/settings/automation', repo_route=True)
432 441
433 442 # Strip
434 443 config.add_route(
435 444 name='edit_repo_strip',
436 445 pattern='/{repo_name:.*?[^/]}/settings/strip', repo_route=True)
437 446
438 447 config.add_route(
439 448 name='strip_check',
440 449 pattern='/{repo_name:.*?[^/]}/settings/strip_check', repo_route=True)
441 450
442 451 config.add_route(
443 452 name='strip_execute',
444 453 pattern='/{repo_name:.*?[^/]}/settings/strip_execute', repo_route=True)
445 454
446 455 # Audit logs
447 456 config.add_route(
448 457 name='edit_repo_audit_logs',
449 458 pattern='/{repo_name:.*?[^/]}/settings/audit_logs', repo_route=True)
450 459
451 460 # ATOM/RSS Feed
452 461 config.add_route(
453 462 name='rss_feed_home',
454 463 pattern='/{repo_name:.*?[^/]}/feed/rss', repo_route=True)
455 464
456 465 config.add_route(
457 466 name='atom_feed_home',
458 467 pattern='/{repo_name:.*?[^/]}/feed/atom', repo_route=True)
459 468
460 469 # NOTE(marcink): needs to be at the end for catch-all
461 470 add_route_with_slash(
462 471 config,
463 472 name='repo_summary',
464 473 pattern='/{repo_name:.*?[^/]}', repo_route=True)
465 474
466 475 # Scan module for configuration decorators.
467 476 config.scan('.views', ignore='.tests')
@@ -1,2195 +1,2295 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2018 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 time
27 27 import inspect
28 28 import collections
29 29 import fnmatch
30 30 import hashlib
31 31 import itertools
32 32 import logging
33 33 import random
34 34 import traceback
35 35 from functools import wraps
36 36
37 37 import ipaddress
38 38
39 39 from pyramid.httpexceptions import HTTPForbidden, HTTPFound, HTTPNotFound
40 40 from sqlalchemy.orm.exc import ObjectDeletedError
41 41 from sqlalchemy.orm import joinedload
42 42 from zope.cachedescriptors.property import Lazy as LazyProperty
43 43
44 44 import rhodecode
45 45 from rhodecode.model import meta
46 46 from rhodecode.model.meta import Session
47 47 from rhodecode.model.user import UserModel
48 48 from rhodecode.model.db import (
49 49 User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember,
50 50 UserIpMap, UserApiKeys, RepoGroup, UserGroup)
51 51 from rhodecode.lib import rc_cache
52 52 from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5, safe_int, sha1
53 53 from rhodecode.lib.utils import (
54 54 get_repo_slug, get_repo_group_slug, get_user_group_slug)
55 55 from rhodecode.lib.caching_query import FromCache
56 56
57 57
58 58 if rhodecode.is_unix:
59 59 import bcrypt
60 60
61 61 log = logging.getLogger(__name__)
62 62
63 63 csrf_token_key = "csrf_token"
64 64
65 65
66 66 class PasswordGenerator(object):
67 67 """
68 68 This is a simple class for generating password from different sets of
69 69 characters
70 70 usage::
71 71
72 72 passwd_gen = PasswordGenerator()
73 73 #print 8-letter password containing only big and small letters
74 74 of alphabet
75 75 passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
76 76 """
77 77 ALPHABETS_NUM = r'''1234567890'''
78 78 ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
79 79 ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
80 80 ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
81 81 ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
82 82 + ALPHABETS_NUM + ALPHABETS_SPECIAL
83 83 ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
84 84 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
85 85 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
86 86 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
87 87
88 88 def __init__(self, passwd=''):
89 89 self.passwd = passwd
90 90
91 91 def gen_password(self, length, type_=None):
92 92 if type_ is None:
93 93 type_ = self.ALPHABETS_FULL
94 94 self.passwd = ''.join([random.choice(type_) for _ in range(length)])
95 95 return self.passwd
96 96
97 97
98 98 class _RhodeCodeCryptoBase(object):
99 99 ENC_PREF = None
100 100
101 101 def hash_create(self, str_):
102 102 """
103 103 hash the string using
104 104
105 105 :param str_: password to hash
106 106 """
107 107 raise NotImplementedError
108 108
109 109 def hash_check_with_upgrade(self, password, hashed):
110 110 """
111 111 Returns tuple in which first element is boolean that states that
112 112 given password matches it's hashed version, and the second is new hash
113 113 of the password, in case this password should be migrated to new
114 114 cipher.
115 115 """
116 116 checked_hash = self.hash_check(password, hashed)
117 117 return checked_hash, None
118 118
119 119 def hash_check(self, password, hashed):
120 120 """
121 121 Checks matching password with it's hashed value.
122 122
123 123 :param password: password
124 124 :param hashed: password in hashed form
125 125 """
126 126 raise NotImplementedError
127 127
128 128 def _assert_bytes(self, value):
129 129 """
130 130 Passing in an `unicode` object can lead to hard to detect issues
131 131 if passwords contain non-ascii characters. Doing a type check
132 132 during runtime, so that such mistakes are detected early on.
133 133 """
134 134 if not isinstance(value, str):
135 135 raise TypeError(
136 136 "Bytestring required as input, got %r." % (value, ))
137 137
138 138
139 139 class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase):
140 140 ENC_PREF = ('$2a$10', '$2b$10')
141 141
142 142 def hash_create(self, str_):
143 143 self._assert_bytes(str_)
144 144 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
145 145
146 146 def hash_check_with_upgrade(self, password, hashed):
147 147 """
148 148 Returns tuple in which first element is boolean that states that
149 149 given password matches it's hashed version, and the second is new hash
150 150 of the password, in case this password should be migrated to new
151 151 cipher.
152 152
153 153 This implements special upgrade logic which works like that:
154 154 - check if the given password == bcrypted hash, if yes then we
155 155 properly used password and it was already in bcrypt. Proceed
156 156 without any changes
157 157 - if bcrypt hash check is not working try with sha256. If hash compare
158 158 is ok, it means we using correct but old hashed password. indicate
159 159 hash change and proceed
160 160 """
161 161
162 162 new_hash = None
163 163
164 164 # regular pw check
165 165 password_match_bcrypt = self.hash_check(password, hashed)
166 166
167 167 # now we want to know if the password was maybe from sha256
168 168 # basically calling _RhodeCodeCryptoSha256().hash_check()
169 169 if not password_match_bcrypt:
170 170 if _RhodeCodeCryptoSha256().hash_check(password, hashed):
171 171 new_hash = self.hash_create(password) # make new bcrypt hash
172 172 password_match_bcrypt = True
173 173
174 174 return password_match_bcrypt, new_hash
175 175
176 176 def hash_check(self, password, hashed):
177 177 """
178 178 Checks matching password with it's hashed value.
179 179
180 180 :param password: password
181 181 :param hashed: password in hashed form
182 182 """
183 183 self._assert_bytes(password)
184 184 try:
185 185 return bcrypt.hashpw(password, hashed) == hashed
186 186 except ValueError as e:
187 187 # we're having a invalid salt here probably, we should not crash
188 188 # just return with False as it would be a wrong password.
189 189 log.debug('Failed to check password hash using bcrypt %s',
190 190 safe_str(e))
191 191
192 192 return False
193 193
194 194
195 195 class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase):
196 196 ENC_PREF = '_'
197 197
198 198 def hash_create(self, str_):
199 199 self._assert_bytes(str_)
200 200 return hashlib.sha256(str_).hexdigest()
201 201
202 202 def hash_check(self, password, hashed):
203 203 """
204 204 Checks matching password with it's hashed value.
205 205
206 206 :param password: password
207 207 :param hashed: password in hashed form
208 208 """
209 209 self._assert_bytes(password)
210 210 return hashlib.sha256(password).hexdigest() == hashed
211 211
212 212
213 213 class _RhodeCodeCryptoTest(_RhodeCodeCryptoBase):
214 214 ENC_PREF = '_'
215 215
216 216 def hash_create(self, str_):
217 217 self._assert_bytes(str_)
218 218 return sha1(str_)
219 219
220 220 def hash_check(self, password, hashed):
221 221 """
222 222 Checks matching password with it's hashed value.
223 223
224 224 :param password: password
225 225 :param hashed: password in hashed form
226 226 """
227 227 self._assert_bytes(password)
228 228 return sha1(password) == hashed
229 229
230 230
231 231 def crypto_backend():
232 232 """
233 233 Return the matching crypto backend.
234 234
235 235 Selection is based on if we run tests or not, we pick sha1-test backend to run
236 236 tests faster since BCRYPT is expensive to calculate
237 237 """
238 238 if rhodecode.is_test:
239 239 RhodeCodeCrypto = _RhodeCodeCryptoTest()
240 240 else:
241 241 RhodeCodeCrypto = _RhodeCodeCryptoBCrypt()
242 242
243 243 return RhodeCodeCrypto
244 244
245 245
246 246 def get_crypt_password(password):
247 247 """
248 248 Create the hash of `password` with the active crypto backend.
249 249
250 250 :param password: The cleartext password.
251 251 :type password: unicode
252 252 """
253 253 password = safe_str(password)
254 254 return crypto_backend().hash_create(password)
255 255
256 256
257 257 def check_password(password, hashed):
258 258 """
259 259 Check if the value in `password` matches the hash in `hashed`.
260 260
261 261 :param password: The cleartext password.
262 262 :type password: unicode
263 263
264 264 :param hashed: The expected hashed version of the password.
265 265 :type hashed: The hash has to be passed in in text representation.
266 266 """
267 267 password = safe_str(password)
268 268 return crypto_backend().hash_check(password, hashed)
269 269
270 270
271 271 def generate_auth_token(data, salt=None):
272 272 """
273 273 Generates API KEY from given string
274 274 """
275 275
276 276 if salt is None:
277 277 salt = os.urandom(16)
278 278 return hashlib.sha1(safe_str(data) + salt).hexdigest()
279 279
280 280
281 281 def get_came_from(request):
282 282 """
283 283 get query_string+path from request sanitized after removing auth_token
284 284 """
285 285 _req = request
286 286
287 287 path = _req.path
288 288 if 'auth_token' in _req.GET:
289 289 # sanitize the request and remove auth_token for redirection
290 290 _req.GET.pop('auth_token')
291 291 qs = _req.query_string
292 292 if qs:
293 293 path += '?' + qs
294 294
295 295 return path
296 296
297 297
298 298 class CookieStoreWrapper(object):
299 299
300 300 def __init__(self, cookie_store):
301 301 self.cookie_store = cookie_store
302 302
303 303 def __repr__(self):
304 304 return 'CookieStore<%s>' % (self.cookie_store)
305 305
306 306 def get(self, key, other=None):
307 307 if isinstance(self.cookie_store, dict):
308 308 return self.cookie_store.get(key, other)
309 309 elif isinstance(self.cookie_store, AuthUser):
310 310 return self.cookie_store.__dict__.get(key, other)
311 311
312 312
313 313 def _cached_perms_data(user_id, scope, user_is_admin,
314 314 user_inherit_default_permissions, explicit, algo,
315 315 calculate_super_admin):
316 316
317 317 permissions = PermissionCalculator(
318 318 user_id, scope, user_is_admin, user_inherit_default_permissions,
319 319 explicit, algo, calculate_super_admin)
320 320 return permissions.calculate()
321 321
322 322
323 323 class PermOrigin(object):
324 324 SUPER_ADMIN = 'superadmin'
325 325
326 326 REPO_USER = 'user:%s'
327 327 REPO_USERGROUP = 'usergroup:%s'
328 328 REPO_OWNER = 'repo.owner'
329 329 REPO_DEFAULT = 'repo.default'
330 330 REPO_DEFAULT_NO_INHERIT = 'repo.default.no.inherit'
331 331 REPO_PRIVATE = 'repo.private'
332 332
333 333 REPOGROUP_USER = 'user:%s'
334 334 REPOGROUP_USERGROUP = 'usergroup:%s'
335 335 REPOGROUP_OWNER = 'group.owner'
336 336 REPOGROUP_DEFAULT = 'group.default'
337 337 REPOGROUP_DEFAULT_NO_INHERIT = 'group.default.no.inherit'
338 338
339 339 USERGROUP_USER = 'user:%s'
340 340 USERGROUP_USERGROUP = 'usergroup:%s'
341 341 USERGROUP_OWNER = 'usergroup.owner'
342 342 USERGROUP_DEFAULT = 'usergroup.default'
343 343 USERGROUP_DEFAULT_NO_INHERIT = 'usergroup.default.no.inherit'
344 344
345 345
346 346 class PermOriginDict(dict):
347 347 """
348 348 A special dict used for tracking permissions along with their origins.
349 349
350 350 `__setitem__` has been overridden to expect a tuple(perm, origin)
351 351 `__getitem__` will return only the perm
352 352 `.perm_origin_stack` will return the stack of (perm, origin) set per key
353 353
354 354 >>> perms = PermOriginDict()
355 355 >>> perms['resource'] = 'read', 'default'
356 356 >>> perms['resource']
357 357 'read'
358 358 >>> perms['resource'] = 'write', 'admin'
359 359 >>> perms['resource']
360 360 'write'
361 361 >>> perms.perm_origin_stack
362 362 {'resource': [('read', 'default'), ('write', 'admin')]}
363 363 """
364 364
365 365 def __init__(self, *args, **kw):
366 366 dict.__init__(self, *args, **kw)
367 367 self.perm_origin_stack = collections.OrderedDict()
368 368
369 369 def __setitem__(self, key, (perm, origin)):
370 self.perm_origin_stack.setdefault(key, []).append((perm, origin))
370 self.perm_origin_stack.setdefault(key, []).append(
371 (perm, origin))
371 372 dict.__setitem__(self, key, perm)
372 373
373 374
375 class BranchPermOriginDict(PermOriginDict):
376 """
377 Dedicated branch permissions dict, with tracking of patterns and origins.
378
379 >>> perms = BranchPermOriginDict()
380 >>> perms['resource'] = '*pattern', 'read', 'default'
381 >>> perms['resource']
382 {'*pattern': 'read'}
383 >>> perms['resource'] = '*pattern', 'write', 'admin'
384 >>> perms['resource']
385 {'*pattern': 'write'}
386 >>> perms.perm_origin_stack
387 {'resource': {'*pattern': [('read', 'default'), ('write', 'admin')]}}
388 """
389 def __setitem__(self, key, (pattern, perm, origin)):
390
391 self.perm_origin_stack.setdefault(key, {}) \
392 .setdefault(pattern, []).append((perm, origin))
393
394 if key in self:
395 self[key].__setitem__(pattern, perm)
396 else:
397 patterns = collections.OrderedDict()
398 patterns[pattern] = perm
399 dict.__setitem__(self, key, patterns)
400
401
374 402 class PermissionCalculator(object):
375 403
376 404 def __init__(
377 405 self, user_id, scope, user_is_admin,
378 406 user_inherit_default_permissions, explicit, algo,
379 407 calculate_super_admin=False):
380 408
381 409 self.user_id = user_id
382 410 self.user_is_admin = user_is_admin
383 411 self.inherit_default_permissions = user_inherit_default_permissions
384 412 self.explicit = explicit
385 413 self.algo = algo
386 414 self.calculate_super_admin = calculate_super_admin
387 415
388 416 scope = scope or {}
389 417 self.scope_repo_id = scope.get('repo_id')
390 418 self.scope_repo_group_id = scope.get('repo_group_id')
391 419 self.scope_user_group_id = scope.get('user_group_id')
392 420
393 421 self.default_user_id = User.get_default_user(cache=True).user_id
394 422
395 423 self.permissions_repositories = PermOriginDict()
396 424 self.permissions_repository_groups = PermOriginDict()
397 425 self.permissions_user_groups = PermOriginDict()
426 self.permissions_repository_branches = BranchPermOriginDict()
398 427 self.permissions_global = set()
399 428
400 429 self.default_repo_perms = Permission.get_default_repo_perms(
401 430 self.default_user_id, self.scope_repo_id)
402 431 self.default_repo_groups_perms = Permission.get_default_group_perms(
403 432 self.default_user_id, self.scope_repo_group_id)
404 433 self.default_user_group_perms = \
405 434 Permission.get_default_user_group_perms(
406 435 self.default_user_id, self.scope_user_group_id)
407 436
437 # default branch perms
438 self.default_branch_repo_perms = \
439 Permission.get_default_repo_branch_perms(
440 self.default_user_id, self.scope_repo_id)
441
408 442 def calculate(self):
409 443 if self.user_is_admin and not self.calculate_super_admin:
410 444 return self._admin_permissions()
411 445
412 446 self._calculate_global_default_permissions()
413 447 self._calculate_global_permissions()
414 448 self._calculate_default_permissions()
415 449 self._calculate_repository_permissions()
450 self._calculate_repository_branch_permissions()
416 451 self._calculate_repository_group_permissions()
417 452 self._calculate_user_group_permissions()
418 453 return self._permission_structure()
419 454
420 455 def _admin_permissions(self):
421 456 """
422 457 admin user have all default rights for repositories
423 458 and groups set to admin
424 459 """
425 460 self.permissions_global.add('hg.admin')
426 461 self.permissions_global.add('hg.create.write_on_repogroup.true')
427 462
428 463 # repositories
429 464 for perm in self.default_repo_perms:
430 465 r_k = perm.UserRepoToPerm.repository.repo_name
431 466 p = 'repository.admin'
432 467 self.permissions_repositories[r_k] = p, PermOrigin.SUPER_ADMIN
433 468
434 469 # repository groups
435 470 for perm in self.default_repo_groups_perms:
436 471 rg_k = perm.UserRepoGroupToPerm.group.group_name
437 472 p = 'group.admin'
438 473 self.permissions_repository_groups[rg_k] = p, PermOrigin.SUPER_ADMIN
439 474
440 475 # user groups
441 476 for perm in self.default_user_group_perms:
442 477 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
443 478 p = 'usergroup.admin'
444 479 self.permissions_user_groups[u_k] = p, PermOrigin.SUPER_ADMIN
445 480
481 # branch permissions
482 # TODO(marcink): validate this, especially
483 # how this should work using multiple patterns specified ??
484 # looks ok, but still needs double check !!
485 for perm in self.default_branch_repo_perms:
486 r_k = perm.UserRepoToPerm.repository.repo_name
487 p = 'branch.push_force'
488 self.permissions_repository_branches[r_k] = '*', p, PermOrigin.SUPER_ADMIN
489
446 490 return self._permission_structure()
447 491
448 492 def _calculate_global_default_permissions(self):
449 493 """
450 494 global permissions taken from the default user
451 495 """
452 496 default_global_perms = UserToPerm.query()\
453 497 .filter(UserToPerm.user_id == self.default_user_id)\
454 498 .options(joinedload(UserToPerm.permission))
455 499
456 500 for perm in default_global_perms:
457 501 self.permissions_global.add(perm.permission.permission_name)
458 502
459 503 if self.user_is_admin:
460 504 self.permissions_global.add('hg.admin')
461 505 self.permissions_global.add('hg.create.write_on_repogroup.true')
462 506
463 507 def _calculate_global_permissions(self):
464 508 """
465 509 Set global system permissions with user permissions or permissions
466 510 taken from the user groups of the current user.
467 511
468 512 The permissions include repo creating, repo group creating, forking
469 513 etc.
470 514 """
471 515
472 516 # now we read the defined permissions and overwrite what we have set
473 517 # before those can be configured from groups or users explicitly.
474 518
475 # TODO: johbo: This seems to be out of sync, find out the reason
476 # for the comment below and update it.
477
478 # In case we want to extend this list we should be always in sync with
479 # User.DEFAULT_USER_PERMISSIONS definitions
519 # In case we want to extend this list we should make sure
520 # this is in sync with User.DEFAULT_USER_PERMISSIONS definitions
480 521 _configurable = frozenset([
481 522 'hg.fork.none', 'hg.fork.repository',
482 523 'hg.create.none', 'hg.create.repository',
483 524 'hg.usergroup.create.false', 'hg.usergroup.create.true',
484 525 'hg.repogroup.create.false', 'hg.repogroup.create.true',
485 'hg.create.write_on_repogroup.false',
486 'hg.create.write_on_repogroup.true',
526 'hg.create.write_on_repogroup.false', 'hg.create.write_on_repogroup.true',
487 527 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true'
488 528 ])
489 529
490 530 # USER GROUPS comes first user group global permissions
491 531 user_perms_from_users_groups = Session().query(UserGroupToPerm)\
492 532 .options(joinedload(UserGroupToPerm.permission))\
493 533 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
494 534 UserGroupMember.users_group_id))\
495 535 .filter(UserGroupMember.user_id == self.user_id)\
496 536 .order_by(UserGroupToPerm.users_group_id)\
497 537 .all()
498 538
499 539 # need to group here by groups since user can be in more than
500 540 # one group, so we get all groups
501 541 _explicit_grouped_perms = [
502 542 [x, list(y)] for x, y in
503 543 itertools.groupby(user_perms_from_users_groups,
504 544 lambda _x: _x.users_group)]
505 545
506 546 for gr, perms in _explicit_grouped_perms:
507 547 # since user can be in multiple groups iterate over them and
508 548 # select the lowest permissions first (more explicit)
509 # TODO: marcink: do this^^
549 # TODO(marcink): do this^^
510 550
511 551 # group doesn't inherit default permissions so we actually set them
512 552 if not gr.inherit_default_permissions:
513 553 # NEED TO IGNORE all previously set configurable permissions
514 554 # and replace them with explicitly set from this user
515 555 # group permissions
516 556 self.permissions_global = self.permissions_global.difference(
517 557 _configurable)
518 558 for perm in perms:
519 559 self.permissions_global.add(perm.permission.permission_name)
520 560
521 561 # user explicit global permissions
522 562 user_perms = Session().query(UserToPerm)\
523 563 .options(joinedload(UserToPerm.permission))\
524 564 .filter(UserToPerm.user_id == self.user_id).all()
525 565
526 566 if not self.inherit_default_permissions:
527 567 # NEED TO IGNORE all configurable permissions and
528 568 # replace them with explicitly set from this user permissions
529 569 self.permissions_global = self.permissions_global.difference(
530 570 _configurable)
531 571 for perm in user_perms:
532 572 self.permissions_global.add(perm.permission.permission_name)
533 573
534 574 def _calculate_default_permissions(self):
535 575 """
536 Set default user permissions for repositories, repository groups
537 taken from the default user.
576 Set default user permissions for repositories, repository branches,
577 repository groups, user groups taken from the default user.
538 578
539 579 Calculate inheritance of object permissions based on what we have now
540 580 in GLOBAL permissions. We check if .false is in GLOBAL since this is
541 581 explicitly set. Inherit is the opposite of .false being there.
542 582
543 583 .. note::
544 584
545 585 the syntax is little bit odd but what we need to check here is
546 586 the opposite of .false permission being in the list so even for
547 587 inconsistent state when both .true/.false is there
548 588 .false is more important
549 589
550 590 """
551 591 user_inherit_object_permissions = not ('hg.inherit_default_perms.false'
552 592 in self.permissions_global)
553 593
554 # defaults for repositories, taken from `default` user permissions
555 # on given repo
594 # default permissions for repositories, taken from `default` user permissions
556 595 for perm in self.default_repo_perms:
557 596 r_k = perm.UserRepoToPerm.repository.repo_name
558 597 p = perm.Permission.permission_name
559 598 o = PermOrigin.REPO_DEFAULT
560 599 self.permissions_repositories[r_k] = p, o
561 600
562 601 # if we decide this user isn't inheriting permissions from
563 602 # default user we set him to .none so only explicit
564 603 # permissions work
565 604 if not user_inherit_object_permissions:
566 605 p = 'repository.none'
567 606 o = PermOrigin.REPO_DEFAULT_NO_INHERIT
568 607 self.permissions_repositories[r_k] = p, o
569 608
570 609 if perm.Repository.private and not (
571 610 perm.Repository.user_id == self.user_id):
572 611 # disable defaults for private repos,
573 612 p = 'repository.none'
574 613 o = PermOrigin.REPO_PRIVATE
575 614 self.permissions_repositories[r_k] = p, o
576 615
577 616 elif perm.Repository.user_id == self.user_id:
578 617 # set admin if owner
579 618 p = 'repository.admin'
580 619 o = PermOrigin.REPO_OWNER
581 620 self.permissions_repositories[r_k] = p, o
582 621
583 622 if self.user_is_admin:
584 623 p = 'repository.admin'
585 624 o = PermOrigin.SUPER_ADMIN
586 625 self.permissions_repositories[r_k] = p, o
587 626
588 # defaults for repository groups taken from `default` user permission
589 # on given group
627 # default permissions branch for repositories, taken from `default` user permissions
628 for perm in self.default_branch_repo_perms:
629
630 r_k = perm.UserRepoToPerm.repository.repo_name
631 p = perm.Permission.permission_name
632 pattern = perm.UserToRepoBranchPermission.branch_pattern
633 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
634
635 if not self.explicit:
636 # TODO(marcink): fix this for multiple entries
637 cur_perm = self.permissions_repository_branches.get(r_k) or 'branch.none'
638 p = self._choose_permission(p, cur_perm)
639
640 # NOTE(marcink): register all pattern/perm instances in this
641 # special dict that aggregates entries
642 self.permissions_repository_branches[r_k] = pattern, p, o
643
644 # default permissions for repository groups taken from `default` user permission
590 645 for perm in self.default_repo_groups_perms:
591 646 rg_k = perm.UserRepoGroupToPerm.group.group_name
592 647 p = perm.Permission.permission_name
593 648 o = PermOrigin.REPOGROUP_DEFAULT
594 649 self.permissions_repository_groups[rg_k] = p, o
595 650
596 651 # if we decide this user isn't inheriting permissions from default
597 652 # user we set him to .none so only explicit permissions work
598 653 if not user_inherit_object_permissions:
599 654 p = 'group.none'
600 655 o = PermOrigin.REPOGROUP_DEFAULT_NO_INHERIT
601 656 self.permissions_repository_groups[rg_k] = p, o
602 657
603 658 if perm.RepoGroup.user_id == self.user_id:
604 659 # set admin if owner
605 660 p = 'group.admin'
606 661 o = PermOrigin.REPOGROUP_OWNER
607 662 self.permissions_repository_groups[rg_k] = p, o
608 663
609 664 if self.user_is_admin:
610 665 p = 'group.admin'
611 666 o = PermOrigin.SUPER_ADMIN
612 667 self.permissions_repository_groups[rg_k] = p, o
613 668
614 # defaults for user groups taken from `default` user permission
615 # on given user group
669 # default permissions for user groups taken from `default` user permission
616 670 for perm in self.default_user_group_perms:
617 671 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
618 672 p = perm.Permission.permission_name
619 673 o = PermOrigin.USERGROUP_DEFAULT
620 674 self.permissions_user_groups[u_k] = p, o
621 675
622 676 # if we decide this user isn't inheriting permissions from default
623 677 # user we set him to .none so only explicit permissions work
624 678 if not user_inherit_object_permissions:
625 679 p = 'usergroup.none'
626 680 o = PermOrigin.USERGROUP_DEFAULT_NO_INHERIT
627 681 self.permissions_user_groups[u_k] = p, o
628 682
629 683 if perm.UserGroup.user_id == self.user_id:
630 684 # set admin if owner
631 685 p = 'usergroup.admin'
632 686 o = PermOrigin.USERGROUP_OWNER
633 687 self.permissions_user_groups[u_k] = p, o
634 688
635 689 if self.user_is_admin:
636 690 p = 'usergroup.admin'
637 691 o = PermOrigin.SUPER_ADMIN
638 692 self.permissions_user_groups[u_k] = p, o
639 693
640 694 def _calculate_repository_permissions(self):
641 695 """
642 696 Repository permissions for the current user.
643 697
644 698 Check if the user is part of user groups for this repository and
645 699 fill in the permission from it. `_choose_permission` decides of which
646 700 permission should be selected based on selected method.
647 701 """
648 702
649 703 # user group for repositories permissions
650 704 user_repo_perms_from_user_group = Permission\
651 705 .get_default_repo_perms_from_user_group(
652 706 self.user_id, self.scope_repo_id)
653 707
654 708 multiple_counter = collections.defaultdict(int)
655 709 for perm in user_repo_perms_from_user_group:
656 710 r_k = perm.UserGroupRepoToPerm.repository.repo_name
657 711 multiple_counter[r_k] += 1
658 712 p = perm.Permission.permission_name
659 713 o = PermOrigin.REPO_USERGROUP % perm.UserGroupRepoToPerm\
660 714 .users_group.users_group_name
661 715
662 716 if multiple_counter[r_k] > 1:
663 717 cur_perm = self.permissions_repositories[r_k]
664 718 p = self._choose_permission(p, cur_perm)
665 719
666 720 self.permissions_repositories[r_k] = p, o
667 721
668 722 if perm.Repository.user_id == self.user_id:
669 723 # set admin if owner
670 724 p = 'repository.admin'
671 725 o = PermOrigin.REPO_OWNER
672 726 self.permissions_repositories[r_k] = p, o
673 727
674 728 if self.user_is_admin:
675 729 p = 'repository.admin'
676 730 o = PermOrigin.SUPER_ADMIN
677 731 self.permissions_repositories[r_k] = p, o
678 732
679 733 # user explicit permissions for repositories, overrides any specified
680 734 # by the group permission
681 735 user_repo_perms = Permission.get_default_repo_perms(
682 736 self.user_id, self.scope_repo_id)
683 737 for perm in user_repo_perms:
684 738 r_k = perm.UserRepoToPerm.repository.repo_name
685 739 p = perm.Permission.permission_name
686 740 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
687 741
688 742 if not self.explicit:
689 743 cur_perm = self.permissions_repositories.get(
690 744 r_k, 'repository.none')
691 745 p = self._choose_permission(p, cur_perm)
692 746
693 747 self.permissions_repositories[r_k] = p, o
694 748
695 749 if perm.Repository.user_id == self.user_id:
696 750 # set admin if owner
697 751 p = 'repository.admin'
698 752 o = PermOrigin.REPO_OWNER
699 753 self.permissions_repositories[r_k] = p, o
700 754
701 755 if self.user_is_admin:
702 756 p = 'repository.admin'
703 757 o = PermOrigin.SUPER_ADMIN
704 758 self.permissions_repositories[r_k] = p, o
705 759
760 def _calculate_repository_branch_permissions(self):
761 # user group for repositories permissions
762 user_repo_branch_perms_from_user_group = Permission\
763 .get_default_repo_branch_perms_from_user_group(
764 self.user_id, self.scope_repo_id)
765
766 multiple_counter = collections.defaultdict(int)
767 for perm in user_repo_branch_perms_from_user_group:
768 r_k = perm.UserGroupRepoToPerm.repository.repo_name
769 p = perm.Permission.permission_name
770 pattern = perm.UserGroupToRepoBranchPermission.branch_pattern
771 o = PermOrigin.REPO_USERGROUP % perm.UserGroupRepoToPerm\
772 .users_group.users_group_name
773
774 multiple_counter[r_k] += 1
775 if multiple_counter[r_k] > 1:
776 # TODO(marcink): fix this for multi branch support, and multiple entries
777 cur_perm = self.permissions_repository_branches[r_k]
778 p = self._choose_permission(p, cur_perm)
779
780 self.permissions_repository_branches[r_k] = pattern, p, o
781
782 # user explicit branch permissions for repositories, overrides
783 # any specified by the group permission
784 user_repo_branch_perms = Permission.get_default_repo_branch_perms(
785 self.user_id, self.scope_repo_id)
786 for perm in user_repo_branch_perms:
787
788 r_k = perm.UserRepoToPerm.repository.repo_name
789 p = perm.Permission.permission_name
790 pattern = perm.UserToRepoBranchPermission.branch_pattern
791 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
792
793 if not self.explicit:
794 # TODO(marcink): fix this for multiple entries
795 cur_perm = self.permissions_repository_branches.get(r_k) or 'branch.none'
796 p = self._choose_permission(p, cur_perm)
797
798 # NOTE(marcink): register all pattern/perm instances in this
799 # special dict that aggregates entries
800 self.permissions_repository_branches[r_k] = pattern, p, o
801
802
706 803 def _calculate_repository_group_permissions(self):
707 804 """
708 805 Repository group permissions for the current user.
709 806
710 807 Check if the user is part of user groups for repository groups and
711 808 fill in the permissions from it. `_choose_permission` decides of which
712 809 permission should be selected based on selected method.
713 810 """
714 811 # user group for repo groups permissions
715 812 user_repo_group_perms_from_user_group = Permission\
716 813 .get_default_group_perms_from_user_group(
717 814 self.user_id, self.scope_repo_group_id)
718 815
719 816 multiple_counter = collections.defaultdict(int)
720 817 for perm in user_repo_group_perms_from_user_group:
721 818 rg_k = perm.UserGroupRepoGroupToPerm.group.group_name
722 819 multiple_counter[rg_k] += 1
723 820 o = PermOrigin.REPOGROUP_USERGROUP % perm.UserGroupRepoGroupToPerm\
724 821 .users_group.users_group_name
725 822 p = perm.Permission.permission_name
726 823
727 824 if multiple_counter[rg_k] > 1:
728 825 cur_perm = self.permissions_repository_groups[rg_k]
729 826 p = self._choose_permission(p, cur_perm)
730 827 self.permissions_repository_groups[rg_k] = p, o
731 828
732 829 if perm.RepoGroup.user_id == self.user_id:
733 830 # set admin if owner, even for member of other user group
734 831 p = 'group.admin'
735 832 o = PermOrigin.REPOGROUP_OWNER
736 833 self.permissions_repository_groups[rg_k] = p, o
737 834
738 835 if self.user_is_admin:
739 836 p = 'group.admin'
740 837 o = PermOrigin.SUPER_ADMIN
741 838 self.permissions_repository_groups[rg_k] = p, o
742 839
743 840 # user explicit permissions for repository groups
744 841 user_repo_groups_perms = Permission.get_default_group_perms(
745 842 self.user_id, self.scope_repo_group_id)
746 843 for perm in user_repo_groups_perms:
747 844 rg_k = perm.UserRepoGroupToPerm.group.group_name
748 845 o = PermOrigin.REPOGROUP_USER % perm.UserRepoGroupToPerm\
749 846 .user.username
750 847 p = perm.Permission.permission_name
751 848
752 849 if not self.explicit:
753 850 cur_perm = self.permissions_repository_groups.get(
754 851 rg_k, 'group.none')
755 852 p = self._choose_permission(p, cur_perm)
756 853
757 854 self.permissions_repository_groups[rg_k] = p, o
758 855
759 856 if perm.RepoGroup.user_id == self.user_id:
760 857 # set admin if owner
761 858 p = 'group.admin'
762 859 o = PermOrigin.REPOGROUP_OWNER
763 860 self.permissions_repository_groups[rg_k] = p, o
764 861
765 862 if self.user_is_admin:
766 863 p = 'group.admin'
767 864 o = PermOrigin.SUPER_ADMIN
768 865 self.permissions_repository_groups[rg_k] = p, o
769 866
770 867 def _calculate_user_group_permissions(self):
771 868 """
772 869 User group permissions for the current user.
773 870 """
774 871 # user group for user group permissions
775 872 user_group_from_user_group = Permission\
776 873 .get_default_user_group_perms_from_user_group(
777 874 self.user_id, self.scope_user_group_id)
778 875
779 876 multiple_counter = collections.defaultdict(int)
780 877 for perm in user_group_from_user_group:
781 878 ug_k = perm.UserGroupUserGroupToPerm\
782 879 .target_user_group.users_group_name
783 880 multiple_counter[ug_k] += 1
784 881 o = PermOrigin.USERGROUP_USERGROUP % perm.UserGroupUserGroupToPerm\
785 882 .user_group.users_group_name
786 883 p = perm.Permission.permission_name
787 884
788 885 if multiple_counter[ug_k] > 1:
789 886 cur_perm = self.permissions_user_groups[ug_k]
790 887 p = self._choose_permission(p, cur_perm)
791 888
792 889 self.permissions_user_groups[ug_k] = p, o
793 890
794 891 if perm.UserGroup.user_id == self.user_id:
795 892 # set admin if owner, even for member of other user group
796 893 p = 'usergroup.admin'
797 894 o = PermOrigin.USERGROUP_OWNER
798 895 self.permissions_user_groups[ug_k] = p, o
799 896
800 897 if self.user_is_admin:
801 898 p = 'usergroup.admin'
802 899 o = PermOrigin.SUPER_ADMIN
803 900 self.permissions_user_groups[ug_k] = p, o
804 901
805 902 # user explicit permission for user groups
806 903 user_user_groups_perms = Permission.get_default_user_group_perms(
807 904 self.user_id, self.scope_user_group_id)
808 905 for perm in user_user_groups_perms:
809 906 ug_k = perm.UserUserGroupToPerm.user_group.users_group_name
810 907 o = PermOrigin.USERGROUP_USER % perm.UserUserGroupToPerm\
811 908 .user.username
812 909 p = perm.Permission.permission_name
813 910
814 911 if not self.explicit:
815 912 cur_perm = self.permissions_user_groups.get(
816 913 ug_k, 'usergroup.none')
817 914 p = self._choose_permission(p, cur_perm)
818 915
819 916 self.permissions_user_groups[ug_k] = p, o
820 917
821 918 if perm.UserGroup.user_id == self.user_id:
822 919 # set admin if owner
823 920 p = 'usergroup.admin'
824 921 o = PermOrigin.USERGROUP_OWNER
825 922 self.permissions_user_groups[ug_k] = p, o
826 923
827 924 if self.user_is_admin:
828 925 p = 'usergroup.admin'
829 926 o = PermOrigin.SUPER_ADMIN
830 927 self.permissions_user_groups[ug_k] = p, o
831 928
832 929 def _choose_permission(self, new_perm, cur_perm):
833 930 new_perm_val = Permission.PERM_WEIGHTS[new_perm]
834 931 cur_perm_val = Permission.PERM_WEIGHTS[cur_perm]
835 932 if self.algo == 'higherwin':
836 933 if new_perm_val > cur_perm_val:
837 934 return new_perm
838 935 return cur_perm
839 936 elif self.algo == 'lowerwin':
840 937 if new_perm_val < cur_perm_val:
841 938 return new_perm
842 939 return cur_perm
843 940
844 941 def _permission_structure(self):
845 942 return {
846 943 'global': self.permissions_global,
847 944 'repositories': self.permissions_repositories,
945 'repository_branches': self.permissions_repository_branches,
848 946 'repositories_groups': self.permissions_repository_groups,
849 947 'user_groups': self.permissions_user_groups,
850 948 }
851 949
852 950
853 951 def allowed_auth_token_access(view_name, auth_token, whitelist=None):
854 952 """
855 953 Check if given controller_name is in whitelist of auth token access
856 954 """
857 955 if not whitelist:
858 956 from rhodecode import CONFIG
859 957 whitelist = aslist(
860 958 CONFIG.get('api_access_controllers_whitelist'), sep=',')
861 959 # backward compat translation
862 960 compat = {
863 961 # old controller, new VIEW
864 962 'ChangesetController:*': 'RepoCommitsView:*',
865 963 'ChangesetController:changeset_patch': 'RepoCommitsView:repo_commit_patch',
866 964 'ChangesetController:changeset_raw': 'RepoCommitsView:repo_commit_raw',
867 965 'FilesController:raw': 'RepoCommitsView:repo_commit_raw',
868 966 'FilesController:archivefile': 'RepoFilesView:repo_archivefile',
869 967 'GistsController:*': 'GistView:*',
870 968 }
871 969
872 970 log.debug(
873 971 'Allowed views for AUTH TOKEN access: %s' % (whitelist,))
874 972 auth_token_access_valid = False
875 973
876 974 for entry in whitelist:
877 975 token_match = True
878 976 if entry in compat:
879 977 # translate from old Controllers to Pyramid Views
880 978 entry = compat[entry]
881 979
882 980 if '@' in entry:
883 981 # specific AuthToken
884 982 entry, allowed_token = entry.split('@', 1)
885 983 token_match = auth_token == allowed_token
886 984
887 985 if fnmatch.fnmatch(view_name, entry) and token_match:
888 986 auth_token_access_valid = True
889 987 break
890 988
891 989 if auth_token_access_valid:
892 990 log.debug('view: `%s` matches entry in whitelist: %s'
893 991 % (view_name, whitelist))
894 992 else:
895 993 msg = ('view: `%s` does *NOT* match any entry in whitelist: %s'
896 994 % (view_name, whitelist))
897 995 if auth_token:
898 996 # if we use auth token key and don't have access it's a warning
899 997 log.warning(msg)
900 998 else:
901 999 log.debug(msg)
902 1000
903 1001 return auth_token_access_valid
904 1002
905 1003
906 1004 class AuthUser(object):
907 1005 """
908 1006 A simple object that handles all attributes of user in RhodeCode
909 1007
910 1008 It does lookup based on API key,given user, or user present in session
911 1009 Then it fills all required information for such user. It also checks if
912 1010 anonymous access is enabled and if so, it returns default user as logged in
913 1011 """
914 1012 GLOBAL_PERMS = [x[0] for x in Permission.PERMS]
915 1013
916 1014 def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None):
917 1015
918 1016 self.user_id = user_id
919 1017 self._api_key = api_key
920 1018
921 1019 self.api_key = None
922 1020 self.username = username
923 1021 self.ip_addr = ip_addr
924 1022 self.name = ''
925 1023 self.lastname = ''
926 1024 self.first_name = ''
927 1025 self.last_name = ''
928 1026 self.email = ''
929 1027 self.is_authenticated = False
930 1028 self.admin = False
931 1029 self.inherit_default_permissions = False
932 1030 self.password = ''
933 1031
934 1032 self.anonymous_user = None # propagated on propagate_data
935 1033 self.propagate_data()
936 1034 self._instance = None
937 1035 self._permissions_scoped_cache = {} # used to bind scoped calculation
938 1036
939 1037 @LazyProperty
940 1038 def permissions(self):
941 1039 return self.get_perms(user=self, cache=False)
942 1040
943 1041 @LazyProperty
944 1042 def permissions_safe(self):
945 1043 """
946 1044 Filtered permissions excluding not allowed repositories
947 1045 """
948 1046 perms = self.get_perms(user=self, cache=False)
949 1047
950 1048 perms['repositories'] = {
951 1049 k: v for k, v in perms['repositories'].items()
952 1050 if v != 'repository.none'}
953 1051 perms['repositories_groups'] = {
954 1052 k: v for k, v in perms['repositories_groups'].items()
955 1053 if v != 'group.none'}
956 1054 perms['user_groups'] = {
957 1055 k: v for k, v in perms['user_groups'].items()
958 1056 if v != 'usergroup.none'}
1057 perms['repository_branches'] = {
1058 k: v for k, v in perms['repository_branches'].iteritems()
1059 if v != 'branch.none'}
959 1060 return perms
960 1061
961 1062 @LazyProperty
962 1063 def permissions_full_details(self):
963 1064 return self.get_perms(
964 1065 user=self, cache=False, calculate_super_admin=True)
965 1066
966 1067 def permissions_with_scope(self, scope):
967 1068 """
968 1069 Call the get_perms function with scoped data. The scope in that function
969 1070 narrows the SQL calls to the given ID of objects resulting in fetching
970 1071 Just particular permission we want to obtain. If scope is an empty dict
971 1072 then it basically narrows the scope to GLOBAL permissions only.
972 1073
973 1074 :param scope: dict
974 1075 """
975 1076 if 'repo_name' in scope:
976 1077 obj = Repository.get_by_repo_name(scope['repo_name'])
977 1078 if obj:
978 1079 scope['repo_id'] = obj.repo_id
979 1080 _scope = collections.OrderedDict()
980 1081 _scope['repo_id'] = -1
981 1082 _scope['user_group_id'] = -1
982 1083 _scope['repo_group_id'] = -1
983 1084
984 1085 for k in sorted(scope.keys()):
985 1086 _scope[k] = scope[k]
986 1087
987 1088 # store in cache to mimic how the @LazyProperty works,
988 1089 # the difference here is that we use the unique key calculated
989 1090 # from params and values
990 1091 return self.get_perms(user=self, cache=False, scope=_scope)
991 1092
992 1093 def get_instance(self):
993 1094 return User.get(self.user_id)
994 1095
995 1096 def propagate_data(self):
996 1097 """
997 1098 Fills in user data and propagates values to this instance. Maps fetched
998 1099 user attributes to this class instance attributes
999 1100 """
1000 1101 log.debug('AuthUser: starting data propagation for new potential user')
1001 1102 user_model = UserModel()
1002 1103 anon_user = self.anonymous_user = User.get_default_user(cache=True)
1003 1104 is_user_loaded = False
1004 1105
1005 1106 # lookup by userid
1006 1107 if self.user_id is not None and self.user_id != anon_user.user_id:
1007 1108 log.debug('Trying Auth User lookup by USER ID: `%s`', self.user_id)
1008 1109 is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
1009 1110
1010 1111 # try go get user by api key
1011 1112 elif self._api_key and self._api_key != anon_user.api_key:
1012 1113 log.debug('Trying Auth User lookup by API KEY: `%s`', self._api_key)
1013 1114 is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
1014 1115
1015 1116 # lookup by username
1016 1117 elif self.username:
1017 1118 log.debug('Trying Auth User lookup by USER NAME: `%s`', self.username)
1018 1119 is_user_loaded = user_model.fill_data(self, username=self.username)
1019 1120 else:
1020 1121 log.debug('No data in %s that could been used to log in', self)
1021 1122
1022 1123 if not is_user_loaded:
1023 1124 log.debug(
1024 1125 'Failed to load user. Fallback to default user %s', anon_user)
1025 1126 # if we cannot authenticate user try anonymous
1026 1127 if anon_user.active:
1027 1128 log.debug('default user is active, using it as a session user')
1028 1129 user_model.fill_data(self, user_id=anon_user.user_id)
1029 1130 # then we set this user is logged in
1030 1131 self.is_authenticated = True
1031 1132 else:
1032 1133 log.debug('default user is NOT active')
1033 1134 # in case of disabled anonymous user we reset some of the
1034 1135 # parameters so such user is "corrupted", skipping the fill_data
1035 1136 for attr in ['user_id', 'username', 'admin', 'active']:
1036 1137 setattr(self, attr, None)
1037 1138 self.is_authenticated = False
1038 1139
1039 1140 if not self.username:
1040 1141 self.username = 'None'
1041 1142
1042 1143 log.debug('AuthUser: propagated user is now %s', self)
1043 1144
1044 1145 def get_perms(self, user, scope=None, explicit=True, algo='higherwin',
1045 1146 calculate_super_admin=False, cache=False):
1046 1147 """
1047 1148 Fills user permission attribute with permissions taken from database
1048 1149 works for permissions given for repositories, and for permissions that
1049 1150 are granted to groups
1050 1151
1051 1152 :param user: instance of User object from database
1052 1153 :param explicit: In case there are permissions both for user and a group
1053 1154 that user is part of, explicit flag will defiine if user will
1054 1155 explicitly override permissions from group, if it's False it will
1055 1156 make decision based on the algo
1056 1157 :param algo: algorithm to decide what permission should be choose if
1057 1158 it's multiple defined, eg user in two different groups. It also
1058 1159 decides if explicit flag is turned off how to specify the permission
1059 1160 for case when user is in a group + have defined separate permission
1060 1161 """
1061 1162 user_id = user.user_id
1062 1163 user_is_admin = user.is_admin
1063 1164
1064 1165 # inheritance of global permissions like create repo/fork repo etc
1065 1166 user_inherit_default_permissions = user.inherit_default_permissions
1066 1167
1067 1168 cache_seconds = safe_int(
1068 1169 rhodecode.CONFIG.get('rc_cache.cache_perms.expiration_time'))
1069 1170
1070 1171 cache_on = cache or cache_seconds > 0
1071 1172 log.debug(
1072 1173 'Computing PERMISSION tree for user %s scope `%s` '
1073 1174 'with caching: %s[TTL: %ss]' % (user, scope, cache_on, cache_seconds or 0))
1074 1175
1075 1176 cache_namespace_uid = 'cache_user_auth.{}'.format(user_id)
1076 1177 region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid)
1077 1178
1078 1179 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid,
1079 1180 condition=cache_on)
1080 1181 def compute_perm_tree(cache_name,
1081 1182 user_id, scope, user_is_admin,user_inherit_default_permissions,
1082 1183 explicit, algo, calculate_super_admin):
1083 1184 return _cached_perms_data(
1084 1185 user_id, scope, user_is_admin, user_inherit_default_permissions,
1085 1186 explicit, algo, calculate_super_admin)
1086 1187
1087 1188 start = time.time()
1088 1189 result = compute_perm_tree('permissions', user_id, scope, user_is_admin,
1089 1190 user_inherit_default_permissions, explicit, algo,
1090 1191 calculate_super_admin)
1091 1192
1092 1193 result_repr = []
1093 1194 for k in result:
1094 1195 result_repr.append((k, len(result[k])))
1095 1196 total = time.time() - start
1096 1197 log.debug('PERMISSION tree for user %s computed in %.3fs: %s' % (
1097 1198 user, total, result_repr))
1098 1199
1099 1200 return result
1100 1201
1101 1202 @property
1102 1203 def is_default(self):
1103 1204 return self.username == User.DEFAULT_USER
1104 1205
1105 1206 @property
1106 1207 def is_admin(self):
1107 1208 return self.admin
1108 1209
1109 1210 @property
1110 1211 def is_user_object(self):
1111 1212 return self.user_id is not None
1112 1213
1113 1214 @property
1114 1215 def repositories_admin(self):
1115 1216 """
1116 1217 Returns list of repositories you're an admin of
1117 1218 """
1118 1219 return [
1119 1220 x[0] for x in self.permissions['repositories'].items()
1120 1221 if x[1] == 'repository.admin']
1121 1222
1122 1223 @property
1123 1224 def repository_groups_admin(self):
1124 1225 """
1125 1226 Returns list of repository groups you're an admin of
1126 1227 """
1127 1228 return [
1128 1229 x[0] for x in self.permissions['repositories_groups'].items()
1129 1230 if x[1] == 'group.admin']
1130 1231
1131 1232 @property
1132 1233 def user_groups_admin(self):
1133 1234 """
1134 1235 Returns list of user groups you're an admin of
1135 1236 """
1136 1237 return [
1137 1238 x[0] for x in self.permissions['user_groups'].items()
1138 1239 if x[1] == 'usergroup.admin']
1139 1240
1140 1241 def repo_acl_ids(self, perms=None, name_filter=None, cache=False):
1141 1242 """
1142 1243 Returns list of repository ids that user have access to based on given
1143 1244 perms. The cache flag should be only used in cases that are used for
1144 1245 display purposes, NOT IN ANY CASE for permission checks.
1145 1246 """
1146 1247 from rhodecode.model.scm import RepoList
1147 1248 if not perms:
1148 1249 perms = [
1149 1250 'repository.read', 'repository.write', 'repository.admin']
1150 1251
1151 1252 def _cached_repo_acl(user_id, perm_def, _name_filter):
1152 1253 qry = Repository.query()
1153 1254 if _name_filter:
1154 1255 ilike_expression = u'%{}%'.format(safe_unicode(_name_filter))
1155 1256 qry = qry.filter(
1156 1257 Repository.repo_name.ilike(ilike_expression))
1157 1258
1158 1259 return [x.repo_id for x in
1159 1260 RepoList(qry, perm_set=perm_def)]
1160 1261
1161 1262 return _cached_repo_acl(self.user_id, perms, name_filter)
1162 1263
1163 1264 def repo_group_acl_ids(self, perms=None, name_filter=None, cache=False):
1164 1265 """
1165 1266 Returns list of repository group ids that user have access to based on given
1166 1267 perms. The cache flag should be only used in cases that are used for
1167 1268 display purposes, NOT IN ANY CASE for permission checks.
1168 1269 """
1169 1270 from rhodecode.model.scm import RepoGroupList
1170 1271 if not perms:
1171 1272 perms = [
1172 1273 'group.read', 'group.write', 'group.admin']
1173 1274
1174 1275 def _cached_repo_group_acl(user_id, perm_def, _name_filter):
1175 1276 qry = RepoGroup.query()
1176 1277 if _name_filter:
1177 1278 ilike_expression = u'%{}%'.format(safe_unicode(_name_filter))
1178 1279 qry = qry.filter(
1179 1280 RepoGroup.group_name.ilike(ilike_expression))
1180 1281
1181 1282 return [x.group_id for x in
1182 1283 RepoGroupList(qry, perm_set=perm_def)]
1183 1284
1184 1285 return _cached_repo_group_acl(self.user_id, perms, name_filter)
1185 1286
1186 1287 def user_group_acl_ids(self, perms=None, name_filter=None, cache=False):
1187 1288 """
1188 1289 Returns list of user group ids that user have access to based on given
1189 1290 perms. The cache flag should be only used in cases that are used for
1190 1291 display purposes, NOT IN ANY CASE for permission checks.
1191 1292 """
1192 1293 from rhodecode.model.scm import UserGroupList
1193 1294 if not perms:
1194 1295 perms = [
1195 1296 'usergroup.read', 'usergroup.write', 'usergroup.admin']
1196 1297
1197 1298 def _cached_user_group_acl(user_id, perm_def, name_filter):
1198 1299 qry = UserGroup.query()
1199 1300 if name_filter:
1200 1301 ilike_expression = u'%{}%'.format(safe_unicode(name_filter))
1201 1302 qry = qry.filter(
1202 1303 UserGroup.users_group_name.ilike(ilike_expression))
1203 1304
1204 1305 return [x.users_group_id for x in
1205 1306 UserGroupList(qry, perm_set=perm_def)]
1206 1307
1207 1308 return _cached_user_group_acl(self.user_id, perms, name_filter)
1208 1309
1209 1310 @property
1210 1311 def ip_allowed(self):
1211 1312 """
1212 1313 Checks if ip_addr used in constructor is allowed from defined list of
1213 1314 allowed ip_addresses for user
1214 1315
1215 1316 :returns: boolean, True if ip is in allowed ip range
1216 1317 """
1217 1318 # check IP
1218 1319 inherit = self.inherit_default_permissions
1219 1320 return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
1220 1321 inherit_from_default=inherit)
1221 1322 @property
1222 1323 def personal_repo_group(self):
1223 1324 return RepoGroup.get_user_personal_repo_group(self.user_id)
1224 1325
1225 1326 @LazyProperty
1226 1327 def feed_token(self):
1227 1328 return self.get_instance().feed_token
1228 1329
1229 1330 @classmethod
1230 1331 def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
1231 1332 allowed_ips = AuthUser.get_allowed_ips(
1232 1333 user_id, cache=True, inherit_from_default=inherit_from_default)
1233 1334 if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
1234 1335 log.debug('IP:%s for user %s is in range of %s' % (
1235 1336 ip_addr, user_id, allowed_ips))
1236 1337 return True
1237 1338 else:
1238 1339 log.info('Access for IP:%s forbidden for user %s, '
1239 1340 'not in %s' % (ip_addr, user_id, allowed_ips))
1240 1341 return False
1241 1342
1242 1343 def __repr__(self):
1243 1344 return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
1244 1345 % (self.user_id, self.username, self.ip_addr, self.is_authenticated)
1245 1346
1246 1347 def set_authenticated(self, authenticated=True):
1247 1348 if self.user_id != self.anonymous_user.user_id:
1248 1349 self.is_authenticated = authenticated
1249 1350
1250 1351 def get_cookie_store(self):
1251 1352 return {
1252 1353 'username': self.username,
1253 1354 'password': md5(self.password or ''),
1254 1355 'user_id': self.user_id,
1255 1356 'is_authenticated': self.is_authenticated
1256 1357 }
1257 1358
1258 1359 @classmethod
1259 1360 def from_cookie_store(cls, cookie_store):
1260 1361 """
1261 1362 Creates AuthUser from a cookie store
1262 1363
1263 1364 :param cls:
1264 1365 :param cookie_store:
1265 1366 """
1266 1367 user_id = cookie_store.get('user_id')
1267 1368 username = cookie_store.get('username')
1268 1369 api_key = cookie_store.get('api_key')
1269 1370 return AuthUser(user_id, api_key, username)
1270 1371
1271 1372 @classmethod
1272 1373 def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
1273 1374 _set = set()
1274 1375
1275 1376 if inherit_from_default:
1276 1377 def_user_id = User.get_default_user(cache=True).user_id
1277 1378 default_ips = UserIpMap.query().filter(UserIpMap.user_id == def_user_id)
1278 1379 if cache:
1279 1380 default_ips = default_ips.options(
1280 1381 FromCache("sql_cache_short", "get_user_ips_default"))
1281 1382
1282 1383 # populate from default user
1283 1384 for ip in default_ips:
1284 1385 try:
1285 1386 _set.add(ip.ip_addr)
1286 1387 except ObjectDeletedError:
1287 1388 # since we use heavy caching sometimes it happens that
1288 1389 # we get deleted objects here, we just skip them
1289 1390 pass
1290 1391
1291 1392 # NOTE:(marcink) we don't want to load any rules for empty
1292 1393 # user_id which is the case of access of non logged users when anonymous
1293 1394 # access is disabled
1294 1395 user_ips = []
1295 1396 if user_id:
1296 1397 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
1297 1398 if cache:
1298 1399 user_ips = user_ips.options(
1299 1400 FromCache("sql_cache_short", "get_user_ips_%s" % user_id))
1300 1401
1301 1402 for ip in user_ips:
1302 1403 try:
1303 1404 _set.add(ip.ip_addr)
1304 1405 except ObjectDeletedError:
1305 1406 # since we use heavy caching sometimes it happens that we get
1306 1407 # deleted objects here, we just skip them
1307 1408 pass
1308 1409 return _set or {ip for ip in ['0.0.0.0/0', '::/0']}
1309 1410
1310 1411
1311 1412 def set_available_permissions(settings):
1312 1413 """
1313 1414 This function will propagate pyramid settings with all available defined
1314 1415 permission given in db. We don't want to check each time from db for new
1315 1416 permissions since adding a new permission also requires application restart
1316 1417 ie. to decorate new views with the newly created permission
1317 1418
1318 1419 :param settings: current pyramid registry.settings
1319 1420
1320 1421 """
1321 1422 log.debug('auth: getting information about all available permissions')
1322 1423 try:
1323 1424 sa = meta.Session
1324 1425 all_perms = sa.query(Permission).all()
1325 1426 settings.setdefault('available_permissions',
1326 1427 [x.permission_name for x in all_perms])
1327 1428 log.debug('auth: set available permissions')
1328 1429 except Exception:
1329 1430 log.exception('Failed to fetch permissions from the database.')
1330 1431 raise
1331 1432
1332 1433
1333 1434 def get_csrf_token(session, force_new=False, save_if_missing=True):
1334 1435 """
1335 1436 Return the current authentication token, creating one if one doesn't
1336 1437 already exist and the save_if_missing flag is present.
1337 1438
1338 1439 :param session: pass in the pyramid session, else we use the global ones
1339 1440 :param force_new: force to re-generate the token and store it in session
1340 1441 :param save_if_missing: save the newly generated token if it's missing in
1341 1442 session
1342 1443 """
1343 1444 # NOTE(marcink): probably should be replaced with below one from pyramid 1.9
1344 1445 # from pyramid.csrf import get_csrf_token
1345 1446
1346 1447 if (csrf_token_key not in session and save_if_missing) or force_new:
1347 1448 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
1348 1449 session[csrf_token_key] = token
1349 1450 if hasattr(session, 'save'):
1350 1451 session.save()
1351 1452 return session.get(csrf_token_key)
1352 1453
1353 1454
1354 1455 def get_request(perm_class_instance):
1355 1456 from pyramid.threadlocal import get_current_request
1356 1457 pyramid_request = get_current_request()
1357 1458 return pyramid_request
1358 1459
1359 1460
1360 1461 # CHECK DECORATORS
1361 1462 class CSRFRequired(object):
1362 1463 """
1363 1464 Decorator for authenticating a form
1364 1465
1365 1466 This decorator uses an authorization token stored in the client's
1366 1467 session for prevention of certain Cross-site request forgery (CSRF)
1367 1468 attacks (See
1368 1469 http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
1369 1470 information).
1370 1471
1371 1472 For use with the ``webhelpers.secure_form`` helper functions.
1372 1473
1373 1474 """
1374 1475 def __init__(self, token=csrf_token_key, header='X-CSRF-Token',
1375 1476 except_methods=None):
1376 1477 self.token = token
1377 1478 self.header = header
1378 1479 self.except_methods = except_methods or []
1379 1480
1380 1481 def __call__(self, func):
1381 1482 return get_cython_compat_decorator(self.__wrapper, func)
1382 1483
1383 1484 def _get_csrf(self, _request):
1384 1485 return _request.POST.get(self.token, _request.headers.get(self.header))
1385 1486
1386 1487 def check_csrf(self, _request, cur_token):
1387 1488 supplied_token = self._get_csrf(_request)
1388 1489 return supplied_token and supplied_token == cur_token
1389 1490
1390 1491 def _get_request(self):
1391 1492 return get_request(self)
1392 1493
1393 1494 def __wrapper(self, func, *fargs, **fkwargs):
1394 1495 request = self._get_request()
1395 1496
1396 1497 if request.method in self.except_methods:
1397 1498 return func(*fargs, **fkwargs)
1398 1499
1399 1500 cur_token = get_csrf_token(request.session, save_if_missing=False)
1400 1501 if self.check_csrf(request, cur_token):
1401 1502 if request.POST.get(self.token):
1402 1503 del request.POST[self.token]
1403 1504 return func(*fargs, **fkwargs)
1404 1505 else:
1405 1506 reason = 'token-missing'
1406 1507 supplied_token = self._get_csrf(request)
1407 1508 if supplied_token and cur_token != supplied_token:
1408 1509 reason = 'token-mismatch [%s:%s]' % (
1409 1510 cur_token or ''[:6], supplied_token or ''[:6])
1410 1511
1411 1512 csrf_message = \
1412 1513 ("Cross-site request forgery detected, request denied. See "
1413 1514 "http://en.wikipedia.org/wiki/Cross-site_request_forgery for "
1414 1515 "more information.")
1415 1516 log.warn('Cross-site request forgery detected, request %r DENIED: %s '
1416 1517 'REMOTE_ADDR:%s, HEADERS:%s' % (
1417 1518 request, reason, request.remote_addr, request.headers))
1418 1519
1419 1520 raise HTTPForbidden(explanation=csrf_message)
1420 1521
1421 1522
1422 1523 class LoginRequired(object):
1423 1524 """
1424 1525 Must be logged in to execute this function else
1425 1526 redirect to login page
1426 1527
1427 1528 :param api_access: if enabled this checks only for valid auth token
1428 1529 and grants access based on valid token
1429 1530 """
1430 1531 def __init__(self, auth_token_access=None):
1431 1532 self.auth_token_access = auth_token_access
1432 1533
1433 1534 def __call__(self, func):
1434 1535 return get_cython_compat_decorator(self.__wrapper, func)
1435 1536
1436 1537 def _get_request(self):
1437 1538 return get_request(self)
1438 1539
1439 1540 def __wrapper(self, func, *fargs, **fkwargs):
1440 1541 from rhodecode.lib import helpers as h
1441 1542 cls = fargs[0]
1442 1543 user = cls._rhodecode_user
1443 1544 request = self._get_request()
1444 1545 _ = request.translate
1445 1546
1446 1547 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1447 1548 log.debug('Starting login restriction checks for user: %s' % (user,))
1448 1549 # check if our IP is allowed
1449 1550 ip_access_valid = True
1450 1551 if not user.ip_allowed:
1451 1552 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1452 1553 category='warning')
1453 1554 ip_access_valid = False
1454 1555
1455 1556 # check if we used an APIKEY and it's a valid one
1456 1557 # defined white-list of controllers which API access will be enabled
1457 1558 _auth_token = request.GET.get(
1458 1559 'auth_token', '') or request.GET.get('api_key', '')
1459 1560 auth_token_access_valid = allowed_auth_token_access(
1460 1561 loc, auth_token=_auth_token)
1461 1562
1462 1563 # explicit controller is enabled or API is in our whitelist
1463 1564 if self.auth_token_access or auth_token_access_valid:
1464 1565 log.debug('Checking AUTH TOKEN access for %s' % (cls,))
1465 1566 db_user = user.get_instance()
1466 1567
1467 1568 if db_user:
1468 1569 if self.auth_token_access:
1469 1570 roles = self.auth_token_access
1470 1571 else:
1471 1572 roles = [UserApiKeys.ROLE_HTTP]
1472 1573 token_match = db_user.authenticate_by_token(
1473 1574 _auth_token, roles=roles)
1474 1575 else:
1475 1576 log.debug('Unable to fetch db instance for auth user: %s', user)
1476 1577 token_match = False
1477 1578
1478 1579 if _auth_token and token_match:
1479 1580 auth_token_access_valid = True
1480 1581 log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],))
1481 1582 else:
1482 1583 auth_token_access_valid = False
1483 1584 if not _auth_token:
1484 1585 log.debug("AUTH TOKEN *NOT* present in request")
1485 1586 else:
1486 1587 log.warning(
1487 1588 "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:])
1488 1589
1489 1590 log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
1490 1591 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1491 1592 else 'AUTH_TOKEN_AUTH'
1492 1593
1493 1594 if ip_access_valid and (
1494 1595 user.is_authenticated or auth_token_access_valid):
1495 1596 log.info(
1496 1597 'user %s authenticating with:%s IS authenticated on func %s'
1497 1598 % (user, reason, loc))
1498 1599
1499 1600 return func(*fargs, **fkwargs)
1500 1601 else:
1501 1602 log.warning(
1502 1603 'user %s authenticating with:%s NOT authenticated on '
1503 1604 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s'
1504 1605 % (user, reason, loc, ip_access_valid,
1505 1606 auth_token_access_valid))
1506 1607 # we preserve the get PARAM
1507 1608 came_from = get_came_from(request)
1508 1609
1509 1610 log.debug('redirecting to login page with %s' % (came_from,))
1510 1611 raise HTTPFound(
1511 1612 h.route_path('login', _query={'came_from': came_from}))
1512 1613
1513 1614
1514 1615 class NotAnonymous(object):
1515 1616 """
1516 1617 Must be logged in to execute this function else
1517 1618 redirect to login page
1518 1619 """
1519 1620
1520 1621 def __call__(self, func):
1521 1622 return get_cython_compat_decorator(self.__wrapper, func)
1522 1623
1523 1624 def _get_request(self):
1524 1625 return get_request(self)
1525 1626
1526 1627 def __wrapper(self, func, *fargs, **fkwargs):
1527 1628 import rhodecode.lib.helpers as h
1528 1629 cls = fargs[0]
1529 1630 self.user = cls._rhodecode_user
1530 1631 request = self._get_request()
1531 1632 _ = request.translate
1532 1633 log.debug('Checking if user is not anonymous @%s' % cls)
1533 1634
1534 1635 anonymous = self.user.username == User.DEFAULT_USER
1535 1636
1536 1637 if anonymous:
1537 1638 came_from = get_came_from(request)
1538 1639 h.flash(_('You need to be a registered user to '
1539 1640 'perform this action'),
1540 1641 category='warning')
1541 1642 raise HTTPFound(
1542 1643 h.route_path('login', _query={'came_from': came_from}))
1543 1644 else:
1544 1645 return func(*fargs, **fkwargs)
1545 1646
1546 1647
1547 1648 class PermsDecorator(object):
1548 1649 """
1549 1650 Base class for controller decorators, we extract the current user from
1550 1651 the class itself, which has it stored in base controllers
1551 1652 """
1552 1653
1553 1654 def __init__(self, *required_perms):
1554 1655 self.required_perms = set(required_perms)
1555 1656
1556 1657 def __call__(self, func):
1557 1658 return get_cython_compat_decorator(self.__wrapper, func)
1558 1659
1559 1660 def _get_request(self):
1560 1661 return get_request(self)
1561 1662
1562 1663 def __wrapper(self, func, *fargs, **fkwargs):
1563 1664 import rhodecode.lib.helpers as h
1564 1665 cls = fargs[0]
1565 1666 _user = cls._rhodecode_user
1566 1667 request = self._get_request()
1567 1668 _ = request.translate
1568 1669
1569 1670 log.debug('checking %s permissions %s for %s %s',
1570 1671 self.__class__.__name__, self.required_perms, cls, _user)
1571 1672
1572 1673 if self.check_permissions(_user):
1573 1674 log.debug('Permission granted for %s %s', cls, _user)
1574 1675 return func(*fargs, **fkwargs)
1575 1676
1576 1677 else:
1577 1678 log.debug('Permission denied for %s %s', cls, _user)
1578 1679 anonymous = _user.username == User.DEFAULT_USER
1579 1680
1580 1681 if anonymous:
1581 1682 came_from = get_came_from(self._get_request())
1582 1683 h.flash(_('You need to be signed in to view this page'),
1583 1684 category='warning')
1584 1685 raise HTTPFound(
1585 1686 h.route_path('login', _query={'came_from': came_from}))
1586 1687
1587 1688 else:
1588 1689 # redirect with 404 to prevent resource discovery
1589 1690 raise HTTPNotFound()
1590 1691
1591 1692 def check_permissions(self, user):
1592 1693 """Dummy function for overriding"""
1593 1694 raise NotImplementedError(
1594 1695 'You have to write this function in child class')
1595 1696
1596 1697
1597 1698 class HasPermissionAllDecorator(PermsDecorator):
1598 1699 """
1599 1700 Checks for access permission for all given predicates. All of them
1600 1701 have to be meet in order to fulfill the request
1601 1702 """
1602 1703
1603 1704 def check_permissions(self, user):
1604 1705 perms = user.permissions_with_scope({})
1605 1706 if self.required_perms.issubset(perms['global']):
1606 1707 return True
1607 1708 return False
1608 1709
1609 1710
1610 1711 class HasPermissionAnyDecorator(PermsDecorator):
1611 1712 """
1612 1713 Checks for access permission for any of given predicates. In order to
1613 1714 fulfill the request any of predicates must be meet
1614 1715 """
1615 1716
1616 1717 def check_permissions(self, user):
1617 1718 perms = user.permissions_with_scope({})
1618 1719 if self.required_perms.intersection(perms['global']):
1619 1720 return True
1620 1721 return False
1621 1722
1622 1723
1623 1724 class HasRepoPermissionAllDecorator(PermsDecorator):
1624 1725 """
1625 1726 Checks for access permission for all given predicates for specific
1626 1727 repository. All of them have to be meet in order to fulfill the request
1627 1728 """
1628 1729 def _get_repo_name(self):
1629 1730 _request = self._get_request()
1630 1731 return get_repo_slug(_request)
1631 1732
1632 1733 def check_permissions(self, user):
1633 1734 perms = user.permissions
1634 1735 repo_name = self._get_repo_name()
1635 1736
1636 1737 try:
1637 1738 user_perms = {perms['repositories'][repo_name]}
1638 1739 except KeyError:
1639 1740 log.debug('cannot locate repo with name: `%s` in permissions defs',
1640 1741 repo_name)
1641 1742 return False
1642 1743
1643 1744 log.debug('checking `%s` permissions for repo `%s`',
1644 1745 user_perms, repo_name)
1645 1746 if self.required_perms.issubset(user_perms):
1646 1747 return True
1647 1748 return False
1648 1749
1649 1750
1650 1751 class HasRepoPermissionAnyDecorator(PermsDecorator):
1651 1752 """
1652 1753 Checks for access permission for any of given predicates for specific
1653 1754 repository. In order to fulfill the request any of predicates must be meet
1654 1755 """
1655 1756 def _get_repo_name(self):
1656 1757 _request = self._get_request()
1657 1758 return get_repo_slug(_request)
1658 1759
1659 1760 def check_permissions(self, user):
1660 1761 perms = user.permissions
1661 1762 repo_name = self._get_repo_name()
1662 1763
1663 1764 try:
1664 1765 user_perms = {perms['repositories'][repo_name]}
1665 1766 except KeyError:
1666 1767 log.debug(
1667 1768 'cannot locate repo with name: `%s` in permissions defs',
1668 1769 repo_name)
1669 1770 return False
1670 1771
1671 1772 log.debug('checking `%s` permissions for repo `%s`',
1672 1773 user_perms, repo_name)
1673 1774 if self.required_perms.intersection(user_perms):
1674 1775 return True
1675 1776 return False
1676 1777
1677 1778
1678 1779 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1679 1780 """
1680 1781 Checks for access permission for all given predicates for specific
1681 1782 repository group. All of them have to be meet in order to
1682 1783 fulfill the request
1683 1784 """
1684 1785 def _get_repo_group_name(self):
1685 1786 _request = self._get_request()
1686 1787 return get_repo_group_slug(_request)
1687 1788
1688 1789 def check_permissions(self, user):
1689 1790 perms = user.permissions
1690 1791 group_name = self._get_repo_group_name()
1691 1792 try:
1692 1793 user_perms = {perms['repositories_groups'][group_name]}
1693 1794 except KeyError:
1694 1795 log.debug(
1695 1796 'cannot locate repo group with name: `%s` in permissions defs',
1696 1797 group_name)
1697 1798 return False
1698 1799
1699 1800 log.debug('checking `%s` permissions for repo group `%s`',
1700 1801 user_perms, group_name)
1701 1802 if self.required_perms.issubset(user_perms):
1702 1803 return True
1703 1804 return False
1704 1805
1705 1806
1706 1807 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1707 1808 """
1708 1809 Checks for access permission for any of given predicates for specific
1709 1810 repository group. In order to fulfill the request any
1710 1811 of predicates must be met
1711 1812 """
1712 1813 def _get_repo_group_name(self):
1713 1814 _request = self._get_request()
1714 1815 return get_repo_group_slug(_request)
1715 1816
1716 1817 def check_permissions(self, user):
1717 1818 perms = user.permissions
1718 1819 group_name = self._get_repo_group_name()
1719 1820
1720 1821 try:
1721 1822 user_perms = {perms['repositories_groups'][group_name]}
1722 1823 except KeyError:
1723 1824 log.debug(
1724 1825 'cannot locate repo group with name: `%s` in permissions defs',
1725 1826 group_name)
1726 1827 return False
1727 1828
1728 1829 log.debug('checking `%s` permissions for repo group `%s`',
1729 1830 user_perms, group_name)
1730 1831 if self.required_perms.intersection(user_perms):
1731 1832 return True
1732 1833 return False
1733 1834
1734 1835
1735 1836 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1736 1837 """
1737 1838 Checks for access permission for all given predicates for specific
1738 1839 user group. All of them have to be meet in order to fulfill the request
1739 1840 """
1740 1841 def _get_user_group_name(self):
1741 1842 _request = self._get_request()
1742 1843 return get_user_group_slug(_request)
1743 1844
1744 1845 def check_permissions(self, user):
1745 1846 perms = user.permissions
1746 1847 group_name = self._get_user_group_name()
1747 1848 try:
1748 1849 user_perms = {perms['user_groups'][group_name]}
1749 1850 except KeyError:
1750 1851 return False
1751 1852
1752 1853 if self.required_perms.issubset(user_perms):
1753 1854 return True
1754 1855 return False
1755 1856
1756 1857
1757 1858 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1758 1859 """
1759 1860 Checks for access permission for any of given predicates for specific
1760 1861 user group. In order to fulfill the request any of predicates must be meet
1761 1862 """
1762 1863 def _get_user_group_name(self):
1763 1864 _request = self._get_request()
1764 1865 return get_user_group_slug(_request)
1765 1866
1766 1867 def check_permissions(self, user):
1767 1868 perms = user.permissions
1768 1869 group_name = self._get_user_group_name()
1769 1870 try:
1770 1871 user_perms = {perms['user_groups'][group_name]}
1771 1872 except KeyError:
1772 1873 return False
1773 1874
1774 1875 if self.required_perms.intersection(user_perms):
1775 1876 return True
1776 1877 return False
1777 1878
1778 1879
1779 1880 # CHECK FUNCTIONS
1780 1881 class PermsFunction(object):
1781 1882 """Base function for other check functions"""
1782 1883
1783 1884 def __init__(self, *perms):
1784 1885 self.required_perms = set(perms)
1785 1886 self.repo_name = None
1786 1887 self.repo_group_name = None
1787 1888 self.user_group_name = None
1788 1889
1789 1890 def __bool__(self):
1790 1891 frame = inspect.currentframe()
1791 1892 stack_trace = traceback.format_stack(frame)
1792 1893 log.error('Checking bool value on a class instance of perm '
1793 1894 'function is not allowed: %s' % ''.join(stack_trace))
1794 1895 # rather than throwing errors, here we always return False so if by
1795 1896 # accident someone checks truth for just an instance it will always end
1796 1897 # up in returning False
1797 1898 return False
1798 1899 __nonzero__ = __bool__
1799 1900
1800 1901 def __call__(self, check_location='', user=None):
1801 1902 if not user:
1802 1903 log.debug('Using user attribute from global request')
1803 # TODO: remove this someday,put as user as attribute here
1804 1904 request = self._get_request()
1805 1905 user = request.user
1806 1906
1807 1907 # init auth user if not already given
1808 1908 if not isinstance(user, AuthUser):
1809 1909 log.debug('Wrapping user %s into AuthUser', user)
1810 1910 user = AuthUser(user.user_id)
1811 1911
1812 1912 cls_name = self.__class__.__name__
1813 1913 check_scope = self._get_check_scope(cls_name)
1814 1914 check_location = check_location or 'unspecified location'
1815 1915
1816 1916 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1817 1917 self.required_perms, user, check_scope, check_location)
1818 1918 if not user:
1819 1919 log.warning('Empty user given for permission check')
1820 1920 return False
1821 1921
1822 1922 if self.check_permissions(user):
1823 1923 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1824 1924 check_scope, user, check_location)
1825 1925 return True
1826 1926
1827 1927 else:
1828 1928 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1829 1929 check_scope, user, check_location)
1830 1930 return False
1831 1931
1832 1932 def _get_request(self):
1833 1933 return get_request(self)
1834 1934
1835 1935 def _get_check_scope(self, cls_name):
1836 1936 return {
1837 1937 'HasPermissionAll': 'GLOBAL',
1838 1938 'HasPermissionAny': 'GLOBAL',
1839 1939 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
1840 1940 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
1841 1941 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
1842 1942 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
1843 1943 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
1844 1944 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
1845 1945 }.get(cls_name, '?:%s' % cls_name)
1846 1946
1847 1947 def check_permissions(self, user):
1848 1948 """Dummy function for overriding"""
1849 1949 raise Exception('You have to write this function in child class')
1850 1950
1851 1951
1852 1952 class HasPermissionAll(PermsFunction):
1853 1953 def check_permissions(self, user):
1854 1954 perms = user.permissions_with_scope({})
1855 1955 if self.required_perms.issubset(perms.get('global')):
1856 1956 return True
1857 1957 return False
1858 1958
1859 1959
1860 1960 class HasPermissionAny(PermsFunction):
1861 1961 def check_permissions(self, user):
1862 1962 perms = user.permissions_with_scope({})
1863 1963 if self.required_perms.intersection(perms.get('global')):
1864 1964 return True
1865 1965 return False
1866 1966
1867 1967
1868 1968 class HasRepoPermissionAll(PermsFunction):
1869 1969 def __call__(self, repo_name=None, check_location='', user=None):
1870 1970 self.repo_name = repo_name
1871 1971 return super(HasRepoPermissionAll, self).__call__(check_location, user)
1872 1972
1873 1973 def _get_repo_name(self):
1874 1974 if not self.repo_name:
1875 1975 _request = self._get_request()
1876 1976 self.repo_name = get_repo_slug(_request)
1877 1977 return self.repo_name
1878 1978
1879 1979 def check_permissions(self, user):
1880 1980 self.repo_name = self._get_repo_name()
1881 1981 perms = user.permissions
1882 1982 try:
1883 1983 user_perms = {perms['repositories'][self.repo_name]}
1884 1984 except KeyError:
1885 1985 return False
1886 1986 if self.required_perms.issubset(user_perms):
1887 1987 return True
1888 1988 return False
1889 1989
1890 1990
1891 1991 class HasRepoPermissionAny(PermsFunction):
1892 1992 def __call__(self, repo_name=None, check_location='', user=None):
1893 1993 self.repo_name = repo_name
1894 1994 return super(HasRepoPermissionAny, self).__call__(check_location, user)
1895 1995
1896 1996 def _get_repo_name(self):
1897 1997 if not self.repo_name:
1898 1998 _request = self._get_request()
1899 1999 self.repo_name = get_repo_slug(_request)
1900 2000 return self.repo_name
1901 2001
1902 2002 def check_permissions(self, user):
1903 2003 self.repo_name = self._get_repo_name()
1904 2004 perms = user.permissions
1905 2005 try:
1906 2006 user_perms = {perms['repositories'][self.repo_name]}
1907 2007 except KeyError:
1908 2008 return False
1909 2009 if self.required_perms.intersection(user_perms):
1910 2010 return True
1911 2011 return False
1912 2012
1913 2013
1914 2014 class HasRepoGroupPermissionAny(PermsFunction):
1915 2015 def __call__(self, group_name=None, check_location='', user=None):
1916 2016 self.repo_group_name = group_name
1917 2017 return super(HasRepoGroupPermissionAny, self).__call__(
1918 2018 check_location, user)
1919 2019
1920 2020 def check_permissions(self, user):
1921 2021 perms = user.permissions
1922 2022 try:
1923 2023 user_perms = {perms['repositories_groups'][self.repo_group_name]}
1924 2024 except KeyError:
1925 2025 return False
1926 2026 if self.required_perms.intersection(user_perms):
1927 2027 return True
1928 2028 return False
1929 2029
1930 2030
1931 2031 class HasRepoGroupPermissionAll(PermsFunction):
1932 2032 def __call__(self, group_name=None, check_location='', user=None):
1933 2033 self.repo_group_name = group_name
1934 2034 return super(HasRepoGroupPermissionAll, self).__call__(
1935 2035 check_location, user)
1936 2036
1937 2037 def check_permissions(self, user):
1938 2038 perms = user.permissions
1939 2039 try:
1940 2040 user_perms = {perms['repositories_groups'][self.repo_group_name]}
1941 2041 except KeyError:
1942 2042 return False
1943 2043 if self.required_perms.issubset(user_perms):
1944 2044 return True
1945 2045 return False
1946 2046
1947 2047
1948 2048 class HasUserGroupPermissionAny(PermsFunction):
1949 2049 def __call__(self, user_group_name=None, check_location='', user=None):
1950 2050 self.user_group_name = user_group_name
1951 2051 return super(HasUserGroupPermissionAny, self).__call__(
1952 2052 check_location, user)
1953 2053
1954 2054 def check_permissions(self, user):
1955 2055 perms = user.permissions
1956 2056 try:
1957 2057 user_perms = {perms['user_groups'][self.user_group_name]}
1958 2058 except KeyError:
1959 2059 return False
1960 2060 if self.required_perms.intersection(user_perms):
1961 2061 return True
1962 2062 return False
1963 2063
1964 2064
1965 2065 class HasUserGroupPermissionAll(PermsFunction):
1966 2066 def __call__(self, user_group_name=None, check_location='', user=None):
1967 2067 self.user_group_name = user_group_name
1968 2068 return super(HasUserGroupPermissionAll, self).__call__(
1969 2069 check_location, user)
1970 2070
1971 2071 def check_permissions(self, user):
1972 2072 perms = user.permissions
1973 2073 try:
1974 2074 user_perms = {perms['user_groups'][self.user_group_name]}
1975 2075 except KeyError:
1976 2076 return False
1977 2077 if self.required_perms.issubset(user_perms):
1978 2078 return True
1979 2079 return False
1980 2080
1981 2081
1982 2082 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
1983 2083 class HasPermissionAnyMiddleware(object):
1984 2084 def __init__(self, *perms):
1985 2085 self.required_perms = set(perms)
1986 2086
1987 2087 def __call__(self, user, repo_name):
1988 2088 # repo_name MUST be unicode, since we handle keys in permission
1989 2089 # dict by unicode
1990 2090 repo_name = safe_unicode(repo_name)
1991 2091 user = AuthUser(user.user_id)
1992 2092 log.debug(
1993 2093 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
1994 2094 self.required_perms, user, repo_name)
1995 2095
1996 2096 if self.check_permissions(user, repo_name):
1997 2097 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
1998 2098 repo_name, user, 'PermissionMiddleware')
1999 2099 return True
2000 2100
2001 2101 else:
2002 2102 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
2003 2103 repo_name, user, 'PermissionMiddleware')
2004 2104 return False
2005 2105
2006 2106 def check_permissions(self, user, repo_name):
2007 2107 perms = user.permissions_with_scope({'repo_name': repo_name})
2008 2108
2009 2109 try:
2010 2110 user_perms = {perms['repositories'][repo_name]}
2011 2111 except Exception:
2012 2112 log.exception('Error while accessing user permissions')
2013 2113 return False
2014 2114
2015 2115 if self.required_perms.intersection(user_perms):
2016 2116 return True
2017 2117 return False
2018 2118
2019 2119
2020 2120 # SPECIAL VERSION TO HANDLE API AUTH
2021 2121 class _BaseApiPerm(object):
2022 2122 def __init__(self, *perms):
2023 2123 self.required_perms = set(perms)
2024 2124
2025 2125 def __call__(self, check_location=None, user=None, repo_name=None,
2026 2126 group_name=None, user_group_name=None):
2027 2127 cls_name = self.__class__.__name__
2028 2128 check_scope = 'global:%s' % (self.required_perms,)
2029 2129 if repo_name:
2030 2130 check_scope += ', repo_name:%s' % (repo_name,)
2031 2131
2032 2132 if group_name:
2033 2133 check_scope += ', repo_group_name:%s' % (group_name,)
2034 2134
2035 2135 if user_group_name:
2036 2136 check_scope += ', user_group_name:%s' % (user_group_name,)
2037 2137
2038 2138 log.debug(
2039 2139 'checking cls:%s %s %s @ %s'
2040 2140 % (cls_name, self.required_perms, check_scope, check_location))
2041 2141 if not user:
2042 2142 log.debug('Empty User passed into arguments')
2043 2143 return False
2044 2144
2045 2145 # process user
2046 2146 if not isinstance(user, AuthUser):
2047 2147 user = AuthUser(user.user_id)
2048 2148 if not check_location:
2049 2149 check_location = 'unspecified'
2050 2150 if self.check_permissions(user.permissions, repo_name, group_name,
2051 2151 user_group_name):
2052 2152 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
2053 2153 check_scope, user, check_location)
2054 2154 return True
2055 2155
2056 2156 else:
2057 2157 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
2058 2158 check_scope, user, check_location)
2059 2159 return False
2060 2160
2061 2161 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2062 2162 user_group_name=None):
2063 2163 """
2064 2164 implement in child class should return True if permissions are ok,
2065 2165 False otherwise
2066 2166
2067 2167 :param perm_defs: dict with permission definitions
2068 2168 :param repo_name: repo name
2069 2169 """
2070 2170 raise NotImplementedError()
2071 2171
2072 2172
2073 2173 class HasPermissionAllApi(_BaseApiPerm):
2074 2174 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2075 2175 user_group_name=None):
2076 2176 if self.required_perms.issubset(perm_defs.get('global')):
2077 2177 return True
2078 2178 return False
2079 2179
2080 2180
2081 2181 class HasPermissionAnyApi(_BaseApiPerm):
2082 2182 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2083 2183 user_group_name=None):
2084 2184 if self.required_perms.intersection(perm_defs.get('global')):
2085 2185 return True
2086 2186 return False
2087 2187
2088 2188
2089 2189 class HasRepoPermissionAllApi(_BaseApiPerm):
2090 2190 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2091 2191 user_group_name=None):
2092 2192 try:
2093 2193 _user_perms = {perm_defs['repositories'][repo_name]}
2094 2194 except KeyError:
2095 2195 log.warning(traceback.format_exc())
2096 2196 return False
2097 2197 if self.required_perms.issubset(_user_perms):
2098 2198 return True
2099 2199 return False
2100 2200
2101 2201
2102 2202 class HasRepoPermissionAnyApi(_BaseApiPerm):
2103 2203 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2104 2204 user_group_name=None):
2105 2205 try:
2106 2206 _user_perms = {perm_defs['repositories'][repo_name]}
2107 2207 except KeyError:
2108 2208 log.warning(traceback.format_exc())
2109 2209 return False
2110 2210 if self.required_perms.intersection(_user_perms):
2111 2211 return True
2112 2212 return False
2113 2213
2114 2214
2115 2215 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
2116 2216 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2117 2217 user_group_name=None):
2118 2218 try:
2119 2219 _user_perms = {perm_defs['repositories_groups'][group_name]}
2120 2220 except KeyError:
2121 2221 log.warning(traceback.format_exc())
2122 2222 return False
2123 2223 if self.required_perms.intersection(_user_perms):
2124 2224 return True
2125 2225 return False
2126 2226
2127 2227
2128 2228 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
2129 2229 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2130 2230 user_group_name=None):
2131 2231 try:
2132 2232 _user_perms = {perm_defs['repositories_groups'][group_name]}
2133 2233 except KeyError:
2134 2234 log.warning(traceback.format_exc())
2135 2235 return False
2136 2236 if self.required_perms.issubset(_user_perms):
2137 2237 return True
2138 2238 return False
2139 2239
2140 2240
2141 2241 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
2142 2242 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2143 2243 user_group_name=None):
2144 2244 try:
2145 2245 _user_perms = {perm_defs['user_groups'][user_group_name]}
2146 2246 except KeyError:
2147 2247 log.warning(traceback.format_exc())
2148 2248 return False
2149 2249 if self.required_perms.intersection(_user_perms):
2150 2250 return True
2151 2251 return False
2152 2252
2153 2253
2154 2254 def check_ip_access(source_ip, allowed_ips=None):
2155 2255 """
2156 2256 Checks if source_ip is a subnet of any of allowed_ips.
2157 2257
2158 2258 :param source_ip:
2159 2259 :param allowed_ips: list of allowed ips together with mask
2160 2260 """
2161 2261 log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips))
2162 2262 source_ip_address = ipaddress.ip_address(safe_unicode(source_ip))
2163 2263 if isinstance(allowed_ips, (tuple, list, set)):
2164 2264 for ip in allowed_ips:
2165 2265 ip = safe_unicode(ip)
2166 2266 try:
2167 2267 network_address = ipaddress.ip_network(ip, strict=False)
2168 2268 if source_ip_address in network_address:
2169 2269 log.debug('IP %s is network %s' %
2170 2270 (source_ip_address, network_address))
2171 2271 return True
2172 2272 # for any case we cannot determine the IP, don't crash just
2173 2273 # skip it and log as error, we want to say forbidden still when
2174 2274 # sending bad IP
2175 2275 except Exception:
2176 2276 log.error(traceback.format_exc())
2177 2277 continue
2178 2278 return False
2179 2279
2180 2280
2181 2281 def get_cython_compat_decorator(wrapper, func):
2182 2282 """
2183 2283 Creates a cython compatible decorator. The previously used
2184 2284 decorator.decorator() function seems to be incompatible with cython.
2185 2285
2186 2286 :param wrapper: __wrapper method of the decorator class
2187 2287 :param func: decorated function
2188 2288 """
2189 2289 @wraps(func)
2190 2290 def local_wrapper(*args, **kwds):
2191 2291 return wrapper(func, *args, **kwds)
2192 2292 local_wrapper.__wrapped__ = func
2193 2293 return local_wrapper
2194 2294
2195 2295
@@ -1,1004 +1,1011 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2011-2018 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 """
23 23 Some simple helper functions
24 24 """
25 25
26 26 import collections
27 27 import datetime
28 28 import dateutil.relativedelta
29 29 import hashlib
30 30 import logging
31 31 import re
32 32 import sys
33 33 import time
34 34 import urllib
35 35 import urlobject
36 36 import uuid
37 37 import getpass
38 38
39 39 import pygments.lexers
40 40 import sqlalchemy
41 41 import sqlalchemy.engine.url
42 42 import sqlalchemy.exc
43 43 import sqlalchemy.sql
44 44 import webob
45 45 import pyramid.threadlocal
46 46
47 47 import rhodecode
48 48 from rhodecode.translation import _, _pluralize
49 49
50 50
51 51 def md5(s):
52 52 return hashlib.md5(s).hexdigest()
53 53
54 54
55 55 def md5_safe(s):
56 56 return md5(safe_str(s))
57 57
58 58
59 59 def sha1(s):
60 60 return hashlib.sha1(s).hexdigest()
61 61
62 62
63 63 def sha1_safe(s):
64 64 return sha1(safe_str(s))
65 65
66 66
67 67 def __get_lem(extra_mapping=None):
68 68 """
69 69 Get language extension map based on what's inside pygments lexers
70 70 """
71 71 d = collections.defaultdict(lambda: [])
72 72
73 73 def __clean(s):
74 74 s = s.lstrip('*')
75 75 s = s.lstrip('.')
76 76
77 77 if s.find('[') != -1:
78 78 exts = []
79 79 start, stop = s.find('['), s.find(']')
80 80
81 81 for suffix in s[start + 1:stop]:
82 82 exts.append(s[:s.find('[')] + suffix)
83 83 return [e.lower() for e in exts]
84 84 else:
85 85 return [s.lower()]
86 86
87 87 for lx, t in sorted(pygments.lexers.LEXERS.items()):
88 88 m = map(__clean, t[-2])
89 89 if m:
90 90 m = reduce(lambda x, y: x + y, m)
91 91 for ext in m:
92 92 desc = lx.replace('Lexer', '')
93 93 d[ext].append(desc)
94 94
95 95 data = dict(d)
96 96
97 97 extra_mapping = extra_mapping or {}
98 98 if extra_mapping:
99 99 for k, v in extra_mapping.items():
100 100 if k not in data:
101 101 # register new mapping2lexer
102 102 data[k] = [v]
103 103
104 104 return data
105 105
106 106
107 107 def str2bool(_str):
108 108 """
109 109 returns True/False value from given string, it tries to translate the
110 110 string into boolean
111 111
112 112 :param _str: string value to translate into boolean
113 113 :rtype: boolean
114 114 :returns: boolean from given string
115 115 """
116 116 if _str is None:
117 117 return False
118 118 if _str in (True, False):
119 119 return _str
120 120 _str = str(_str).strip().lower()
121 121 return _str in ('t', 'true', 'y', 'yes', 'on', '1')
122 122
123 123
124 124 def aslist(obj, sep=None, strip=True):
125 125 """
126 126 Returns given string separated by sep as list
127 127
128 128 :param obj:
129 129 :param sep:
130 130 :param strip:
131 131 """
132 132 if isinstance(obj, (basestring,)):
133 133 lst = obj.split(sep)
134 134 if strip:
135 135 lst = [v.strip() for v in lst]
136 136 return lst
137 137 elif isinstance(obj, (list, tuple)):
138 138 return obj
139 139 elif obj is None:
140 140 return []
141 141 else:
142 142 return [obj]
143 143
144 144
145 145 def convert_line_endings(line, mode):
146 146 """
147 147 Converts a given line "line end" accordingly to given mode
148 148
149 149 Available modes are::
150 150 0 - Unix
151 151 1 - Mac
152 152 2 - DOS
153 153
154 154 :param line: given line to convert
155 155 :param mode: mode to convert to
156 156 :rtype: str
157 157 :return: converted line according to mode
158 158 """
159 159 if mode == 0:
160 160 line = line.replace('\r\n', '\n')
161 161 line = line.replace('\r', '\n')
162 162 elif mode == 1:
163 163 line = line.replace('\r\n', '\r')
164 164 line = line.replace('\n', '\r')
165 165 elif mode == 2:
166 166 line = re.sub('\r(?!\n)|(?<!\r)\n', '\r\n', line)
167 167 return line
168 168
169 169
170 170 def detect_mode(line, default):
171 171 """
172 172 Detects line break for given line, if line break couldn't be found
173 173 given default value is returned
174 174
175 175 :param line: str line
176 176 :param default: default
177 177 :rtype: int
178 178 :return: value of line end on of 0 - Unix, 1 - Mac, 2 - DOS
179 179 """
180 180 if line.endswith('\r\n'):
181 181 return 2
182 182 elif line.endswith('\n'):
183 183 return 0
184 184 elif line.endswith('\r'):
185 185 return 1
186 186 else:
187 187 return default
188 188
189 189
190 190 def safe_int(val, default=None):
191 191 """
192 192 Returns int() of val if val is not convertable to int use default
193 193 instead
194 194
195 195 :param val:
196 196 :param default:
197 197 """
198 198
199 199 try:
200 200 val = int(val)
201 201 except (ValueError, TypeError):
202 202 val = default
203 203
204 204 return val
205 205
206 206
207 207 def safe_unicode(str_, from_encoding=None):
208 208 """
209 209 safe unicode function. Does few trick to turn str_ into unicode
210 210
211 211 In case of UnicodeDecode error, we try to return it with encoding detected
212 212 by chardet library if it fails fallback to unicode with errors replaced
213 213
214 214 :param str_: string to decode
215 215 :rtype: unicode
216 216 :returns: unicode object
217 217 """
218 218 if isinstance(str_, unicode):
219 219 return str_
220 220
221 221 if not from_encoding:
222 222 DEFAULT_ENCODINGS = aslist(rhodecode.CONFIG.get('default_encoding',
223 223 'utf8'), sep=',')
224 224 from_encoding = DEFAULT_ENCODINGS
225 225
226 226 if not isinstance(from_encoding, (list, tuple)):
227 227 from_encoding = [from_encoding]
228 228
229 229 try:
230 230 return unicode(str_)
231 231 except UnicodeDecodeError:
232 232 pass
233 233
234 234 for enc in from_encoding:
235 235 try:
236 236 return unicode(str_, enc)
237 237 except UnicodeDecodeError:
238 238 pass
239 239
240 240 try:
241 241 import chardet
242 242 encoding = chardet.detect(str_)['encoding']
243 243 if encoding is None:
244 244 raise Exception()
245 245 return str_.decode(encoding)
246 246 except (ImportError, UnicodeDecodeError, Exception):
247 247 return unicode(str_, from_encoding[0], 'replace')
248 248
249 249
250 250 def safe_str(unicode_, to_encoding=None):
251 251 """
252 252 safe str function. Does few trick to turn unicode_ into string
253 253
254 254 In case of UnicodeEncodeError, we try to return it with encoding detected
255 255 by chardet library if it fails fallback to string with errors replaced
256 256
257 257 :param unicode_: unicode to encode
258 258 :rtype: str
259 259 :returns: str object
260 260 """
261 261
262 262 # if it's not basestr cast to str
263 263 if not isinstance(unicode_, basestring):
264 264 return str(unicode_)
265 265
266 266 if isinstance(unicode_, str):
267 267 return unicode_
268 268
269 269 if not to_encoding:
270 270 DEFAULT_ENCODINGS = aslist(rhodecode.CONFIG.get('default_encoding',
271 271 'utf8'), sep=',')
272 272 to_encoding = DEFAULT_ENCODINGS
273 273
274 274 if not isinstance(to_encoding, (list, tuple)):
275 275 to_encoding = [to_encoding]
276 276
277 277 for enc in to_encoding:
278 278 try:
279 279 return unicode_.encode(enc)
280 280 except UnicodeEncodeError:
281 281 pass
282 282
283 283 try:
284 284 import chardet
285 285 encoding = chardet.detect(unicode_)['encoding']
286 286 if encoding is None:
287 287 raise UnicodeEncodeError()
288 288
289 289 return unicode_.encode(encoding)
290 290 except (ImportError, UnicodeEncodeError):
291 291 return unicode_.encode(to_encoding[0], 'replace')
292 292
293 293
294 294 def remove_suffix(s, suffix):
295 295 if s.endswith(suffix):
296 296 s = s[:-1 * len(suffix)]
297 297 return s
298 298
299 299
300 300 def remove_prefix(s, prefix):
301 301 if s.startswith(prefix):
302 302 s = s[len(prefix):]
303 303 return s
304 304
305 305
306 306 def find_calling_context(ignore_modules=None):
307 307 """
308 308 Look through the calling stack and return the frame which called
309 309 this function and is part of core module ( ie. rhodecode.* )
310 310
311 311 :param ignore_modules: list of modules to ignore eg. ['rhodecode.lib']
312 312 """
313 313
314 314 ignore_modules = ignore_modules or []
315 315
316 316 f = sys._getframe(2)
317 317 while f.f_back is not None:
318 318 name = f.f_globals.get('__name__')
319 319 if name and name.startswith(__name__.split('.')[0]):
320 320 if name not in ignore_modules:
321 321 return f
322 322 f = f.f_back
323 323 return None
324 324
325 325
326 326 def ping_connection(connection, branch):
327 327 if branch:
328 328 # "branch" refers to a sub-connection of a connection,
329 329 # we don't want to bother pinging on these.
330 330 return
331 331
332 332 # turn off "close with result". This flag is only used with
333 333 # "connectionless" execution, otherwise will be False in any case
334 334 save_should_close_with_result = connection.should_close_with_result
335 335 connection.should_close_with_result = False
336 336
337 337 try:
338 338 # run a SELECT 1. use a core select() so that
339 339 # the SELECT of a scalar value without a table is
340 340 # appropriately formatted for the backend
341 341 connection.scalar(sqlalchemy.sql.select([1]))
342 342 except sqlalchemy.exc.DBAPIError as err:
343 343 # catch SQLAlchemy's DBAPIError, which is a wrapper
344 344 # for the DBAPI's exception. It includes a .connection_invalidated
345 345 # attribute which specifies if this connection is a "disconnect"
346 346 # condition, which is based on inspection of the original exception
347 347 # by the dialect in use.
348 348 if err.connection_invalidated:
349 349 # run the same SELECT again - the connection will re-validate
350 350 # itself and establish a new connection. The disconnect detection
351 351 # here also causes the whole connection pool to be invalidated
352 352 # so that all stale connections are discarded.
353 353 connection.scalar(sqlalchemy.sql.select([1]))
354 354 else:
355 355 raise
356 356 finally:
357 357 # restore "close with result"
358 358 connection.should_close_with_result = save_should_close_with_result
359 359
360 360
361 361 def engine_from_config(configuration, prefix='sqlalchemy.', **kwargs):
362 362 """Custom engine_from_config functions."""
363 363 log = logging.getLogger('sqlalchemy.engine')
364 364 _ping_connection = configuration.pop('sqlalchemy.db1.ping_connection', None)
365 365
366 366 engine = sqlalchemy.engine_from_config(configuration, prefix, **kwargs)
367 367
368 368 def color_sql(sql):
369 369 color_seq = '\033[1;33m' # This is yellow: code 33
370 370 normal = '\x1b[0m'
371 371 return ''.join([color_seq, sql, normal])
372 372
373 373 if configuration['debug'] or _ping_connection:
374 374 sqlalchemy.event.listen(engine, "engine_connect", ping_connection)
375 375
376 376 if configuration['debug']:
377 377 # attach events only for debug configuration
378 378
379 379 def before_cursor_execute(conn, cursor, statement,
380 380 parameters, context, executemany):
381 381 setattr(conn, 'query_start_time', time.time())
382 382 log.info(color_sql(">>>>> STARTING QUERY >>>>>"))
383 383 calling_context = find_calling_context(ignore_modules=[
384 384 'rhodecode.lib.caching_query',
385 385 'rhodecode.model.settings',
386 386 ])
387 387 if calling_context:
388 388 log.info(color_sql('call context %s:%s' % (
389 389 calling_context.f_code.co_filename,
390 390 calling_context.f_lineno,
391 391 )))
392 392
393 393 def after_cursor_execute(conn, cursor, statement,
394 394 parameters, context, executemany):
395 395 delattr(conn, 'query_start_time')
396 396
397 397 sqlalchemy.event.listen(engine, "before_cursor_execute",
398 398 before_cursor_execute)
399 399 sqlalchemy.event.listen(engine, "after_cursor_execute",
400 400 after_cursor_execute)
401 401
402 402 return engine
403 403
404 404
405 405 def get_encryption_key(config):
406 406 secret = config.get('rhodecode.encrypted_values.secret')
407 407 default = config['beaker.session.secret']
408 408 return secret or default
409 409
410 410
411 411 def age(prevdate, now=None, show_short_version=False, show_suffix=True,
412 412 short_format=False):
413 413 """
414 414 Turns a datetime into an age string.
415 415 If show_short_version is True, this generates a shorter string with
416 416 an approximate age; ex. '1 day ago', rather than '1 day and 23 hours ago'.
417 417
418 418 * IMPORTANT*
419 419 Code of this function is written in special way so it's easier to
420 420 backport it to javascript. If you mean to update it, please also update
421 421 `jquery.timeago-extension.js` file
422 422
423 423 :param prevdate: datetime object
424 424 :param now: get current time, if not define we use
425 425 `datetime.datetime.now()`
426 426 :param show_short_version: if it should approximate the date and
427 427 return a shorter string
428 428 :param show_suffix:
429 429 :param short_format: show short format, eg 2D instead of 2 days
430 430 :rtype: unicode
431 431 :returns: unicode words describing age
432 432 """
433 433
434 434 def _get_relative_delta(now, prevdate):
435 435 base = dateutil.relativedelta.relativedelta(now, prevdate)
436 436 return {
437 437 'year': base.years,
438 438 'month': base.months,
439 439 'day': base.days,
440 440 'hour': base.hours,
441 441 'minute': base.minutes,
442 442 'second': base.seconds,
443 443 }
444 444
445 445 def _is_leap_year(year):
446 446 return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
447 447
448 448 def get_month(prevdate):
449 449 return prevdate.month
450 450
451 451 def get_year(prevdate):
452 452 return prevdate.year
453 453
454 454 now = now or datetime.datetime.now()
455 455 order = ['year', 'month', 'day', 'hour', 'minute', 'second']
456 456 deltas = {}
457 457 future = False
458 458
459 459 if prevdate > now:
460 460 now_old = now
461 461 now = prevdate
462 462 prevdate = now_old
463 463 future = True
464 464 if future:
465 465 prevdate = prevdate.replace(microsecond=0)
466 466 # Get date parts deltas
467 467 for part in order:
468 468 rel_delta = _get_relative_delta(now, prevdate)
469 469 deltas[part] = rel_delta[part]
470 470
471 471 # Fix negative offsets (there is 1 second between 10:59:59 and 11:00:00,
472 472 # not 1 hour, -59 minutes and -59 seconds)
473 473 offsets = [[5, 60], [4, 60], [3, 24]]
474 474 for element in offsets: # seconds, minutes, hours
475 475 num = element[0]
476 476 length = element[1]
477 477
478 478 part = order[num]
479 479 carry_part = order[num - 1]
480 480
481 481 if deltas[part] < 0:
482 482 deltas[part] += length
483 483 deltas[carry_part] -= 1
484 484
485 485 # Same thing for days except that the increment depends on the (variable)
486 486 # number of days in the month
487 487 month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
488 488 if deltas['day'] < 0:
489 489 if get_month(prevdate) == 2 and _is_leap_year(get_year(prevdate)):
490 490 deltas['day'] += 29
491 491 else:
492 492 deltas['day'] += month_lengths[get_month(prevdate) - 1]
493 493
494 494 deltas['month'] -= 1
495 495
496 496 if deltas['month'] < 0:
497 497 deltas['month'] += 12
498 498 deltas['year'] -= 1
499 499
500 500 # Format the result
501 501 if short_format:
502 502 fmt_funcs = {
503 503 'year': lambda d: u'%dy' % d,
504 504 'month': lambda d: u'%dm' % d,
505 505 'day': lambda d: u'%dd' % d,
506 506 'hour': lambda d: u'%dh' % d,
507 507 'minute': lambda d: u'%dmin' % d,
508 508 'second': lambda d: u'%dsec' % d,
509 509 }
510 510 else:
511 511 fmt_funcs = {
512 512 'year': lambda d: _pluralize(u'${num} year', u'${num} years', d, mapping={'num': d}).interpolate(),
513 513 'month': lambda d: _pluralize(u'${num} month', u'${num} months', d, mapping={'num': d}).interpolate(),
514 514 'day': lambda d: _pluralize(u'${num} day', u'${num} days', d, mapping={'num': d}).interpolate(),
515 515 'hour': lambda d: _pluralize(u'${num} hour', u'${num} hours', d, mapping={'num': d}).interpolate(),
516 516 'minute': lambda d: _pluralize(u'${num} minute', u'${num} minutes', d, mapping={'num': d}).interpolate(),
517 517 'second': lambda d: _pluralize(u'${num} second', u'${num} seconds', d, mapping={'num': d}).interpolate(),
518 518 }
519 519
520 520 i = 0
521 521 for part in order:
522 522 value = deltas[part]
523 523 if value != 0:
524 524
525 525 if i < 5:
526 526 sub_part = order[i + 1]
527 527 sub_value = deltas[sub_part]
528 528 else:
529 529 sub_value = 0
530 530
531 531 if sub_value == 0 or show_short_version:
532 532 _val = fmt_funcs[part](value)
533 533 if future:
534 534 if show_suffix:
535 535 return _(u'in ${ago}', mapping={'ago': _val})
536 536 else:
537 537 return _(_val)
538 538
539 539 else:
540 540 if show_suffix:
541 541 return _(u'${ago} ago', mapping={'ago': _val})
542 542 else:
543 543 return _(_val)
544 544
545 545 val = fmt_funcs[part](value)
546 546 val_detail = fmt_funcs[sub_part](sub_value)
547 547 mapping = {'val': val, 'detail': val_detail}
548 548
549 549 if short_format:
550 550 datetime_tmpl = _(u'${val}, ${detail}', mapping=mapping)
551 551 if show_suffix:
552 552 datetime_tmpl = _(u'${val}, ${detail} ago', mapping=mapping)
553 553 if future:
554 554 datetime_tmpl = _(u'in ${val}, ${detail}', mapping=mapping)
555 555 else:
556 556 datetime_tmpl = _(u'${val} and ${detail}', mapping=mapping)
557 557 if show_suffix:
558 558 datetime_tmpl = _(u'${val} and ${detail} ago', mapping=mapping)
559 559 if future:
560 560 datetime_tmpl = _(u'in ${val} and ${detail}', mapping=mapping)
561 561
562 562 return datetime_tmpl
563 563 i += 1
564 564 return _(u'just now')
565 565
566 566
567 567 def cleaned_uri(uri):
568 568 """
569 569 Quotes '[' and ']' from uri if there is only one of them.
570 570 according to RFC3986 we cannot use such chars in uri
571 571 :param uri:
572 572 :return: uri without this chars
573 573 """
574 574 return urllib.quote(uri, safe='@$:/')
575 575
576 576
577 577 def uri_filter(uri):
578 578 """
579 579 Removes user:password from given url string
580 580
581 581 :param uri:
582 582 :rtype: unicode
583 583 :returns: filtered list of strings
584 584 """
585 585 if not uri:
586 586 return ''
587 587
588 588 proto = ''
589 589
590 590 for pat in ('https://', 'http://'):
591 591 if uri.startswith(pat):
592 592 uri = uri[len(pat):]
593 593 proto = pat
594 594 break
595 595
596 596 # remove passwords and username
597 597 uri = uri[uri.find('@') + 1:]
598 598
599 599 # get the port
600 600 cred_pos = uri.find(':')
601 601 if cred_pos == -1:
602 602 host, port = uri, None
603 603 else:
604 604 host, port = uri[:cred_pos], uri[cred_pos + 1:]
605 605
606 606 return filter(None, [proto, host, port])
607 607
608 608
609 609 def credentials_filter(uri):
610 610 """
611 611 Returns a url with removed credentials
612 612
613 613 :param uri:
614 614 """
615 615
616 616 uri = uri_filter(uri)
617 617 # check if we have port
618 618 if len(uri) > 2 and uri[2]:
619 619 uri[2] = ':' + uri[2]
620 620
621 621 return ''.join(uri)
622 622
623 623
624 624 def get_clone_url(request, uri_tmpl, repo_name, repo_id, **override):
625 625 qualifed_home_url = request.route_url('home')
626 626 parsed_url = urlobject.URLObject(qualifed_home_url)
627 627 decoded_path = safe_unicode(urllib.unquote(parsed_url.path.rstrip('/')))
628 628
629 629 args = {
630 630 'scheme': parsed_url.scheme,
631 631 'user': '',
632 632 'sys_user': getpass.getuser(),
633 633 # path if we use proxy-prefix
634 634 'netloc': parsed_url.netloc+decoded_path,
635 635 'hostname': parsed_url.hostname,
636 636 'prefix': decoded_path,
637 637 'repo': repo_name,
638 638 'repoid': str(repo_id)
639 639 }
640 640 args.update(override)
641 641 args['user'] = urllib.quote(safe_str(args['user']))
642 642
643 643 for k, v in args.items():
644 644 uri_tmpl = uri_tmpl.replace('{%s}' % k, v)
645 645
646 646 # remove leading @ sign if it's present. Case of empty user
647 647 url_obj = urlobject.URLObject(uri_tmpl)
648 648 url = url_obj.with_netloc(url_obj.netloc.lstrip('@'))
649 649
650 650 return safe_unicode(url)
651 651
652 652
653 653 def get_commit_safe(repo, commit_id=None, commit_idx=None, pre_load=None):
654 654 """
655 655 Safe version of get_commit if this commit doesn't exists for a
656 656 repository it returns a Dummy one instead
657 657
658 658 :param repo: repository instance
659 659 :param commit_id: commit id as str
660 660 :param pre_load: optional list of commit attributes to load
661 661 """
662 662 # TODO(skreft): remove these circular imports
663 663 from rhodecode.lib.vcs.backends.base import BaseRepository, EmptyCommit
664 664 from rhodecode.lib.vcs.exceptions import RepositoryError
665 665 if not isinstance(repo, BaseRepository):
666 666 raise Exception('You must pass an Repository '
667 667 'object as first argument got %s', type(repo))
668 668
669 669 try:
670 670 commit = repo.get_commit(
671 671 commit_id=commit_id, commit_idx=commit_idx, pre_load=pre_load)
672 672 except (RepositoryError, LookupError):
673 673 commit = EmptyCommit()
674 674 return commit
675 675
676 676
677 677 def datetime_to_time(dt):
678 678 if dt:
679 679 return time.mktime(dt.timetuple())
680 680
681 681
682 682 def time_to_datetime(tm):
683 683 if tm:
684 684 if isinstance(tm, basestring):
685 685 try:
686 686 tm = float(tm)
687 687 except ValueError:
688 688 return
689 689 return datetime.datetime.fromtimestamp(tm)
690 690
691 691
692 692 def time_to_utcdatetime(tm):
693 693 if tm:
694 694 if isinstance(tm, basestring):
695 695 try:
696 696 tm = float(tm)
697 697 except ValueError:
698 698 return
699 699 return datetime.datetime.utcfromtimestamp(tm)
700 700
701 701
702 702 MENTIONS_REGEX = re.compile(
703 703 # ^@ or @ without any special chars in front
704 704 r'(?:^@|[^a-zA-Z0-9\-\_\.]@)'
705 705 # main body starts with letter, then can be . - _
706 706 r'([a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+)',
707 707 re.VERBOSE | re.MULTILINE)
708 708
709 709
710 710 def extract_mentioned_users(s):
711 711 """
712 712 Returns unique usernames from given string s that have @mention
713 713
714 714 :param s: string to get mentions
715 715 """
716 716 usrs = set()
717 717 for username in MENTIONS_REGEX.findall(s):
718 718 usrs.add(username)
719 719
720 720 return sorted(list(usrs), key=lambda k: k.lower())
721 721
722 722
723 723 class AttributeDictBase(dict):
724 724 def __getstate__(self):
725 725 odict = self.__dict__ # get attribute dictionary
726 726 return odict
727 727
728 728 def __setstate__(self, dict):
729 729 self.__dict__ = dict
730 730
731 731 __setattr__ = dict.__setitem__
732 732 __delattr__ = dict.__delitem__
733 733
734 734
735 735 class StrictAttributeDict(AttributeDictBase):
736 736 """
737 737 Strict Version of Attribute dict which raises an Attribute error when
738 738 requested attribute is not set
739 739 """
740 740 def __getattr__(self, attr):
741 741 try:
742 742 return self[attr]
743 743 except KeyError:
744 744 raise AttributeError('%s object has no attribute %s' % (
745 745 self.__class__, attr))
746 746
747 747
748 748 class AttributeDict(AttributeDictBase):
749 749 def __getattr__(self, attr):
750 750 return self.get(attr, None)
751 751
752 752
753 753
754 class OrderedDefaultDict(collections.OrderedDict, collections.defaultdict):
755 def __init__(self, default_factory=None, *args, **kwargs):
756 # in python3 you can omit the args to super
757 super(OrderedDefaultDict, self).__init__(*args, **kwargs)
758 self.default_factory = default_factory
759
760
754 761 def fix_PATH(os_=None):
755 762 """
756 763 Get current active python path, and append it to PATH variable to fix
757 764 issues of subprocess calls and different python versions
758 765 """
759 766 if os_ is None:
760 767 import os
761 768 else:
762 769 os = os_
763 770
764 771 cur_path = os.path.split(sys.executable)[0]
765 772 if not os.environ['PATH'].startswith(cur_path):
766 773 os.environ['PATH'] = '%s:%s' % (cur_path, os.environ['PATH'])
767 774
768 775
769 776 def obfuscate_url_pw(engine):
770 777 _url = engine or ''
771 778 try:
772 779 _url = sqlalchemy.engine.url.make_url(engine)
773 780 if _url.password:
774 781 _url.password = 'XXXXX'
775 782 except Exception:
776 783 pass
777 784 return unicode(_url)
778 785
779 786
780 787 def get_server_url(environ):
781 788 req = webob.Request(environ)
782 789 return req.host_url + req.script_name
783 790
784 791
785 792 def unique_id(hexlen=32):
786 793 alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz"
787 794 return suuid(truncate_to=hexlen, alphabet=alphabet)
788 795
789 796
790 797 def suuid(url=None, truncate_to=22, alphabet=None):
791 798 """
792 799 Generate and return a short URL safe UUID.
793 800
794 801 If the url parameter is provided, set the namespace to the provided
795 802 URL and generate a UUID.
796 803
797 804 :param url to get the uuid for
798 805 :truncate_to: truncate the basic 22 UUID to shorter version
799 806
800 807 The IDs won't be universally unique any longer, but the probability of
801 808 a collision will still be very low.
802 809 """
803 810 # Define our alphabet.
804 811 _ALPHABET = alphabet or "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
805 812
806 813 # If no URL is given, generate a random UUID.
807 814 if url is None:
808 815 unique_id = uuid.uuid4().int
809 816 else:
810 817 unique_id = uuid.uuid3(uuid.NAMESPACE_URL, url).int
811 818
812 819 alphabet_length = len(_ALPHABET)
813 820 output = []
814 821 while unique_id > 0:
815 822 digit = unique_id % alphabet_length
816 823 output.append(_ALPHABET[digit])
817 824 unique_id = int(unique_id / alphabet_length)
818 825 return "".join(output)[:truncate_to]
819 826
820 827
821 828 def get_current_rhodecode_user(request=None):
822 829 """
823 830 Gets rhodecode user from request
824 831 """
825 832 pyramid_request = request or pyramid.threadlocal.get_current_request()
826 833
827 834 # web case
828 835 if pyramid_request and hasattr(pyramid_request, 'user'):
829 836 return pyramid_request.user
830 837
831 838 # api case
832 839 if pyramid_request and hasattr(pyramid_request, 'rpc_user'):
833 840 return pyramid_request.rpc_user
834 841
835 842 return None
836 843
837 844
838 845 def action_logger_generic(action, namespace=''):
839 846 """
840 847 A generic logger for actions useful to the system overview, tries to find
841 848 an acting user for the context of the call otherwise reports unknown user
842 849
843 850 :param action: logging message eg 'comment 5 deleted'
844 851 :param type: string
845 852
846 853 :param namespace: namespace of the logging message eg. 'repo.comments'
847 854 :param type: string
848 855
849 856 """
850 857
851 858 logger_name = 'rhodecode.actions'
852 859
853 860 if namespace:
854 861 logger_name += '.' + namespace
855 862
856 863 log = logging.getLogger(logger_name)
857 864
858 865 # get a user if we can
859 866 user = get_current_rhodecode_user()
860 867
861 868 logfunc = log.info
862 869
863 870 if not user:
864 871 user = '<unknown user>'
865 872 logfunc = log.warning
866 873
867 874 logfunc('Logging action by {}: {}'.format(user, action))
868 875
869 876
870 877 def escape_split(text, sep=',', maxsplit=-1):
871 878 r"""
872 879 Allows for escaping of the separator: e.g. arg='foo\, bar'
873 880
874 881 It should be noted that the way bash et. al. do command line parsing, those
875 882 single quotes are required.
876 883 """
877 884 escaped_sep = r'\%s' % sep
878 885
879 886 if escaped_sep not in text:
880 887 return text.split(sep, maxsplit)
881 888
882 889 before, _mid, after = text.partition(escaped_sep)
883 890 startlist = before.split(sep, maxsplit) # a regular split is fine here
884 891 unfinished = startlist[-1]
885 892 startlist = startlist[:-1]
886 893
887 894 # recurse because there may be more escaped separators
888 895 endlist = escape_split(after, sep, maxsplit)
889 896
890 897 # finish building the escaped value. we use endlist[0] becaue the first
891 898 # part of the string sent in recursion is the rest of the escaped value.
892 899 unfinished += sep + endlist[0]
893 900
894 901 return startlist + [unfinished] + endlist[1:] # put together all the parts
895 902
896 903
897 904 class OptionalAttr(object):
898 905 """
899 906 Special Optional Option that defines other attribute. Example::
900 907
901 908 def test(apiuser, userid=Optional(OAttr('apiuser')):
902 909 user = Optional.extract(userid)
903 910 # calls
904 911
905 912 """
906 913
907 914 def __init__(self, attr_name):
908 915 self.attr_name = attr_name
909 916
910 917 def __repr__(self):
911 918 return '<OptionalAttr:%s>' % self.attr_name
912 919
913 920 def __call__(self):
914 921 return self
915 922
916 923
917 924 # alias
918 925 OAttr = OptionalAttr
919 926
920 927
921 928 class Optional(object):
922 929 """
923 930 Defines an optional parameter::
924 931
925 932 param = param.getval() if isinstance(param, Optional) else param
926 933 param = param() if isinstance(param, Optional) else param
927 934
928 935 is equivalent of::
929 936
930 937 param = Optional.extract(param)
931 938
932 939 """
933 940
934 941 def __init__(self, type_):
935 942 self.type_ = type_
936 943
937 944 def __repr__(self):
938 945 return '<Optional:%s>' % self.type_.__repr__()
939 946
940 947 def __call__(self):
941 948 return self.getval()
942 949
943 950 def getval(self):
944 951 """
945 952 returns value from this Optional instance
946 953 """
947 954 if isinstance(self.type_, OAttr):
948 955 # use params name
949 956 return self.type_.attr_name
950 957 return self.type_
951 958
952 959 @classmethod
953 960 def extract(cls, val):
954 961 """
955 962 Extracts value from Optional() instance
956 963
957 964 :param val:
958 965 :return: original value if it's not Optional instance else
959 966 value of instance
960 967 """
961 968 if isinstance(val, cls):
962 969 return val.getval()
963 970 return val
964 971
965 972
966 973 def glob2re(pat):
967 974 """
968 975 Translate a shell PATTERN to a regular expression.
969 976
970 977 There is no way to quote meta-characters.
971 978 """
972 979
973 980 i, n = 0, len(pat)
974 981 res = ''
975 982 while i < n:
976 983 c = pat[i]
977 984 i = i+1
978 985 if c == '*':
979 986 #res = res + '.*'
980 987 res = res + '[^/]*'
981 988 elif c == '?':
982 989 #res = res + '.'
983 990 res = res + '[^/]'
984 991 elif c == '[':
985 992 j = i
986 993 if j < n and pat[j] == '!':
987 994 j = j+1
988 995 if j < n and pat[j] == ']':
989 996 j = j+1
990 997 while j < n and pat[j] != ']':
991 998 j = j+1
992 999 if j >= n:
993 1000 res = res + '\\['
994 1001 else:
995 1002 stuff = pat[i:j].replace('\\','\\\\')
996 1003 i = j+1
997 1004 if stuff[0] == '!':
998 1005 stuff = '^' + stuff[1:]
999 1006 elif stuff[0] == '^':
1000 1007 stuff = '\\' + stuff
1001 1008 res = '%s[%s]' % (res, stuff)
1002 1009 else:
1003 1010 res = res + re.escape(c)
1004 1011 return res + '\Z(?ms)'
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: 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: 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
General Comments 0
You need to be logged in to leave comments. Login now