##// END OF EJS Templates
artifacts: expose a special auth-token based artifacts download urls....
marcink -
r4003:09f31efc default
parent child Browse files
Show More
@@ -1,49 +1,52 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2016-2019 RhodeCode GmbH
3 # Copyright (C) 2016-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 import os
20 import os
21 from rhodecode.apps.file_store import config_keys
21 from rhodecode.apps.file_store import config_keys
22 from rhodecode.config.middleware import _bool_setting, _string_setting
22 from rhodecode.config.middleware import _bool_setting, _string_setting
23
23
24
24
25 def _sanitize_settings_and_apply_defaults(settings):
25 def _sanitize_settings_and_apply_defaults(settings):
26 """
26 """
27 Set defaults, convert to python types and validate settings.
27 Set defaults, convert to python types and validate settings.
28 """
28 """
29 _bool_setting(settings, config_keys.enabled, 'true')
29 _bool_setting(settings, config_keys.enabled, 'true')
30
30
31 _string_setting(settings, config_keys.backend, 'local')
31 _string_setting(settings, config_keys.backend, 'local')
32
32
33 default_store = os.path.join(os.path.dirname(settings['__file__']), 'upload_store')
33 default_store = os.path.join(os.path.dirname(settings['__file__']), 'upload_store')
34 _string_setting(settings, config_keys.store_path, default_store)
34 _string_setting(settings, config_keys.store_path, default_store)
35
35
36
36
37 def includeme(config):
37 def includeme(config):
38 settings = config.registry.settings
38 settings = config.registry.settings
39 _sanitize_settings_and_apply_defaults(settings)
39 _sanitize_settings_and_apply_defaults(settings)
40
40
41 config.add_route(
41 config.add_route(
42 name='upload_file',
42 name='upload_file',
43 pattern='/_file_store/upload')
43 pattern='/_file_store/upload')
44 config.add_route(
44 config.add_route(
45 name='download_file',
45 name='download_file',
46 pattern='/_file_store/download/{fid}')
46 pattern='/_file_store/download/{fid}')
47 config.add_route(
48 name='download_file_by_token',
49 pattern='/_file_store/token-download/{_auth_token}/{fid}')
47
50
48 # Scan module for configuration decorators.
51 # Scan module for configuration decorators.
49 config.scan('.views', ignore='.tests')
52 config.scan('.views', ignore='.tests')
@@ -1,146 +1,166 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2016-2019 RhodeCode GmbH
3 # Copyright (C) 2016-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 import logging
20 import logging
21
21
22 from pyramid.view import view_config
22 from pyramid.view import view_config
23 from pyramid.response import FileResponse
23 from pyramid.response import FileResponse
24 from pyramid.httpexceptions import HTTPFound, HTTPNotFound
24 from pyramid.httpexceptions import HTTPFound, HTTPNotFound
25
25
26 from rhodecode.apps._base import BaseAppView
26 from rhodecode.apps._base import BaseAppView
27 from rhodecode.apps.file_store import utils
27 from rhodecode.apps.file_store import utils
28 from rhodecode.apps.file_store.exceptions import (
28 from rhodecode.apps.file_store.exceptions import (
29 FileNotAllowedException, FileOverSizeException)
29 FileNotAllowedException, FileOverSizeException)
30
30
31 from rhodecode.lib import helpers as h
31 from rhodecode.lib import helpers as h
32 from rhodecode.lib import audit_logger
32 from rhodecode.lib import audit_logger
33 from rhodecode.lib.auth import (CSRFRequired, NotAnonymous, HasRepoPermissionAny, HasRepoGroupPermissionAny)
33 from rhodecode.lib.auth import (
34 from rhodecode.model.db import Session, FileStore
34 CSRFRequired, NotAnonymous, HasRepoPermissionAny, HasRepoGroupPermissionAny,
35 LoginRequired)
36 from rhodecode.model.db import Session, FileStore, UserApiKeys
35
37
36 log = logging.getLogger(__name__)
38 log = logging.getLogger(__name__)
37
39
38
40
39 class FileStoreView(BaseAppView):
41 class FileStoreView(BaseAppView):
40 upload_key = 'store_file'
42 upload_key = 'store_file'
41
43
42 def load_default_context(self):
44 def load_default_context(self):
43 c = self._get_local_tmpl_context()
45 c = self._get_local_tmpl_context()
44 self.storage = utils.get_file_storage(self.request.registry.settings)
46 self.storage = utils.get_file_storage(self.request.registry.settings)
45 return c
47 return c
46
48
49 @LoginRequired()
47 @NotAnonymous()
50 @NotAnonymous()
48 @CSRFRequired()
51 @CSRFRequired()
49 @view_config(route_name='upload_file', request_method='POST', renderer='json_ext')
52 @view_config(route_name='upload_file', request_method='POST', renderer='json_ext')
50 def upload_file(self):
53 def upload_file(self):
51 self.load_default_context()
54 self.load_default_context()
52 file_obj = self.request.POST.get(self.upload_key)
55 file_obj = self.request.POST.get(self.upload_key)
53
56
54 if file_obj is None:
57 if file_obj is None:
55 return {'store_fid': None,
58 return {'store_fid': None,
56 'access_path': None,
59 'access_path': None,
57 'error': '{} data field is missing'.format(self.upload_key)}
60 'error': '{} data field is missing'.format(self.upload_key)}
58
61
59 if not hasattr(file_obj, 'filename'):
62 if not hasattr(file_obj, 'filename'):
60 return {'store_fid': None,
63 return {'store_fid': None,
61 'access_path': None,
64 'access_path': None,
62 'error': 'filename cannot be read from the data field'}
65 'error': 'filename cannot be read from the data field'}
63
66
64 filename = file_obj.filename
67 filename = file_obj.filename
65
68
66 metadata = {
69 metadata = {
67 'user_uploaded': {'username': self._rhodecode_user.username,
70 'user_uploaded': {'username': self._rhodecode_user.username,
68 'user_id': self._rhodecode_user.user_id,
71 'user_id': self._rhodecode_user.user_id,
69 'ip': self._rhodecode_user.ip_addr}}
72 'ip': self._rhodecode_user.ip_addr}}
70 try:
73 try:
71 store_uid, metadata = self.storage.save_file(
74 store_uid, metadata = self.storage.save_file(
72 file_obj.file, filename, extra_metadata=metadata)
75 file_obj.file, filename, extra_metadata=metadata)
73 except FileNotAllowedException:
76 except FileNotAllowedException:
74 return {'store_fid': None,
77 return {'store_fid': None,
75 'access_path': None,
78 'access_path': None,
76 'error': 'File {} is not allowed.'.format(filename)}
79 'error': 'File {} is not allowed.'.format(filename)}
77
80
78 except FileOverSizeException:
81 except FileOverSizeException:
79 return {'store_fid': None,
82 return {'store_fid': None,
80 'access_path': None,
83 'access_path': None,
81 'error': 'File {} is exceeding allowed limit.'.format(filename)}
84 'error': 'File {} is exceeding allowed limit.'.format(filename)}
82
85
83 try:
86 try:
84 entry = FileStore.create(
87 entry = FileStore.create(
85 file_uid=store_uid, filename=metadata["filename"],
88 file_uid=store_uid, filename=metadata["filename"],
86 file_hash=metadata["sha256"], file_size=metadata["size"],
89 file_hash=metadata["sha256"], file_size=metadata["size"],
87 file_description='upload attachment',
90 file_description='upload attachment',
88 check_acl=False, user_id=self._rhodecode_user.user_id
91 check_acl=False, user_id=self._rhodecode_user.user_id
89 )
92 )
90 Session().add(entry)
93 Session().add(entry)
91 Session().commit()
94 Session().commit()
92 log.debug('Stored upload in DB as %s', entry)
95 log.debug('Stored upload in DB as %s', entry)
93 except Exception:
96 except Exception:
94 log.exception('Failed to store file %s', filename)
97 log.exception('Failed to store file %s', filename)
95 return {'store_fid': None,
98 return {'store_fid': None,
96 'access_path': None,
99 'access_path': None,
97 'error': 'File {} failed to store in DB.'.format(filename)}
100 'error': 'File {} failed to store in DB.'.format(filename)}
98
101
99 return {'store_fid': store_uid,
102 return {'store_fid': store_uid,
100 'access_path': h.route_path('download_file', fid=store_uid)}
103 'access_path': h.route_path('download_file', fid=store_uid)}
101
104
102 @view_config(route_name='download_file')
105 def _serve_file(self, file_uid):
103 def download_file(self):
104 self.load_default_context()
105 file_uid = self.request.matchdict['fid']
106 log.debug('Requesting FID:%s from store %s', file_uid, self.storage)
107
106
108 if not self.storage.exists(file_uid):
107 if not self.storage.exists(file_uid):
109 store_path = self.storage.store_path(file_uid)
108 store_path = self.storage.store_path(file_uid)
110 log.debug('File with FID:%s not found in the store under `%s`',
109 log.debug('File with FID:%s not found in the store under `%s`',
111 file_uid, store_path)
110 file_uid, store_path)
112 raise HTTPNotFound()
111 raise HTTPNotFound()
113
112
114 db_obj = FileStore().query().filter(FileStore.file_uid == file_uid).scalar()
113 db_obj = FileStore().query().filter(FileStore.file_uid == file_uid).scalar()
115 if not db_obj:
114 if not db_obj:
116 raise HTTPNotFound()
115 raise HTTPNotFound()
117
116
118 # private upload for user
117 # private upload for user
119 if db_obj.check_acl and db_obj.scope_user_id:
118 if db_obj.check_acl and db_obj.scope_user_id:
120 user = db_obj.user
119 user = db_obj.user
121 if self._rhodecode_db_user.user_id != user.user_id:
120 if self._rhodecode_db_user.user_id != user.user_id:
122 log.warning('Access to file store object forbidden')
121 log.warning('Access to file store object forbidden')
123 raise HTTPNotFound()
122 raise HTTPNotFound()
124
123
125 # scoped to repository permissions
124 # scoped to repository permissions
126 if db_obj.check_acl and db_obj.scope_repo_id:
125 if db_obj.check_acl and db_obj.scope_repo_id:
127 repo = db_obj.repo
126 repo = db_obj.repo
128 perm_set = ['repository.read', 'repository.write', 'repository.admin']
127 perm_set = ['repository.read', 'repository.write', 'repository.admin']
129 has_perm = HasRepoPermissionAny(*perm_set)(repo.repo_name, 'FileStore check')
128 has_perm = HasRepoPermissionAny(*perm_set)(repo.repo_name, 'FileStore check')
130 if not has_perm:
129 if not has_perm:
131 log.warning('Access to file store object forbidden')
130 log.warning('Access to file store object `%s` forbidden', file_uid)
132 raise HTTPNotFound()
131 raise HTTPNotFound()
133
132
134 # scoped to repository group permissions
133 # scoped to repository group permissions
135 if db_obj.check_acl and db_obj.scope_repo_group_id:
134 if db_obj.check_acl and db_obj.scope_repo_group_id:
136 repo_group = db_obj.repo_group
135 repo_group = db_obj.repo_group
137 perm_set = ['group.read', 'group.write', 'group.admin']
136 perm_set = ['group.read', 'group.write', 'group.admin']
138 has_perm = HasRepoGroupPermissionAny(*perm_set)(repo_group.group_name, 'FileStore check')
137 has_perm = HasRepoGroupPermissionAny(*perm_set)(repo_group.group_name, 'FileStore check')
139 if not has_perm:
138 if not has_perm:
140 log.warning('Access to file store object forbidden')
139 log.warning('Access to file store object `%s` forbidden', file_uid)
141 raise HTTPNotFound()
140 raise HTTPNotFound()
142
141
143 FileStore.bump_access_counter(file_uid)
142 FileStore.bump_access_counter(file_uid)
144
143
145 file_path = self.storage.store_path(file_uid)
144 file_path = self.storage.store_path(file_uid)
146 return FileResponse(file_path)
145 return FileResponse(file_path)
146
147 # ACL is checked by scopes, if no scope the file is accessible to all
148 @view_config(route_name='download_file')
149 def download_file(self):
150 self.load_default_context()
151 file_uid = self.request.matchdict['fid']
152 log.debug('Requesting FID:%s from store %s', file_uid, self.storage)
153 return self._serve_file(file_uid)
154
155 @LoginRequired(auth_token_access=[UserApiKeys.ROLE_ARTIFACT_DOWNLOAD])
156 @view_config(route_name='download_file_by_token')
157 def download_file_by_token(self):
158 """
159 Special view that allows to access the download file by special URL that
160 is stored inside the URL.
161
162 http://example.com/_file_store/token-download/TOKEN/FILE_UID
163 """
164 self.load_default_context()
165 file_uid = self.request.matchdict['fid']
166 return self._serve_file(file_uid)
@@ -1,2352 +1,2369 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2019 RhodeCode GmbH
3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 authentication and permission libraries
22 authentication and permission libraries
23 """
23 """
24
24
25 import os
25 import os
26 import time
26 import time
27 import inspect
27 import inspect
28 import collections
28 import collections
29 import fnmatch
29 import fnmatch
30 import hashlib
30 import hashlib
31 import itertools
31 import itertools
32 import logging
32 import logging
33 import random
33 import random
34 import traceback
34 import traceback
35 from functools import wraps
35 from functools import wraps
36
36
37 import ipaddress
37 import ipaddress
38
38
39 from pyramid.httpexceptions import HTTPForbidden, HTTPFound, HTTPNotFound
39 from pyramid.httpexceptions import HTTPForbidden, HTTPFound, HTTPNotFound
40 from sqlalchemy.orm.exc import ObjectDeletedError
40 from sqlalchemy.orm.exc import ObjectDeletedError
41 from sqlalchemy.orm import joinedload
41 from sqlalchemy.orm import joinedload
42 from zope.cachedescriptors.property import Lazy as LazyProperty
42 from zope.cachedescriptors.property import Lazy as LazyProperty
43
43
44 import rhodecode
44 import rhodecode
45 from rhodecode.model import meta
45 from rhodecode.model import meta
46 from rhodecode.model.meta import Session
46 from rhodecode.model.meta import Session
47 from rhodecode.model.user import UserModel
47 from rhodecode.model.user import UserModel
48 from rhodecode.model.db import (
48 from rhodecode.model.db import (
49 User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember,
49 User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember,
50 UserIpMap, UserApiKeys, RepoGroup, UserGroup)
50 UserIpMap, UserApiKeys, RepoGroup, UserGroup)
51 from rhodecode.lib import rc_cache
51 from rhodecode.lib import rc_cache
52 from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5, safe_int, sha1
52 from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5, safe_int, sha1
53 from rhodecode.lib.utils import (
53 from rhodecode.lib.utils import (
54 get_repo_slug, get_repo_group_slug, get_user_group_slug)
54 get_repo_slug, get_repo_group_slug, get_user_group_slug)
55 from rhodecode.lib.caching_query import FromCache
55 from rhodecode.lib.caching_query import FromCache
56
56
57
57
58 if rhodecode.is_unix:
58 if rhodecode.is_unix:
59 import bcrypt
59 import bcrypt
60
60
61 log = logging.getLogger(__name__)
61 log = logging.getLogger(__name__)
62
62
63 csrf_token_key = "csrf_token"
63 csrf_token_key = "csrf_token"
64
64
65
65
66 class PasswordGenerator(object):
66 class PasswordGenerator(object):
67 """
67 """
68 This is a simple class for generating password from different sets of
68 This is a simple class for generating password from different sets of
69 characters
69 characters
70 usage::
70 usage::
71 passwd_gen = PasswordGenerator()
71 passwd_gen = PasswordGenerator()
72 #print 8-letter password containing only big and small letters
72 #print 8-letter password containing only big and small letters
73 of alphabet
73 of alphabet
74 passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
74 passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
75 """
75 """
76 ALPHABETS_NUM = r'''1234567890'''
76 ALPHABETS_NUM = r'''1234567890'''
77 ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
77 ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
78 ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
78 ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
79 ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
79 ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
80 ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
80 ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
81 + ALPHABETS_NUM + ALPHABETS_SPECIAL
81 + ALPHABETS_NUM + ALPHABETS_SPECIAL
82 ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
82 ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
83 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
83 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
84 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
84 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
85 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
85 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
86
86
87 def __init__(self, passwd=''):
87 def __init__(self, passwd=''):
88 self.passwd = passwd
88 self.passwd = passwd
89
89
90 def gen_password(self, length, type_=None):
90 def gen_password(self, length, type_=None):
91 if type_ is None:
91 if type_ is None:
92 type_ = self.ALPHABETS_FULL
92 type_ = self.ALPHABETS_FULL
93 self.passwd = ''.join([random.choice(type_) for _ in range(length)])
93 self.passwd = ''.join([random.choice(type_) for _ in range(length)])
94 return self.passwd
94 return self.passwd
95
95
96
96
97 class _RhodeCodeCryptoBase(object):
97 class _RhodeCodeCryptoBase(object):
98 ENC_PREF = None
98 ENC_PREF = None
99
99
100 def hash_create(self, str_):
100 def hash_create(self, str_):
101 """
101 """
102 hash the string using
102 hash the string using
103
103
104 :param str_: password to hash
104 :param str_: password to hash
105 """
105 """
106 raise NotImplementedError
106 raise NotImplementedError
107
107
108 def hash_check_with_upgrade(self, password, hashed):
108 def hash_check_with_upgrade(self, password, hashed):
109 """
109 """
110 Returns tuple in which first element is boolean that states that
110 Returns tuple in which first element is boolean that states that
111 given password matches it's hashed version, and the second is new hash
111 given password matches it's hashed version, and the second is new hash
112 of the password, in case this password should be migrated to new
112 of the password, in case this password should be migrated to new
113 cipher.
113 cipher.
114 """
114 """
115 checked_hash = self.hash_check(password, hashed)
115 checked_hash = self.hash_check(password, hashed)
116 return checked_hash, None
116 return checked_hash, None
117
117
118 def hash_check(self, password, hashed):
118 def hash_check(self, password, hashed):
119 """
119 """
120 Checks matching password with it's hashed value.
120 Checks matching password with it's hashed value.
121
121
122 :param password: password
122 :param password: password
123 :param hashed: password in hashed form
123 :param hashed: password in hashed form
124 """
124 """
125 raise NotImplementedError
125 raise NotImplementedError
126
126
127 def _assert_bytes(self, value):
127 def _assert_bytes(self, value):
128 """
128 """
129 Passing in an `unicode` object can lead to hard to detect issues
129 Passing in an `unicode` object can lead to hard to detect issues
130 if passwords contain non-ascii characters. Doing a type check
130 if passwords contain non-ascii characters. Doing a type check
131 during runtime, so that such mistakes are detected early on.
131 during runtime, so that such mistakes are detected early on.
132 """
132 """
133 if not isinstance(value, str):
133 if not isinstance(value, str):
134 raise TypeError(
134 raise TypeError(
135 "Bytestring required as input, got %r." % (value, ))
135 "Bytestring required as input, got %r." % (value, ))
136
136
137
137
138 class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase):
138 class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase):
139 ENC_PREF = ('$2a$10', '$2b$10')
139 ENC_PREF = ('$2a$10', '$2b$10')
140
140
141 def hash_create(self, str_):
141 def hash_create(self, str_):
142 self._assert_bytes(str_)
142 self._assert_bytes(str_)
143 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
143 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
144
144
145 def hash_check_with_upgrade(self, password, hashed):
145 def hash_check_with_upgrade(self, password, hashed):
146 """
146 """
147 Returns tuple in which first element is boolean that states that
147 Returns tuple in which first element is boolean that states that
148 given password matches it's hashed version, and the second is new hash
148 given password matches it's hashed version, and the second is new hash
149 of the password, in case this password should be migrated to new
149 of the password, in case this password should be migrated to new
150 cipher.
150 cipher.
151
151
152 This implements special upgrade logic which works like that:
152 This implements special upgrade logic which works like that:
153 - check if the given password == bcrypted hash, if yes then we
153 - check if the given password == bcrypted hash, if yes then we
154 properly used password and it was already in bcrypt. Proceed
154 properly used password and it was already in bcrypt. Proceed
155 without any changes
155 without any changes
156 - if bcrypt hash check is not working try with sha256. If hash compare
156 - if bcrypt hash check is not working try with sha256. If hash compare
157 is ok, it means we using correct but old hashed password. indicate
157 is ok, it means we using correct but old hashed password. indicate
158 hash change and proceed
158 hash change and proceed
159 """
159 """
160
160
161 new_hash = None
161 new_hash = None
162
162
163 # regular pw check
163 # regular pw check
164 password_match_bcrypt = self.hash_check(password, hashed)
164 password_match_bcrypt = self.hash_check(password, hashed)
165
165
166 # now we want to know if the password was maybe from sha256
166 # now we want to know if the password was maybe from sha256
167 # basically calling _RhodeCodeCryptoSha256().hash_check()
167 # basically calling _RhodeCodeCryptoSha256().hash_check()
168 if not password_match_bcrypt:
168 if not password_match_bcrypt:
169 if _RhodeCodeCryptoSha256().hash_check(password, hashed):
169 if _RhodeCodeCryptoSha256().hash_check(password, hashed):
170 new_hash = self.hash_create(password) # make new bcrypt hash
170 new_hash = self.hash_create(password) # make new bcrypt hash
171 password_match_bcrypt = True
171 password_match_bcrypt = True
172
172
173 return password_match_bcrypt, new_hash
173 return password_match_bcrypt, new_hash
174
174
175 def hash_check(self, password, hashed):
175 def hash_check(self, password, hashed):
176 """
176 """
177 Checks matching password with it's hashed value.
177 Checks matching password with it's hashed value.
178
178
179 :param password: password
179 :param password: password
180 :param hashed: password in hashed form
180 :param hashed: password in hashed form
181 """
181 """
182 self._assert_bytes(password)
182 self._assert_bytes(password)
183 try:
183 try:
184 return bcrypt.hashpw(password, hashed) == hashed
184 return bcrypt.hashpw(password, hashed) == hashed
185 except ValueError as e:
185 except ValueError as e:
186 # we're having a invalid salt here probably, we should not crash
186 # we're having a invalid salt here probably, we should not crash
187 # just return with False as it would be a wrong password.
187 # just return with False as it would be a wrong password.
188 log.debug('Failed to check password hash using bcrypt %s',
188 log.debug('Failed to check password hash using bcrypt %s',
189 safe_str(e))
189 safe_str(e))
190
190
191 return False
191 return False
192
192
193
193
194 class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase):
194 class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase):
195 ENC_PREF = '_'
195 ENC_PREF = '_'
196
196
197 def hash_create(self, str_):
197 def hash_create(self, str_):
198 self._assert_bytes(str_)
198 self._assert_bytes(str_)
199 return hashlib.sha256(str_).hexdigest()
199 return hashlib.sha256(str_).hexdigest()
200
200
201 def hash_check(self, password, hashed):
201 def hash_check(self, password, hashed):
202 """
202 """
203 Checks matching password with it's hashed value.
203 Checks matching password with it's hashed value.
204
204
205 :param password: password
205 :param password: password
206 :param hashed: password in hashed form
206 :param hashed: password in hashed form
207 """
207 """
208 self._assert_bytes(password)
208 self._assert_bytes(password)
209 return hashlib.sha256(password).hexdigest() == hashed
209 return hashlib.sha256(password).hexdigest() == hashed
210
210
211
211
212 class _RhodeCodeCryptoTest(_RhodeCodeCryptoBase):
212 class _RhodeCodeCryptoTest(_RhodeCodeCryptoBase):
213 ENC_PREF = '_'
213 ENC_PREF = '_'
214
214
215 def hash_create(self, str_):
215 def hash_create(self, str_):
216 self._assert_bytes(str_)
216 self._assert_bytes(str_)
217 return sha1(str_)
217 return sha1(str_)
218
218
219 def hash_check(self, password, hashed):
219 def hash_check(self, password, hashed):
220 """
220 """
221 Checks matching password with it's hashed value.
221 Checks matching password with it's hashed value.
222
222
223 :param password: password
223 :param password: password
224 :param hashed: password in hashed form
224 :param hashed: password in hashed form
225 """
225 """
226 self._assert_bytes(password)
226 self._assert_bytes(password)
227 return sha1(password) == hashed
227 return sha1(password) == hashed
228
228
229
229
230 def crypto_backend():
230 def crypto_backend():
231 """
231 """
232 Return the matching crypto backend.
232 Return the matching crypto backend.
233
233
234 Selection is based on if we run tests or not, we pick sha1-test backend to run
234 Selection is based on if we run tests or not, we pick sha1-test backend to run
235 tests faster since BCRYPT is expensive to calculate
235 tests faster since BCRYPT is expensive to calculate
236 """
236 """
237 if rhodecode.is_test:
237 if rhodecode.is_test:
238 RhodeCodeCrypto = _RhodeCodeCryptoTest()
238 RhodeCodeCrypto = _RhodeCodeCryptoTest()
239 else:
239 else:
240 RhodeCodeCrypto = _RhodeCodeCryptoBCrypt()
240 RhodeCodeCrypto = _RhodeCodeCryptoBCrypt()
241
241
242 return RhodeCodeCrypto
242 return RhodeCodeCrypto
243
243
244
244
245 def get_crypt_password(password):
245 def get_crypt_password(password):
246 """
246 """
247 Create the hash of `password` with the active crypto backend.
247 Create the hash of `password` with the active crypto backend.
248
248
249 :param password: The cleartext password.
249 :param password: The cleartext password.
250 :type password: unicode
250 :type password: unicode
251 """
251 """
252 password = safe_str(password)
252 password = safe_str(password)
253 return crypto_backend().hash_create(password)
253 return crypto_backend().hash_create(password)
254
254
255
255
256 def check_password(password, hashed):
256 def check_password(password, hashed):
257 """
257 """
258 Check if the value in `password` matches the hash in `hashed`.
258 Check if the value in `password` matches the hash in `hashed`.
259
259
260 :param password: The cleartext password.
260 :param password: The cleartext password.
261 :type password: unicode
261 :type password: unicode
262
262
263 :param hashed: The expected hashed version of the password.
263 :param hashed: The expected hashed version of the password.
264 :type hashed: The hash has to be passed in in text representation.
264 :type hashed: The hash has to be passed in in text representation.
265 """
265 """
266 password = safe_str(password)
266 password = safe_str(password)
267 return crypto_backend().hash_check(password, hashed)
267 return crypto_backend().hash_check(password, hashed)
268
268
269
269
270 def generate_auth_token(data, salt=None):
270 def generate_auth_token(data, salt=None):
271 """
271 """
272 Generates API KEY from given string
272 Generates API KEY from given string
273 """
273 """
274
274
275 if salt is None:
275 if salt is None:
276 salt = os.urandom(16)
276 salt = os.urandom(16)
277 return hashlib.sha1(safe_str(data) + salt).hexdigest()
277 return hashlib.sha1(safe_str(data) + salt).hexdigest()
278
278
279
279
280 def get_came_from(request):
280 def get_came_from(request):
281 """
281 """
282 get query_string+path from request sanitized after removing auth_token
282 get query_string+path from request sanitized after removing auth_token
283 """
283 """
284 _req = request
284 _req = request
285
285
286 path = _req.path
286 path = _req.path
287 if 'auth_token' in _req.GET:
287 if 'auth_token' in _req.GET:
288 # sanitize the request and remove auth_token for redirection
288 # sanitize the request and remove auth_token for redirection
289 _req.GET.pop('auth_token')
289 _req.GET.pop('auth_token')
290 qs = _req.query_string
290 qs = _req.query_string
291 if qs:
291 if qs:
292 path += '?' + qs
292 path += '?' + qs
293
293
294 return path
294 return path
295
295
296
296
297 class CookieStoreWrapper(object):
297 class CookieStoreWrapper(object):
298
298
299 def __init__(self, cookie_store):
299 def __init__(self, cookie_store):
300 self.cookie_store = cookie_store
300 self.cookie_store = cookie_store
301
301
302 def __repr__(self):
302 def __repr__(self):
303 return 'CookieStore<%s>' % (self.cookie_store)
303 return 'CookieStore<%s>' % (self.cookie_store)
304
304
305 def get(self, key, other=None):
305 def get(self, key, other=None):
306 if isinstance(self.cookie_store, dict):
306 if isinstance(self.cookie_store, dict):
307 return self.cookie_store.get(key, other)
307 return self.cookie_store.get(key, other)
308 elif isinstance(self.cookie_store, AuthUser):
308 elif isinstance(self.cookie_store, AuthUser):
309 return self.cookie_store.__dict__.get(key, other)
309 return self.cookie_store.__dict__.get(key, other)
310
310
311
311
312 def _cached_perms_data(user_id, scope, user_is_admin,
312 def _cached_perms_data(user_id, scope, user_is_admin,
313 user_inherit_default_permissions, explicit, algo,
313 user_inherit_default_permissions, explicit, algo,
314 calculate_super_admin):
314 calculate_super_admin):
315
315
316 permissions = PermissionCalculator(
316 permissions = PermissionCalculator(
317 user_id, scope, user_is_admin, user_inherit_default_permissions,
317 user_id, scope, user_is_admin, user_inherit_default_permissions,
318 explicit, algo, calculate_super_admin)
318 explicit, algo, calculate_super_admin)
319 return permissions.calculate()
319 return permissions.calculate()
320
320
321
321
322 class PermOrigin(object):
322 class PermOrigin(object):
323 SUPER_ADMIN = 'superadmin'
323 SUPER_ADMIN = 'superadmin'
324 ARCHIVED = 'archived'
324 ARCHIVED = 'archived'
325
325
326 REPO_USER = 'user:%s'
326 REPO_USER = 'user:%s'
327 REPO_USERGROUP = 'usergroup:%s'
327 REPO_USERGROUP = 'usergroup:%s'
328 REPO_OWNER = 'repo.owner'
328 REPO_OWNER = 'repo.owner'
329 REPO_DEFAULT = 'repo.default'
329 REPO_DEFAULT = 'repo.default'
330 REPO_DEFAULT_NO_INHERIT = 'repo.default.no.inherit'
330 REPO_DEFAULT_NO_INHERIT = 'repo.default.no.inherit'
331 REPO_PRIVATE = 'repo.private'
331 REPO_PRIVATE = 'repo.private'
332
332
333 REPOGROUP_USER = 'user:%s'
333 REPOGROUP_USER = 'user:%s'
334 REPOGROUP_USERGROUP = 'usergroup:%s'
334 REPOGROUP_USERGROUP = 'usergroup:%s'
335 REPOGROUP_OWNER = 'group.owner'
335 REPOGROUP_OWNER = 'group.owner'
336 REPOGROUP_DEFAULT = 'group.default'
336 REPOGROUP_DEFAULT = 'group.default'
337 REPOGROUP_DEFAULT_NO_INHERIT = 'group.default.no.inherit'
337 REPOGROUP_DEFAULT_NO_INHERIT = 'group.default.no.inherit'
338
338
339 USERGROUP_USER = 'user:%s'
339 USERGROUP_USER = 'user:%s'
340 USERGROUP_USERGROUP = 'usergroup:%s'
340 USERGROUP_USERGROUP = 'usergroup:%s'
341 USERGROUP_OWNER = 'usergroup.owner'
341 USERGROUP_OWNER = 'usergroup.owner'
342 USERGROUP_DEFAULT = 'usergroup.default'
342 USERGROUP_DEFAULT = 'usergroup.default'
343 USERGROUP_DEFAULT_NO_INHERIT = 'usergroup.default.no.inherit'
343 USERGROUP_DEFAULT_NO_INHERIT = 'usergroup.default.no.inherit'
344
344
345
345
346 class PermOriginDict(dict):
346 class PermOriginDict(dict):
347 """
347 """
348 A special dict used for tracking permissions along with their origins.
348 A special dict used for tracking permissions along with their origins.
349
349
350 `__setitem__` has been overridden to expect a tuple(perm, origin)
350 `__setitem__` has been overridden to expect a tuple(perm, origin)
351 `__getitem__` will return only the perm
351 `__getitem__` will return only the perm
352 `.perm_origin_stack` will return the stack of (perm, origin) set per key
352 `.perm_origin_stack` will return the stack of (perm, origin) set per key
353
353
354 >>> perms = PermOriginDict()
354 >>> perms = PermOriginDict()
355 >>> perms['resource'] = 'read', 'default'
355 >>> perms['resource'] = 'read', 'default'
356 >>> perms['resource']
356 >>> perms['resource']
357 'read'
357 'read'
358 >>> perms['resource'] = 'write', 'admin'
358 >>> perms['resource'] = 'write', 'admin'
359 >>> perms['resource']
359 >>> perms['resource']
360 'write'
360 'write'
361 >>> perms.perm_origin_stack
361 >>> perms.perm_origin_stack
362 {'resource': [('read', 'default'), ('write', 'admin')]}
362 {'resource': [('read', 'default'), ('write', 'admin')]}
363 """
363 """
364
364
365 def __init__(self, *args, **kw):
365 def __init__(self, *args, **kw):
366 dict.__init__(self, *args, **kw)
366 dict.__init__(self, *args, **kw)
367 self.perm_origin_stack = collections.OrderedDict()
367 self.perm_origin_stack = collections.OrderedDict()
368
368
369 def __setitem__(self, key, (perm, origin)):
369 def __setitem__(self, key, (perm, origin)):
370 self.perm_origin_stack.setdefault(key, []).append(
370 self.perm_origin_stack.setdefault(key, []).append(
371 (perm, origin))
371 (perm, origin))
372 dict.__setitem__(self, key, perm)
372 dict.__setitem__(self, key, perm)
373
373
374
374
375 class BranchPermOriginDict(PermOriginDict):
375 class BranchPermOriginDict(PermOriginDict):
376 """
376 """
377 Dedicated branch permissions dict, with tracking of patterns and origins.
377 Dedicated branch permissions dict, with tracking of patterns and origins.
378
378
379 >>> perms = BranchPermOriginDict()
379 >>> perms = BranchPermOriginDict()
380 >>> perms['resource'] = '*pattern', 'read', 'default'
380 >>> perms['resource'] = '*pattern', 'read', 'default'
381 >>> perms['resource']
381 >>> perms['resource']
382 {'*pattern': 'read'}
382 {'*pattern': 'read'}
383 >>> perms['resource'] = '*pattern', 'write', 'admin'
383 >>> perms['resource'] = '*pattern', 'write', 'admin'
384 >>> perms['resource']
384 >>> perms['resource']
385 {'*pattern': 'write'}
385 {'*pattern': 'write'}
386 >>> perms.perm_origin_stack
386 >>> perms.perm_origin_stack
387 {'resource': {'*pattern': [('read', 'default'), ('write', 'admin')]}}
387 {'resource': {'*pattern': [('read', 'default'), ('write', 'admin')]}}
388 """
388 """
389 def __setitem__(self, key, (pattern, perm, origin)):
389 def __setitem__(self, key, (pattern, perm, origin)):
390
390
391 self.perm_origin_stack.setdefault(key, {}) \
391 self.perm_origin_stack.setdefault(key, {}) \
392 .setdefault(pattern, []).append((perm, origin))
392 .setdefault(pattern, []).append((perm, origin))
393
393
394 if key in self:
394 if key in self:
395 self[key].__setitem__(pattern, perm)
395 self[key].__setitem__(pattern, perm)
396 else:
396 else:
397 patterns = collections.OrderedDict()
397 patterns = collections.OrderedDict()
398 patterns[pattern] = perm
398 patterns[pattern] = perm
399 dict.__setitem__(self, key, patterns)
399 dict.__setitem__(self, key, patterns)
400
400
401
401
402 class PermissionCalculator(object):
402 class PermissionCalculator(object):
403
403
404 def __init__(
404 def __init__(
405 self, user_id, scope, user_is_admin,
405 self, user_id, scope, user_is_admin,
406 user_inherit_default_permissions, explicit, algo,
406 user_inherit_default_permissions, explicit, algo,
407 calculate_super_admin_as_user=False):
407 calculate_super_admin_as_user=False):
408
408
409 self.user_id = user_id
409 self.user_id = user_id
410 self.user_is_admin = user_is_admin
410 self.user_is_admin = user_is_admin
411 self.inherit_default_permissions = user_inherit_default_permissions
411 self.inherit_default_permissions = user_inherit_default_permissions
412 self.explicit = explicit
412 self.explicit = explicit
413 self.algo = algo
413 self.algo = algo
414 self.calculate_super_admin_as_user = calculate_super_admin_as_user
414 self.calculate_super_admin_as_user = calculate_super_admin_as_user
415
415
416 scope = scope or {}
416 scope = scope or {}
417 self.scope_repo_id = scope.get('repo_id')
417 self.scope_repo_id = scope.get('repo_id')
418 self.scope_repo_group_id = scope.get('repo_group_id')
418 self.scope_repo_group_id = scope.get('repo_group_id')
419 self.scope_user_group_id = scope.get('user_group_id')
419 self.scope_user_group_id = scope.get('user_group_id')
420
420
421 self.default_user_id = User.get_default_user(cache=True).user_id
421 self.default_user_id = User.get_default_user(cache=True).user_id
422
422
423 self.permissions_repositories = PermOriginDict()
423 self.permissions_repositories = PermOriginDict()
424 self.permissions_repository_groups = PermOriginDict()
424 self.permissions_repository_groups = PermOriginDict()
425 self.permissions_user_groups = PermOriginDict()
425 self.permissions_user_groups = PermOriginDict()
426 self.permissions_repository_branches = BranchPermOriginDict()
426 self.permissions_repository_branches = BranchPermOriginDict()
427 self.permissions_global = set()
427 self.permissions_global = set()
428
428
429 self.default_repo_perms = Permission.get_default_repo_perms(
429 self.default_repo_perms = Permission.get_default_repo_perms(
430 self.default_user_id, self.scope_repo_id)
430 self.default_user_id, self.scope_repo_id)
431 self.default_repo_groups_perms = Permission.get_default_group_perms(
431 self.default_repo_groups_perms = Permission.get_default_group_perms(
432 self.default_user_id, self.scope_repo_group_id)
432 self.default_user_id, self.scope_repo_group_id)
433 self.default_user_group_perms = \
433 self.default_user_group_perms = \
434 Permission.get_default_user_group_perms(
434 Permission.get_default_user_group_perms(
435 self.default_user_id, self.scope_user_group_id)
435 self.default_user_id, self.scope_user_group_id)
436
436
437 # default branch perms
437 # default branch perms
438 self.default_branch_repo_perms = \
438 self.default_branch_repo_perms = \
439 Permission.get_default_repo_branch_perms(
439 Permission.get_default_repo_branch_perms(
440 self.default_user_id, self.scope_repo_id)
440 self.default_user_id, self.scope_repo_id)
441
441
442 def calculate(self):
442 def calculate(self):
443 if self.user_is_admin and not self.calculate_super_admin_as_user:
443 if self.user_is_admin and not self.calculate_super_admin_as_user:
444 return self._calculate_admin_permissions()
444 return self._calculate_admin_permissions()
445
445
446 self._calculate_global_default_permissions()
446 self._calculate_global_default_permissions()
447 self._calculate_global_permissions()
447 self._calculate_global_permissions()
448 self._calculate_default_permissions()
448 self._calculate_default_permissions()
449 self._calculate_repository_permissions()
449 self._calculate_repository_permissions()
450 self._calculate_repository_branch_permissions()
450 self._calculate_repository_branch_permissions()
451 self._calculate_repository_group_permissions()
451 self._calculate_repository_group_permissions()
452 self._calculate_user_group_permissions()
452 self._calculate_user_group_permissions()
453 return self._permission_structure()
453 return self._permission_structure()
454
454
455 def _calculate_admin_permissions(self):
455 def _calculate_admin_permissions(self):
456 """
456 """
457 admin user have all default rights for repositories
457 admin user have all default rights for repositories
458 and groups set to admin
458 and groups set to admin
459 """
459 """
460 self.permissions_global.add('hg.admin')
460 self.permissions_global.add('hg.admin')
461 self.permissions_global.add('hg.create.write_on_repogroup.true')
461 self.permissions_global.add('hg.create.write_on_repogroup.true')
462
462
463 # repositories
463 # repositories
464 for perm in self.default_repo_perms:
464 for perm in self.default_repo_perms:
465 r_k = perm.UserRepoToPerm.repository.repo_name
465 r_k = perm.UserRepoToPerm.repository.repo_name
466 archived = perm.UserRepoToPerm.repository.archived
466 archived = perm.UserRepoToPerm.repository.archived
467 p = 'repository.admin'
467 p = 'repository.admin'
468 self.permissions_repositories[r_k] = p, PermOrigin.SUPER_ADMIN
468 self.permissions_repositories[r_k] = p, PermOrigin.SUPER_ADMIN
469 # special case for archived repositories, which we block still even for
469 # special case for archived repositories, which we block still even for
470 # super admins
470 # super admins
471 if archived:
471 if archived:
472 p = 'repository.read'
472 p = 'repository.read'
473 self.permissions_repositories[r_k] = p, PermOrigin.ARCHIVED
473 self.permissions_repositories[r_k] = p, PermOrigin.ARCHIVED
474
474
475 # repository groups
475 # repository groups
476 for perm in self.default_repo_groups_perms:
476 for perm in self.default_repo_groups_perms:
477 rg_k = perm.UserRepoGroupToPerm.group.group_name
477 rg_k = perm.UserRepoGroupToPerm.group.group_name
478 p = 'group.admin'
478 p = 'group.admin'
479 self.permissions_repository_groups[rg_k] = p, PermOrigin.SUPER_ADMIN
479 self.permissions_repository_groups[rg_k] = p, PermOrigin.SUPER_ADMIN
480
480
481 # user groups
481 # user groups
482 for perm in self.default_user_group_perms:
482 for perm in self.default_user_group_perms:
483 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
483 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
484 p = 'usergroup.admin'
484 p = 'usergroup.admin'
485 self.permissions_user_groups[u_k] = p, PermOrigin.SUPER_ADMIN
485 self.permissions_user_groups[u_k] = p, PermOrigin.SUPER_ADMIN
486
486
487 # branch permissions
487 # branch permissions
488 # since super-admin also can have custom rule permissions
488 # since super-admin also can have custom rule permissions
489 # we *always* need to calculate those inherited from default, and also explicit
489 # we *always* need to calculate those inherited from default, and also explicit
490 self._calculate_default_permissions_repository_branches(
490 self._calculate_default_permissions_repository_branches(
491 user_inherit_object_permissions=False)
491 user_inherit_object_permissions=False)
492 self._calculate_repository_branch_permissions()
492 self._calculate_repository_branch_permissions()
493
493
494 return self._permission_structure()
494 return self._permission_structure()
495
495
496 def _calculate_global_default_permissions(self):
496 def _calculate_global_default_permissions(self):
497 """
497 """
498 global permissions taken from the default user
498 global permissions taken from the default user
499 """
499 """
500 default_global_perms = UserToPerm.query()\
500 default_global_perms = UserToPerm.query()\
501 .filter(UserToPerm.user_id == self.default_user_id)\
501 .filter(UserToPerm.user_id == self.default_user_id)\
502 .options(joinedload(UserToPerm.permission))
502 .options(joinedload(UserToPerm.permission))
503
503
504 for perm in default_global_perms:
504 for perm in default_global_perms:
505 self.permissions_global.add(perm.permission.permission_name)
505 self.permissions_global.add(perm.permission.permission_name)
506
506
507 if self.user_is_admin:
507 if self.user_is_admin:
508 self.permissions_global.add('hg.admin')
508 self.permissions_global.add('hg.admin')
509 self.permissions_global.add('hg.create.write_on_repogroup.true')
509 self.permissions_global.add('hg.create.write_on_repogroup.true')
510
510
511 def _calculate_global_permissions(self):
511 def _calculate_global_permissions(self):
512 """
512 """
513 Set global system permissions with user permissions or permissions
513 Set global system permissions with user permissions or permissions
514 taken from the user groups of the current user.
514 taken from the user groups of the current user.
515
515
516 The permissions include repo creating, repo group creating, forking
516 The permissions include repo creating, repo group creating, forking
517 etc.
517 etc.
518 """
518 """
519
519
520 # now we read the defined permissions and overwrite what we have set
520 # now we read the defined permissions and overwrite what we have set
521 # before those can be configured from groups or users explicitly.
521 # before those can be configured from groups or users explicitly.
522
522
523 # In case we want to extend this list we should make sure
523 # In case we want to extend this list we should make sure
524 # this is in sync with User.DEFAULT_USER_PERMISSIONS definitions
524 # this is in sync with User.DEFAULT_USER_PERMISSIONS definitions
525 _configurable = frozenset([
525 _configurable = frozenset([
526 'hg.fork.none', 'hg.fork.repository',
526 'hg.fork.none', 'hg.fork.repository',
527 'hg.create.none', 'hg.create.repository',
527 'hg.create.none', 'hg.create.repository',
528 'hg.usergroup.create.false', 'hg.usergroup.create.true',
528 'hg.usergroup.create.false', 'hg.usergroup.create.true',
529 'hg.repogroup.create.false', 'hg.repogroup.create.true',
529 'hg.repogroup.create.false', 'hg.repogroup.create.true',
530 'hg.create.write_on_repogroup.false', 'hg.create.write_on_repogroup.true',
530 'hg.create.write_on_repogroup.false', 'hg.create.write_on_repogroup.true',
531 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true'
531 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true'
532 ])
532 ])
533
533
534 # USER GROUPS comes first user group global permissions
534 # USER GROUPS comes first user group global permissions
535 user_perms_from_users_groups = Session().query(UserGroupToPerm)\
535 user_perms_from_users_groups = Session().query(UserGroupToPerm)\
536 .options(joinedload(UserGroupToPerm.permission))\
536 .options(joinedload(UserGroupToPerm.permission))\
537 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
537 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
538 UserGroupMember.users_group_id))\
538 UserGroupMember.users_group_id))\
539 .filter(UserGroupMember.user_id == self.user_id)\
539 .filter(UserGroupMember.user_id == self.user_id)\
540 .order_by(UserGroupToPerm.users_group_id)\
540 .order_by(UserGroupToPerm.users_group_id)\
541 .all()
541 .all()
542
542
543 # need to group here by groups since user can be in more than
543 # need to group here by groups since user can be in more than
544 # one group, so we get all groups
544 # one group, so we get all groups
545 _explicit_grouped_perms = [
545 _explicit_grouped_perms = [
546 [x, list(y)] for x, y in
546 [x, list(y)] for x, y in
547 itertools.groupby(user_perms_from_users_groups,
547 itertools.groupby(user_perms_from_users_groups,
548 lambda _x: _x.users_group)]
548 lambda _x: _x.users_group)]
549
549
550 for gr, perms in _explicit_grouped_perms:
550 for gr, perms in _explicit_grouped_perms:
551 # since user can be in multiple groups iterate over them and
551 # since user can be in multiple groups iterate over them and
552 # select the lowest permissions first (more explicit)
552 # select the lowest permissions first (more explicit)
553 # TODO(marcink): do this^^
553 # TODO(marcink): do this^^
554
554
555 # group doesn't inherit default permissions so we actually set them
555 # group doesn't inherit default permissions so we actually set them
556 if not gr.inherit_default_permissions:
556 if not gr.inherit_default_permissions:
557 # NEED TO IGNORE all previously set configurable permissions
557 # NEED TO IGNORE all previously set configurable permissions
558 # and replace them with explicitly set from this user
558 # and replace them with explicitly set from this user
559 # group permissions
559 # group permissions
560 self.permissions_global = self.permissions_global.difference(
560 self.permissions_global = self.permissions_global.difference(
561 _configurable)
561 _configurable)
562 for perm in perms:
562 for perm in perms:
563 self.permissions_global.add(perm.permission.permission_name)
563 self.permissions_global.add(perm.permission.permission_name)
564
564
565 # user explicit global permissions
565 # user explicit global permissions
566 user_perms = Session().query(UserToPerm)\
566 user_perms = Session().query(UserToPerm)\
567 .options(joinedload(UserToPerm.permission))\
567 .options(joinedload(UserToPerm.permission))\
568 .filter(UserToPerm.user_id == self.user_id).all()
568 .filter(UserToPerm.user_id == self.user_id).all()
569
569
570 if not self.inherit_default_permissions:
570 if not self.inherit_default_permissions:
571 # NEED TO IGNORE all configurable permissions and
571 # NEED TO IGNORE all configurable permissions and
572 # replace them with explicitly set from this user permissions
572 # replace them with explicitly set from this user permissions
573 self.permissions_global = self.permissions_global.difference(
573 self.permissions_global = self.permissions_global.difference(
574 _configurable)
574 _configurable)
575 for perm in user_perms:
575 for perm in user_perms:
576 self.permissions_global.add(perm.permission.permission_name)
576 self.permissions_global.add(perm.permission.permission_name)
577
577
578 def _calculate_default_permissions_repositories(self, user_inherit_object_permissions):
578 def _calculate_default_permissions_repositories(self, user_inherit_object_permissions):
579 for perm in self.default_repo_perms:
579 for perm in self.default_repo_perms:
580 r_k = perm.UserRepoToPerm.repository.repo_name
580 r_k = perm.UserRepoToPerm.repository.repo_name
581 archived = perm.UserRepoToPerm.repository.archived
581 archived = perm.UserRepoToPerm.repository.archived
582 p = perm.Permission.permission_name
582 p = perm.Permission.permission_name
583 o = PermOrigin.REPO_DEFAULT
583 o = PermOrigin.REPO_DEFAULT
584 self.permissions_repositories[r_k] = p, o
584 self.permissions_repositories[r_k] = p, o
585
585
586 # if we decide this user isn't inheriting permissions from
586 # if we decide this user isn't inheriting permissions from
587 # default user we set him to .none so only explicit
587 # default user we set him to .none so only explicit
588 # permissions work
588 # permissions work
589 if not user_inherit_object_permissions:
589 if not user_inherit_object_permissions:
590 p = 'repository.none'
590 p = 'repository.none'
591 o = PermOrigin.REPO_DEFAULT_NO_INHERIT
591 o = PermOrigin.REPO_DEFAULT_NO_INHERIT
592 self.permissions_repositories[r_k] = p, o
592 self.permissions_repositories[r_k] = p, o
593
593
594 if perm.Repository.private and not (
594 if perm.Repository.private and not (
595 perm.Repository.user_id == self.user_id):
595 perm.Repository.user_id == self.user_id):
596 # disable defaults for private repos,
596 # disable defaults for private repos,
597 p = 'repository.none'
597 p = 'repository.none'
598 o = PermOrigin.REPO_PRIVATE
598 o = PermOrigin.REPO_PRIVATE
599 self.permissions_repositories[r_k] = p, o
599 self.permissions_repositories[r_k] = p, o
600
600
601 elif perm.Repository.user_id == self.user_id:
601 elif perm.Repository.user_id == self.user_id:
602 # set admin if owner
602 # set admin if owner
603 p = 'repository.admin'
603 p = 'repository.admin'
604 o = PermOrigin.REPO_OWNER
604 o = PermOrigin.REPO_OWNER
605 self.permissions_repositories[r_k] = p, o
605 self.permissions_repositories[r_k] = p, o
606
606
607 if self.user_is_admin:
607 if self.user_is_admin:
608 p = 'repository.admin'
608 p = 'repository.admin'
609 o = PermOrigin.SUPER_ADMIN
609 o = PermOrigin.SUPER_ADMIN
610 self.permissions_repositories[r_k] = p, o
610 self.permissions_repositories[r_k] = p, o
611
611
612 # finally in case of archived repositories, we downgrade higher
612 # finally in case of archived repositories, we downgrade higher
613 # permissions to read
613 # permissions to read
614 if archived:
614 if archived:
615 current_perm = self.permissions_repositories[r_k]
615 current_perm = self.permissions_repositories[r_k]
616 if current_perm in ['repository.write', 'repository.admin']:
616 if current_perm in ['repository.write', 'repository.admin']:
617 p = 'repository.read'
617 p = 'repository.read'
618 o = PermOrigin.ARCHIVED
618 o = PermOrigin.ARCHIVED
619 self.permissions_repositories[r_k] = p, o
619 self.permissions_repositories[r_k] = p, o
620
620
621 def _calculate_default_permissions_repository_branches(self, user_inherit_object_permissions):
621 def _calculate_default_permissions_repository_branches(self, user_inherit_object_permissions):
622 for perm in self.default_branch_repo_perms:
622 for perm in self.default_branch_repo_perms:
623
623
624 r_k = perm.UserRepoToPerm.repository.repo_name
624 r_k = perm.UserRepoToPerm.repository.repo_name
625 p = perm.Permission.permission_name
625 p = perm.Permission.permission_name
626 pattern = perm.UserToRepoBranchPermission.branch_pattern
626 pattern = perm.UserToRepoBranchPermission.branch_pattern
627 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
627 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
628
628
629 if not self.explicit:
629 if not self.explicit:
630 cur_perm = self.permissions_repository_branches.get(r_k)
630 cur_perm = self.permissions_repository_branches.get(r_k)
631 if cur_perm:
631 if cur_perm:
632 cur_perm = cur_perm[pattern]
632 cur_perm = cur_perm[pattern]
633 cur_perm = cur_perm or 'branch.none'
633 cur_perm = cur_perm or 'branch.none'
634
634
635 p = self._choose_permission(p, cur_perm)
635 p = self._choose_permission(p, cur_perm)
636
636
637 # NOTE(marcink): register all pattern/perm instances in this
637 # NOTE(marcink): register all pattern/perm instances in this
638 # special dict that aggregates entries
638 # special dict that aggregates entries
639 self.permissions_repository_branches[r_k] = pattern, p, o
639 self.permissions_repository_branches[r_k] = pattern, p, o
640
640
641 def _calculate_default_permissions_repository_groups(self, user_inherit_object_permissions):
641 def _calculate_default_permissions_repository_groups(self, user_inherit_object_permissions):
642 for perm in self.default_repo_groups_perms:
642 for perm in self.default_repo_groups_perms:
643 rg_k = perm.UserRepoGroupToPerm.group.group_name
643 rg_k = perm.UserRepoGroupToPerm.group.group_name
644 p = perm.Permission.permission_name
644 p = perm.Permission.permission_name
645 o = PermOrigin.REPOGROUP_DEFAULT
645 o = PermOrigin.REPOGROUP_DEFAULT
646 self.permissions_repository_groups[rg_k] = p, o
646 self.permissions_repository_groups[rg_k] = p, o
647
647
648 # if we decide this user isn't inheriting permissions from default
648 # if we decide this user isn't inheriting permissions from default
649 # user we set him to .none so only explicit permissions work
649 # user we set him to .none so only explicit permissions work
650 if not user_inherit_object_permissions:
650 if not user_inherit_object_permissions:
651 p = 'group.none'
651 p = 'group.none'
652 o = PermOrigin.REPOGROUP_DEFAULT_NO_INHERIT
652 o = PermOrigin.REPOGROUP_DEFAULT_NO_INHERIT
653 self.permissions_repository_groups[rg_k] = p, o
653 self.permissions_repository_groups[rg_k] = p, o
654
654
655 if perm.RepoGroup.user_id == self.user_id:
655 if perm.RepoGroup.user_id == self.user_id:
656 # set admin if owner
656 # set admin if owner
657 p = 'group.admin'
657 p = 'group.admin'
658 o = PermOrigin.REPOGROUP_OWNER
658 o = PermOrigin.REPOGROUP_OWNER
659 self.permissions_repository_groups[rg_k] = p, o
659 self.permissions_repository_groups[rg_k] = p, o
660
660
661 if self.user_is_admin:
661 if self.user_is_admin:
662 p = 'group.admin'
662 p = 'group.admin'
663 o = PermOrigin.SUPER_ADMIN
663 o = PermOrigin.SUPER_ADMIN
664 self.permissions_repository_groups[rg_k] = p, o
664 self.permissions_repository_groups[rg_k] = p, o
665
665
666 def _calculate_default_permissions_user_groups(self, user_inherit_object_permissions):
666 def _calculate_default_permissions_user_groups(self, user_inherit_object_permissions):
667 for perm in self.default_user_group_perms:
667 for perm in self.default_user_group_perms:
668 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
668 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
669 p = perm.Permission.permission_name
669 p = perm.Permission.permission_name
670 o = PermOrigin.USERGROUP_DEFAULT
670 o = PermOrigin.USERGROUP_DEFAULT
671 self.permissions_user_groups[u_k] = p, o
671 self.permissions_user_groups[u_k] = p, o
672
672
673 # if we decide this user isn't inheriting permissions from default
673 # if we decide this user isn't inheriting permissions from default
674 # user we set him to .none so only explicit permissions work
674 # user we set him to .none so only explicit permissions work
675 if not user_inherit_object_permissions:
675 if not user_inherit_object_permissions:
676 p = 'usergroup.none'
676 p = 'usergroup.none'
677 o = PermOrigin.USERGROUP_DEFAULT_NO_INHERIT
677 o = PermOrigin.USERGROUP_DEFAULT_NO_INHERIT
678 self.permissions_user_groups[u_k] = p, o
678 self.permissions_user_groups[u_k] = p, o
679
679
680 if perm.UserGroup.user_id == self.user_id:
680 if perm.UserGroup.user_id == self.user_id:
681 # set admin if owner
681 # set admin if owner
682 p = 'usergroup.admin'
682 p = 'usergroup.admin'
683 o = PermOrigin.USERGROUP_OWNER
683 o = PermOrigin.USERGROUP_OWNER
684 self.permissions_user_groups[u_k] = p, o
684 self.permissions_user_groups[u_k] = p, o
685
685
686 if self.user_is_admin:
686 if self.user_is_admin:
687 p = 'usergroup.admin'
687 p = 'usergroup.admin'
688 o = PermOrigin.SUPER_ADMIN
688 o = PermOrigin.SUPER_ADMIN
689 self.permissions_user_groups[u_k] = p, o
689 self.permissions_user_groups[u_k] = p, o
690
690
691 def _calculate_default_permissions(self):
691 def _calculate_default_permissions(self):
692 """
692 """
693 Set default user permissions for repositories, repository branches,
693 Set default user permissions for repositories, repository branches,
694 repository groups, user groups taken from the default user.
694 repository groups, user groups taken from the default user.
695
695
696 Calculate inheritance of object permissions based on what we have now
696 Calculate inheritance of object permissions based on what we have now
697 in GLOBAL permissions. We check if .false is in GLOBAL since this is
697 in GLOBAL permissions. We check if .false is in GLOBAL since this is
698 explicitly set. Inherit is the opposite of .false being there.
698 explicitly set. Inherit is the opposite of .false being there.
699
699
700 .. note::
700 .. note::
701
701
702 the syntax is little bit odd but what we need to check here is
702 the syntax is little bit odd but what we need to check here is
703 the opposite of .false permission being in the list so even for
703 the opposite of .false permission being in the list so even for
704 inconsistent state when both .true/.false is there
704 inconsistent state when both .true/.false is there
705 .false is more important
705 .false is more important
706
706
707 """
707 """
708 user_inherit_object_permissions = not ('hg.inherit_default_perms.false'
708 user_inherit_object_permissions = not ('hg.inherit_default_perms.false'
709 in self.permissions_global)
709 in self.permissions_global)
710
710
711 # default permissions inherited from `default` user permissions
711 # default permissions inherited from `default` user permissions
712 self._calculate_default_permissions_repositories(
712 self._calculate_default_permissions_repositories(
713 user_inherit_object_permissions)
713 user_inherit_object_permissions)
714
714
715 self._calculate_default_permissions_repository_branches(
715 self._calculate_default_permissions_repository_branches(
716 user_inherit_object_permissions)
716 user_inherit_object_permissions)
717
717
718 self._calculate_default_permissions_repository_groups(
718 self._calculate_default_permissions_repository_groups(
719 user_inherit_object_permissions)
719 user_inherit_object_permissions)
720
720
721 self._calculate_default_permissions_user_groups(
721 self._calculate_default_permissions_user_groups(
722 user_inherit_object_permissions)
722 user_inherit_object_permissions)
723
723
724 def _calculate_repository_permissions(self):
724 def _calculate_repository_permissions(self):
725 """
725 """
726 Repository access permissions for the current user.
726 Repository access permissions for the current user.
727
727
728 Check if the user is part of user groups for this repository and
728 Check if the user is part of user groups for this repository and
729 fill in the permission from it. `_choose_permission` decides of which
729 fill in the permission from it. `_choose_permission` decides of which
730 permission should be selected based on selected method.
730 permission should be selected based on selected method.
731 """
731 """
732
732
733 # user group for repositories permissions
733 # user group for repositories permissions
734 user_repo_perms_from_user_group = Permission\
734 user_repo_perms_from_user_group = Permission\
735 .get_default_repo_perms_from_user_group(
735 .get_default_repo_perms_from_user_group(
736 self.user_id, self.scope_repo_id)
736 self.user_id, self.scope_repo_id)
737
737
738 multiple_counter = collections.defaultdict(int)
738 multiple_counter = collections.defaultdict(int)
739 for perm in user_repo_perms_from_user_group:
739 for perm in user_repo_perms_from_user_group:
740 r_k = perm.UserGroupRepoToPerm.repository.repo_name
740 r_k = perm.UserGroupRepoToPerm.repository.repo_name
741 multiple_counter[r_k] += 1
741 multiple_counter[r_k] += 1
742 p = perm.Permission.permission_name
742 p = perm.Permission.permission_name
743 o = PermOrigin.REPO_USERGROUP % perm.UserGroupRepoToPerm\
743 o = PermOrigin.REPO_USERGROUP % perm.UserGroupRepoToPerm\
744 .users_group.users_group_name
744 .users_group.users_group_name
745
745
746 if multiple_counter[r_k] > 1:
746 if multiple_counter[r_k] > 1:
747 cur_perm = self.permissions_repositories[r_k]
747 cur_perm = self.permissions_repositories[r_k]
748 p = self._choose_permission(p, cur_perm)
748 p = self._choose_permission(p, cur_perm)
749
749
750 self.permissions_repositories[r_k] = p, o
750 self.permissions_repositories[r_k] = p, o
751
751
752 if perm.Repository.user_id == self.user_id:
752 if perm.Repository.user_id == self.user_id:
753 # set admin if owner
753 # set admin if owner
754 p = 'repository.admin'
754 p = 'repository.admin'
755 o = PermOrigin.REPO_OWNER
755 o = PermOrigin.REPO_OWNER
756 self.permissions_repositories[r_k] = p, o
756 self.permissions_repositories[r_k] = p, o
757
757
758 if self.user_is_admin:
758 if self.user_is_admin:
759 p = 'repository.admin'
759 p = 'repository.admin'
760 o = PermOrigin.SUPER_ADMIN
760 o = PermOrigin.SUPER_ADMIN
761 self.permissions_repositories[r_k] = p, o
761 self.permissions_repositories[r_k] = p, o
762
762
763 # user explicit permissions for repositories, overrides any specified
763 # user explicit permissions for repositories, overrides any specified
764 # by the group permission
764 # by the group permission
765 user_repo_perms = Permission.get_default_repo_perms(
765 user_repo_perms = Permission.get_default_repo_perms(
766 self.user_id, self.scope_repo_id)
766 self.user_id, self.scope_repo_id)
767 for perm in user_repo_perms:
767 for perm in user_repo_perms:
768 r_k = perm.UserRepoToPerm.repository.repo_name
768 r_k = perm.UserRepoToPerm.repository.repo_name
769 p = perm.Permission.permission_name
769 p = perm.Permission.permission_name
770 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
770 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
771
771
772 if not self.explicit:
772 if not self.explicit:
773 cur_perm = self.permissions_repositories.get(
773 cur_perm = self.permissions_repositories.get(
774 r_k, 'repository.none')
774 r_k, 'repository.none')
775 p = self._choose_permission(p, cur_perm)
775 p = self._choose_permission(p, cur_perm)
776
776
777 self.permissions_repositories[r_k] = p, o
777 self.permissions_repositories[r_k] = p, o
778
778
779 if perm.Repository.user_id == self.user_id:
779 if perm.Repository.user_id == self.user_id:
780 # set admin if owner
780 # set admin if owner
781 p = 'repository.admin'
781 p = 'repository.admin'
782 o = PermOrigin.REPO_OWNER
782 o = PermOrigin.REPO_OWNER
783 self.permissions_repositories[r_k] = p, o
783 self.permissions_repositories[r_k] = p, o
784
784
785 if self.user_is_admin:
785 if self.user_is_admin:
786 p = 'repository.admin'
786 p = 'repository.admin'
787 o = PermOrigin.SUPER_ADMIN
787 o = PermOrigin.SUPER_ADMIN
788 self.permissions_repositories[r_k] = p, o
788 self.permissions_repositories[r_k] = p, o
789
789
790 def _calculate_repository_branch_permissions(self):
790 def _calculate_repository_branch_permissions(self):
791 # user group for repositories permissions
791 # user group for repositories permissions
792 user_repo_branch_perms_from_user_group = Permission\
792 user_repo_branch_perms_from_user_group = Permission\
793 .get_default_repo_branch_perms_from_user_group(
793 .get_default_repo_branch_perms_from_user_group(
794 self.user_id, self.scope_repo_id)
794 self.user_id, self.scope_repo_id)
795
795
796 multiple_counter = collections.defaultdict(int)
796 multiple_counter = collections.defaultdict(int)
797 for perm in user_repo_branch_perms_from_user_group:
797 for perm in user_repo_branch_perms_from_user_group:
798 r_k = perm.UserGroupRepoToPerm.repository.repo_name
798 r_k = perm.UserGroupRepoToPerm.repository.repo_name
799 p = perm.Permission.permission_name
799 p = perm.Permission.permission_name
800 pattern = perm.UserGroupToRepoBranchPermission.branch_pattern
800 pattern = perm.UserGroupToRepoBranchPermission.branch_pattern
801 o = PermOrigin.REPO_USERGROUP % perm.UserGroupRepoToPerm\
801 o = PermOrigin.REPO_USERGROUP % perm.UserGroupRepoToPerm\
802 .users_group.users_group_name
802 .users_group.users_group_name
803
803
804 multiple_counter[r_k] += 1
804 multiple_counter[r_k] += 1
805 if multiple_counter[r_k] > 1:
805 if multiple_counter[r_k] > 1:
806 cur_perm = self.permissions_repository_branches[r_k][pattern]
806 cur_perm = self.permissions_repository_branches[r_k][pattern]
807 p = self._choose_permission(p, cur_perm)
807 p = self._choose_permission(p, cur_perm)
808
808
809 self.permissions_repository_branches[r_k] = pattern, p, o
809 self.permissions_repository_branches[r_k] = pattern, p, o
810
810
811 # user explicit branch permissions for repositories, overrides
811 # user explicit branch permissions for repositories, overrides
812 # any specified by the group permission
812 # any specified by the group permission
813 user_repo_branch_perms = Permission.get_default_repo_branch_perms(
813 user_repo_branch_perms = Permission.get_default_repo_branch_perms(
814 self.user_id, self.scope_repo_id)
814 self.user_id, self.scope_repo_id)
815
815
816 for perm in user_repo_branch_perms:
816 for perm in user_repo_branch_perms:
817
817
818 r_k = perm.UserRepoToPerm.repository.repo_name
818 r_k = perm.UserRepoToPerm.repository.repo_name
819 p = perm.Permission.permission_name
819 p = perm.Permission.permission_name
820 pattern = perm.UserToRepoBranchPermission.branch_pattern
820 pattern = perm.UserToRepoBranchPermission.branch_pattern
821 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
821 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
822
822
823 if not self.explicit:
823 if not self.explicit:
824 cur_perm = self.permissions_repository_branches.get(r_k)
824 cur_perm = self.permissions_repository_branches.get(r_k)
825 if cur_perm:
825 if cur_perm:
826 cur_perm = cur_perm[pattern]
826 cur_perm = cur_perm[pattern]
827 cur_perm = cur_perm or 'branch.none'
827 cur_perm = cur_perm or 'branch.none'
828 p = self._choose_permission(p, cur_perm)
828 p = self._choose_permission(p, cur_perm)
829
829
830 # NOTE(marcink): register all pattern/perm instances in this
830 # NOTE(marcink): register all pattern/perm instances in this
831 # special dict that aggregates entries
831 # special dict that aggregates entries
832 self.permissions_repository_branches[r_k] = pattern, p, o
832 self.permissions_repository_branches[r_k] = pattern, p, o
833
833
834 def _calculate_repository_group_permissions(self):
834 def _calculate_repository_group_permissions(self):
835 """
835 """
836 Repository group permissions for the current user.
836 Repository group permissions for the current user.
837
837
838 Check if the user is part of user groups for repository groups and
838 Check if the user is part of user groups for repository groups and
839 fill in the permissions from it. `_choose_permission` decides of which
839 fill in the permissions from it. `_choose_permission` decides of which
840 permission should be selected based on selected method.
840 permission should be selected based on selected method.
841 """
841 """
842 # user group for repo groups permissions
842 # user group for repo groups permissions
843 user_repo_group_perms_from_user_group = Permission\
843 user_repo_group_perms_from_user_group = Permission\
844 .get_default_group_perms_from_user_group(
844 .get_default_group_perms_from_user_group(
845 self.user_id, self.scope_repo_group_id)
845 self.user_id, self.scope_repo_group_id)
846
846
847 multiple_counter = collections.defaultdict(int)
847 multiple_counter = collections.defaultdict(int)
848 for perm in user_repo_group_perms_from_user_group:
848 for perm in user_repo_group_perms_from_user_group:
849 rg_k = perm.UserGroupRepoGroupToPerm.group.group_name
849 rg_k = perm.UserGroupRepoGroupToPerm.group.group_name
850 multiple_counter[rg_k] += 1
850 multiple_counter[rg_k] += 1
851 o = PermOrigin.REPOGROUP_USERGROUP % perm.UserGroupRepoGroupToPerm\
851 o = PermOrigin.REPOGROUP_USERGROUP % perm.UserGroupRepoGroupToPerm\
852 .users_group.users_group_name
852 .users_group.users_group_name
853 p = perm.Permission.permission_name
853 p = perm.Permission.permission_name
854
854
855 if multiple_counter[rg_k] > 1:
855 if multiple_counter[rg_k] > 1:
856 cur_perm = self.permissions_repository_groups[rg_k]
856 cur_perm = self.permissions_repository_groups[rg_k]
857 p = self._choose_permission(p, cur_perm)
857 p = self._choose_permission(p, cur_perm)
858 self.permissions_repository_groups[rg_k] = p, o
858 self.permissions_repository_groups[rg_k] = p, o
859
859
860 if perm.RepoGroup.user_id == self.user_id:
860 if perm.RepoGroup.user_id == self.user_id:
861 # set admin if owner, even for member of other user group
861 # set admin if owner, even for member of other user group
862 p = 'group.admin'
862 p = 'group.admin'
863 o = PermOrigin.REPOGROUP_OWNER
863 o = PermOrigin.REPOGROUP_OWNER
864 self.permissions_repository_groups[rg_k] = p, o
864 self.permissions_repository_groups[rg_k] = p, o
865
865
866 if self.user_is_admin:
866 if self.user_is_admin:
867 p = 'group.admin'
867 p = 'group.admin'
868 o = PermOrigin.SUPER_ADMIN
868 o = PermOrigin.SUPER_ADMIN
869 self.permissions_repository_groups[rg_k] = p, o
869 self.permissions_repository_groups[rg_k] = p, o
870
870
871 # user explicit permissions for repository groups
871 # user explicit permissions for repository groups
872 user_repo_groups_perms = Permission.get_default_group_perms(
872 user_repo_groups_perms = Permission.get_default_group_perms(
873 self.user_id, self.scope_repo_group_id)
873 self.user_id, self.scope_repo_group_id)
874 for perm in user_repo_groups_perms:
874 for perm in user_repo_groups_perms:
875 rg_k = perm.UserRepoGroupToPerm.group.group_name
875 rg_k = perm.UserRepoGroupToPerm.group.group_name
876 o = PermOrigin.REPOGROUP_USER % perm.UserRepoGroupToPerm\
876 o = PermOrigin.REPOGROUP_USER % perm.UserRepoGroupToPerm\
877 .user.username
877 .user.username
878 p = perm.Permission.permission_name
878 p = perm.Permission.permission_name
879
879
880 if not self.explicit:
880 if not self.explicit:
881 cur_perm = self.permissions_repository_groups.get(rg_k, 'group.none')
881 cur_perm = self.permissions_repository_groups.get(rg_k, 'group.none')
882 p = self._choose_permission(p, cur_perm)
882 p = self._choose_permission(p, cur_perm)
883
883
884 self.permissions_repository_groups[rg_k] = p, o
884 self.permissions_repository_groups[rg_k] = p, o
885
885
886 if perm.RepoGroup.user_id == self.user_id:
886 if perm.RepoGroup.user_id == self.user_id:
887 # set admin if owner
887 # set admin if owner
888 p = 'group.admin'
888 p = 'group.admin'
889 o = PermOrigin.REPOGROUP_OWNER
889 o = PermOrigin.REPOGROUP_OWNER
890 self.permissions_repository_groups[rg_k] = p, o
890 self.permissions_repository_groups[rg_k] = p, o
891
891
892 if self.user_is_admin:
892 if self.user_is_admin:
893 p = 'group.admin'
893 p = 'group.admin'
894 o = PermOrigin.SUPER_ADMIN
894 o = PermOrigin.SUPER_ADMIN
895 self.permissions_repository_groups[rg_k] = p, o
895 self.permissions_repository_groups[rg_k] = p, o
896
896
897 def _calculate_user_group_permissions(self):
897 def _calculate_user_group_permissions(self):
898 """
898 """
899 User group permissions for the current user.
899 User group permissions for the current user.
900 """
900 """
901 # user group for user group permissions
901 # user group for user group permissions
902 user_group_from_user_group = Permission\
902 user_group_from_user_group = Permission\
903 .get_default_user_group_perms_from_user_group(
903 .get_default_user_group_perms_from_user_group(
904 self.user_id, self.scope_user_group_id)
904 self.user_id, self.scope_user_group_id)
905
905
906 multiple_counter = collections.defaultdict(int)
906 multiple_counter = collections.defaultdict(int)
907 for perm in user_group_from_user_group:
907 for perm in user_group_from_user_group:
908 ug_k = perm.UserGroupUserGroupToPerm\
908 ug_k = perm.UserGroupUserGroupToPerm\
909 .target_user_group.users_group_name
909 .target_user_group.users_group_name
910 multiple_counter[ug_k] += 1
910 multiple_counter[ug_k] += 1
911 o = PermOrigin.USERGROUP_USERGROUP % perm.UserGroupUserGroupToPerm\
911 o = PermOrigin.USERGROUP_USERGROUP % perm.UserGroupUserGroupToPerm\
912 .user_group.users_group_name
912 .user_group.users_group_name
913 p = perm.Permission.permission_name
913 p = perm.Permission.permission_name
914
914
915 if multiple_counter[ug_k] > 1:
915 if multiple_counter[ug_k] > 1:
916 cur_perm = self.permissions_user_groups[ug_k]
916 cur_perm = self.permissions_user_groups[ug_k]
917 p = self._choose_permission(p, cur_perm)
917 p = self._choose_permission(p, cur_perm)
918
918
919 self.permissions_user_groups[ug_k] = p, o
919 self.permissions_user_groups[ug_k] = p, o
920
920
921 if perm.UserGroup.user_id == self.user_id:
921 if perm.UserGroup.user_id == self.user_id:
922 # set admin if owner, even for member of other user group
922 # set admin if owner, even for member of other user group
923 p = 'usergroup.admin'
923 p = 'usergroup.admin'
924 o = PermOrigin.USERGROUP_OWNER
924 o = PermOrigin.USERGROUP_OWNER
925 self.permissions_user_groups[ug_k] = p, o
925 self.permissions_user_groups[ug_k] = p, o
926
926
927 if self.user_is_admin:
927 if self.user_is_admin:
928 p = 'usergroup.admin'
928 p = 'usergroup.admin'
929 o = PermOrigin.SUPER_ADMIN
929 o = PermOrigin.SUPER_ADMIN
930 self.permissions_user_groups[ug_k] = p, o
930 self.permissions_user_groups[ug_k] = p, o
931
931
932 # user explicit permission for user groups
932 # user explicit permission for user groups
933 user_user_groups_perms = Permission.get_default_user_group_perms(
933 user_user_groups_perms = Permission.get_default_user_group_perms(
934 self.user_id, self.scope_user_group_id)
934 self.user_id, self.scope_user_group_id)
935 for perm in user_user_groups_perms:
935 for perm in user_user_groups_perms:
936 ug_k = perm.UserUserGroupToPerm.user_group.users_group_name
936 ug_k = perm.UserUserGroupToPerm.user_group.users_group_name
937 o = PermOrigin.USERGROUP_USER % perm.UserUserGroupToPerm\
937 o = PermOrigin.USERGROUP_USER % perm.UserUserGroupToPerm\
938 .user.username
938 .user.username
939 p = perm.Permission.permission_name
939 p = perm.Permission.permission_name
940
940
941 if not self.explicit:
941 if not self.explicit:
942 cur_perm = self.permissions_user_groups.get(ug_k, 'usergroup.none')
942 cur_perm = self.permissions_user_groups.get(ug_k, 'usergroup.none')
943 p = self._choose_permission(p, cur_perm)
943 p = self._choose_permission(p, cur_perm)
944
944
945 self.permissions_user_groups[ug_k] = p, o
945 self.permissions_user_groups[ug_k] = p, o
946
946
947 if perm.UserGroup.user_id == self.user_id:
947 if perm.UserGroup.user_id == self.user_id:
948 # set admin if owner
948 # set admin if owner
949 p = 'usergroup.admin'
949 p = 'usergroup.admin'
950 o = PermOrigin.USERGROUP_OWNER
950 o = PermOrigin.USERGROUP_OWNER
951 self.permissions_user_groups[ug_k] = p, o
951 self.permissions_user_groups[ug_k] = p, o
952
952
953 if self.user_is_admin:
953 if self.user_is_admin:
954 p = 'usergroup.admin'
954 p = 'usergroup.admin'
955 o = PermOrigin.SUPER_ADMIN
955 o = PermOrigin.SUPER_ADMIN
956 self.permissions_user_groups[ug_k] = p, o
956 self.permissions_user_groups[ug_k] = p, o
957
957
958 def _choose_permission(self, new_perm, cur_perm):
958 def _choose_permission(self, new_perm, cur_perm):
959 new_perm_val = Permission.PERM_WEIGHTS[new_perm]
959 new_perm_val = Permission.PERM_WEIGHTS[new_perm]
960 cur_perm_val = Permission.PERM_WEIGHTS[cur_perm]
960 cur_perm_val = Permission.PERM_WEIGHTS[cur_perm]
961 if self.algo == 'higherwin':
961 if self.algo == 'higherwin':
962 if new_perm_val > cur_perm_val:
962 if new_perm_val > cur_perm_val:
963 return new_perm
963 return new_perm
964 return cur_perm
964 return cur_perm
965 elif self.algo == 'lowerwin':
965 elif self.algo == 'lowerwin':
966 if new_perm_val < cur_perm_val:
966 if new_perm_val < cur_perm_val:
967 return new_perm
967 return new_perm
968 return cur_perm
968 return cur_perm
969
969
970 def _permission_structure(self):
970 def _permission_structure(self):
971 return {
971 return {
972 'global': self.permissions_global,
972 'global': self.permissions_global,
973 'repositories': self.permissions_repositories,
973 'repositories': self.permissions_repositories,
974 'repository_branches': self.permissions_repository_branches,
974 'repository_branches': self.permissions_repository_branches,
975 'repositories_groups': self.permissions_repository_groups,
975 'repositories_groups': self.permissions_repository_groups,
976 'user_groups': self.permissions_user_groups,
976 'user_groups': self.permissions_user_groups,
977 }
977 }
978
978
979
979
980 def allowed_auth_token_access(view_name, auth_token, whitelist=None):
980 def allowed_auth_token_access(view_name, auth_token, whitelist=None):
981 """
981 """
982 Check if given controller_name is in whitelist of auth token access
982 Check if given controller_name is in whitelist of auth token access
983 """
983 """
984 if not whitelist:
984 if not whitelist:
985 from rhodecode import CONFIG
985 from rhodecode import CONFIG
986 whitelist = aslist(
986 whitelist = aslist(
987 CONFIG.get('api_access_controllers_whitelist'), sep=',')
987 CONFIG.get('api_access_controllers_whitelist'), sep=',')
988 # backward compat translation
988 # backward compat translation
989 compat = {
989 compat = {
990 # old controller, new VIEW
990 # old controller, new VIEW
991 'ChangesetController:*': 'RepoCommitsView:*',
991 'ChangesetController:*': 'RepoCommitsView:*',
992 'ChangesetController:changeset_patch': 'RepoCommitsView:repo_commit_patch',
992 'ChangesetController:changeset_patch': 'RepoCommitsView:repo_commit_patch',
993 'ChangesetController:changeset_raw': 'RepoCommitsView:repo_commit_raw',
993 'ChangesetController:changeset_raw': 'RepoCommitsView:repo_commit_raw',
994 'FilesController:raw': 'RepoCommitsView:repo_commit_raw',
994 'FilesController:raw': 'RepoCommitsView:repo_commit_raw',
995 'FilesController:archivefile': 'RepoFilesView:repo_archivefile',
995 'FilesController:archivefile': 'RepoFilesView:repo_archivefile',
996 'GistsController:*': 'GistView:*',
996 'GistsController:*': 'GistView:*',
997 }
997 }
998
998
999 log.debug(
999 log.debug(
1000 'Allowed views for AUTH TOKEN access: %s', whitelist)
1000 'Allowed views for AUTH TOKEN access: %s', whitelist)
1001 auth_token_access_valid = False
1001 auth_token_access_valid = False
1002
1002
1003 for entry in whitelist:
1003 for entry in whitelist:
1004 token_match = True
1004 token_match = True
1005 if entry in compat:
1005 if entry in compat:
1006 # translate from old Controllers to Pyramid Views
1006 # translate from old Controllers to Pyramid Views
1007 entry = compat[entry]
1007 entry = compat[entry]
1008
1008
1009 if '@' in entry:
1009 if '@' in entry:
1010 # specific AuthToken
1010 # specific AuthToken
1011 entry, allowed_token = entry.split('@', 1)
1011 entry, allowed_token = entry.split('@', 1)
1012 token_match = auth_token == allowed_token
1012 token_match = auth_token == allowed_token
1013
1013
1014 if fnmatch.fnmatch(view_name, entry) and token_match:
1014 if fnmatch.fnmatch(view_name, entry) and token_match:
1015 auth_token_access_valid = True
1015 auth_token_access_valid = True
1016 break
1016 break
1017
1017
1018 if auth_token_access_valid:
1018 if auth_token_access_valid:
1019 log.debug('view: `%s` matches entry in whitelist: %s',
1019 log.debug('view: `%s` matches entry in whitelist: %s',
1020 view_name, whitelist)
1020 view_name, whitelist)
1021
1021
1022 else:
1022 else:
1023 msg = ('view: `%s` does *NOT* match any entry in whitelist: %s'
1023 msg = ('view: `%s` does *NOT* match any entry in whitelist: %s'
1024 % (view_name, whitelist))
1024 % (view_name, whitelist))
1025 if auth_token:
1025 if auth_token:
1026 # if we use auth token key and don't have access it's a warning
1026 # if we use auth token key and don't have access it's a warning
1027 log.warning(msg)
1027 log.warning(msg)
1028 else:
1028 else:
1029 log.debug(msg)
1029 log.debug(msg)
1030
1030
1031 return auth_token_access_valid
1031 return auth_token_access_valid
1032
1032
1033
1033
1034 class AuthUser(object):
1034 class AuthUser(object):
1035 """
1035 """
1036 A simple object that handles all attributes of user in RhodeCode
1036 A simple object that handles all attributes of user in RhodeCode
1037
1037
1038 It does lookup based on API key,given user, or user present in session
1038 It does lookup based on API key,given user, or user present in session
1039 Then it fills all required information for such user. It also checks if
1039 Then it fills all required information for such user. It also checks if
1040 anonymous access is enabled and if so, it returns default user as logged in
1040 anonymous access is enabled and if so, it returns default user as logged in
1041 """
1041 """
1042 GLOBAL_PERMS = [x[0] for x in Permission.PERMS]
1042 GLOBAL_PERMS = [x[0] for x in Permission.PERMS]
1043
1043
1044 def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None):
1044 def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None):
1045
1045
1046 self.user_id = user_id
1046 self.user_id = user_id
1047 self._api_key = api_key
1047 self._api_key = api_key
1048
1048
1049 self.api_key = None
1049 self.api_key = None
1050 self.username = username
1050 self.username = username
1051 self.ip_addr = ip_addr
1051 self.ip_addr = ip_addr
1052 self.name = ''
1052 self.name = ''
1053 self.lastname = ''
1053 self.lastname = ''
1054 self.first_name = ''
1054 self.first_name = ''
1055 self.last_name = ''
1055 self.last_name = ''
1056 self.email = ''
1056 self.email = ''
1057 self.is_authenticated = False
1057 self.is_authenticated = False
1058 self.admin = False
1058 self.admin = False
1059 self.inherit_default_permissions = False
1059 self.inherit_default_permissions = False
1060 self.password = ''
1060 self.password = ''
1061
1061
1062 self.anonymous_user = None # propagated on propagate_data
1062 self.anonymous_user = None # propagated on propagate_data
1063 self.propagate_data()
1063 self.propagate_data()
1064 self._instance = None
1064 self._instance = None
1065 self._permissions_scoped_cache = {} # used to bind scoped calculation
1065 self._permissions_scoped_cache = {} # used to bind scoped calculation
1066
1066
1067 @LazyProperty
1067 @LazyProperty
1068 def permissions(self):
1068 def permissions(self):
1069 return self.get_perms(user=self, cache=None)
1069 return self.get_perms(user=self, cache=None)
1070
1070
1071 @LazyProperty
1071 @LazyProperty
1072 def permissions_safe(self):
1072 def permissions_safe(self):
1073 """
1073 """
1074 Filtered permissions excluding not allowed repositories
1074 Filtered permissions excluding not allowed repositories
1075 """
1075 """
1076 perms = self.get_perms(user=self, cache=None)
1076 perms = self.get_perms(user=self, cache=None)
1077
1077
1078 perms['repositories'] = {
1078 perms['repositories'] = {
1079 k: v for k, v in perms['repositories'].items()
1079 k: v for k, v in perms['repositories'].items()
1080 if v != 'repository.none'}
1080 if v != 'repository.none'}
1081 perms['repositories_groups'] = {
1081 perms['repositories_groups'] = {
1082 k: v for k, v in perms['repositories_groups'].items()
1082 k: v for k, v in perms['repositories_groups'].items()
1083 if v != 'group.none'}
1083 if v != 'group.none'}
1084 perms['user_groups'] = {
1084 perms['user_groups'] = {
1085 k: v for k, v in perms['user_groups'].items()
1085 k: v for k, v in perms['user_groups'].items()
1086 if v != 'usergroup.none'}
1086 if v != 'usergroup.none'}
1087 perms['repository_branches'] = {
1087 perms['repository_branches'] = {
1088 k: v for k, v in perms['repository_branches'].iteritems()
1088 k: v for k, v in perms['repository_branches'].iteritems()
1089 if v != 'branch.none'}
1089 if v != 'branch.none'}
1090 return perms
1090 return perms
1091
1091
1092 @LazyProperty
1092 @LazyProperty
1093 def permissions_full_details(self):
1093 def permissions_full_details(self):
1094 return self.get_perms(
1094 return self.get_perms(
1095 user=self, cache=None, calculate_super_admin=True)
1095 user=self, cache=None, calculate_super_admin=True)
1096
1096
1097 def permissions_with_scope(self, scope):
1097 def permissions_with_scope(self, scope):
1098 """
1098 """
1099 Call the get_perms function with scoped data. The scope in that function
1099 Call the get_perms function with scoped data. The scope in that function
1100 narrows the SQL calls to the given ID of objects resulting in fetching
1100 narrows the SQL calls to the given ID of objects resulting in fetching
1101 Just particular permission we want to obtain. If scope is an empty dict
1101 Just particular permission we want to obtain. If scope is an empty dict
1102 then it basically narrows the scope to GLOBAL permissions only.
1102 then it basically narrows the scope to GLOBAL permissions only.
1103
1103
1104 :param scope: dict
1104 :param scope: dict
1105 """
1105 """
1106 if 'repo_name' in scope:
1106 if 'repo_name' in scope:
1107 obj = Repository.get_by_repo_name(scope['repo_name'])
1107 obj = Repository.get_by_repo_name(scope['repo_name'])
1108 if obj:
1108 if obj:
1109 scope['repo_id'] = obj.repo_id
1109 scope['repo_id'] = obj.repo_id
1110 _scope = collections.OrderedDict()
1110 _scope = collections.OrderedDict()
1111 _scope['repo_id'] = -1
1111 _scope['repo_id'] = -1
1112 _scope['user_group_id'] = -1
1112 _scope['user_group_id'] = -1
1113 _scope['repo_group_id'] = -1
1113 _scope['repo_group_id'] = -1
1114
1114
1115 for k in sorted(scope.keys()):
1115 for k in sorted(scope.keys()):
1116 _scope[k] = scope[k]
1116 _scope[k] = scope[k]
1117
1117
1118 # store in cache to mimic how the @LazyProperty works,
1118 # store in cache to mimic how the @LazyProperty works,
1119 # the difference here is that we use the unique key calculated
1119 # the difference here is that we use the unique key calculated
1120 # from params and values
1120 # from params and values
1121 return self.get_perms(user=self, cache=None, scope=_scope)
1121 return self.get_perms(user=self, cache=None, scope=_scope)
1122
1122
1123 def get_instance(self):
1123 def get_instance(self):
1124 return User.get(self.user_id)
1124 return User.get(self.user_id)
1125
1125
1126 def propagate_data(self):
1126 def propagate_data(self):
1127 """
1127 """
1128 Fills in user data and propagates values to this instance. Maps fetched
1128 Fills in user data and propagates values to this instance. Maps fetched
1129 user attributes to this class instance attributes
1129 user attributes to this class instance attributes
1130 """
1130 """
1131 log.debug('AuthUser: starting data propagation for new potential user')
1131 log.debug('AuthUser: starting data propagation for new potential user')
1132 user_model = UserModel()
1132 user_model = UserModel()
1133 anon_user = self.anonymous_user = User.get_default_user(cache=True)
1133 anon_user = self.anonymous_user = User.get_default_user(cache=True)
1134 is_user_loaded = False
1134 is_user_loaded = False
1135
1135
1136 # lookup by userid
1136 # lookup by userid
1137 if self.user_id is not None and self.user_id != anon_user.user_id:
1137 if self.user_id is not None and self.user_id != anon_user.user_id:
1138 log.debug('Trying Auth User lookup by USER ID: `%s`', self.user_id)
1138 log.debug('Trying Auth User lookup by USER ID: `%s`', self.user_id)
1139 is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
1139 is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
1140
1140
1141 # try go get user by api key
1141 # try go get user by api key
1142 elif self._api_key and self._api_key != anon_user.api_key:
1142 elif self._api_key and self._api_key != anon_user.api_key:
1143 log.debug('Trying Auth User lookup by API KEY: `%s`', self._api_key)
1143 log.debug('Trying Auth User lookup by API KEY: `...%s`', self._api_key[-4:])
1144 is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
1144 is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
1145
1145
1146 # lookup by username
1146 # lookup by username
1147 elif self.username:
1147 elif self.username:
1148 log.debug('Trying Auth User lookup by USER NAME: `%s`', self.username)
1148 log.debug('Trying Auth User lookup by USER NAME: `%s`', self.username)
1149 is_user_loaded = user_model.fill_data(self, username=self.username)
1149 is_user_loaded = user_model.fill_data(self, username=self.username)
1150 else:
1150 else:
1151 log.debug('No data in %s that could been used to log in', self)
1151 log.debug('No data in %s that could been used to log in', self)
1152
1152
1153 if not is_user_loaded:
1153 if not is_user_loaded:
1154 log.debug(
1154 log.debug(
1155 'Failed to load user. Fallback to default user %s', anon_user)
1155 'Failed to load user. Fallback to default user %s', anon_user)
1156 # if we cannot authenticate user try anonymous
1156 # if we cannot authenticate user try anonymous
1157 if anon_user.active:
1157 if anon_user.active:
1158 log.debug('default user is active, using it as a session user')
1158 log.debug('default user is active, using it as a session user')
1159 user_model.fill_data(self, user_id=anon_user.user_id)
1159 user_model.fill_data(self, user_id=anon_user.user_id)
1160 # then we set this user is logged in
1160 # then we set this user is logged in
1161 self.is_authenticated = True
1161 self.is_authenticated = True
1162 else:
1162 else:
1163 log.debug('default user is NOT active')
1163 log.debug('default user is NOT active')
1164 # in case of disabled anonymous user we reset some of the
1164 # in case of disabled anonymous user we reset some of the
1165 # parameters so such user is "corrupted", skipping the fill_data
1165 # parameters so such user is "corrupted", skipping the fill_data
1166 for attr in ['user_id', 'username', 'admin', 'active']:
1166 for attr in ['user_id', 'username', 'admin', 'active']:
1167 setattr(self, attr, None)
1167 setattr(self, attr, None)
1168 self.is_authenticated = False
1168 self.is_authenticated = False
1169
1169
1170 if not self.username:
1170 if not self.username:
1171 self.username = 'None'
1171 self.username = 'None'
1172
1172
1173 log.debug('AuthUser: propagated user is now %s', self)
1173 log.debug('AuthUser: propagated user is now %s', self)
1174
1174
1175 def get_perms(self, user, scope=None, explicit=True, algo='higherwin',
1175 def get_perms(self, user, scope=None, explicit=True, algo='higherwin',
1176 calculate_super_admin=False, cache=None):
1176 calculate_super_admin=False, cache=None):
1177 """
1177 """
1178 Fills user permission attribute with permissions taken from database
1178 Fills user permission attribute with permissions taken from database
1179 works for permissions given for repositories, and for permissions that
1179 works for permissions given for repositories, and for permissions that
1180 are granted to groups
1180 are granted to groups
1181
1181
1182 :param user: instance of User object from database
1182 :param user: instance of User object from database
1183 :param explicit: In case there are permissions both for user and a group
1183 :param explicit: In case there are permissions both for user and a group
1184 that user is part of, explicit flag will defiine if user will
1184 that user is part of, explicit flag will defiine if user will
1185 explicitly override permissions from group, if it's False it will
1185 explicitly override permissions from group, if it's False it will
1186 make decision based on the algo
1186 make decision based on the algo
1187 :param algo: algorithm to decide what permission should be choose if
1187 :param algo: algorithm to decide what permission should be choose if
1188 it's multiple defined, eg user in two different groups. It also
1188 it's multiple defined, eg user in two different groups. It also
1189 decides if explicit flag is turned off how to specify the permission
1189 decides if explicit flag is turned off how to specify the permission
1190 for case when user is in a group + have defined separate permission
1190 for case when user is in a group + have defined separate permission
1191 :param calculate_super_admin: calculate permissions for super-admin in the
1191 :param calculate_super_admin: calculate permissions for super-admin in the
1192 same way as for regular user without speedups
1192 same way as for regular user without speedups
1193 :param cache: Use caching for calculation, None = let the cache backend decide
1193 :param cache: Use caching for calculation, None = let the cache backend decide
1194 """
1194 """
1195 user_id = user.user_id
1195 user_id = user.user_id
1196 user_is_admin = user.is_admin
1196 user_is_admin = user.is_admin
1197
1197
1198 # inheritance of global permissions like create repo/fork repo etc
1198 # inheritance of global permissions like create repo/fork repo etc
1199 user_inherit_default_permissions = user.inherit_default_permissions
1199 user_inherit_default_permissions = user.inherit_default_permissions
1200
1200
1201 cache_seconds = safe_int(
1201 cache_seconds = safe_int(
1202 rhodecode.CONFIG.get('rc_cache.cache_perms.expiration_time'))
1202 rhodecode.CONFIG.get('rc_cache.cache_perms.expiration_time'))
1203
1203
1204 if cache is None:
1204 if cache is None:
1205 # let the backend cache decide
1205 # let the backend cache decide
1206 cache_on = cache_seconds > 0
1206 cache_on = cache_seconds > 0
1207 else:
1207 else:
1208 cache_on = cache
1208 cache_on = cache
1209
1209
1210 log.debug(
1210 log.debug(
1211 'Computing PERMISSION tree for user %s scope `%s` '
1211 'Computing PERMISSION tree for user %s scope `%s` '
1212 'with caching: %s[TTL: %ss]', user, scope, cache_on, cache_seconds or 0)
1212 'with caching: %s[TTL: %ss]', user, scope, cache_on, cache_seconds or 0)
1213
1213
1214 cache_namespace_uid = 'cache_user_auth.{}'.format(user_id)
1214 cache_namespace_uid = 'cache_user_auth.{}'.format(user_id)
1215 region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid)
1215 region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid)
1216
1216
1217 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid,
1217 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid,
1218 condition=cache_on)
1218 condition=cache_on)
1219 def compute_perm_tree(cache_name,
1219 def compute_perm_tree(cache_name,
1220 user_id, scope, user_is_admin,user_inherit_default_permissions,
1220 user_id, scope, user_is_admin,user_inherit_default_permissions,
1221 explicit, algo, calculate_super_admin):
1221 explicit, algo, calculate_super_admin):
1222 return _cached_perms_data(
1222 return _cached_perms_data(
1223 user_id, scope, user_is_admin, user_inherit_default_permissions,
1223 user_id, scope, user_is_admin, user_inherit_default_permissions,
1224 explicit, algo, calculate_super_admin)
1224 explicit, algo, calculate_super_admin)
1225
1225
1226 start = time.time()
1226 start = time.time()
1227 result = compute_perm_tree(
1227 result = compute_perm_tree(
1228 'permissions', user_id, scope, user_is_admin,
1228 'permissions', user_id, scope, user_is_admin,
1229 user_inherit_default_permissions, explicit, algo,
1229 user_inherit_default_permissions, explicit, algo,
1230 calculate_super_admin)
1230 calculate_super_admin)
1231
1231
1232 result_repr = []
1232 result_repr = []
1233 for k in result:
1233 for k in result:
1234 result_repr.append((k, len(result[k])))
1234 result_repr.append((k, len(result[k])))
1235 total = time.time() - start
1235 total = time.time() - start
1236 log.debug('PERMISSION tree for user %s computed in %.4fs: %s',
1236 log.debug('PERMISSION tree for user %s computed in %.4fs: %s',
1237 user, total, result_repr)
1237 user, total, result_repr)
1238
1238
1239 return result
1239 return result
1240
1240
1241 @property
1241 @property
1242 def is_default(self):
1242 def is_default(self):
1243 return self.username == User.DEFAULT_USER
1243 return self.username == User.DEFAULT_USER
1244
1244
1245 @property
1245 @property
1246 def is_admin(self):
1246 def is_admin(self):
1247 return self.admin
1247 return self.admin
1248
1248
1249 @property
1249 @property
1250 def is_user_object(self):
1250 def is_user_object(self):
1251 return self.user_id is not None
1251 return self.user_id is not None
1252
1252
1253 @property
1253 @property
1254 def repositories_admin(self):
1254 def repositories_admin(self):
1255 """
1255 """
1256 Returns list of repositories you're an admin of
1256 Returns list of repositories you're an admin of
1257 """
1257 """
1258 return [
1258 return [
1259 x[0] for x in self.permissions['repositories'].items()
1259 x[0] for x in self.permissions['repositories'].items()
1260 if x[1] == 'repository.admin']
1260 if x[1] == 'repository.admin']
1261
1261
1262 @property
1262 @property
1263 def repository_groups_admin(self):
1263 def repository_groups_admin(self):
1264 """
1264 """
1265 Returns list of repository groups you're an admin of
1265 Returns list of repository groups you're an admin of
1266 """
1266 """
1267 return [
1267 return [
1268 x[0] for x in self.permissions['repositories_groups'].items()
1268 x[0] for x in self.permissions['repositories_groups'].items()
1269 if x[1] == 'group.admin']
1269 if x[1] == 'group.admin']
1270
1270
1271 @property
1271 @property
1272 def user_groups_admin(self):
1272 def user_groups_admin(self):
1273 """
1273 """
1274 Returns list of user groups you're an admin of
1274 Returns list of user groups you're an admin of
1275 """
1275 """
1276 return [
1276 return [
1277 x[0] for x in self.permissions['user_groups'].items()
1277 x[0] for x in self.permissions['user_groups'].items()
1278 if x[1] == 'usergroup.admin']
1278 if x[1] == 'usergroup.admin']
1279
1279
1280 def repo_acl_ids(self, perms=None, name_filter=None, cache=False):
1280 def repo_acl_ids(self, perms=None, name_filter=None, cache=False):
1281 """
1281 """
1282 Returns list of repository ids that user have access to based on given
1282 Returns list of repository ids that user have access to based on given
1283 perms. The cache flag should be only used in cases that are used for
1283 perms. The cache flag should be only used in cases that are used for
1284 display purposes, NOT IN ANY CASE for permission checks.
1284 display purposes, NOT IN ANY CASE for permission checks.
1285 """
1285 """
1286 from rhodecode.model.scm import RepoList
1286 from rhodecode.model.scm import RepoList
1287 if not perms:
1287 if not perms:
1288 perms = [
1288 perms = [
1289 'repository.read', 'repository.write', 'repository.admin']
1289 'repository.read', 'repository.write', 'repository.admin']
1290
1290
1291 def _cached_repo_acl(user_id, perm_def, _name_filter):
1291 def _cached_repo_acl(user_id, perm_def, _name_filter):
1292 qry = Repository.query()
1292 qry = Repository.query()
1293 if _name_filter:
1293 if _name_filter:
1294 ilike_expression = u'%{}%'.format(safe_unicode(_name_filter))
1294 ilike_expression = u'%{}%'.format(safe_unicode(_name_filter))
1295 qry = qry.filter(
1295 qry = qry.filter(
1296 Repository.repo_name.ilike(ilike_expression))
1296 Repository.repo_name.ilike(ilike_expression))
1297
1297
1298 return [x.repo_id for x in
1298 return [x.repo_id for x in
1299 RepoList(qry, perm_set=perm_def)]
1299 RepoList(qry, perm_set=perm_def)]
1300
1300
1301 return _cached_repo_acl(self.user_id, perms, name_filter)
1301 return _cached_repo_acl(self.user_id, perms, name_filter)
1302
1302
1303 def repo_group_acl_ids(self, perms=None, name_filter=None, cache=False):
1303 def repo_group_acl_ids(self, perms=None, name_filter=None, cache=False):
1304 """
1304 """
1305 Returns list of repository group ids that user have access to based on given
1305 Returns list of repository group ids that user have access to based on given
1306 perms. The cache flag should be only used in cases that are used for
1306 perms. The cache flag should be only used in cases that are used for
1307 display purposes, NOT IN ANY CASE for permission checks.
1307 display purposes, NOT IN ANY CASE for permission checks.
1308 """
1308 """
1309 from rhodecode.model.scm import RepoGroupList
1309 from rhodecode.model.scm import RepoGroupList
1310 if not perms:
1310 if not perms:
1311 perms = [
1311 perms = [
1312 'group.read', 'group.write', 'group.admin']
1312 'group.read', 'group.write', 'group.admin']
1313
1313
1314 def _cached_repo_group_acl(user_id, perm_def, _name_filter):
1314 def _cached_repo_group_acl(user_id, perm_def, _name_filter):
1315 qry = RepoGroup.query()
1315 qry = RepoGroup.query()
1316 if _name_filter:
1316 if _name_filter:
1317 ilike_expression = u'%{}%'.format(safe_unicode(_name_filter))
1317 ilike_expression = u'%{}%'.format(safe_unicode(_name_filter))
1318 qry = qry.filter(
1318 qry = qry.filter(
1319 RepoGroup.group_name.ilike(ilike_expression))
1319 RepoGroup.group_name.ilike(ilike_expression))
1320
1320
1321 return [x.group_id for x in
1321 return [x.group_id for x in
1322 RepoGroupList(qry, perm_set=perm_def)]
1322 RepoGroupList(qry, perm_set=perm_def)]
1323
1323
1324 return _cached_repo_group_acl(self.user_id, perms, name_filter)
1324 return _cached_repo_group_acl(self.user_id, perms, name_filter)
1325
1325
1326 def user_group_acl_ids(self, perms=None, name_filter=None, cache=False):
1326 def user_group_acl_ids(self, perms=None, name_filter=None, cache=False):
1327 """
1327 """
1328 Returns list of user group ids that user have access to based on given
1328 Returns list of user group ids that user have access to based on given
1329 perms. The cache flag should be only used in cases that are used for
1329 perms. The cache flag should be only used in cases that are used for
1330 display purposes, NOT IN ANY CASE for permission checks.
1330 display purposes, NOT IN ANY CASE for permission checks.
1331 """
1331 """
1332 from rhodecode.model.scm import UserGroupList
1332 from rhodecode.model.scm import UserGroupList
1333 if not perms:
1333 if not perms:
1334 perms = [
1334 perms = [
1335 'usergroup.read', 'usergroup.write', 'usergroup.admin']
1335 'usergroup.read', 'usergroup.write', 'usergroup.admin']
1336
1336
1337 def _cached_user_group_acl(user_id, perm_def, name_filter):
1337 def _cached_user_group_acl(user_id, perm_def, name_filter):
1338 qry = UserGroup.query()
1338 qry = UserGroup.query()
1339 if name_filter:
1339 if name_filter:
1340 ilike_expression = u'%{}%'.format(safe_unicode(name_filter))
1340 ilike_expression = u'%{}%'.format(safe_unicode(name_filter))
1341 qry = qry.filter(
1341 qry = qry.filter(
1342 UserGroup.users_group_name.ilike(ilike_expression))
1342 UserGroup.users_group_name.ilike(ilike_expression))
1343
1343
1344 return [x.users_group_id for x in
1344 return [x.users_group_id for x in
1345 UserGroupList(qry, perm_set=perm_def)]
1345 UserGroupList(qry, perm_set=perm_def)]
1346
1346
1347 return _cached_user_group_acl(self.user_id, perms, name_filter)
1347 return _cached_user_group_acl(self.user_id, perms, name_filter)
1348
1348
1349 @property
1349 @property
1350 def ip_allowed(self):
1350 def ip_allowed(self):
1351 """
1351 """
1352 Checks if ip_addr used in constructor is allowed from defined list of
1352 Checks if ip_addr used in constructor is allowed from defined list of
1353 allowed ip_addresses for user
1353 allowed ip_addresses for user
1354
1354
1355 :returns: boolean, True if ip is in allowed ip range
1355 :returns: boolean, True if ip is in allowed ip range
1356 """
1356 """
1357 # check IP
1357 # check IP
1358 inherit = self.inherit_default_permissions
1358 inherit = self.inherit_default_permissions
1359 return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
1359 return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
1360 inherit_from_default=inherit)
1360 inherit_from_default=inherit)
1361 @property
1361 @property
1362 def personal_repo_group(self):
1362 def personal_repo_group(self):
1363 return RepoGroup.get_user_personal_repo_group(self.user_id)
1363 return RepoGroup.get_user_personal_repo_group(self.user_id)
1364
1364
1365 @LazyProperty
1365 @LazyProperty
1366 def feed_token(self):
1366 def feed_token(self):
1367 return self.get_instance().feed_token
1367 return self.get_instance().feed_token
1368
1368
1369 @LazyProperty
1370 def artifact_token(self):
1371 return self.get_instance().artifact_token
1372
1369 @classmethod
1373 @classmethod
1370 def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
1374 def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
1371 allowed_ips = AuthUser.get_allowed_ips(
1375 allowed_ips = AuthUser.get_allowed_ips(
1372 user_id, cache=True, inherit_from_default=inherit_from_default)
1376 user_id, cache=True, inherit_from_default=inherit_from_default)
1373 if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
1377 if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
1374 log.debug('IP:%s for user %s is in range of %s',
1378 log.debug('IP:%s for user %s is in range of %s',
1375 ip_addr, user_id, allowed_ips)
1379 ip_addr, user_id, allowed_ips)
1376 return True
1380 return True
1377 else:
1381 else:
1378 log.info('Access for IP:%s forbidden for user %s, '
1382 log.info('Access for IP:%s forbidden for user %s, '
1379 'not in %s', ip_addr, user_id, allowed_ips)
1383 'not in %s', ip_addr, user_id, allowed_ips)
1380 return False
1384 return False
1381
1385
1382 def get_branch_permissions(self, repo_name, perms=None):
1386 def get_branch_permissions(self, repo_name, perms=None):
1383 perms = perms or self.permissions_with_scope({'repo_name': repo_name})
1387 perms = perms or self.permissions_with_scope({'repo_name': repo_name})
1384 branch_perms = perms.get('repository_branches', {})
1388 branch_perms = perms.get('repository_branches', {})
1385 if not branch_perms:
1389 if not branch_perms:
1386 return {}
1390 return {}
1387 repo_branch_perms = branch_perms.get(repo_name)
1391 repo_branch_perms = branch_perms.get(repo_name)
1388 return repo_branch_perms or {}
1392 return repo_branch_perms or {}
1389
1393
1390 def get_rule_and_branch_permission(self, repo_name, branch_name):
1394 def get_rule_and_branch_permission(self, repo_name, branch_name):
1391 """
1395 """
1392 Check if this AuthUser has defined any permissions for branches. If any of
1396 Check if this AuthUser has defined any permissions for branches. If any of
1393 the rules match in order, we return the matching permissions
1397 the rules match in order, we return the matching permissions
1394 """
1398 """
1395
1399
1396 rule = default_perm = ''
1400 rule = default_perm = ''
1397
1401
1398 repo_branch_perms = self.get_branch_permissions(repo_name=repo_name)
1402 repo_branch_perms = self.get_branch_permissions(repo_name=repo_name)
1399 if not repo_branch_perms:
1403 if not repo_branch_perms:
1400 return rule, default_perm
1404 return rule, default_perm
1401
1405
1402 # now calculate the permissions
1406 # now calculate the permissions
1403 for pattern, branch_perm in repo_branch_perms.items():
1407 for pattern, branch_perm in repo_branch_perms.items():
1404 if fnmatch.fnmatch(branch_name, pattern):
1408 if fnmatch.fnmatch(branch_name, pattern):
1405 rule = '`{}`=>{}'.format(pattern, branch_perm)
1409 rule = '`{}`=>{}'.format(pattern, branch_perm)
1406 return rule, branch_perm
1410 return rule, branch_perm
1407
1411
1408 return rule, default_perm
1412 return rule, default_perm
1409
1413
1410 def __repr__(self):
1414 def __repr__(self):
1411 return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
1415 return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
1412 % (self.user_id, self.username, self.ip_addr, self.is_authenticated)
1416 % (self.user_id, self.username, self.ip_addr, self.is_authenticated)
1413
1417
1414 def set_authenticated(self, authenticated=True):
1418 def set_authenticated(self, authenticated=True):
1415 if self.user_id != self.anonymous_user.user_id:
1419 if self.user_id != self.anonymous_user.user_id:
1416 self.is_authenticated = authenticated
1420 self.is_authenticated = authenticated
1417
1421
1418 def get_cookie_store(self):
1422 def get_cookie_store(self):
1419 return {
1423 return {
1420 'username': self.username,
1424 'username': self.username,
1421 'password': md5(self.password or ''),
1425 'password': md5(self.password or ''),
1422 'user_id': self.user_id,
1426 'user_id': self.user_id,
1423 'is_authenticated': self.is_authenticated
1427 'is_authenticated': self.is_authenticated
1424 }
1428 }
1425
1429
1426 @classmethod
1430 @classmethod
1427 def from_cookie_store(cls, cookie_store):
1431 def from_cookie_store(cls, cookie_store):
1428 """
1432 """
1429 Creates AuthUser from a cookie store
1433 Creates AuthUser from a cookie store
1430
1434
1431 :param cls:
1435 :param cls:
1432 :param cookie_store:
1436 :param cookie_store:
1433 """
1437 """
1434 user_id = cookie_store.get('user_id')
1438 user_id = cookie_store.get('user_id')
1435 username = cookie_store.get('username')
1439 username = cookie_store.get('username')
1436 api_key = cookie_store.get('api_key')
1440 api_key = cookie_store.get('api_key')
1437 return AuthUser(user_id, api_key, username)
1441 return AuthUser(user_id, api_key, username)
1438
1442
1439 @classmethod
1443 @classmethod
1440 def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
1444 def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
1441 _set = set()
1445 _set = set()
1442
1446
1443 if inherit_from_default:
1447 if inherit_from_default:
1444 def_user_id = User.get_default_user(cache=True).user_id
1448 def_user_id = User.get_default_user(cache=True).user_id
1445 default_ips = UserIpMap.query().filter(UserIpMap.user_id == def_user_id)
1449 default_ips = UserIpMap.query().filter(UserIpMap.user_id == def_user_id)
1446 if cache:
1450 if cache:
1447 default_ips = default_ips.options(
1451 default_ips = default_ips.options(
1448 FromCache("sql_cache_short", "get_user_ips_default"))
1452 FromCache("sql_cache_short", "get_user_ips_default"))
1449
1453
1450 # populate from default user
1454 # populate from default user
1451 for ip in default_ips:
1455 for ip in default_ips:
1452 try:
1456 try:
1453 _set.add(ip.ip_addr)
1457 _set.add(ip.ip_addr)
1454 except ObjectDeletedError:
1458 except ObjectDeletedError:
1455 # since we use heavy caching sometimes it happens that
1459 # since we use heavy caching sometimes it happens that
1456 # we get deleted objects here, we just skip them
1460 # we get deleted objects here, we just skip them
1457 pass
1461 pass
1458
1462
1459 # NOTE:(marcink) we don't want to load any rules for empty
1463 # NOTE:(marcink) we don't want to load any rules for empty
1460 # user_id which is the case of access of non logged users when anonymous
1464 # user_id which is the case of access of non logged users when anonymous
1461 # access is disabled
1465 # access is disabled
1462 user_ips = []
1466 user_ips = []
1463 if user_id:
1467 if user_id:
1464 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
1468 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
1465 if cache:
1469 if cache:
1466 user_ips = user_ips.options(
1470 user_ips = user_ips.options(
1467 FromCache("sql_cache_short", "get_user_ips_%s" % user_id))
1471 FromCache("sql_cache_short", "get_user_ips_%s" % user_id))
1468
1472
1469 for ip in user_ips:
1473 for ip in user_ips:
1470 try:
1474 try:
1471 _set.add(ip.ip_addr)
1475 _set.add(ip.ip_addr)
1472 except ObjectDeletedError:
1476 except ObjectDeletedError:
1473 # since we use heavy caching sometimes it happens that we get
1477 # since we use heavy caching sometimes it happens that we get
1474 # deleted objects here, we just skip them
1478 # deleted objects here, we just skip them
1475 pass
1479 pass
1476 return _set or {ip for ip in ['0.0.0.0/0', '::/0']}
1480 return _set or {ip for ip in ['0.0.0.0/0', '::/0']}
1477
1481
1478
1482
1479 def set_available_permissions(settings):
1483 def set_available_permissions(settings):
1480 """
1484 """
1481 This function will propagate pyramid settings with all available defined
1485 This function will propagate pyramid settings with all available defined
1482 permission given in db. We don't want to check each time from db for new
1486 permission given in db. We don't want to check each time from db for new
1483 permissions since adding a new permission also requires application restart
1487 permissions since adding a new permission also requires application restart
1484 ie. to decorate new views with the newly created permission
1488 ie. to decorate new views with the newly created permission
1485
1489
1486 :param settings: current pyramid registry.settings
1490 :param settings: current pyramid registry.settings
1487
1491
1488 """
1492 """
1489 log.debug('auth: getting information about all available permissions')
1493 log.debug('auth: getting information about all available permissions')
1490 try:
1494 try:
1491 sa = meta.Session
1495 sa = meta.Session
1492 all_perms = sa.query(Permission).all()
1496 all_perms = sa.query(Permission).all()
1493 settings.setdefault('available_permissions',
1497 settings.setdefault('available_permissions',
1494 [x.permission_name for x in all_perms])
1498 [x.permission_name for x in all_perms])
1495 log.debug('auth: set available permissions')
1499 log.debug('auth: set available permissions')
1496 except Exception:
1500 except Exception:
1497 log.exception('Failed to fetch permissions from the database.')
1501 log.exception('Failed to fetch permissions from the database.')
1498 raise
1502 raise
1499
1503
1500
1504
1501 def get_csrf_token(session, force_new=False, save_if_missing=True):
1505 def get_csrf_token(session, force_new=False, save_if_missing=True):
1502 """
1506 """
1503 Return the current authentication token, creating one if one doesn't
1507 Return the current authentication token, creating one if one doesn't
1504 already exist and the save_if_missing flag is present.
1508 already exist and the save_if_missing flag is present.
1505
1509
1506 :param session: pass in the pyramid session, else we use the global ones
1510 :param session: pass in the pyramid session, else we use the global ones
1507 :param force_new: force to re-generate the token and store it in session
1511 :param force_new: force to re-generate the token and store it in session
1508 :param save_if_missing: save the newly generated token if it's missing in
1512 :param save_if_missing: save the newly generated token if it's missing in
1509 session
1513 session
1510 """
1514 """
1511 # NOTE(marcink): probably should be replaced with below one from pyramid 1.9
1515 # NOTE(marcink): probably should be replaced with below one from pyramid 1.9
1512 # from pyramid.csrf import get_csrf_token
1516 # from pyramid.csrf import get_csrf_token
1513
1517
1514 if (csrf_token_key not in session and save_if_missing) or force_new:
1518 if (csrf_token_key not in session and save_if_missing) or force_new:
1515 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
1519 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
1516 session[csrf_token_key] = token
1520 session[csrf_token_key] = token
1517 if hasattr(session, 'save'):
1521 if hasattr(session, 'save'):
1518 session.save()
1522 session.save()
1519 return session.get(csrf_token_key)
1523 return session.get(csrf_token_key)
1520
1524
1521
1525
1522 def get_request(perm_class_instance):
1526 def get_request(perm_class_instance):
1523 from pyramid.threadlocal import get_current_request
1527 from pyramid.threadlocal import get_current_request
1524 pyramid_request = get_current_request()
1528 pyramid_request = get_current_request()
1525 return pyramid_request
1529 return pyramid_request
1526
1530
1527
1531
1528 # CHECK DECORATORS
1532 # CHECK DECORATORS
1529 class CSRFRequired(object):
1533 class CSRFRequired(object):
1530 """
1534 """
1531 Decorator for authenticating a form
1535 Decorator for authenticating a form
1532
1536
1533 This decorator uses an authorization token stored in the client's
1537 This decorator uses an authorization token stored in the client's
1534 session for prevention of certain Cross-site request forgery (CSRF)
1538 session for prevention of certain Cross-site request forgery (CSRF)
1535 attacks (See
1539 attacks (See
1536 http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
1540 http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
1537 information).
1541 information).
1538
1542
1539 For use with the ``webhelpers.secure_form`` helper functions.
1543 For use with the ``webhelpers.secure_form`` helper functions.
1540
1544
1541 """
1545 """
1542 def __init__(self, token=csrf_token_key, header='X-CSRF-Token',
1546 def __init__(self, token=csrf_token_key, header='X-CSRF-Token',
1543 except_methods=None):
1547 except_methods=None):
1544 self.token = token
1548 self.token = token
1545 self.header = header
1549 self.header = header
1546 self.except_methods = except_methods or []
1550 self.except_methods = except_methods or []
1547
1551
1548 def __call__(self, func):
1552 def __call__(self, func):
1549 return get_cython_compat_decorator(self.__wrapper, func)
1553 return get_cython_compat_decorator(self.__wrapper, func)
1550
1554
1551 def _get_csrf(self, _request):
1555 def _get_csrf(self, _request):
1552 return _request.POST.get(self.token, _request.headers.get(self.header))
1556 return _request.POST.get(self.token, _request.headers.get(self.header))
1553
1557
1554 def check_csrf(self, _request, cur_token):
1558 def check_csrf(self, _request, cur_token):
1555 supplied_token = self._get_csrf(_request)
1559 supplied_token = self._get_csrf(_request)
1556 return supplied_token and supplied_token == cur_token
1560 return supplied_token and supplied_token == cur_token
1557
1561
1558 def _get_request(self):
1562 def _get_request(self):
1559 return get_request(self)
1563 return get_request(self)
1560
1564
1561 def __wrapper(self, func, *fargs, **fkwargs):
1565 def __wrapper(self, func, *fargs, **fkwargs):
1562 request = self._get_request()
1566 request = self._get_request()
1563
1567
1564 if request.method in self.except_methods:
1568 if request.method in self.except_methods:
1565 return func(*fargs, **fkwargs)
1569 return func(*fargs, **fkwargs)
1566
1570
1567 cur_token = get_csrf_token(request.session, save_if_missing=False)
1571 cur_token = get_csrf_token(request.session, save_if_missing=False)
1568 if self.check_csrf(request, cur_token):
1572 if self.check_csrf(request, cur_token):
1569 if request.POST.get(self.token):
1573 if request.POST.get(self.token):
1570 del request.POST[self.token]
1574 del request.POST[self.token]
1571 return func(*fargs, **fkwargs)
1575 return func(*fargs, **fkwargs)
1572 else:
1576 else:
1573 reason = 'token-missing'
1577 reason = 'token-missing'
1574 supplied_token = self._get_csrf(request)
1578 supplied_token = self._get_csrf(request)
1575 if supplied_token and cur_token != supplied_token:
1579 if supplied_token and cur_token != supplied_token:
1576 reason = 'token-mismatch [%s:%s]' % (
1580 reason = 'token-mismatch [%s:%s]' % (
1577 cur_token or ''[:6], supplied_token or ''[:6])
1581 cur_token or ''[:6], supplied_token or ''[:6])
1578
1582
1579 csrf_message = \
1583 csrf_message = \
1580 ("Cross-site request forgery detected, request denied. See "
1584 ("Cross-site request forgery detected, request denied. See "
1581 "http://en.wikipedia.org/wiki/Cross-site_request_forgery for "
1585 "http://en.wikipedia.org/wiki/Cross-site_request_forgery for "
1582 "more information.")
1586 "more information.")
1583 log.warn('Cross-site request forgery detected, request %r DENIED: %s '
1587 log.warn('Cross-site request forgery detected, request %r DENIED: %s '
1584 'REMOTE_ADDR:%s, HEADERS:%s' % (
1588 'REMOTE_ADDR:%s, HEADERS:%s' % (
1585 request, reason, request.remote_addr, request.headers))
1589 request, reason, request.remote_addr, request.headers))
1586
1590
1587 raise HTTPForbidden(explanation=csrf_message)
1591 raise HTTPForbidden(explanation=csrf_message)
1588
1592
1589
1593
1590 class LoginRequired(object):
1594 class LoginRequired(object):
1591 """
1595 """
1592 Must be logged in to execute this function else
1596 Must be logged in to execute this function else
1593 redirect to login page
1597 redirect to login page
1594
1598
1595 :param api_access: if enabled this checks only for valid auth token
1599 :param api_access: if enabled this checks only for valid auth token
1596 and grants access based on valid token
1600 and grants access based on valid token
1597 """
1601 """
1598 def __init__(self, auth_token_access=None):
1602 def __init__(self, auth_token_access=None):
1599 self.auth_token_access = auth_token_access
1603 self.auth_token_access = auth_token_access
1604 if self.auth_token_access:
1605 valid_type = set(auth_token_access).intersection(set(UserApiKeys.ROLES))
1606 if not valid_type:
1607 raise ValueError('auth_token_access must be on of {}, got {}'.format(
1608 UserApiKeys.ROLES, auth_token_access))
1600
1609
1601 def __call__(self, func):
1610 def __call__(self, func):
1602 return get_cython_compat_decorator(self.__wrapper, func)
1611 return get_cython_compat_decorator(self.__wrapper, func)
1603
1612
1604 def _get_request(self):
1613 def _get_request(self):
1605 return get_request(self)
1614 return get_request(self)
1606
1615
1607 def __wrapper(self, func, *fargs, **fkwargs):
1616 def __wrapper(self, func, *fargs, **fkwargs):
1608 from rhodecode.lib import helpers as h
1617 from rhodecode.lib import helpers as h
1609 cls = fargs[0]
1618 cls = fargs[0]
1610 user = cls._rhodecode_user
1619 user = cls._rhodecode_user
1611 request = self._get_request()
1620 request = self._get_request()
1612 _ = request.translate
1621 _ = request.translate
1613
1622
1614 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1623 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1615 log.debug('Starting login restriction checks for user: %s', user)
1624 log.debug('Starting login restriction checks for user: %s', user)
1616 # check if our IP is allowed
1625 # check if our IP is allowed
1617 ip_access_valid = True
1626 ip_access_valid = True
1618 if not user.ip_allowed:
1627 if not user.ip_allowed:
1619 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1628 h.flash(h.literal(_('IP {} not allowed'.format(user.ip_addr))),
1620 category='warning')
1629 category='warning')
1621 ip_access_valid = False
1630 ip_access_valid = False
1622
1631
1623 # check if we used an APIKEY and it's a valid one
1632 # we used stored token that is extract from GET or URL param (if any)
1633 _auth_token = request.user_auth_token
1634
1635 # check if we used an AUTH_TOKEN and it's a valid one
1624 # defined white-list of controllers which API access will be enabled
1636 # defined white-list of controllers which API access will be enabled
1625 _auth_token = request.GET.get(
1637 whitelist = None
1626 'auth_token', '') or request.GET.get('api_key', '')
1638 if self.auth_token_access:
1639 # since this location is allowed by @LoginRequired decorator it's our
1640 # only whitelist
1641 whitelist = [loc]
1627 auth_token_access_valid = allowed_auth_token_access(
1642 auth_token_access_valid = allowed_auth_token_access(
1628 loc, auth_token=_auth_token)
1643 loc, whitelist=whitelist, auth_token=_auth_token)
1629
1644
1630 # explicit controller is enabled or API is in our whitelist
1645 # explicit controller is enabled or API is in our whitelist
1631 if self.auth_token_access or auth_token_access_valid:
1646 if auth_token_access_valid:
1632 log.debug('Checking AUTH TOKEN access for %s', cls)
1647 log.debug('Checking AUTH TOKEN access for %s', cls)
1633 db_user = user.get_instance()
1648 db_user = user.get_instance()
1634
1649
1635 if db_user:
1650 if db_user:
1636 if self.auth_token_access:
1651 if self.auth_token_access:
1637 roles = self.auth_token_access
1652 roles = self.auth_token_access
1638 else:
1653 else:
1639 roles = [UserApiKeys.ROLE_HTTP]
1654 roles = [UserApiKeys.ROLE_HTTP]
1655 log.debug('AUTH TOKEN: checking auth for user %s and roles %s',
1656 db_user, roles)
1640 token_match = db_user.authenticate_by_token(
1657 token_match = db_user.authenticate_by_token(
1641 _auth_token, roles=roles)
1658 _auth_token, roles=roles)
1642 else:
1659 else:
1643 log.debug('Unable to fetch db instance for auth user: %s', user)
1660 log.debug('Unable to fetch db instance for auth user: %s', user)
1644 token_match = False
1661 token_match = False
1645
1662
1646 if _auth_token and token_match:
1663 if _auth_token and token_match:
1647 auth_token_access_valid = True
1664 auth_token_access_valid = True
1648 log.debug('AUTH TOKEN ****%s is VALID', _auth_token[-4:])
1665 log.debug('AUTH TOKEN ****%s is VALID', _auth_token[-4:])
1649 else:
1666 else:
1650 auth_token_access_valid = False
1667 auth_token_access_valid = False
1651 if not _auth_token:
1668 if not _auth_token:
1652 log.debug("AUTH TOKEN *NOT* present in request")
1669 log.debug("AUTH TOKEN *NOT* present in request")
1653 else:
1670 else:
1654 log.warning("AUTH TOKEN ****%s *NOT* valid", _auth_token[-4:])
1671 log.warning("AUTH TOKEN ****%s *NOT* valid", _auth_token[-4:])
1655
1672
1656 log.debug('Checking if %s is authenticated @ %s', user.username, loc)
1673 log.debug('Checking if %s is authenticated @ %s', user.username, loc)
1657 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1674 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1658 else 'AUTH_TOKEN_AUTH'
1675 else 'AUTH_TOKEN_AUTH'
1659
1676
1660 if ip_access_valid and (
1677 if ip_access_valid and (
1661 user.is_authenticated or auth_token_access_valid):
1678 user.is_authenticated or auth_token_access_valid):
1662 log.info('user %s authenticating with:%s IS authenticated on func %s',
1679 log.info('user %s authenticating with:%s IS authenticated on func %s',
1663 user, reason, loc)
1680 user, reason, loc)
1664
1681
1665 return func(*fargs, **fkwargs)
1682 return func(*fargs, **fkwargs)
1666 else:
1683 else:
1667 log.warning(
1684 log.warning(
1668 'user %s authenticating with:%s NOT authenticated on '
1685 'user %s authenticating with:%s NOT authenticated on '
1669 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s',
1686 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s',
1670 user, reason, loc, ip_access_valid, auth_token_access_valid)
1687 user, reason, loc, ip_access_valid, auth_token_access_valid)
1671 # we preserve the get PARAM
1688 # we preserve the get PARAM
1672 came_from = get_came_from(request)
1689 came_from = get_came_from(request)
1673
1690
1674 log.debug('redirecting to login page with %s', came_from)
1691 log.debug('redirecting to login page with %s', came_from)
1675 raise HTTPFound(
1692 raise HTTPFound(
1676 h.route_path('login', _query={'came_from': came_from}))
1693 h.route_path('login', _query={'came_from': came_from}))
1677
1694
1678
1695
1679 class NotAnonymous(object):
1696 class NotAnonymous(object):
1680 """
1697 """
1681 Must be logged in to execute this function else
1698 Must be logged in to execute this function else
1682 redirect to login page
1699 redirect to login page
1683 """
1700 """
1684
1701
1685 def __call__(self, func):
1702 def __call__(self, func):
1686 return get_cython_compat_decorator(self.__wrapper, func)
1703 return get_cython_compat_decorator(self.__wrapper, func)
1687
1704
1688 def _get_request(self):
1705 def _get_request(self):
1689 return get_request(self)
1706 return get_request(self)
1690
1707
1691 def __wrapper(self, func, *fargs, **fkwargs):
1708 def __wrapper(self, func, *fargs, **fkwargs):
1692 import rhodecode.lib.helpers as h
1709 import rhodecode.lib.helpers as h
1693 cls = fargs[0]
1710 cls = fargs[0]
1694 self.user = cls._rhodecode_user
1711 self.user = cls._rhodecode_user
1695 request = self._get_request()
1712 request = self._get_request()
1696 _ = request.translate
1713 _ = request.translate
1697 log.debug('Checking if user is not anonymous @%s', cls)
1714 log.debug('Checking if user is not anonymous @%s', cls)
1698
1715
1699 anonymous = self.user.username == User.DEFAULT_USER
1716 anonymous = self.user.username == User.DEFAULT_USER
1700
1717
1701 if anonymous:
1718 if anonymous:
1702 came_from = get_came_from(request)
1719 came_from = get_came_from(request)
1703 h.flash(_('You need to be a registered user to '
1720 h.flash(_('You need to be a registered user to '
1704 'perform this action'),
1721 'perform this action'),
1705 category='warning')
1722 category='warning')
1706 raise HTTPFound(
1723 raise HTTPFound(
1707 h.route_path('login', _query={'came_from': came_from}))
1724 h.route_path('login', _query={'came_from': came_from}))
1708 else:
1725 else:
1709 return func(*fargs, **fkwargs)
1726 return func(*fargs, **fkwargs)
1710
1727
1711
1728
1712 class PermsDecorator(object):
1729 class PermsDecorator(object):
1713 """
1730 """
1714 Base class for controller decorators, we extract the current user from
1731 Base class for controller decorators, we extract the current user from
1715 the class itself, which has it stored in base controllers
1732 the class itself, which has it stored in base controllers
1716 """
1733 """
1717
1734
1718 def __init__(self, *required_perms):
1735 def __init__(self, *required_perms):
1719 self.required_perms = set(required_perms)
1736 self.required_perms = set(required_perms)
1720
1737
1721 def __call__(self, func):
1738 def __call__(self, func):
1722 return get_cython_compat_decorator(self.__wrapper, func)
1739 return get_cython_compat_decorator(self.__wrapper, func)
1723
1740
1724 def _get_request(self):
1741 def _get_request(self):
1725 return get_request(self)
1742 return get_request(self)
1726
1743
1727 def __wrapper(self, func, *fargs, **fkwargs):
1744 def __wrapper(self, func, *fargs, **fkwargs):
1728 import rhodecode.lib.helpers as h
1745 import rhodecode.lib.helpers as h
1729 cls = fargs[0]
1746 cls = fargs[0]
1730 _user = cls._rhodecode_user
1747 _user = cls._rhodecode_user
1731 request = self._get_request()
1748 request = self._get_request()
1732 _ = request.translate
1749 _ = request.translate
1733
1750
1734 log.debug('checking %s permissions %s for %s %s',
1751 log.debug('checking %s permissions %s for %s %s',
1735 self.__class__.__name__, self.required_perms, cls, _user)
1752 self.__class__.__name__, self.required_perms, cls, _user)
1736
1753
1737 if self.check_permissions(_user):
1754 if self.check_permissions(_user):
1738 log.debug('Permission granted for %s %s', cls, _user)
1755 log.debug('Permission granted for %s %s', cls, _user)
1739 return func(*fargs, **fkwargs)
1756 return func(*fargs, **fkwargs)
1740
1757
1741 else:
1758 else:
1742 log.debug('Permission denied for %s %s', cls, _user)
1759 log.debug('Permission denied for %s %s', cls, _user)
1743 anonymous = _user.username == User.DEFAULT_USER
1760 anonymous = _user.username == User.DEFAULT_USER
1744
1761
1745 if anonymous:
1762 if anonymous:
1746 came_from = get_came_from(self._get_request())
1763 came_from = get_came_from(self._get_request())
1747 h.flash(_('You need to be signed in to view this page'),
1764 h.flash(_('You need to be signed in to view this page'),
1748 category='warning')
1765 category='warning')
1749 raise HTTPFound(
1766 raise HTTPFound(
1750 h.route_path('login', _query={'came_from': came_from}))
1767 h.route_path('login', _query={'came_from': came_from}))
1751
1768
1752 else:
1769 else:
1753 # redirect with 404 to prevent resource discovery
1770 # redirect with 404 to prevent resource discovery
1754 raise HTTPNotFound()
1771 raise HTTPNotFound()
1755
1772
1756 def check_permissions(self, user):
1773 def check_permissions(self, user):
1757 """Dummy function for overriding"""
1774 """Dummy function for overriding"""
1758 raise NotImplementedError(
1775 raise NotImplementedError(
1759 'You have to write this function in child class')
1776 'You have to write this function in child class')
1760
1777
1761
1778
1762 class HasPermissionAllDecorator(PermsDecorator):
1779 class HasPermissionAllDecorator(PermsDecorator):
1763 """
1780 """
1764 Checks for access permission for all given predicates. All of them
1781 Checks for access permission for all given predicates. All of them
1765 have to be meet in order to fulfill the request
1782 have to be meet in order to fulfill the request
1766 """
1783 """
1767
1784
1768 def check_permissions(self, user):
1785 def check_permissions(self, user):
1769 perms = user.permissions_with_scope({})
1786 perms = user.permissions_with_scope({})
1770 if self.required_perms.issubset(perms['global']):
1787 if self.required_perms.issubset(perms['global']):
1771 return True
1788 return True
1772 return False
1789 return False
1773
1790
1774
1791
1775 class HasPermissionAnyDecorator(PermsDecorator):
1792 class HasPermissionAnyDecorator(PermsDecorator):
1776 """
1793 """
1777 Checks for access permission for any of given predicates. In order to
1794 Checks for access permission for any of given predicates. In order to
1778 fulfill the request any of predicates must be meet
1795 fulfill the request any of predicates must be meet
1779 """
1796 """
1780
1797
1781 def check_permissions(self, user):
1798 def check_permissions(self, user):
1782 perms = user.permissions_with_scope({})
1799 perms = user.permissions_with_scope({})
1783 if self.required_perms.intersection(perms['global']):
1800 if self.required_perms.intersection(perms['global']):
1784 return True
1801 return True
1785 return False
1802 return False
1786
1803
1787
1804
1788 class HasRepoPermissionAllDecorator(PermsDecorator):
1805 class HasRepoPermissionAllDecorator(PermsDecorator):
1789 """
1806 """
1790 Checks for access permission for all given predicates for specific
1807 Checks for access permission for all given predicates for specific
1791 repository. All of them have to be meet in order to fulfill the request
1808 repository. All of them have to be meet in order to fulfill the request
1792 """
1809 """
1793 def _get_repo_name(self):
1810 def _get_repo_name(self):
1794 _request = self._get_request()
1811 _request = self._get_request()
1795 return get_repo_slug(_request)
1812 return get_repo_slug(_request)
1796
1813
1797 def check_permissions(self, user):
1814 def check_permissions(self, user):
1798 perms = user.permissions
1815 perms = user.permissions
1799 repo_name = self._get_repo_name()
1816 repo_name = self._get_repo_name()
1800
1817
1801 try:
1818 try:
1802 user_perms = {perms['repositories'][repo_name]}
1819 user_perms = {perms['repositories'][repo_name]}
1803 except KeyError:
1820 except KeyError:
1804 log.debug('cannot locate repo with name: `%s` in permissions defs',
1821 log.debug('cannot locate repo with name: `%s` in permissions defs',
1805 repo_name)
1822 repo_name)
1806 return False
1823 return False
1807
1824
1808 log.debug('checking `%s` permissions for repo `%s`',
1825 log.debug('checking `%s` permissions for repo `%s`',
1809 user_perms, repo_name)
1826 user_perms, repo_name)
1810 if self.required_perms.issubset(user_perms):
1827 if self.required_perms.issubset(user_perms):
1811 return True
1828 return True
1812 return False
1829 return False
1813
1830
1814
1831
1815 class HasRepoPermissionAnyDecorator(PermsDecorator):
1832 class HasRepoPermissionAnyDecorator(PermsDecorator):
1816 """
1833 """
1817 Checks for access permission for any of given predicates for specific
1834 Checks for access permission for any of given predicates for specific
1818 repository. In order to fulfill the request any of predicates must be meet
1835 repository. In order to fulfill the request any of predicates must be meet
1819 """
1836 """
1820 def _get_repo_name(self):
1837 def _get_repo_name(self):
1821 _request = self._get_request()
1838 _request = self._get_request()
1822 return get_repo_slug(_request)
1839 return get_repo_slug(_request)
1823
1840
1824 def check_permissions(self, user):
1841 def check_permissions(self, user):
1825 perms = user.permissions
1842 perms = user.permissions
1826 repo_name = self._get_repo_name()
1843 repo_name = self._get_repo_name()
1827
1844
1828 try:
1845 try:
1829 user_perms = {perms['repositories'][repo_name]}
1846 user_perms = {perms['repositories'][repo_name]}
1830 except KeyError:
1847 except KeyError:
1831 log.debug(
1848 log.debug(
1832 'cannot locate repo with name: `%s` in permissions defs',
1849 'cannot locate repo with name: `%s` in permissions defs',
1833 repo_name)
1850 repo_name)
1834 return False
1851 return False
1835
1852
1836 log.debug('checking `%s` permissions for repo `%s`',
1853 log.debug('checking `%s` permissions for repo `%s`',
1837 user_perms, repo_name)
1854 user_perms, repo_name)
1838 if self.required_perms.intersection(user_perms):
1855 if self.required_perms.intersection(user_perms):
1839 return True
1856 return True
1840 return False
1857 return False
1841
1858
1842
1859
1843 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1860 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1844 """
1861 """
1845 Checks for access permission for all given predicates for specific
1862 Checks for access permission for all given predicates for specific
1846 repository group. All of them have to be meet in order to
1863 repository group. All of them have to be meet in order to
1847 fulfill the request
1864 fulfill the request
1848 """
1865 """
1849 def _get_repo_group_name(self):
1866 def _get_repo_group_name(self):
1850 _request = self._get_request()
1867 _request = self._get_request()
1851 return get_repo_group_slug(_request)
1868 return get_repo_group_slug(_request)
1852
1869
1853 def check_permissions(self, user):
1870 def check_permissions(self, user):
1854 perms = user.permissions
1871 perms = user.permissions
1855 group_name = self._get_repo_group_name()
1872 group_name = self._get_repo_group_name()
1856 try:
1873 try:
1857 user_perms = {perms['repositories_groups'][group_name]}
1874 user_perms = {perms['repositories_groups'][group_name]}
1858 except KeyError:
1875 except KeyError:
1859 log.debug(
1876 log.debug(
1860 'cannot locate repo group with name: `%s` in permissions defs',
1877 'cannot locate repo group with name: `%s` in permissions defs',
1861 group_name)
1878 group_name)
1862 return False
1879 return False
1863
1880
1864 log.debug('checking `%s` permissions for repo group `%s`',
1881 log.debug('checking `%s` permissions for repo group `%s`',
1865 user_perms, group_name)
1882 user_perms, group_name)
1866 if self.required_perms.issubset(user_perms):
1883 if self.required_perms.issubset(user_perms):
1867 return True
1884 return True
1868 return False
1885 return False
1869
1886
1870
1887
1871 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1888 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1872 """
1889 """
1873 Checks for access permission for any of given predicates for specific
1890 Checks for access permission for any of given predicates for specific
1874 repository group. In order to fulfill the request any
1891 repository group. In order to fulfill the request any
1875 of predicates must be met
1892 of predicates must be met
1876 """
1893 """
1877 def _get_repo_group_name(self):
1894 def _get_repo_group_name(self):
1878 _request = self._get_request()
1895 _request = self._get_request()
1879 return get_repo_group_slug(_request)
1896 return get_repo_group_slug(_request)
1880
1897
1881 def check_permissions(self, user):
1898 def check_permissions(self, user):
1882 perms = user.permissions
1899 perms = user.permissions
1883 group_name = self._get_repo_group_name()
1900 group_name = self._get_repo_group_name()
1884
1901
1885 try:
1902 try:
1886 user_perms = {perms['repositories_groups'][group_name]}
1903 user_perms = {perms['repositories_groups'][group_name]}
1887 except KeyError:
1904 except KeyError:
1888 log.debug(
1905 log.debug(
1889 'cannot locate repo group with name: `%s` in permissions defs',
1906 'cannot locate repo group with name: `%s` in permissions defs',
1890 group_name)
1907 group_name)
1891 return False
1908 return False
1892
1909
1893 log.debug('checking `%s` permissions for repo group `%s`',
1910 log.debug('checking `%s` permissions for repo group `%s`',
1894 user_perms, group_name)
1911 user_perms, group_name)
1895 if self.required_perms.intersection(user_perms):
1912 if self.required_perms.intersection(user_perms):
1896 return True
1913 return True
1897 return False
1914 return False
1898
1915
1899
1916
1900 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1917 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1901 """
1918 """
1902 Checks for access permission for all given predicates for specific
1919 Checks for access permission for all given predicates for specific
1903 user group. All of them have to be meet in order to fulfill the request
1920 user group. All of them have to be meet in order to fulfill the request
1904 """
1921 """
1905 def _get_user_group_name(self):
1922 def _get_user_group_name(self):
1906 _request = self._get_request()
1923 _request = self._get_request()
1907 return get_user_group_slug(_request)
1924 return get_user_group_slug(_request)
1908
1925
1909 def check_permissions(self, user):
1926 def check_permissions(self, user):
1910 perms = user.permissions
1927 perms = user.permissions
1911 group_name = self._get_user_group_name()
1928 group_name = self._get_user_group_name()
1912 try:
1929 try:
1913 user_perms = {perms['user_groups'][group_name]}
1930 user_perms = {perms['user_groups'][group_name]}
1914 except KeyError:
1931 except KeyError:
1915 return False
1932 return False
1916
1933
1917 if self.required_perms.issubset(user_perms):
1934 if self.required_perms.issubset(user_perms):
1918 return True
1935 return True
1919 return False
1936 return False
1920
1937
1921
1938
1922 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1939 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1923 """
1940 """
1924 Checks for access permission for any of given predicates for specific
1941 Checks for access permission for any of given predicates for specific
1925 user group. In order to fulfill the request any of predicates must be meet
1942 user group. In order to fulfill the request any of predicates must be meet
1926 """
1943 """
1927 def _get_user_group_name(self):
1944 def _get_user_group_name(self):
1928 _request = self._get_request()
1945 _request = self._get_request()
1929 return get_user_group_slug(_request)
1946 return get_user_group_slug(_request)
1930
1947
1931 def check_permissions(self, user):
1948 def check_permissions(self, user):
1932 perms = user.permissions
1949 perms = user.permissions
1933 group_name = self._get_user_group_name()
1950 group_name = self._get_user_group_name()
1934 try:
1951 try:
1935 user_perms = {perms['user_groups'][group_name]}
1952 user_perms = {perms['user_groups'][group_name]}
1936 except KeyError:
1953 except KeyError:
1937 return False
1954 return False
1938
1955
1939 if self.required_perms.intersection(user_perms):
1956 if self.required_perms.intersection(user_perms):
1940 return True
1957 return True
1941 return False
1958 return False
1942
1959
1943
1960
1944 # CHECK FUNCTIONS
1961 # CHECK FUNCTIONS
1945 class PermsFunction(object):
1962 class PermsFunction(object):
1946 """Base function for other check functions"""
1963 """Base function for other check functions"""
1947
1964
1948 def __init__(self, *perms):
1965 def __init__(self, *perms):
1949 self.required_perms = set(perms)
1966 self.required_perms = set(perms)
1950 self.repo_name = None
1967 self.repo_name = None
1951 self.repo_group_name = None
1968 self.repo_group_name = None
1952 self.user_group_name = None
1969 self.user_group_name = None
1953
1970
1954 def __bool__(self):
1971 def __bool__(self):
1955 frame = inspect.currentframe()
1972 frame = inspect.currentframe()
1956 stack_trace = traceback.format_stack(frame)
1973 stack_trace = traceback.format_stack(frame)
1957 log.error('Checking bool value on a class instance of perm '
1974 log.error('Checking bool value on a class instance of perm '
1958 'function is not allowed: %s', ''.join(stack_trace))
1975 'function is not allowed: %s', ''.join(stack_trace))
1959 # rather than throwing errors, here we always return False so if by
1976 # rather than throwing errors, here we always return False so if by
1960 # accident someone checks truth for just an instance it will always end
1977 # accident someone checks truth for just an instance it will always end
1961 # up in returning False
1978 # up in returning False
1962 return False
1979 return False
1963 __nonzero__ = __bool__
1980 __nonzero__ = __bool__
1964
1981
1965 def __call__(self, check_location='', user=None):
1982 def __call__(self, check_location='', user=None):
1966 if not user:
1983 if not user:
1967 log.debug('Using user attribute from global request')
1984 log.debug('Using user attribute from global request')
1968 request = self._get_request()
1985 request = self._get_request()
1969 user = request.user
1986 user = request.user
1970
1987
1971 # init auth user if not already given
1988 # init auth user if not already given
1972 if not isinstance(user, AuthUser):
1989 if not isinstance(user, AuthUser):
1973 log.debug('Wrapping user %s into AuthUser', user)
1990 log.debug('Wrapping user %s into AuthUser', user)
1974 user = AuthUser(user.user_id)
1991 user = AuthUser(user.user_id)
1975
1992
1976 cls_name = self.__class__.__name__
1993 cls_name = self.__class__.__name__
1977 check_scope = self._get_check_scope(cls_name)
1994 check_scope = self._get_check_scope(cls_name)
1978 check_location = check_location or 'unspecified location'
1995 check_location = check_location or 'unspecified location'
1979
1996
1980 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1997 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1981 self.required_perms, user, check_scope, check_location)
1998 self.required_perms, user, check_scope, check_location)
1982 if not user:
1999 if not user:
1983 log.warning('Empty user given for permission check')
2000 log.warning('Empty user given for permission check')
1984 return False
2001 return False
1985
2002
1986 if self.check_permissions(user):
2003 if self.check_permissions(user):
1987 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
2004 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1988 check_scope, user, check_location)
2005 check_scope, user, check_location)
1989 return True
2006 return True
1990
2007
1991 else:
2008 else:
1992 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
2009 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1993 check_scope, user, check_location)
2010 check_scope, user, check_location)
1994 return False
2011 return False
1995
2012
1996 def _get_request(self):
2013 def _get_request(self):
1997 return get_request(self)
2014 return get_request(self)
1998
2015
1999 def _get_check_scope(self, cls_name):
2016 def _get_check_scope(self, cls_name):
2000 return {
2017 return {
2001 'HasPermissionAll': 'GLOBAL',
2018 'HasPermissionAll': 'GLOBAL',
2002 'HasPermissionAny': 'GLOBAL',
2019 'HasPermissionAny': 'GLOBAL',
2003 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
2020 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
2004 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
2021 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
2005 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
2022 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
2006 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
2023 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
2007 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
2024 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
2008 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
2025 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
2009 }.get(cls_name, '?:%s' % cls_name)
2026 }.get(cls_name, '?:%s' % cls_name)
2010
2027
2011 def check_permissions(self, user):
2028 def check_permissions(self, user):
2012 """Dummy function for overriding"""
2029 """Dummy function for overriding"""
2013 raise Exception('You have to write this function in child class')
2030 raise Exception('You have to write this function in child class')
2014
2031
2015
2032
2016 class HasPermissionAll(PermsFunction):
2033 class HasPermissionAll(PermsFunction):
2017 def check_permissions(self, user):
2034 def check_permissions(self, user):
2018 perms = user.permissions_with_scope({})
2035 perms = user.permissions_with_scope({})
2019 if self.required_perms.issubset(perms.get('global')):
2036 if self.required_perms.issubset(perms.get('global')):
2020 return True
2037 return True
2021 return False
2038 return False
2022
2039
2023
2040
2024 class HasPermissionAny(PermsFunction):
2041 class HasPermissionAny(PermsFunction):
2025 def check_permissions(self, user):
2042 def check_permissions(self, user):
2026 perms = user.permissions_with_scope({})
2043 perms = user.permissions_with_scope({})
2027 if self.required_perms.intersection(perms.get('global')):
2044 if self.required_perms.intersection(perms.get('global')):
2028 return True
2045 return True
2029 return False
2046 return False
2030
2047
2031
2048
2032 class HasRepoPermissionAll(PermsFunction):
2049 class HasRepoPermissionAll(PermsFunction):
2033 def __call__(self, repo_name=None, check_location='', user=None):
2050 def __call__(self, repo_name=None, check_location='', user=None):
2034 self.repo_name = repo_name
2051 self.repo_name = repo_name
2035 return super(HasRepoPermissionAll, self).__call__(check_location, user)
2052 return super(HasRepoPermissionAll, self).__call__(check_location, user)
2036
2053
2037 def _get_repo_name(self):
2054 def _get_repo_name(self):
2038 if not self.repo_name:
2055 if not self.repo_name:
2039 _request = self._get_request()
2056 _request = self._get_request()
2040 self.repo_name = get_repo_slug(_request)
2057 self.repo_name = get_repo_slug(_request)
2041 return self.repo_name
2058 return self.repo_name
2042
2059
2043 def check_permissions(self, user):
2060 def check_permissions(self, user):
2044 self.repo_name = self._get_repo_name()
2061 self.repo_name = self._get_repo_name()
2045 perms = user.permissions
2062 perms = user.permissions
2046 try:
2063 try:
2047 user_perms = {perms['repositories'][self.repo_name]}
2064 user_perms = {perms['repositories'][self.repo_name]}
2048 except KeyError:
2065 except KeyError:
2049 return False
2066 return False
2050 if self.required_perms.issubset(user_perms):
2067 if self.required_perms.issubset(user_perms):
2051 return True
2068 return True
2052 return False
2069 return False
2053
2070
2054
2071
2055 class HasRepoPermissionAny(PermsFunction):
2072 class HasRepoPermissionAny(PermsFunction):
2056 def __call__(self, repo_name=None, check_location='', user=None):
2073 def __call__(self, repo_name=None, check_location='', user=None):
2057 self.repo_name = repo_name
2074 self.repo_name = repo_name
2058 return super(HasRepoPermissionAny, self).__call__(check_location, user)
2075 return super(HasRepoPermissionAny, self).__call__(check_location, user)
2059
2076
2060 def _get_repo_name(self):
2077 def _get_repo_name(self):
2061 if not self.repo_name:
2078 if not self.repo_name:
2062 _request = self._get_request()
2079 _request = self._get_request()
2063 self.repo_name = get_repo_slug(_request)
2080 self.repo_name = get_repo_slug(_request)
2064 return self.repo_name
2081 return self.repo_name
2065
2082
2066 def check_permissions(self, user):
2083 def check_permissions(self, user):
2067 self.repo_name = self._get_repo_name()
2084 self.repo_name = self._get_repo_name()
2068 perms = user.permissions
2085 perms = user.permissions
2069 try:
2086 try:
2070 user_perms = {perms['repositories'][self.repo_name]}
2087 user_perms = {perms['repositories'][self.repo_name]}
2071 except KeyError:
2088 except KeyError:
2072 return False
2089 return False
2073 if self.required_perms.intersection(user_perms):
2090 if self.required_perms.intersection(user_perms):
2074 return True
2091 return True
2075 return False
2092 return False
2076
2093
2077
2094
2078 class HasRepoGroupPermissionAny(PermsFunction):
2095 class HasRepoGroupPermissionAny(PermsFunction):
2079 def __call__(self, group_name=None, check_location='', user=None):
2096 def __call__(self, group_name=None, check_location='', user=None):
2080 self.repo_group_name = group_name
2097 self.repo_group_name = group_name
2081 return super(HasRepoGroupPermissionAny, self).__call__(check_location, user)
2098 return super(HasRepoGroupPermissionAny, self).__call__(check_location, user)
2082
2099
2083 def check_permissions(self, user):
2100 def check_permissions(self, user):
2084 perms = user.permissions
2101 perms = user.permissions
2085 try:
2102 try:
2086 user_perms = {perms['repositories_groups'][self.repo_group_name]}
2103 user_perms = {perms['repositories_groups'][self.repo_group_name]}
2087 except KeyError:
2104 except KeyError:
2088 return False
2105 return False
2089 if self.required_perms.intersection(user_perms):
2106 if self.required_perms.intersection(user_perms):
2090 return True
2107 return True
2091 return False
2108 return False
2092
2109
2093
2110
2094 class HasRepoGroupPermissionAll(PermsFunction):
2111 class HasRepoGroupPermissionAll(PermsFunction):
2095 def __call__(self, group_name=None, check_location='', user=None):
2112 def __call__(self, group_name=None, check_location='', user=None):
2096 self.repo_group_name = group_name
2113 self.repo_group_name = group_name
2097 return super(HasRepoGroupPermissionAll, self).__call__(check_location, user)
2114 return super(HasRepoGroupPermissionAll, self).__call__(check_location, user)
2098
2115
2099 def check_permissions(self, user):
2116 def check_permissions(self, user):
2100 perms = user.permissions
2117 perms = user.permissions
2101 try:
2118 try:
2102 user_perms = {perms['repositories_groups'][self.repo_group_name]}
2119 user_perms = {perms['repositories_groups'][self.repo_group_name]}
2103 except KeyError:
2120 except KeyError:
2104 return False
2121 return False
2105 if self.required_perms.issubset(user_perms):
2122 if self.required_perms.issubset(user_perms):
2106 return True
2123 return True
2107 return False
2124 return False
2108
2125
2109
2126
2110 class HasUserGroupPermissionAny(PermsFunction):
2127 class HasUserGroupPermissionAny(PermsFunction):
2111 def __call__(self, user_group_name=None, check_location='', user=None):
2128 def __call__(self, user_group_name=None, check_location='', user=None):
2112 self.user_group_name = user_group_name
2129 self.user_group_name = user_group_name
2113 return super(HasUserGroupPermissionAny, self).__call__(check_location, user)
2130 return super(HasUserGroupPermissionAny, self).__call__(check_location, user)
2114
2131
2115 def check_permissions(self, user):
2132 def check_permissions(self, user):
2116 perms = user.permissions
2133 perms = user.permissions
2117 try:
2134 try:
2118 user_perms = {perms['user_groups'][self.user_group_name]}
2135 user_perms = {perms['user_groups'][self.user_group_name]}
2119 except KeyError:
2136 except KeyError:
2120 return False
2137 return False
2121 if self.required_perms.intersection(user_perms):
2138 if self.required_perms.intersection(user_perms):
2122 return True
2139 return True
2123 return False
2140 return False
2124
2141
2125
2142
2126 class HasUserGroupPermissionAll(PermsFunction):
2143 class HasUserGroupPermissionAll(PermsFunction):
2127 def __call__(self, user_group_name=None, check_location='', user=None):
2144 def __call__(self, user_group_name=None, check_location='', user=None):
2128 self.user_group_name = user_group_name
2145 self.user_group_name = user_group_name
2129 return super(HasUserGroupPermissionAll, self).__call__(check_location, user)
2146 return super(HasUserGroupPermissionAll, self).__call__(check_location, user)
2130
2147
2131 def check_permissions(self, user):
2148 def check_permissions(self, user):
2132 perms = user.permissions
2149 perms = user.permissions
2133 try:
2150 try:
2134 user_perms = {perms['user_groups'][self.user_group_name]}
2151 user_perms = {perms['user_groups'][self.user_group_name]}
2135 except KeyError:
2152 except KeyError:
2136 return False
2153 return False
2137 if self.required_perms.issubset(user_perms):
2154 if self.required_perms.issubset(user_perms):
2138 return True
2155 return True
2139 return False
2156 return False
2140
2157
2141
2158
2142 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
2159 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
2143 class HasPermissionAnyMiddleware(object):
2160 class HasPermissionAnyMiddleware(object):
2144 def __init__(self, *perms):
2161 def __init__(self, *perms):
2145 self.required_perms = set(perms)
2162 self.required_perms = set(perms)
2146
2163
2147 def __call__(self, auth_user, repo_name):
2164 def __call__(self, auth_user, repo_name):
2148 # repo_name MUST be unicode, since we handle keys in permission
2165 # repo_name MUST be unicode, since we handle keys in permission
2149 # dict by unicode
2166 # dict by unicode
2150 repo_name = safe_unicode(repo_name)
2167 repo_name = safe_unicode(repo_name)
2151 log.debug(
2168 log.debug(
2152 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
2169 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
2153 self.required_perms, auth_user, repo_name)
2170 self.required_perms, auth_user, repo_name)
2154
2171
2155 if self.check_permissions(auth_user, repo_name):
2172 if self.check_permissions(auth_user, repo_name):
2156 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
2173 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
2157 repo_name, auth_user, 'PermissionMiddleware')
2174 repo_name, auth_user, 'PermissionMiddleware')
2158 return True
2175 return True
2159
2176
2160 else:
2177 else:
2161 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
2178 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
2162 repo_name, auth_user, 'PermissionMiddleware')
2179 repo_name, auth_user, 'PermissionMiddleware')
2163 return False
2180 return False
2164
2181
2165 def check_permissions(self, user, repo_name):
2182 def check_permissions(self, user, repo_name):
2166 perms = user.permissions_with_scope({'repo_name': repo_name})
2183 perms = user.permissions_with_scope({'repo_name': repo_name})
2167
2184
2168 try:
2185 try:
2169 user_perms = {perms['repositories'][repo_name]}
2186 user_perms = {perms['repositories'][repo_name]}
2170 except Exception:
2187 except Exception:
2171 log.exception('Error while accessing user permissions')
2188 log.exception('Error while accessing user permissions')
2172 return False
2189 return False
2173
2190
2174 if self.required_perms.intersection(user_perms):
2191 if self.required_perms.intersection(user_perms):
2175 return True
2192 return True
2176 return False
2193 return False
2177
2194
2178
2195
2179 # SPECIAL VERSION TO HANDLE API AUTH
2196 # SPECIAL VERSION TO HANDLE API AUTH
2180 class _BaseApiPerm(object):
2197 class _BaseApiPerm(object):
2181 def __init__(self, *perms):
2198 def __init__(self, *perms):
2182 self.required_perms = set(perms)
2199 self.required_perms = set(perms)
2183
2200
2184 def __call__(self, check_location=None, user=None, repo_name=None,
2201 def __call__(self, check_location=None, user=None, repo_name=None,
2185 group_name=None, user_group_name=None):
2202 group_name=None, user_group_name=None):
2186 cls_name = self.__class__.__name__
2203 cls_name = self.__class__.__name__
2187 check_scope = 'global:%s' % (self.required_perms,)
2204 check_scope = 'global:%s' % (self.required_perms,)
2188 if repo_name:
2205 if repo_name:
2189 check_scope += ', repo_name:%s' % (repo_name,)
2206 check_scope += ', repo_name:%s' % (repo_name,)
2190
2207
2191 if group_name:
2208 if group_name:
2192 check_scope += ', repo_group_name:%s' % (group_name,)
2209 check_scope += ', repo_group_name:%s' % (group_name,)
2193
2210
2194 if user_group_name:
2211 if user_group_name:
2195 check_scope += ', user_group_name:%s' % (user_group_name,)
2212 check_scope += ', user_group_name:%s' % (user_group_name,)
2196
2213
2197 log.debug('checking cls:%s %s %s @ %s',
2214 log.debug('checking cls:%s %s %s @ %s',
2198 cls_name, self.required_perms, check_scope, check_location)
2215 cls_name, self.required_perms, check_scope, check_location)
2199 if not user:
2216 if not user:
2200 log.debug('Empty User passed into arguments')
2217 log.debug('Empty User passed into arguments')
2201 return False
2218 return False
2202
2219
2203 # process user
2220 # process user
2204 if not isinstance(user, AuthUser):
2221 if not isinstance(user, AuthUser):
2205 user = AuthUser(user.user_id)
2222 user = AuthUser(user.user_id)
2206 if not check_location:
2223 if not check_location:
2207 check_location = 'unspecified'
2224 check_location = 'unspecified'
2208 if self.check_permissions(user.permissions, repo_name, group_name,
2225 if self.check_permissions(user.permissions, repo_name, group_name,
2209 user_group_name):
2226 user_group_name):
2210 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
2227 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
2211 check_scope, user, check_location)
2228 check_scope, user, check_location)
2212 return True
2229 return True
2213
2230
2214 else:
2231 else:
2215 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
2232 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
2216 check_scope, user, check_location)
2233 check_scope, user, check_location)
2217 return False
2234 return False
2218
2235
2219 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2236 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2220 user_group_name=None):
2237 user_group_name=None):
2221 """
2238 """
2222 implement in child class should return True if permissions are ok,
2239 implement in child class should return True if permissions are ok,
2223 False otherwise
2240 False otherwise
2224
2241
2225 :param perm_defs: dict with permission definitions
2242 :param perm_defs: dict with permission definitions
2226 :param repo_name: repo name
2243 :param repo_name: repo name
2227 """
2244 """
2228 raise NotImplementedError()
2245 raise NotImplementedError()
2229
2246
2230
2247
2231 class HasPermissionAllApi(_BaseApiPerm):
2248 class HasPermissionAllApi(_BaseApiPerm):
2232 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2249 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2233 user_group_name=None):
2250 user_group_name=None):
2234 if self.required_perms.issubset(perm_defs.get('global')):
2251 if self.required_perms.issubset(perm_defs.get('global')):
2235 return True
2252 return True
2236 return False
2253 return False
2237
2254
2238
2255
2239 class HasPermissionAnyApi(_BaseApiPerm):
2256 class HasPermissionAnyApi(_BaseApiPerm):
2240 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2257 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2241 user_group_name=None):
2258 user_group_name=None):
2242 if self.required_perms.intersection(perm_defs.get('global')):
2259 if self.required_perms.intersection(perm_defs.get('global')):
2243 return True
2260 return True
2244 return False
2261 return False
2245
2262
2246
2263
2247 class HasRepoPermissionAllApi(_BaseApiPerm):
2264 class HasRepoPermissionAllApi(_BaseApiPerm):
2248 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2265 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2249 user_group_name=None):
2266 user_group_name=None):
2250 try:
2267 try:
2251 _user_perms = {perm_defs['repositories'][repo_name]}
2268 _user_perms = {perm_defs['repositories'][repo_name]}
2252 except KeyError:
2269 except KeyError:
2253 log.warning(traceback.format_exc())
2270 log.warning(traceback.format_exc())
2254 return False
2271 return False
2255 if self.required_perms.issubset(_user_perms):
2272 if self.required_perms.issubset(_user_perms):
2256 return True
2273 return True
2257 return False
2274 return False
2258
2275
2259
2276
2260 class HasRepoPermissionAnyApi(_BaseApiPerm):
2277 class HasRepoPermissionAnyApi(_BaseApiPerm):
2261 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2278 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2262 user_group_name=None):
2279 user_group_name=None):
2263 try:
2280 try:
2264 _user_perms = {perm_defs['repositories'][repo_name]}
2281 _user_perms = {perm_defs['repositories'][repo_name]}
2265 except KeyError:
2282 except KeyError:
2266 log.warning(traceback.format_exc())
2283 log.warning(traceback.format_exc())
2267 return False
2284 return False
2268 if self.required_perms.intersection(_user_perms):
2285 if self.required_perms.intersection(_user_perms):
2269 return True
2286 return True
2270 return False
2287 return False
2271
2288
2272
2289
2273 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
2290 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
2274 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2291 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2275 user_group_name=None):
2292 user_group_name=None):
2276 try:
2293 try:
2277 _user_perms = {perm_defs['repositories_groups'][group_name]}
2294 _user_perms = {perm_defs['repositories_groups'][group_name]}
2278 except KeyError:
2295 except KeyError:
2279 log.warning(traceback.format_exc())
2296 log.warning(traceback.format_exc())
2280 return False
2297 return False
2281 if self.required_perms.intersection(_user_perms):
2298 if self.required_perms.intersection(_user_perms):
2282 return True
2299 return True
2283 return False
2300 return False
2284
2301
2285
2302
2286 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
2303 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
2287 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2304 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2288 user_group_name=None):
2305 user_group_name=None):
2289 try:
2306 try:
2290 _user_perms = {perm_defs['repositories_groups'][group_name]}
2307 _user_perms = {perm_defs['repositories_groups'][group_name]}
2291 except KeyError:
2308 except KeyError:
2292 log.warning(traceback.format_exc())
2309 log.warning(traceback.format_exc())
2293 return False
2310 return False
2294 if self.required_perms.issubset(_user_perms):
2311 if self.required_perms.issubset(_user_perms):
2295 return True
2312 return True
2296 return False
2313 return False
2297
2314
2298
2315
2299 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
2316 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
2300 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2317 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2301 user_group_name=None):
2318 user_group_name=None):
2302 try:
2319 try:
2303 _user_perms = {perm_defs['user_groups'][user_group_name]}
2320 _user_perms = {perm_defs['user_groups'][user_group_name]}
2304 except KeyError:
2321 except KeyError:
2305 log.warning(traceback.format_exc())
2322 log.warning(traceback.format_exc())
2306 return False
2323 return False
2307 if self.required_perms.intersection(_user_perms):
2324 if self.required_perms.intersection(_user_perms):
2308 return True
2325 return True
2309 return False
2326 return False
2310
2327
2311
2328
2312 def check_ip_access(source_ip, allowed_ips=None):
2329 def check_ip_access(source_ip, allowed_ips=None):
2313 """
2330 """
2314 Checks if source_ip is a subnet of any of allowed_ips.
2331 Checks if source_ip is a subnet of any of allowed_ips.
2315
2332
2316 :param source_ip:
2333 :param source_ip:
2317 :param allowed_ips: list of allowed ips together with mask
2334 :param allowed_ips: list of allowed ips together with mask
2318 """
2335 """
2319 log.debug('checking if ip:%s is subnet of %s', source_ip, allowed_ips)
2336 log.debug('checking if ip:%s is subnet of %s', source_ip, allowed_ips)
2320 source_ip_address = ipaddress.ip_address(safe_unicode(source_ip))
2337 source_ip_address = ipaddress.ip_address(safe_unicode(source_ip))
2321 if isinstance(allowed_ips, (tuple, list, set)):
2338 if isinstance(allowed_ips, (tuple, list, set)):
2322 for ip in allowed_ips:
2339 for ip in allowed_ips:
2323 ip = safe_unicode(ip)
2340 ip = safe_unicode(ip)
2324 try:
2341 try:
2325 network_address = ipaddress.ip_network(ip, strict=False)
2342 network_address = ipaddress.ip_network(ip, strict=False)
2326 if source_ip_address in network_address:
2343 if source_ip_address in network_address:
2327 log.debug('IP %s is network %s', source_ip_address, network_address)
2344 log.debug('IP %s is network %s', source_ip_address, network_address)
2328 return True
2345 return True
2329 # for any case we cannot determine the IP, don't crash just
2346 # for any case we cannot determine the IP, don't crash just
2330 # skip it and log as error, we want to say forbidden still when
2347 # skip it and log as error, we want to say forbidden still when
2331 # sending bad IP
2348 # sending bad IP
2332 except Exception:
2349 except Exception:
2333 log.error(traceback.format_exc())
2350 log.error(traceback.format_exc())
2334 continue
2351 continue
2335 return False
2352 return False
2336
2353
2337
2354
2338 def get_cython_compat_decorator(wrapper, func):
2355 def get_cython_compat_decorator(wrapper, func):
2339 """
2356 """
2340 Creates a cython compatible decorator. The previously used
2357 Creates a cython compatible decorator. The previously used
2341 decorator.decorator() function seems to be incompatible with cython.
2358 decorator.decorator() function seems to be incompatible with cython.
2342
2359
2343 :param wrapper: __wrapper method of the decorator class
2360 :param wrapper: __wrapper method of the decorator class
2344 :param func: decorated function
2361 :param func: decorated function
2345 """
2362 """
2346 @wraps(func)
2363 @wraps(func)
2347 def local_wrapper(*args, **kwds):
2364 def local_wrapper(*args, **kwds):
2348 return wrapper(func, *args, **kwds)
2365 return wrapper(func, *args, **kwds)
2349 local_wrapper.__wrapped__ = func
2366 local_wrapper.__wrapped__ = func
2350 return local_wrapper
2367 return local_wrapper
2351
2368
2352
2369
@@ -1,5380 +1,5399 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2019 RhodeCode GmbH
3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 Database Models for RhodeCode Enterprise
22 Database Models for RhodeCode Enterprise
23 """
23 """
24
24
25 import re
25 import re
26 import os
26 import os
27 import time
27 import time
28 import string
28 import string
29 import hashlib
29 import hashlib
30 import logging
30 import logging
31 import datetime
31 import datetime
32 import uuid
32 import uuid
33 import warnings
33 import warnings
34 import ipaddress
34 import ipaddress
35 import functools
35 import functools
36 import traceback
36 import traceback
37 import collections
37 import collections
38
38
39 from sqlalchemy import (
39 from sqlalchemy import (
40 or_, and_, not_, func, TypeDecorator, event,
40 or_, and_, not_, func, TypeDecorator, event,
41 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
41 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
42 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
42 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
43 Text, Float, PickleType)
43 Text, Float, PickleType)
44 from sqlalchemy.sql.expression import true, false, case
44 from sqlalchemy.sql.expression import true, false, case
45 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
45 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
46 from sqlalchemy.orm import (
46 from sqlalchemy.orm import (
47 relationship, joinedload, class_mapper, validates, aliased)
47 relationship, joinedload, class_mapper, validates, aliased)
48 from sqlalchemy.ext.declarative import declared_attr
48 from sqlalchemy.ext.declarative import declared_attr
49 from sqlalchemy.ext.hybrid import hybrid_property
49 from sqlalchemy.ext.hybrid import hybrid_property
50 from sqlalchemy.exc import IntegrityError # pragma: no cover
50 from sqlalchemy.exc import IntegrityError # pragma: no cover
51 from sqlalchemy.dialects.mysql import LONGTEXT
51 from sqlalchemy.dialects.mysql import LONGTEXT
52 from zope.cachedescriptors.property import Lazy as LazyProperty
52 from zope.cachedescriptors.property import Lazy as LazyProperty
53 from pyramid import compat
53 from pyramid import compat
54 from pyramid.threadlocal import get_current_request
54 from pyramid.threadlocal import get_current_request
55 from webhelpers.text import collapse, remove_formatting
55 from webhelpers.text import collapse, remove_formatting
56
56
57 from rhodecode.translation import _
57 from rhodecode.translation import _
58 from rhodecode.lib.vcs import get_vcs_instance
58 from rhodecode.lib.vcs import get_vcs_instance
59 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
59 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
60 from rhodecode.lib.utils2 import (
60 from rhodecode.lib.utils2 import (
61 str2bool, safe_str, get_commit_safe, safe_unicode, sha1_safe,
61 str2bool, safe_str, get_commit_safe, safe_unicode, sha1_safe,
62 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
62 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
63 glob2re, StrictAttributeDict, cleaned_uri, datetime_to_time, OrderedDefaultDict)
63 glob2re, StrictAttributeDict, cleaned_uri, datetime_to_time, OrderedDefaultDict)
64 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
64 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
65 JsonRaw
65 JsonRaw
66 from rhodecode.lib.ext_json import json
66 from rhodecode.lib.ext_json import json
67 from rhodecode.lib.caching_query import FromCache
67 from rhodecode.lib.caching_query import FromCache
68 from rhodecode.lib.encrypt import AESCipher, validate_and_get_enc_data
68 from rhodecode.lib.encrypt import AESCipher, validate_and_get_enc_data
69 from rhodecode.lib.encrypt2 import Encryptor
69 from rhodecode.lib.encrypt2 import Encryptor
70 from rhodecode.lib.exceptions import (
70 from rhodecode.lib.exceptions import (
71 ArtifactMetadataDuplicate, ArtifactMetadataBadValueType)
71 ArtifactMetadataDuplicate, ArtifactMetadataBadValueType)
72 from rhodecode.model.meta import Base, Session
72 from rhodecode.model.meta import Base, Session
73
73
74 URL_SEP = '/'
74 URL_SEP = '/'
75 log = logging.getLogger(__name__)
75 log = logging.getLogger(__name__)
76
76
77 # =============================================================================
77 # =============================================================================
78 # BASE CLASSES
78 # BASE CLASSES
79 # =============================================================================
79 # =============================================================================
80
80
81 # this is propagated from .ini file rhodecode.encrypted_values.secret or
81 # this is propagated from .ini file rhodecode.encrypted_values.secret or
82 # beaker.session.secret if first is not set.
82 # beaker.session.secret if first is not set.
83 # and initialized at environment.py
83 # and initialized at environment.py
84 ENCRYPTION_KEY = None
84 ENCRYPTION_KEY = None
85
85
86 # used to sort permissions by types, '#' used here is not allowed to be in
86 # used to sort permissions by types, '#' used here is not allowed to be in
87 # usernames, and it's very early in sorted string.printable table.
87 # usernames, and it's very early in sorted string.printable table.
88 PERMISSION_TYPE_SORT = {
88 PERMISSION_TYPE_SORT = {
89 'admin': '####',
89 'admin': '####',
90 'write': '###',
90 'write': '###',
91 'read': '##',
91 'read': '##',
92 'none': '#',
92 'none': '#',
93 }
93 }
94
94
95
95
96 def display_user_sort(obj):
96 def display_user_sort(obj):
97 """
97 """
98 Sort function used to sort permissions in .permissions() function of
98 Sort function used to sort permissions in .permissions() function of
99 Repository, RepoGroup, UserGroup. Also it put the default user in front
99 Repository, RepoGroup, UserGroup. Also it put the default user in front
100 of all other resources
100 of all other resources
101 """
101 """
102
102
103 if obj.username == User.DEFAULT_USER:
103 if obj.username == User.DEFAULT_USER:
104 return '#####'
104 return '#####'
105 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
105 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
106 return prefix + obj.username
106 return prefix + obj.username
107
107
108
108
109 def display_user_group_sort(obj):
109 def display_user_group_sort(obj):
110 """
110 """
111 Sort function used to sort permissions in .permissions() function of
111 Sort function used to sort permissions in .permissions() function of
112 Repository, RepoGroup, UserGroup. Also it put the default user in front
112 Repository, RepoGroup, UserGroup. Also it put the default user in front
113 of all other resources
113 of all other resources
114 """
114 """
115
115
116 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
116 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
117 return prefix + obj.users_group_name
117 return prefix + obj.users_group_name
118
118
119
119
120 def _hash_key(k):
120 def _hash_key(k):
121 return sha1_safe(k)
121 return sha1_safe(k)
122
122
123
123
124 def in_filter_generator(qry, items, limit=500):
124 def in_filter_generator(qry, items, limit=500):
125 """
125 """
126 Splits IN() into multiple with OR
126 Splits IN() into multiple with OR
127 e.g.::
127 e.g.::
128 cnt = Repository.query().filter(
128 cnt = Repository.query().filter(
129 or_(
129 or_(
130 *in_filter_generator(Repository.repo_id, range(100000))
130 *in_filter_generator(Repository.repo_id, range(100000))
131 )).count()
131 )).count()
132 """
132 """
133 if not items:
133 if not items:
134 # empty list will cause empty query which might cause security issues
134 # empty list will cause empty query which might cause security issues
135 # this can lead to hidden unpleasant results
135 # this can lead to hidden unpleasant results
136 items = [-1]
136 items = [-1]
137
137
138 parts = []
138 parts = []
139 for chunk in xrange(0, len(items), limit):
139 for chunk in xrange(0, len(items), limit):
140 parts.append(
140 parts.append(
141 qry.in_(items[chunk: chunk + limit])
141 qry.in_(items[chunk: chunk + limit])
142 )
142 )
143
143
144 return parts
144 return parts
145
145
146
146
147 base_table_args = {
147 base_table_args = {
148 'extend_existing': True,
148 'extend_existing': True,
149 'mysql_engine': 'InnoDB',
149 'mysql_engine': 'InnoDB',
150 'mysql_charset': 'utf8',
150 'mysql_charset': 'utf8',
151 'sqlite_autoincrement': True
151 'sqlite_autoincrement': True
152 }
152 }
153
153
154
154
155 class EncryptedTextValue(TypeDecorator):
155 class EncryptedTextValue(TypeDecorator):
156 """
156 """
157 Special column for encrypted long text data, use like::
157 Special column for encrypted long text data, use like::
158
158
159 value = Column("encrypted_value", EncryptedValue(), nullable=False)
159 value = Column("encrypted_value", EncryptedValue(), nullable=False)
160
160
161 This column is intelligent so if value is in unencrypted form it return
161 This column is intelligent so if value is in unencrypted form it return
162 unencrypted form, but on save it always encrypts
162 unencrypted form, but on save it always encrypts
163 """
163 """
164 impl = Text
164 impl = Text
165
165
166 def process_bind_param(self, value, dialect):
166 def process_bind_param(self, value, dialect):
167 """
167 """
168 Setter for storing value
168 Setter for storing value
169 """
169 """
170 import rhodecode
170 import rhodecode
171 if not value:
171 if not value:
172 return value
172 return value
173
173
174 # protect against double encrypting if values is already encrypted
174 # protect against double encrypting if values is already encrypted
175 if value.startswith('enc$aes$') \
175 if value.startswith('enc$aes$') \
176 or value.startswith('enc$aes_hmac$') \
176 or value.startswith('enc$aes_hmac$') \
177 or value.startswith('enc2$'):
177 or value.startswith('enc2$'):
178 raise ValueError('value needs to be in unencrypted format, '
178 raise ValueError('value needs to be in unencrypted format, '
179 'ie. not starting with enc$ or enc2$')
179 'ie. not starting with enc$ or enc2$')
180
180
181 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
181 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
182 if algo == 'aes':
182 if algo == 'aes':
183 return 'enc$aes_hmac$%s' % AESCipher(ENCRYPTION_KEY, hmac=True).encrypt(value)
183 return 'enc$aes_hmac$%s' % AESCipher(ENCRYPTION_KEY, hmac=True).encrypt(value)
184 elif algo == 'fernet':
184 elif algo == 'fernet':
185 return Encryptor(ENCRYPTION_KEY).encrypt(value)
185 return Encryptor(ENCRYPTION_KEY).encrypt(value)
186 else:
186 else:
187 ValueError('Bad encryption algorithm, should be fernet or aes, got: {}'.format(algo))
187 ValueError('Bad encryption algorithm, should be fernet or aes, got: {}'.format(algo))
188
188
189 def process_result_value(self, value, dialect):
189 def process_result_value(self, value, dialect):
190 """
190 """
191 Getter for retrieving value
191 Getter for retrieving value
192 """
192 """
193
193
194 import rhodecode
194 import rhodecode
195 if not value:
195 if not value:
196 return value
196 return value
197
197
198 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
198 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
199 enc_strict_mode = str2bool(rhodecode.CONFIG.get('rhodecode.encrypted_values.strict') or True)
199 enc_strict_mode = str2bool(rhodecode.CONFIG.get('rhodecode.encrypted_values.strict') or True)
200 if algo == 'aes':
200 if algo == 'aes':
201 decrypted_data = validate_and_get_enc_data(value, ENCRYPTION_KEY, enc_strict_mode)
201 decrypted_data = validate_and_get_enc_data(value, ENCRYPTION_KEY, enc_strict_mode)
202 elif algo == 'fernet':
202 elif algo == 'fernet':
203 return Encryptor(ENCRYPTION_KEY).decrypt(value)
203 return Encryptor(ENCRYPTION_KEY).decrypt(value)
204 else:
204 else:
205 ValueError('Bad encryption algorithm, should be fernet or aes, got: {}'.format(algo))
205 ValueError('Bad encryption algorithm, should be fernet or aes, got: {}'.format(algo))
206 return decrypted_data
206 return decrypted_data
207
207
208
208
209 class BaseModel(object):
209 class BaseModel(object):
210 """
210 """
211 Base Model for all classes
211 Base Model for all classes
212 """
212 """
213
213
214 @classmethod
214 @classmethod
215 def _get_keys(cls):
215 def _get_keys(cls):
216 """return column names for this model """
216 """return column names for this model """
217 return class_mapper(cls).c.keys()
217 return class_mapper(cls).c.keys()
218
218
219 def get_dict(self):
219 def get_dict(self):
220 """
220 """
221 return dict with keys and values corresponding
221 return dict with keys and values corresponding
222 to this model data """
222 to this model data """
223
223
224 d = {}
224 d = {}
225 for k in self._get_keys():
225 for k in self._get_keys():
226 d[k] = getattr(self, k)
226 d[k] = getattr(self, k)
227
227
228 # also use __json__() if present to get additional fields
228 # also use __json__() if present to get additional fields
229 _json_attr = getattr(self, '__json__', None)
229 _json_attr = getattr(self, '__json__', None)
230 if _json_attr:
230 if _json_attr:
231 # update with attributes from __json__
231 # update with attributes from __json__
232 if callable(_json_attr):
232 if callable(_json_attr):
233 _json_attr = _json_attr()
233 _json_attr = _json_attr()
234 for k, val in _json_attr.iteritems():
234 for k, val in _json_attr.iteritems():
235 d[k] = val
235 d[k] = val
236 return d
236 return d
237
237
238 def get_appstruct(self):
238 def get_appstruct(self):
239 """return list with keys and values tuples corresponding
239 """return list with keys and values tuples corresponding
240 to this model data """
240 to this model data """
241
241
242 lst = []
242 lst = []
243 for k in self._get_keys():
243 for k in self._get_keys():
244 lst.append((k, getattr(self, k),))
244 lst.append((k, getattr(self, k),))
245 return lst
245 return lst
246
246
247 def populate_obj(self, populate_dict):
247 def populate_obj(self, populate_dict):
248 """populate model with data from given populate_dict"""
248 """populate model with data from given populate_dict"""
249
249
250 for k in self._get_keys():
250 for k in self._get_keys():
251 if k in populate_dict:
251 if k in populate_dict:
252 setattr(self, k, populate_dict[k])
252 setattr(self, k, populate_dict[k])
253
253
254 @classmethod
254 @classmethod
255 def query(cls):
255 def query(cls):
256 return Session().query(cls)
256 return Session().query(cls)
257
257
258 @classmethod
258 @classmethod
259 def get(cls, id_):
259 def get(cls, id_):
260 if id_:
260 if id_:
261 return cls.query().get(id_)
261 return cls.query().get(id_)
262
262
263 @classmethod
263 @classmethod
264 def get_or_404(cls, id_):
264 def get_or_404(cls, id_):
265 from pyramid.httpexceptions import HTTPNotFound
265 from pyramid.httpexceptions import HTTPNotFound
266
266
267 try:
267 try:
268 id_ = int(id_)
268 id_ = int(id_)
269 except (TypeError, ValueError):
269 except (TypeError, ValueError):
270 raise HTTPNotFound()
270 raise HTTPNotFound()
271
271
272 res = cls.query().get(id_)
272 res = cls.query().get(id_)
273 if not res:
273 if not res:
274 raise HTTPNotFound()
274 raise HTTPNotFound()
275 return res
275 return res
276
276
277 @classmethod
277 @classmethod
278 def getAll(cls):
278 def getAll(cls):
279 # deprecated and left for backward compatibility
279 # deprecated and left for backward compatibility
280 return cls.get_all()
280 return cls.get_all()
281
281
282 @classmethod
282 @classmethod
283 def get_all(cls):
283 def get_all(cls):
284 return cls.query().all()
284 return cls.query().all()
285
285
286 @classmethod
286 @classmethod
287 def delete(cls, id_):
287 def delete(cls, id_):
288 obj = cls.query().get(id_)
288 obj = cls.query().get(id_)
289 Session().delete(obj)
289 Session().delete(obj)
290
290
291 @classmethod
291 @classmethod
292 def identity_cache(cls, session, attr_name, value):
292 def identity_cache(cls, session, attr_name, value):
293 exist_in_session = []
293 exist_in_session = []
294 for (item_cls, pkey), instance in session.identity_map.items():
294 for (item_cls, pkey), instance in session.identity_map.items():
295 if cls == item_cls and getattr(instance, attr_name) == value:
295 if cls == item_cls and getattr(instance, attr_name) == value:
296 exist_in_session.append(instance)
296 exist_in_session.append(instance)
297 if exist_in_session:
297 if exist_in_session:
298 if len(exist_in_session) == 1:
298 if len(exist_in_session) == 1:
299 return exist_in_session[0]
299 return exist_in_session[0]
300 log.exception(
300 log.exception(
301 'multiple objects with attr %s and '
301 'multiple objects with attr %s and '
302 'value %s found with same name: %r',
302 'value %s found with same name: %r',
303 attr_name, value, exist_in_session)
303 attr_name, value, exist_in_session)
304
304
305 def __repr__(self):
305 def __repr__(self):
306 if hasattr(self, '__unicode__'):
306 if hasattr(self, '__unicode__'):
307 # python repr needs to return str
307 # python repr needs to return str
308 try:
308 try:
309 return safe_str(self.__unicode__())
309 return safe_str(self.__unicode__())
310 except UnicodeDecodeError:
310 except UnicodeDecodeError:
311 pass
311 pass
312 return '<DB:%s>' % (self.__class__.__name__)
312 return '<DB:%s>' % (self.__class__.__name__)
313
313
314
314
315 class RhodeCodeSetting(Base, BaseModel):
315 class RhodeCodeSetting(Base, BaseModel):
316 __tablename__ = 'rhodecode_settings'
316 __tablename__ = 'rhodecode_settings'
317 __table_args__ = (
317 __table_args__ = (
318 UniqueConstraint('app_settings_name'),
318 UniqueConstraint('app_settings_name'),
319 base_table_args
319 base_table_args
320 )
320 )
321
321
322 SETTINGS_TYPES = {
322 SETTINGS_TYPES = {
323 'str': safe_str,
323 'str': safe_str,
324 'int': safe_int,
324 'int': safe_int,
325 'unicode': safe_unicode,
325 'unicode': safe_unicode,
326 'bool': str2bool,
326 'bool': str2bool,
327 'list': functools.partial(aslist, sep=',')
327 'list': functools.partial(aslist, sep=',')
328 }
328 }
329 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
329 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
330 GLOBAL_CONF_KEY = 'app_settings'
330 GLOBAL_CONF_KEY = 'app_settings'
331
331
332 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
332 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
333 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
333 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
334 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
334 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
335 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
335 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
336
336
337 def __init__(self, key='', val='', type='unicode'):
337 def __init__(self, key='', val='', type='unicode'):
338 self.app_settings_name = key
338 self.app_settings_name = key
339 self.app_settings_type = type
339 self.app_settings_type = type
340 self.app_settings_value = val
340 self.app_settings_value = val
341
341
342 @validates('_app_settings_value')
342 @validates('_app_settings_value')
343 def validate_settings_value(self, key, val):
343 def validate_settings_value(self, key, val):
344 assert type(val) == unicode
344 assert type(val) == unicode
345 return val
345 return val
346
346
347 @hybrid_property
347 @hybrid_property
348 def app_settings_value(self):
348 def app_settings_value(self):
349 v = self._app_settings_value
349 v = self._app_settings_value
350 _type = self.app_settings_type
350 _type = self.app_settings_type
351 if _type:
351 if _type:
352 _type = self.app_settings_type.split('.')[0]
352 _type = self.app_settings_type.split('.')[0]
353 # decode the encrypted value
353 # decode the encrypted value
354 if 'encrypted' in self.app_settings_type:
354 if 'encrypted' in self.app_settings_type:
355 cipher = EncryptedTextValue()
355 cipher = EncryptedTextValue()
356 v = safe_unicode(cipher.process_result_value(v, None))
356 v = safe_unicode(cipher.process_result_value(v, None))
357
357
358 converter = self.SETTINGS_TYPES.get(_type) or \
358 converter = self.SETTINGS_TYPES.get(_type) or \
359 self.SETTINGS_TYPES['unicode']
359 self.SETTINGS_TYPES['unicode']
360 return converter(v)
360 return converter(v)
361
361
362 @app_settings_value.setter
362 @app_settings_value.setter
363 def app_settings_value(self, val):
363 def app_settings_value(self, val):
364 """
364 """
365 Setter that will always make sure we use unicode in app_settings_value
365 Setter that will always make sure we use unicode in app_settings_value
366
366
367 :param val:
367 :param val:
368 """
368 """
369 val = safe_unicode(val)
369 val = safe_unicode(val)
370 # encode the encrypted value
370 # encode the encrypted value
371 if 'encrypted' in self.app_settings_type:
371 if 'encrypted' in self.app_settings_type:
372 cipher = EncryptedTextValue()
372 cipher = EncryptedTextValue()
373 val = safe_unicode(cipher.process_bind_param(val, None))
373 val = safe_unicode(cipher.process_bind_param(val, None))
374 self._app_settings_value = val
374 self._app_settings_value = val
375
375
376 @hybrid_property
376 @hybrid_property
377 def app_settings_type(self):
377 def app_settings_type(self):
378 return self._app_settings_type
378 return self._app_settings_type
379
379
380 @app_settings_type.setter
380 @app_settings_type.setter
381 def app_settings_type(self, val):
381 def app_settings_type(self, val):
382 if val.split('.')[0] not in self.SETTINGS_TYPES:
382 if val.split('.')[0] not in self.SETTINGS_TYPES:
383 raise Exception('type must be one of %s got %s'
383 raise Exception('type must be one of %s got %s'
384 % (self.SETTINGS_TYPES.keys(), val))
384 % (self.SETTINGS_TYPES.keys(), val))
385 self._app_settings_type = val
385 self._app_settings_type = val
386
386
387 @classmethod
387 @classmethod
388 def get_by_prefix(cls, prefix):
388 def get_by_prefix(cls, prefix):
389 return RhodeCodeSetting.query()\
389 return RhodeCodeSetting.query()\
390 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
390 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
391 .all()
391 .all()
392
392
393 def __unicode__(self):
393 def __unicode__(self):
394 return u"<%s('%s:%s[%s]')>" % (
394 return u"<%s('%s:%s[%s]')>" % (
395 self.__class__.__name__,
395 self.__class__.__name__,
396 self.app_settings_name, self.app_settings_value,
396 self.app_settings_name, self.app_settings_value,
397 self.app_settings_type
397 self.app_settings_type
398 )
398 )
399
399
400
400
401 class RhodeCodeUi(Base, BaseModel):
401 class RhodeCodeUi(Base, BaseModel):
402 __tablename__ = 'rhodecode_ui'
402 __tablename__ = 'rhodecode_ui'
403 __table_args__ = (
403 __table_args__ = (
404 UniqueConstraint('ui_key'),
404 UniqueConstraint('ui_key'),
405 base_table_args
405 base_table_args
406 )
406 )
407
407
408 HOOK_REPO_SIZE = 'changegroup.repo_size'
408 HOOK_REPO_SIZE = 'changegroup.repo_size'
409 # HG
409 # HG
410 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
410 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
411 HOOK_PULL = 'outgoing.pull_logger'
411 HOOK_PULL = 'outgoing.pull_logger'
412 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
412 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
413 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
413 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
414 HOOK_PUSH = 'changegroup.push_logger'
414 HOOK_PUSH = 'changegroup.push_logger'
415 HOOK_PUSH_KEY = 'pushkey.key_push'
415 HOOK_PUSH_KEY = 'pushkey.key_push'
416
416
417 HOOKS_BUILTIN = [
417 HOOKS_BUILTIN = [
418 HOOK_PRE_PULL,
418 HOOK_PRE_PULL,
419 HOOK_PULL,
419 HOOK_PULL,
420 HOOK_PRE_PUSH,
420 HOOK_PRE_PUSH,
421 HOOK_PRETX_PUSH,
421 HOOK_PRETX_PUSH,
422 HOOK_PUSH,
422 HOOK_PUSH,
423 HOOK_PUSH_KEY,
423 HOOK_PUSH_KEY,
424 ]
424 ]
425
425
426 # TODO: johbo: Unify way how hooks are configured for git and hg,
426 # TODO: johbo: Unify way how hooks are configured for git and hg,
427 # git part is currently hardcoded.
427 # git part is currently hardcoded.
428
428
429 # SVN PATTERNS
429 # SVN PATTERNS
430 SVN_BRANCH_ID = 'vcs_svn_branch'
430 SVN_BRANCH_ID = 'vcs_svn_branch'
431 SVN_TAG_ID = 'vcs_svn_tag'
431 SVN_TAG_ID = 'vcs_svn_tag'
432
432
433 ui_id = Column(
433 ui_id = Column(
434 "ui_id", Integer(), nullable=False, unique=True, default=None,
434 "ui_id", Integer(), nullable=False, unique=True, default=None,
435 primary_key=True)
435 primary_key=True)
436 ui_section = Column(
436 ui_section = Column(
437 "ui_section", String(255), nullable=True, unique=None, default=None)
437 "ui_section", String(255), nullable=True, unique=None, default=None)
438 ui_key = Column(
438 ui_key = Column(
439 "ui_key", String(255), nullable=True, unique=None, default=None)
439 "ui_key", String(255), nullable=True, unique=None, default=None)
440 ui_value = Column(
440 ui_value = Column(
441 "ui_value", String(255), nullable=True, unique=None, default=None)
441 "ui_value", String(255), nullable=True, unique=None, default=None)
442 ui_active = Column(
442 ui_active = Column(
443 "ui_active", Boolean(), nullable=True, unique=None, default=True)
443 "ui_active", Boolean(), nullable=True, unique=None, default=True)
444
444
445 def __repr__(self):
445 def __repr__(self):
446 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
446 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
447 self.ui_key, self.ui_value)
447 self.ui_key, self.ui_value)
448
448
449
449
450 class RepoRhodeCodeSetting(Base, BaseModel):
450 class RepoRhodeCodeSetting(Base, BaseModel):
451 __tablename__ = 'repo_rhodecode_settings'
451 __tablename__ = 'repo_rhodecode_settings'
452 __table_args__ = (
452 __table_args__ = (
453 UniqueConstraint(
453 UniqueConstraint(
454 'app_settings_name', 'repository_id',
454 'app_settings_name', 'repository_id',
455 name='uq_repo_rhodecode_setting_name_repo_id'),
455 name='uq_repo_rhodecode_setting_name_repo_id'),
456 base_table_args
456 base_table_args
457 )
457 )
458
458
459 repository_id = Column(
459 repository_id = Column(
460 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
460 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
461 nullable=False)
461 nullable=False)
462 app_settings_id = Column(
462 app_settings_id = Column(
463 "app_settings_id", Integer(), nullable=False, unique=True,
463 "app_settings_id", Integer(), nullable=False, unique=True,
464 default=None, primary_key=True)
464 default=None, primary_key=True)
465 app_settings_name = Column(
465 app_settings_name = Column(
466 "app_settings_name", String(255), nullable=True, unique=None,
466 "app_settings_name", String(255), nullable=True, unique=None,
467 default=None)
467 default=None)
468 _app_settings_value = Column(
468 _app_settings_value = Column(
469 "app_settings_value", String(4096), nullable=True, unique=None,
469 "app_settings_value", String(4096), nullable=True, unique=None,
470 default=None)
470 default=None)
471 _app_settings_type = Column(
471 _app_settings_type = Column(
472 "app_settings_type", String(255), nullable=True, unique=None,
472 "app_settings_type", String(255), nullable=True, unique=None,
473 default=None)
473 default=None)
474
474
475 repository = relationship('Repository')
475 repository = relationship('Repository')
476
476
477 def __init__(self, repository_id, key='', val='', type='unicode'):
477 def __init__(self, repository_id, key='', val='', type='unicode'):
478 self.repository_id = repository_id
478 self.repository_id = repository_id
479 self.app_settings_name = key
479 self.app_settings_name = key
480 self.app_settings_type = type
480 self.app_settings_type = type
481 self.app_settings_value = val
481 self.app_settings_value = val
482
482
483 @validates('_app_settings_value')
483 @validates('_app_settings_value')
484 def validate_settings_value(self, key, val):
484 def validate_settings_value(self, key, val):
485 assert type(val) == unicode
485 assert type(val) == unicode
486 return val
486 return val
487
487
488 @hybrid_property
488 @hybrid_property
489 def app_settings_value(self):
489 def app_settings_value(self):
490 v = self._app_settings_value
490 v = self._app_settings_value
491 type_ = self.app_settings_type
491 type_ = self.app_settings_type
492 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
492 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
493 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
493 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
494 return converter(v)
494 return converter(v)
495
495
496 @app_settings_value.setter
496 @app_settings_value.setter
497 def app_settings_value(self, val):
497 def app_settings_value(self, val):
498 """
498 """
499 Setter that will always make sure we use unicode in app_settings_value
499 Setter that will always make sure we use unicode in app_settings_value
500
500
501 :param val:
501 :param val:
502 """
502 """
503 self._app_settings_value = safe_unicode(val)
503 self._app_settings_value = safe_unicode(val)
504
504
505 @hybrid_property
505 @hybrid_property
506 def app_settings_type(self):
506 def app_settings_type(self):
507 return self._app_settings_type
507 return self._app_settings_type
508
508
509 @app_settings_type.setter
509 @app_settings_type.setter
510 def app_settings_type(self, val):
510 def app_settings_type(self, val):
511 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
511 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
512 if val not in SETTINGS_TYPES:
512 if val not in SETTINGS_TYPES:
513 raise Exception('type must be one of %s got %s'
513 raise Exception('type must be one of %s got %s'
514 % (SETTINGS_TYPES.keys(), val))
514 % (SETTINGS_TYPES.keys(), val))
515 self._app_settings_type = val
515 self._app_settings_type = val
516
516
517 def __unicode__(self):
517 def __unicode__(self):
518 return u"<%s('%s:%s:%s[%s]')>" % (
518 return u"<%s('%s:%s:%s[%s]')>" % (
519 self.__class__.__name__, self.repository.repo_name,
519 self.__class__.__name__, self.repository.repo_name,
520 self.app_settings_name, self.app_settings_value,
520 self.app_settings_name, self.app_settings_value,
521 self.app_settings_type
521 self.app_settings_type
522 )
522 )
523
523
524
524
525 class RepoRhodeCodeUi(Base, BaseModel):
525 class RepoRhodeCodeUi(Base, BaseModel):
526 __tablename__ = 'repo_rhodecode_ui'
526 __tablename__ = 'repo_rhodecode_ui'
527 __table_args__ = (
527 __table_args__ = (
528 UniqueConstraint(
528 UniqueConstraint(
529 'repository_id', 'ui_section', 'ui_key',
529 'repository_id', 'ui_section', 'ui_key',
530 name='uq_repo_rhodecode_ui_repository_id_section_key'),
530 name='uq_repo_rhodecode_ui_repository_id_section_key'),
531 base_table_args
531 base_table_args
532 )
532 )
533
533
534 repository_id = Column(
534 repository_id = Column(
535 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
535 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
536 nullable=False)
536 nullable=False)
537 ui_id = Column(
537 ui_id = Column(
538 "ui_id", Integer(), nullable=False, unique=True, default=None,
538 "ui_id", Integer(), nullable=False, unique=True, default=None,
539 primary_key=True)
539 primary_key=True)
540 ui_section = Column(
540 ui_section = Column(
541 "ui_section", String(255), nullable=True, unique=None, default=None)
541 "ui_section", String(255), nullable=True, unique=None, default=None)
542 ui_key = Column(
542 ui_key = Column(
543 "ui_key", String(255), nullable=True, unique=None, default=None)
543 "ui_key", String(255), nullable=True, unique=None, default=None)
544 ui_value = Column(
544 ui_value = Column(
545 "ui_value", String(255), nullable=True, unique=None, default=None)
545 "ui_value", String(255), nullable=True, unique=None, default=None)
546 ui_active = Column(
546 ui_active = Column(
547 "ui_active", Boolean(), nullable=True, unique=None, default=True)
547 "ui_active", Boolean(), nullable=True, unique=None, default=True)
548
548
549 repository = relationship('Repository')
549 repository = relationship('Repository')
550
550
551 def __repr__(self):
551 def __repr__(self):
552 return '<%s[%s:%s]%s=>%s]>' % (
552 return '<%s[%s:%s]%s=>%s]>' % (
553 self.__class__.__name__, self.repository.repo_name,
553 self.__class__.__name__, self.repository.repo_name,
554 self.ui_section, self.ui_key, self.ui_value)
554 self.ui_section, self.ui_key, self.ui_value)
555
555
556
556
557 class User(Base, BaseModel):
557 class User(Base, BaseModel):
558 __tablename__ = 'users'
558 __tablename__ = 'users'
559 __table_args__ = (
559 __table_args__ = (
560 UniqueConstraint('username'), UniqueConstraint('email'),
560 UniqueConstraint('username'), UniqueConstraint('email'),
561 Index('u_username_idx', 'username'),
561 Index('u_username_idx', 'username'),
562 Index('u_email_idx', 'email'),
562 Index('u_email_idx', 'email'),
563 base_table_args
563 base_table_args
564 )
564 )
565
565
566 DEFAULT_USER = 'default'
566 DEFAULT_USER = 'default'
567 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
567 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
568 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
568 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
569
569
570 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
570 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
571 username = Column("username", String(255), nullable=True, unique=None, default=None)
571 username = Column("username", String(255), nullable=True, unique=None, default=None)
572 password = Column("password", String(255), nullable=True, unique=None, default=None)
572 password = Column("password", String(255), nullable=True, unique=None, default=None)
573 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
573 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
574 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
574 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
575 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
575 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
576 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
576 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
577 _email = Column("email", String(255), nullable=True, unique=None, default=None)
577 _email = Column("email", String(255), nullable=True, unique=None, default=None)
578 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
578 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
579 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
579 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
580
580
581 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
581 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
582 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
582 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
583 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
583 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
584 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
584 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
585 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
585 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
586 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
586 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
587
587
588 user_log = relationship('UserLog')
588 user_log = relationship('UserLog')
589 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all, delete-orphan')
589 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all, delete-orphan')
590
590
591 repositories = relationship('Repository')
591 repositories = relationship('Repository')
592 repository_groups = relationship('RepoGroup')
592 repository_groups = relationship('RepoGroup')
593 user_groups = relationship('UserGroup')
593 user_groups = relationship('UserGroup')
594
594
595 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
595 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
596 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
596 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
597
597
598 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all, delete-orphan')
598 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all, delete-orphan')
599 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan')
599 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan')
600 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan')
600 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan')
601
601
602 group_member = relationship('UserGroupMember', cascade='all')
602 group_member = relationship('UserGroupMember', cascade='all')
603
603
604 notifications = relationship('UserNotification', cascade='all')
604 notifications = relationship('UserNotification', cascade='all')
605 # notifications assigned to this user
605 # notifications assigned to this user
606 user_created_notifications = relationship('Notification', cascade='all')
606 user_created_notifications = relationship('Notification', cascade='all')
607 # comments created by this user
607 # comments created by this user
608 user_comments = relationship('ChangesetComment', cascade='all')
608 user_comments = relationship('ChangesetComment', cascade='all')
609 # user profile extra info
609 # user profile extra info
610 user_emails = relationship('UserEmailMap', cascade='all')
610 user_emails = relationship('UserEmailMap', cascade='all')
611 user_ip_map = relationship('UserIpMap', cascade='all')
611 user_ip_map = relationship('UserIpMap', cascade='all')
612 user_auth_tokens = relationship('UserApiKeys', cascade='all')
612 user_auth_tokens = relationship('UserApiKeys', cascade='all')
613 user_ssh_keys = relationship('UserSshKeys', cascade='all')
613 user_ssh_keys = relationship('UserSshKeys', cascade='all')
614
614
615 # gists
615 # gists
616 user_gists = relationship('Gist', cascade='all')
616 user_gists = relationship('Gist', cascade='all')
617 # user pull requests
617 # user pull requests
618 user_pull_requests = relationship('PullRequest', cascade='all')
618 user_pull_requests = relationship('PullRequest', cascade='all')
619 # external identities
619 # external identities
620 extenal_identities = relationship(
620 extenal_identities = relationship(
621 'ExternalIdentity',
621 'ExternalIdentity',
622 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
622 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
623 cascade='all')
623 cascade='all')
624 # review rules
624 # review rules
625 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
625 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
626
626
627 def __unicode__(self):
627 def __unicode__(self):
628 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
628 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
629 self.user_id, self.username)
629 self.user_id, self.username)
630
630
631 @hybrid_property
631 @hybrid_property
632 def email(self):
632 def email(self):
633 return self._email
633 return self._email
634
634
635 @email.setter
635 @email.setter
636 def email(self, val):
636 def email(self, val):
637 self._email = val.lower() if val else None
637 self._email = val.lower() if val else None
638
638
639 @hybrid_property
639 @hybrid_property
640 def first_name(self):
640 def first_name(self):
641 from rhodecode.lib import helpers as h
641 from rhodecode.lib import helpers as h
642 if self.name:
642 if self.name:
643 return h.escape(self.name)
643 return h.escape(self.name)
644 return self.name
644 return self.name
645
645
646 @hybrid_property
646 @hybrid_property
647 def last_name(self):
647 def last_name(self):
648 from rhodecode.lib import helpers as h
648 from rhodecode.lib import helpers as h
649 if self.lastname:
649 if self.lastname:
650 return h.escape(self.lastname)
650 return h.escape(self.lastname)
651 return self.lastname
651 return self.lastname
652
652
653 @hybrid_property
653 @hybrid_property
654 def api_key(self):
654 def api_key(self):
655 """
655 """
656 Fetch if exist an auth-token with role ALL connected to this user
656 Fetch if exist an auth-token with role ALL connected to this user
657 """
657 """
658 user_auth_token = UserApiKeys.query()\
658 user_auth_token = UserApiKeys.query()\
659 .filter(UserApiKeys.user_id == self.user_id)\
659 .filter(UserApiKeys.user_id == self.user_id)\
660 .filter(or_(UserApiKeys.expires == -1,
660 .filter(or_(UserApiKeys.expires == -1,
661 UserApiKeys.expires >= time.time()))\
661 UserApiKeys.expires >= time.time()))\
662 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
662 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
663 if user_auth_token:
663 if user_auth_token:
664 user_auth_token = user_auth_token.api_key
664 user_auth_token = user_auth_token.api_key
665
665
666 return user_auth_token
666 return user_auth_token
667
667
668 @api_key.setter
668 @api_key.setter
669 def api_key(self, val):
669 def api_key(self, val):
670 # don't allow to set API key this is deprecated for now
670 # don't allow to set API key this is deprecated for now
671 self._api_key = None
671 self._api_key = None
672
672
673 @property
673 @property
674 def reviewer_pull_requests(self):
674 def reviewer_pull_requests(self):
675 return PullRequestReviewers.query() \
675 return PullRequestReviewers.query() \
676 .options(joinedload(PullRequestReviewers.pull_request)) \
676 .options(joinedload(PullRequestReviewers.pull_request)) \
677 .filter(PullRequestReviewers.user_id == self.user_id) \
677 .filter(PullRequestReviewers.user_id == self.user_id) \
678 .all()
678 .all()
679
679
680 @property
680 @property
681 def firstname(self):
681 def firstname(self):
682 # alias for future
682 # alias for future
683 return self.name
683 return self.name
684
684
685 @property
685 @property
686 def emails(self):
686 def emails(self):
687 other = UserEmailMap.query()\
687 other = UserEmailMap.query()\
688 .filter(UserEmailMap.user == self) \
688 .filter(UserEmailMap.user == self) \
689 .order_by(UserEmailMap.email_id.asc()) \
689 .order_by(UserEmailMap.email_id.asc()) \
690 .all()
690 .all()
691 return [self.email] + [x.email for x in other]
691 return [self.email] + [x.email for x in other]
692
692
693 @property
693 @property
694 def auth_tokens(self):
694 def auth_tokens(self):
695 auth_tokens = self.get_auth_tokens()
695 auth_tokens = self.get_auth_tokens()
696 return [x.api_key for x in auth_tokens]
696 return [x.api_key for x in auth_tokens]
697
697
698 def get_auth_tokens(self):
698 def get_auth_tokens(self):
699 return UserApiKeys.query()\
699 return UserApiKeys.query()\
700 .filter(UserApiKeys.user == self)\
700 .filter(UserApiKeys.user == self)\
701 .order_by(UserApiKeys.user_api_key_id.asc())\
701 .order_by(UserApiKeys.user_api_key_id.asc())\
702 .all()
702 .all()
703
703
704 @LazyProperty
704 @LazyProperty
705 def feed_token(self):
705 def feed_token(self):
706 return self.get_feed_token()
706 return self.get_feed_token()
707
707
708 def get_feed_token(self, cache=True):
708 def get_feed_token(self, cache=True):
709 feed_tokens = UserApiKeys.query()\
709 feed_tokens = UserApiKeys.query()\
710 .filter(UserApiKeys.user == self)\
710 .filter(UserApiKeys.user == self)\
711 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
711 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
712 if cache:
712 if cache:
713 feed_tokens = feed_tokens.options(
713 feed_tokens = feed_tokens.options(
714 FromCache("sql_cache_short", "get_user_feed_token_%s" % self.user_id))
714 FromCache("sql_cache_short", "get_user_feed_token_%s" % self.user_id))
715
715
716 feed_tokens = feed_tokens.all()
716 feed_tokens = feed_tokens.all()
717 if feed_tokens:
717 if feed_tokens:
718 return feed_tokens[0].api_key
718 return feed_tokens[0].api_key
719 return 'NO_FEED_TOKEN_AVAILABLE'
719 return 'NO_FEED_TOKEN_AVAILABLE'
720
720
721 @LazyProperty
722 def artifact_token(self):
723 return self.get_artifact_token()
724
725 def get_artifact_token(self, cache=True):
726 artifacts_tokens = UserApiKeys.query()\
727 .filter(UserApiKeys.user == self)\
728 .filter(UserApiKeys.role == UserApiKeys.ROLE_ARTIFACT_DOWNLOAD)
729 if cache:
730 artifacts_tokens = artifacts_tokens.options(
731 FromCache("sql_cache_short", "get_user_artifact_token_%s" % self.user_id))
732
733 artifacts_tokens = artifacts_tokens.all()
734 if artifacts_tokens:
735 return artifacts_tokens[0].api_key
736 return 'NO_ARTIFACT_TOKEN_AVAILABLE'
737
721 @classmethod
738 @classmethod
722 def get(cls, user_id, cache=False):
739 def get(cls, user_id, cache=False):
723 if not user_id:
740 if not user_id:
724 return
741 return
725
742
726 user = cls.query()
743 user = cls.query()
727 if cache:
744 if cache:
728 user = user.options(
745 user = user.options(
729 FromCache("sql_cache_short", "get_users_%s" % user_id))
746 FromCache("sql_cache_short", "get_users_%s" % user_id))
730 return user.get(user_id)
747 return user.get(user_id)
731
748
732 @classmethod
749 @classmethod
733 def extra_valid_auth_tokens(cls, user, role=None):
750 def extra_valid_auth_tokens(cls, user, role=None):
734 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
751 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
735 .filter(or_(UserApiKeys.expires == -1,
752 .filter(or_(UserApiKeys.expires == -1,
736 UserApiKeys.expires >= time.time()))
753 UserApiKeys.expires >= time.time()))
737 if role:
754 if role:
738 tokens = tokens.filter(or_(UserApiKeys.role == role,
755 tokens = tokens.filter(or_(UserApiKeys.role == role,
739 UserApiKeys.role == UserApiKeys.ROLE_ALL))
756 UserApiKeys.role == UserApiKeys.ROLE_ALL))
740 return tokens.all()
757 return tokens.all()
741
758
742 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
759 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
743 from rhodecode.lib import auth
760 from rhodecode.lib import auth
744
761
745 log.debug('Trying to authenticate user: %s via auth-token, '
762 log.debug('Trying to authenticate user: %s via auth-token, '
746 'and roles: %s', self, roles)
763 'and roles: %s', self, roles)
747
764
748 if not auth_token:
765 if not auth_token:
749 return False
766 return False
750
767
751 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
768 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
752 tokens_q = UserApiKeys.query()\
769 tokens_q = UserApiKeys.query()\
753 .filter(UserApiKeys.user_id == self.user_id)\
770 .filter(UserApiKeys.user_id == self.user_id)\
754 .filter(or_(UserApiKeys.expires == -1,
771 .filter(or_(UserApiKeys.expires == -1,
755 UserApiKeys.expires >= time.time()))
772 UserApiKeys.expires >= time.time()))
756
773
757 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
774 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
758
775
759 crypto_backend = auth.crypto_backend()
776 crypto_backend = auth.crypto_backend()
760 enc_token_map = {}
777 enc_token_map = {}
761 plain_token_map = {}
778 plain_token_map = {}
762 for token in tokens_q:
779 for token in tokens_q:
763 if token.api_key.startswith(crypto_backend.ENC_PREF):
780 if token.api_key.startswith(crypto_backend.ENC_PREF):
764 enc_token_map[token.api_key] = token
781 enc_token_map[token.api_key] = token
765 else:
782 else:
766 plain_token_map[token.api_key] = token
783 plain_token_map[token.api_key] = token
767 log.debug(
784 log.debug(
768 'Found %s plain and %s encrypted user tokens to check for authentication',
785 'Found %s plain and %s encrypted tokens to check for authentication for this user',
769 len(plain_token_map), len(enc_token_map))
786 len(plain_token_map), len(enc_token_map))
770
787
771 # plain token match comes first
788 # plain token match comes first
772 match = plain_token_map.get(auth_token)
789 match = plain_token_map.get(auth_token)
773
790
774 # check encrypted tokens now
791 # check encrypted tokens now
775 if not match:
792 if not match:
776 for token_hash, token in enc_token_map.items():
793 for token_hash, token in enc_token_map.items():
777 # NOTE(marcink): this is expensive to calculate, but most secure
794 # NOTE(marcink): this is expensive to calculate, but most secure
778 if crypto_backend.hash_check(auth_token, token_hash):
795 if crypto_backend.hash_check(auth_token, token_hash):
779 match = token
796 match = token
780 break
797 break
781
798
782 if match:
799 if match:
783 log.debug('Found matching token %s', match)
800 log.debug('Found matching token %s', match)
784 if match.repo_id:
801 if match.repo_id:
785 log.debug('Found scope, checking for scope match of token %s', match)
802 log.debug('Found scope, checking for scope match of token %s', match)
786 if match.repo_id == scope_repo_id:
803 if match.repo_id == scope_repo_id:
787 return True
804 return True
788 else:
805 else:
789 log.debug(
806 log.debug(
790 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
807 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
791 'and calling scope is:%s, skipping further checks',
808 'and calling scope is:%s, skipping further checks',
792 match.repo, scope_repo_id)
809 match.repo, scope_repo_id)
793 return False
810 return False
794 else:
811 else:
795 return True
812 return True
796
813
797 return False
814 return False
798
815
799 @property
816 @property
800 def ip_addresses(self):
817 def ip_addresses(self):
801 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
818 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
802 return [x.ip_addr for x in ret]
819 return [x.ip_addr for x in ret]
803
820
804 @property
821 @property
805 def username_and_name(self):
822 def username_and_name(self):
806 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
823 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
807
824
808 @property
825 @property
809 def username_or_name_or_email(self):
826 def username_or_name_or_email(self):
810 full_name = self.full_name if self.full_name is not ' ' else None
827 full_name = self.full_name if self.full_name is not ' ' else None
811 return self.username or full_name or self.email
828 return self.username or full_name or self.email
812
829
813 @property
830 @property
814 def full_name(self):
831 def full_name(self):
815 return '%s %s' % (self.first_name, self.last_name)
832 return '%s %s' % (self.first_name, self.last_name)
816
833
817 @property
834 @property
818 def full_name_or_username(self):
835 def full_name_or_username(self):
819 return ('%s %s' % (self.first_name, self.last_name)
836 return ('%s %s' % (self.first_name, self.last_name)
820 if (self.first_name and self.last_name) else self.username)
837 if (self.first_name and self.last_name) else self.username)
821
838
822 @property
839 @property
823 def full_contact(self):
840 def full_contact(self):
824 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
841 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
825
842
826 @property
843 @property
827 def short_contact(self):
844 def short_contact(self):
828 return '%s %s' % (self.first_name, self.last_name)
845 return '%s %s' % (self.first_name, self.last_name)
829
846
830 @property
847 @property
831 def is_admin(self):
848 def is_admin(self):
832 return self.admin
849 return self.admin
833
850
834 def AuthUser(self, **kwargs):
851 def AuthUser(self, **kwargs):
835 """
852 """
836 Returns instance of AuthUser for this user
853 Returns instance of AuthUser for this user
837 """
854 """
838 from rhodecode.lib.auth import AuthUser
855 from rhodecode.lib.auth import AuthUser
839 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
856 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
840
857
841 @hybrid_property
858 @hybrid_property
842 def user_data(self):
859 def user_data(self):
843 if not self._user_data:
860 if not self._user_data:
844 return {}
861 return {}
845
862
846 try:
863 try:
847 return json.loads(self._user_data)
864 return json.loads(self._user_data)
848 except TypeError:
865 except TypeError:
849 return {}
866 return {}
850
867
851 @user_data.setter
868 @user_data.setter
852 def user_data(self, val):
869 def user_data(self, val):
853 if not isinstance(val, dict):
870 if not isinstance(val, dict):
854 raise Exception('user_data must be dict, got %s' % type(val))
871 raise Exception('user_data must be dict, got %s' % type(val))
855 try:
872 try:
856 self._user_data = json.dumps(val)
873 self._user_data = json.dumps(val)
857 except Exception:
874 except Exception:
858 log.error(traceback.format_exc())
875 log.error(traceback.format_exc())
859
876
860 @classmethod
877 @classmethod
861 def get_by_username(cls, username, case_insensitive=False,
878 def get_by_username(cls, username, case_insensitive=False,
862 cache=False, identity_cache=False):
879 cache=False, identity_cache=False):
863 session = Session()
880 session = Session()
864
881
865 if case_insensitive:
882 if case_insensitive:
866 q = cls.query().filter(
883 q = cls.query().filter(
867 func.lower(cls.username) == func.lower(username))
884 func.lower(cls.username) == func.lower(username))
868 else:
885 else:
869 q = cls.query().filter(cls.username == username)
886 q = cls.query().filter(cls.username == username)
870
887
871 if cache:
888 if cache:
872 if identity_cache:
889 if identity_cache:
873 val = cls.identity_cache(session, 'username', username)
890 val = cls.identity_cache(session, 'username', username)
874 if val:
891 if val:
875 return val
892 return val
876 else:
893 else:
877 cache_key = "get_user_by_name_%s" % _hash_key(username)
894 cache_key = "get_user_by_name_%s" % _hash_key(username)
878 q = q.options(
895 q = q.options(
879 FromCache("sql_cache_short", cache_key))
896 FromCache("sql_cache_short", cache_key))
880
897
881 return q.scalar()
898 return q.scalar()
882
899
883 @classmethod
900 @classmethod
884 def get_by_auth_token(cls, auth_token, cache=False):
901 def get_by_auth_token(cls, auth_token, cache=False):
885 q = UserApiKeys.query()\
902 q = UserApiKeys.query()\
886 .filter(UserApiKeys.api_key == auth_token)\
903 .filter(UserApiKeys.api_key == auth_token)\
887 .filter(or_(UserApiKeys.expires == -1,
904 .filter(or_(UserApiKeys.expires == -1,
888 UserApiKeys.expires >= time.time()))
905 UserApiKeys.expires >= time.time()))
889 if cache:
906 if cache:
890 q = q.options(
907 q = q.options(
891 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
908 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
892
909
893 match = q.first()
910 match = q.first()
894 if match:
911 if match:
895 return match.user
912 return match.user
896
913
897 @classmethod
914 @classmethod
898 def get_by_email(cls, email, case_insensitive=False, cache=False):
915 def get_by_email(cls, email, case_insensitive=False, cache=False):
899
916
900 if case_insensitive:
917 if case_insensitive:
901 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
918 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
902
919
903 else:
920 else:
904 q = cls.query().filter(cls.email == email)
921 q = cls.query().filter(cls.email == email)
905
922
906 email_key = _hash_key(email)
923 email_key = _hash_key(email)
907 if cache:
924 if cache:
908 q = q.options(
925 q = q.options(
909 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
926 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
910
927
911 ret = q.scalar()
928 ret = q.scalar()
912 if ret is None:
929 if ret is None:
913 q = UserEmailMap.query()
930 q = UserEmailMap.query()
914 # try fetching in alternate email map
931 # try fetching in alternate email map
915 if case_insensitive:
932 if case_insensitive:
916 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
933 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
917 else:
934 else:
918 q = q.filter(UserEmailMap.email == email)
935 q = q.filter(UserEmailMap.email == email)
919 q = q.options(joinedload(UserEmailMap.user))
936 q = q.options(joinedload(UserEmailMap.user))
920 if cache:
937 if cache:
921 q = q.options(
938 q = q.options(
922 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
939 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
923 ret = getattr(q.scalar(), 'user', None)
940 ret = getattr(q.scalar(), 'user', None)
924
941
925 return ret
942 return ret
926
943
927 @classmethod
944 @classmethod
928 def get_from_cs_author(cls, author):
945 def get_from_cs_author(cls, author):
929 """
946 """
930 Tries to get User objects out of commit author string
947 Tries to get User objects out of commit author string
931
948
932 :param author:
949 :param author:
933 """
950 """
934 from rhodecode.lib.helpers import email, author_name
951 from rhodecode.lib.helpers import email, author_name
935 # Valid email in the attribute passed, see if they're in the system
952 # Valid email in the attribute passed, see if they're in the system
936 _email = email(author)
953 _email = email(author)
937 if _email:
954 if _email:
938 user = cls.get_by_email(_email, case_insensitive=True)
955 user = cls.get_by_email(_email, case_insensitive=True)
939 if user:
956 if user:
940 return user
957 return user
941 # Maybe we can match by username?
958 # Maybe we can match by username?
942 _author = author_name(author)
959 _author = author_name(author)
943 user = cls.get_by_username(_author, case_insensitive=True)
960 user = cls.get_by_username(_author, case_insensitive=True)
944 if user:
961 if user:
945 return user
962 return user
946
963
947 def update_userdata(self, **kwargs):
964 def update_userdata(self, **kwargs):
948 usr = self
965 usr = self
949 old = usr.user_data
966 old = usr.user_data
950 old.update(**kwargs)
967 old.update(**kwargs)
951 usr.user_data = old
968 usr.user_data = old
952 Session().add(usr)
969 Session().add(usr)
953 log.debug('updated userdata with %s', kwargs)
970 log.debug('updated userdata with %s', kwargs)
954
971
955 def update_lastlogin(self):
972 def update_lastlogin(self):
956 """Update user lastlogin"""
973 """Update user lastlogin"""
957 self.last_login = datetime.datetime.now()
974 self.last_login = datetime.datetime.now()
958 Session().add(self)
975 Session().add(self)
959 log.debug('updated user %s lastlogin', self.username)
976 log.debug('updated user %s lastlogin', self.username)
960
977
961 def update_password(self, new_password):
978 def update_password(self, new_password):
962 from rhodecode.lib.auth import get_crypt_password
979 from rhodecode.lib.auth import get_crypt_password
963
980
964 self.password = get_crypt_password(new_password)
981 self.password = get_crypt_password(new_password)
965 Session().add(self)
982 Session().add(self)
966
983
967 @classmethod
984 @classmethod
968 def get_first_super_admin(cls):
985 def get_first_super_admin(cls):
969 user = User.query()\
986 user = User.query()\
970 .filter(User.admin == true()) \
987 .filter(User.admin == true()) \
971 .order_by(User.user_id.asc()) \
988 .order_by(User.user_id.asc()) \
972 .first()
989 .first()
973
990
974 if user is None:
991 if user is None:
975 raise Exception('FATAL: Missing administrative account!')
992 raise Exception('FATAL: Missing administrative account!')
976 return user
993 return user
977
994
978 @classmethod
995 @classmethod
979 def get_all_super_admins(cls, only_active=False):
996 def get_all_super_admins(cls, only_active=False):
980 """
997 """
981 Returns all admin accounts sorted by username
998 Returns all admin accounts sorted by username
982 """
999 """
983 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
1000 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
984 if only_active:
1001 if only_active:
985 qry = qry.filter(User.active == true())
1002 qry = qry.filter(User.active == true())
986 return qry.all()
1003 return qry.all()
987
1004
988 @classmethod
1005 @classmethod
989 def get_default_user(cls, cache=False, refresh=False):
1006 def get_default_user(cls, cache=False, refresh=False):
990 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
1007 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
991 if user is None:
1008 if user is None:
992 raise Exception('FATAL: Missing default account!')
1009 raise Exception('FATAL: Missing default account!')
993 if refresh:
1010 if refresh:
994 # The default user might be based on outdated state which
1011 # The default user might be based on outdated state which
995 # has been loaded from the cache.
1012 # has been loaded from the cache.
996 # A call to refresh() ensures that the
1013 # A call to refresh() ensures that the
997 # latest state from the database is used.
1014 # latest state from the database is used.
998 Session().refresh(user)
1015 Session().refresh(user)
999 return user
1016 return user
1000
1017
1001 def _get_default_perms(self, user, suffix=''):
1018 def _get_default_perms(self, user, suffix=''):
1002 from rhodecode.model.permission import PermissionModel
1019 from rhodecode.model.permission import PermissionModel
1003 return PermissionModel().get_default_perms(user.user_perms, suffix)
1020 return PermissionModel().get_default_perms(user.user_perms, suffix)
1004
1021
1005 def get_default_perms(self, suffix=''):
1022 def get_default_perms(self, suffix=''):
1006 return self._get_default_perms(self, suffix)
1023 return self._get_default_perms(self, suffix)
1007
1024
1008 def get_api_data(self, include_secrets=False, details='full'):
1025 def get_api_data(self, include_secrets=False, details='full'):
1009 """
1026 """
1010 Common function for generating user related data for API
1027 Common function for generating user related data for API
1011
1028
1012 :param include_secrets: By default secrets in the API data will be replaced
1029 :param include_secrets: By default secrets in the API data will be replaced
1013 by a placeholder value to prevent exposing this data by accident. In case
1030 by a placeholder value to prevent exposing this data by accident. In case
1014 this data shall be exposed, set this flag to ``True``.
1031 this data shall be exposed, set this flag to ``True``.
1015
1032
1016 :param details: details can be 'basic|full' basic gives only a subset of
1033 :param details: details can be 'basic|full' basic gives only a subset of
1017 the available user information that includes user_id, name and emails.
1034 the available user information that includes user_id, name and emails.
1018 """
1035 """
1019 user = self
1036 user = self
1020 user_data = self.user_data
1037 user_data = self.user_data
1021 data = {
1038 data = {
1022 'user_id': user.user_id,
1039 'user_id': user.user_id,
1023 'username': user.username,
1040 'username': user.username,
1024 'firstname': user.name,
1041 'firstname': user.name,
1025 'lastname': user.lastname,
1042 'lastname': user.lastname,
1026 'email': user.email,
1043 'email': user.email,
1027 'emails': user.emails,
1044 'emails': user.emails,
1028 }
1045 }
1029 if details == 'basic':
1046 if details == 'basic':
1030 return data
1047 return data
1031
1048
1032 auth_token_length = 40
1049 auth_token_length = 40
1033 auth_token_replacement = '*' * auth_token_length
1050 auth_token_replacement = '*' * auth_token_length
1034
1051
1035 extras = {
1052 extras = {
1036 'auth_tokens': [auth_token_replacement],
1053 'auth_tokens': [auth_token_replacement],
1037 'active': user.active,
1054 'active': user.active,
1038 'admin': user.admin,
1055 'admin': user.admin,
1039 'extern_type': user.extern_type,
1056 'extern_type': user.extern_type,
1040 'extern_name': user.extern_name,
1057 'extern_name': user.extern_name,
1041 'last_login': user.last_login,
1058 'last_login': user.last_login,
1042 'last_activity': user.last_activity,
1059 'last_activity': user.last_activity,
1043 'ip_addresses': user.ip_addresses,
1060 'ip_addresses': user.ip_addresses,
1044 'language': user_data.get('language')
1061 'language': user_data.get('language')
1045 }
1062 }
1046 data.update(extras)
1063 data.update(extras)
1047
1064
1048 if include_secrets:
1065 if include_secrets:
1049 data['auth_tokens'] = user.auth_tokens
1066 data['auth_tokens'] = user.auth_tokens
1050 return data
1067 return data
1051
1068
1052 def __json__(self):
1069 def __json__(self):
1053 data = {
1070 data = {
1054 'full_name': self.full_name,
1071 'full_name': self.full_name,
1055 'full_name_or_username': self.full_name_or_username,
1072 'full_name_or_username': self.full_name_or_username,
1056 'short_contact': self.short_contact,
1073 'short_contact': self.short_contact,
1057 'full_contact': self.full_contact,
1074 'full_contact': self.full_contact,
1058 }
1075 }
1059 data.update(self.get_api_data())
1076 data.update(self.get_api_data())
1060 return data
1077 return data
1061
1078
1062
1079
1063 class UserApiKeys(Base, BaseModel):
1080 class UserApiKeys(Base, BaseModel):
1064 __tablename__ = 'user_api_keys'
1081 __tablename__ = 'user_api_keys'
1065 __table_args__ = (
1082 __table_args__ = (
1066 Index('uak_api_key_idx', 'api_key'),
1083 Index('uak_api_key_idx', 'api_key'),
1067 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1084 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1068 base_table_args
1085 base_table_args
1069 )
1086 )
1070 __mapper_args__ = {}
1087 __mapper_args__ = {}
1071
1088
1072 # ApiKey role
1089 # ApiKey role
1073 ROLE_ALL = 'token_role_all'
1090 ROLE_ALL = 'token_role_all'
1074 ROLE_HTTP = 'token_role_http'
1091 ROLE_HTTP = 'token_role_http'
1075 ROLE_VCS = 'token_role_vcs'
1092 ROLE_VCS = 'token_role_vcs'
1076 ROLE_API = 'token_role_api'
1093 ROLE_API = 'token_role_api'
1077 ROLE_FEED = 'token_role_feed'
1094 ROLE_FEED = 'token_role_feed'
1095 ROLE_ARTIFACT_DOWNLOAD = 'role_artifact_download'
1078 ROLE_PASSWORD_RESET = 'token_password_reset'
1096 ROLE_PASSWORD_RESET = 'token_password_reset'
1079
1097
1080 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
1098 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED, ROLE_ARTIFACT_DOWNLOAD]
1081
1099
1082 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1100 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1083 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1101 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1084 api_key = Column("api_key", String(255), nullable=False, unique=True)
1102 api_key = Column("api_key", String(255), nullable=False, unique=True)
1085 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1103 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1086 expires = Column('expires', Float(53), nullable=False)
1104 expires = Column('expires', Float(53), nullable=False)
1087 role = Column('role', String(255), nullable=True)
1105 role = Column('role', String(255), nullable=True)
1088 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1106 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1089
1107
1090 # scope columns
1108 # scope columns
1091 repo_id = Column(
1109 repo_id = Column(
1092 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1110 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1093 nullable=True, unique=None, default=None)
1111 nullable=True, unique=None, default=None)
1094 repo = relationship('Repository', lazy='joined')
1112 repo = relationship('Repository', lazy='joined')
1095
1113
1096 repo_group_id = Column(
1114 repo_group_id = Column(
1097 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1115 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1098 nullable=True, unique=None, default=None)
1116 nullable=True, unique=None, default=None)
1099 repo_group = relationship('RepoGroup', lazy='joined')
1117 repo_group = relationship('RepoGroup', lazy='joined')
1100
1118
1101 user = relationship('User', lazy='joined')
1119 user = relationship('User', lazy='joined')
1102
1120
1103 def __unicode__(self):
1121 def __unicode__(self):
1104 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1122 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1105
1123
1106 def __json__(self):
1124 def __json__(self):
1107 data = {
1125 data = {
1108 'auth_token': self.api_key,
1126 'auth_token': self.api_key,
1109 'role': self.role,
1127 'role': self.role,
1110 'scope': self.scope_humanized,
1128 'scope': self.scope_humanized,
1111 'expired': self.expired
1129 'expired': self.expired
1112 }
1130 }
1113 return data
1131 return data
1114
1132
1115 def get_api_data(self, include_secrets=False):
1133 def get_api_data(self, include_secrets=False):
1116 data = self.__json__()
1134 data = self.__json__()
1117 if include_secrets:
1135 if include_secrets:
1118 return data
1136 return data
1119 else:
1137 else:
1120 data['auth_token'] = self.token_obfuscated
1138 data['auth_token'] = self.token_obfuscated
1121 return data
1139 return data
1122
1140
1123 @hybrid_property
1141 @hybrid_property
1124 def description_safe(self):
1142 def description_safe(self):
1125 from rhodecode.lib import helpers as h
1143 from rhodecode.lib import helpers as h
1126 return h.escape(self.description)
1144 return h.escape(self.description)
1127
1145
1128 @property
1146 @property
1129 def expired(self):
1147 def expired(self):
1130 if self.expires == -1:
1148 if self.expires == -1:
1131 return False
1149 return False
1132 return time.time() > self.expires
1150 return time.time() > self.expires
1133
1151
1134 @classmethod
1152 @classmethod
1135 def _get_role_name(cls, role):
1153 def _get_role_name(cls, role):
1136 return {
1154 return {
1137 cls.ROLE_ALL: _('all'),
1155 cls.ROLE_ALL: _('all'),
1138 cls.ROLE_HTTP: _('http/web interface'),
1156 cls.ROLE_HTTP: _('http/web interface'),
1139 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1157 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1140 cls.ROLE_API: _('api calls'),
1158 cls.ROLE_API: _('api calls'),
1141 cls.ROLE_FEED: _('feed access'),
1159 cls.ROLE_FEED: _('feed access'),
1160 cls.ROLE_ARTIFACT_DOWNLOAD: _('artifacts downloads'),
1142 }.get(role, role)
1161 }.get(role, role)
1143
1162
1144 @property
1163 @property
1145 def role_humanized(self):
1164 def role_humanized(self):
1146 return self._get_role_name(self.role)
1165 return self._get_role_name(self.role)
1147
1166
1148 def _get_scope(self):
1167 def _get_scope(self):
1149 if self.repo:
1168 if self.repo:
1150 return 'Repository: {}'.format(self.repo.repo_name)
1169 return 'Repository: {}'.format(self.repo.repo_name)
1151 if self.repo_group:
1170 if self.repo_group:
1152 return 'RepositoryGroup: {} (recursive)'.format(self.repo_group.group_name)
1171 return 'RepositoryGroup: {} (recursive)'.format(self.repo_group.group_name)
1153 return 'Global'
1172 return 'Global'
1154
1173
1155 @property
1174 @property
1156 def scope_humanized(self):
1175 def scope_humanized(self):
1157 return self._get_scope()
1176 return self._get_scope()
1158
1177
1159 @property
1178 @property
1160 def token_obfuscated(self):
1179 def token_obfuscated(self):
1161 if self.api_key:
1180 if self.api_key:
1162 return self.api_key[:4] + "****"
1181 return self.api_key[:4] + "****"
1163
1182
1164
1183
1165 class UserEmailMap(Base, BaseModel):
1184 class UserEmailMap(Base, BaseModel):
1166 __tablename__ = 'user_email_map'
1185 __tablename__ = 'user_email_map'
1167 __table_args__ = (
1186 __table_args__ = (
1168 Index('uem_email_idx', 'email'),
1187 Index('uem_email_idx', 'email'),
1169 UniqueConstraint('email'),
1188 UniqueConstraint('email'),
1170 base_table_args
1189 base_table_args
1171 )
1190 )
1172 __mapper_args__ = {}
1191 __mapper_args__ = {}
1173
1192
1174 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1193 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1175 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1194 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1176 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1195 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1177 user = relationship('User', lazy='joined')
1196 user = relationship('User', lazy='joined')
1178
1197
1179 @validates('_email')
1198 @validates('_email')
1180 def validate_email(self, key, email):
1199 def validate_email(self, key, email):
1181 # check if this email is not main one
1200 # check if this email is not main one
1182 main_email = Session().query(User).filter(User.email == email).scalar()
1201 main_email = Session().query(User).filter(User.email == email).scalar()
1183 if main_email is not None:
1202 if main_email is not None:
1184 raise AttributeError('email %s is present is user table' % email)
1203 raise AttributeError('email %s is present is user table' % email)
1185 return email
1204 return email
1186
1205
1187 @hybrid_property
1206 @hybrid_property
1188 def email(self):
1207 def email(self):
1189 return self._email
1208 return self._email
1190
1209
1191 @email.setter
1210 @email.setter
1192 def email(self, val):
1211 def email(self, val):
1193 self._email = val.lower() if val else None
1212 self._email = val.lower() if val else None
1194
1213
1195
1214
1196 class UserIpMap(Base, BaseModel):
1215 class UserIpMap(Base, BaseModel):
1197 __tablename__ = 'user_ip_map'
1216 __tablename__ = 'user_ip_map'
1198 __table_args__ = (
1217 __table_args__ = (
1199 UniqueConstraint('user_id', 'ip_addr'),
1218 UniqueConstraint('user_id', 'ip_addr'),
1200 base_table_args
1219 base_table_args
1201 )
1220 )
1202 __mapper_args__ = {}
1221 __mapper_args__ = {}
1203
1222
1204 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1223 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1205 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1224 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1206 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1225 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1207 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1226 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1208 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1227 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1209 user = relationship('User', lazy='joined')
1228 user = relationship('User', lazy='joined')
1210
1229
1211 @hybrid_property
1230 @hybrid_property
1212 def description_safe(self):
1231 def description_safe(self):
1213 from rhodecode.lib import helpers as h
1232 from rhodecode.lib import helpers as h
1214 return h.escape(self.description)
1233 return h.escape(self.description)
1215
1234
1216 @classmethod
1235 @classmethod
1217 def _get_ip_range(cls, ip_addr):
1236 def _get_ip_range(cls, ip_addr):
1218 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1237 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1219 return [str(net.network_address), str(net.broadcast_address)]
1238 return [str(net.network_address), str(net.broadcast_address)]
1220
1239
1221 def __json__(self):
1240 def __json__(self):
1222 return {
1241 return {
1223 'ip_addr': self.ip_addr,
1242 'ip_addr': self.ip_addr,
1224 'ip_range': self._get_ip_range(self.ip_addr),
1243 'ip_range': self._get_ip_range(self.ip_addr),
1225 }
1244 }
1226
1245
1227 def __unicode__(self):
1246 def __unicode__(self):
1228 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1247 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1229 self.user_id, self.ip_addr)
1248 self.user_id, self.ip_addr)
1230
1249
1231
1250
1232 class UserSshKeys(Base, BaseModel):
1251 class UserSshKeys(Base, BaseModel):
1233 __tablename__ = 'user_ssh_keys'
1252 __tablename__ = 'user_ssh_keys'
1234 __table_args__ = (
1253 __table_args__ = (
1235 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1254 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1236
1255
1237 UniqueConstraint('ssh_key_fingerprint'),
1256 UniqueConstraint('ssh_key_fingerprint'),
1238
1257
1239 base_table_args
1258 base_table_args
1240 )
1259 )
1241 __mapper_args__ = {}
1260 __mapper_args__ = {}
1242
1261
1243 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1262 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1244 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1263 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1245 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1264 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1246
1265
1247 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1266 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1248
1267
1249 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1268 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1250 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1269 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1251 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1270 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1252
1271
1253 user = relationship('User', lazy='joined')
1272 user = relationship('User', lazy='joined')
1254
1273
1255 def __json__(self):
1274 def __json__(self):
1256 data = {
1275 data = {
1257 'ssh_fingerprint': self.ssh_key_fingerprint,
1276 'ssh_fingerprint': self.ssh_key_fingerprint,
1258 'description': self.description,
1277 'description': self.description,
1259 'created_on': self.created_on
1278 'created_on': self.created_on
1260 }
1279 }
1261 return data
1280 return data
1262
1281
1263 def get_api_data(self):
1282 def get_api_data(self):
1264 data = self.__json__()
1283 data = self.__json__()
1265 return data
1284 return data
1266
1285
1267
1286
1268 class UserLog(Base, BaseModel):
1287 class UserLog(Base, BaseModel):
1269 __tablename__ = 'user_logs'
1288 __tablename__ = 'user_logs'
1270 __table_args__ = (
1289 __table_args__ = (
1271 base_table_args,
1290 base_table_args,
1272 )
1291 )
1273
1292
1274 VERSION_1 = 'v1'
1293 VERSION_1 = 'v1'
1275 VERSION_2 = 'v2'
1294 VERSION_2 = 'v2'
1276 VERSIONS = [VERSION_1, VERSION_2]
1295 VERSIONS = [VERSION_1, VERSION_2]
1277
1296
1278 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1297 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1279 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1298 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1280 username = Column("username", String(255), nullable=True, unique=None, default=None)
1299 username = Column("username", String(255), nullable=True, unique=None, default=None)
1281 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1300 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1282 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1301 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1283 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1302 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1284 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1303 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1285 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1304 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1286
1305
1287 version = Column("version", String(255), nullable=True, default=VERSION_1)
1306 version = Column("version", String(255), nullable=True, default=VERSION_1)
1288 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1307 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1289 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1308 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1290
1309
1291 def __unicode__(self):
1310 def __unicode__(self):
1292 return u"<%s('id:%s:%s')>" % (
1311 return u"<%s('id:%s:%s')>" % (
1293 self.__class__.__name__, self.repository_name, self.action)
1312 self.__class__.__name__, self.repository_name, self.action)
1294
1313
1295 def __json__(self):
1314 def __json__(self):
1296 return {
1315 return {
1297 'user_id': self.user_id,
1316 'user_id': self.user_id,
1298 'username': self.username,
1317 'username': self.username,
1299 'repository_id': self.repository_id,
1318 'repository_id': self.repository_id,
1300 'repository_name': self.repository_name,
1319 'repository_name': self.repository_name,
1301 'user_ip': self.user_ip,
1320 'user_ip': self.user_ip,
1302 'action_date': self.action_date,
1321 'action_date': self.action_date,
1303 'action': self.action,
1322 'action': self.action,
1304 }
1323 }
1305
1324
1306 @hybrid_property
1325 @hybrid_property
1307 def entry_id(self):
1326 def entry_id(self):
1308 return self.user_log_id
1327 return self.user_log_id
1309
1328
1310 @property
1329 @property
1311 def action_as_day(self):
1330 def action_as_day(self):
1312 return datetime.date(*self.action_date.timetuple()[:3])
1331 return datetime.date(*self.action_date.timetuple()[:3])
1313
1332
1314 user = relationship('User')
1333 user = relationship('User')
1315 repository = relationship('Repository', cascade='')
1334 repository = relationship('Repository', cascade='')
1316
1335
1317
1336
1318 class UserGroup(Base, BaseModel):
1337 class UserGroup(Base, BaseModel):
1319 __tablename__ = 'users_groups'
1338 __tablename__ = 'users_groups'
1320 __table_args__ = (
1339 __table_args__ = (
1321 base_table_args,
1340 base_table_args,
1322 )
1341 )
1323
1342
1324 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1343 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1325 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1344 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1326 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1345 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1327 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1346 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1328 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1347 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1329 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1348 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1330 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1349 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1331 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1350 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1332
1351
1333 members = relationship('UserGroupMember', cascade="all, delete-orphan", lazy="joined")
1352 members = relationship('UserGroupMember', cascade="all, delete-orphan", lazy="joined")
1334 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1353 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1335 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1354 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1336 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1355 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1337 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1356 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1338 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1357 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1339
1358
1340 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1359 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1341 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1360 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1342
1361
1343 @classmethod
1362 @classmethod
1344 def _load_group_data(cls, column):
1363 def _load_group_data(cls, column):
1345 if not column:
1364 if not column:
1346 return {}
1365 return {}
1347
1366
1348 try:
1367 try:
1349 return json.loads(column) or {}
1368 return json.loads(column) or {}
1350 except TypeError:
1369 except TypeError:
1351 return {}
1370 return {}
1352
1371
1353 @hybrid_property
1372 @hybrid_property
1354 def description_safe(self):
1373 def description_safe(self):
1355 from rhodecode.lib import helpers as h
1374 from rhodecode.lib import helpers as h
1356 return h.escape(self.user_group_description)
1375 return h.escape(self.user_group_description)
1357
1376
1358 @hybrid_property
1377 @hybrid_property
1359 def group_data(self):
1378 def group_data(self):
1360 return self._load_group_data(self._group_data)
1379 return self._load_group_data(self._group_data)
1361
1380
1362 @group_data.expression
1381 @group_data.expression
1363 def group_data(self, **kwargs):
1382 def group_data(self, **kwargs):
1364 return self._group_data
1383 return self._group_data
1365
1384
1366 @group_data.setter
1385 @group_data.setter
1367 def group_data(self, val):
1386 def group_data(self, val):
1368 try:
1387 try:
1369 self._group_data = json.dumps(val)
1388 self._group_data = json.dumps(val)
1370 except Exception:
1389 except Exception:
1371 log.error(traceback.format_exc())
1390 log.error(traceback.format_exc())
1372
1391
1373 @classmethod
1392 @classmethod
1374 def _load_sync(cls, group_data):
1393 def _load_sync(cls, group_data):
1375 if group_data:
1394 if group_data:
1376 return group_data.get('extern_type')
1395 return group_data.get('extern_type')
1377
1396
1378 @property
1397 @property
1379 def sync(self):
1398 def sync(self):
1380 return self._load_sync(self.group_data)
1399 return self._load_sync(self.group_data)
1381
1400
1382 def __unicode__(self):
1401 def __unicode__(self):
1383 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1402 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1384 self.users_group_id,
1403 self.users_group_id,
1385 self.users_group_name)
1404 self.users_group_name)
1386
1405
1387 @classmethod
1406 @classmethod
1388 def get_by_group_name(cls, group_name, cache=False,
1407 def get_by_group_name(cls, group_name, cache=False,
1389 case_insensitive=False):
1408 case_insensitive=False):
1390 if case_insensitive:
1409 if case_insensitive:
1391 q = cls.query().filter(func.lower(cls.users_group_name) ==
1410 q = cls.query().filter(func.lower(cls.users_group_name) ==
1392 func.lower(group_name))
1411 func.lower(group_name))
1393
1412
1394 else:
1413 else:
1395 q = cls.query().filter(cls.users_group_name == group_name)
1414 q = cls.query().filter(cls.users_group_name == group_name)
1396 if cache:
1415 if cache:
1397 q = q.options(
1416 q = q.options(
1398 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1417 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1399 return q.scalar()
1418 return q.scalar()
1400
1419
1401 @classmethod
1420 @classmethod
1402 def get(cls, user_group_id, cache=False):
1421 def get(cls, user_group_id, cache=False):
1403 if not user_group_id:
1422 if not user_group_id:
1404 return
1423 return
1405
1424
1406 user_group = cls.query()
1425 user_group = cls.query()
1407 if cache:
1426 if cache:
1408 user_group = user_group.options(
1427 user_group = user_group.options(
1409 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1428 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1410 return user_group.get(user_group_id)
1429 return user_group.get(user_group_id)
1411
1430
1412 def permissions(self, with_admins=True, with_owner=True,
1431 def permissions(self, with_admins=True, with_owner=True,
1413 expand_from_user_groups=False):
1432 expand_from_user_groups=False):
1414 """
1433 """
1415 Permissions for user groups
1434 Permissions for user groups
1416 """
1435 """
1417 _admin_perm = 'usergroup.admin'
1436 _admin_perm = 'usergroup.admin'
1418
1437
1419 owner_row = []
1438 owner_row = []
1420 if with_owner:
1439 if with_owner:
1421 usr = AttributeDict(self.user.get_dict())
1440 usr = AttributeDict(self.user.get_dict())
1422 usr.owner_row = True
1441 usr.owner_row = True
1423 usr.permission = _admin_perm
1442 usr.permission = _admin_perm
1424 owner_row.append(usr)
1443 owner_row.append(usr)
1425
1444
1426 super_admin_ids = []
1445 super_admin_ids = []
1427 super_admin_rows = []
1446 super_admin_rows = []
1428 if with_admins:
1447 if with_admins:
1429 for usr in User.get_all_super_admins():
1448 for usr in User.get_all_super_admins():
1430 super_admin_ids.append(usr.user_id)
1449 super_admin_ids.append(usr.user_id)
1431 # if this admin is also owner, don't double the record
1450 # if this admin is also owner, don't double the record
1432 if usr.user_id == owner_row[0].user_id:
1451 if usr.user_id == owner_row[0].user_id:
1433 owner_row[0].admin_row = True
1452 owner_row[0].admin_row = True
1434 else:
1453 else:
1435 usr = AttributeDict(usr.get_dict())
1454 usr = AttributeDict(usr.get_dict())
1436 usr.admin_row = True
1455 usr.admin_row = True
1437 usr.permission = _admin_perm
1456 usr.permission = _admin_perm
1438 super_admin_rows.append(usr)
1457 super_admin_rows.append(usr)
1439
1458
1440 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1459 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1441 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1460 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1442 joinedload(UserUserGroupToPerm.user),
1461 joinedload(UserUserGroupToPerm.user),
1443 joinedload(UserUserGroupToPerm.permission),)
1462 joinedload(UserUserGroupToPerm.permission),)
1444
1463
1445 # get owners and admins and permissions. We do a trick of re-writing
1464 # get owners and admins and permissions. We do a trick of re-writing
1446 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1465 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1447 # has a global reference and changing one object propagates to all
1466 # has a global reference and changing one object propagates to all
1448 # others. This means if admin is also an owner admin_row that change
1467 # others. This means if admin is also an owner admin_row that change
1449 # would propagate to both objects
1468 # would propagate to both objects
1450 perm_rows = []
1469 perm_rows = []
1451 for _usr in q.all():
1470 for _usr in q.all():
1452 usr = AttributeDict(_usr.user.get_dict())
1471 usr = AttributeDict(_usr.user.get_dict())
1453 # if this user is also owner/admin, mark as duplicate record
1472 # if this user is also owner/admin, mark as duplicate record
1454 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1473 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1455 usr.duplicate_perm = True
1474 usr.duplicate_perm = True
1456 usr.permission = _usr.permission.permission_name
1475 usr.permission = _usr.permission.permission_name
1457 perm_rows.append(usr)
1476 perm_rows.append(usr)
1458
1477
1459 # filter the perm rows by 'default' first and then sort them by
1478 # filter the perm rows by 'default' first and then sort them by
1460 # admin,write,read,none permissions sorted again alphabetically in
1479 # admin,write,read,none permissions sorted again alphabetically in
1461 # each group
1480 # each group
1462 perm_rows = sorted(perm_rows, key=display_user_sort)
1481 perm_rows = sorted(perm_rows, key=display_user_sort)
1463
1482
1464 user_groups_rows = []
1483 user_groups_rows = []
1465 if expand_from_user_groups:
1484 if expand_from_user_groups:
1466 for ug in self.permission_user_groups(with_members=True):
1485 for ug in self.permission_user_groups(with_members=True):
1467 for user_data in ug.members:
1486 for user_data in ug.members:
1468 user_groups_rows.append(user_data)
1487 user_groups_rows.append(user_data)
1469
1488
1470 return super_admin_rows + owner_row + perm_rows + user_groups_rows
1489 return super_admin_rows + owner_row + perm_rows + user_groups_rows
1471
1490
1472 def permission_user_groups(self, with_members=False):
1491 def permission_user_groups(self, with_members=False):
1473 q = UserGroupUserGroupToPerm.query()\
1492 q = UserGroupUserGroupToPerm.query()\
1474 .filter(UserGroupUserGroupToPerm.target_user_group == self)
1493 .filter(UserGroupUserGroupToPerm.target_user_group == self)
1475 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1494 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1476 joinedload(UserGroupUserGroupToPerm.target_user_group),
1495 joinedload(UserGroupUserGroupToPerm.target_user_group),
1477 joinedload(UserGroupUserGroupToPerm.permission),)
1496 joinedload(UserGroupUserGroupToPerm.permission),)
1478
1497
1479 perm_rows = []
1498 perm_rows = []
1480 for _user_group in q.all():
1499 for _user_group in q.all():
1481 entry = AttributeDict(_user_group.user_group.get_dict())
1500 entry = AttributeDict(_user_group.user_group.get_dict())
1482 entry.permission = _user_group.permission.permission_name
1501 entry.permission = _user_group.permission.permission_name
1483 if with_members:
1502 if with_members:
1484 entry.members = [x.user.get_dict()
1503 entry.members = [x.user.get_dict()
1485 for x in _user_group.user_group.members]
1504 for x in _user_group.user_group.members]
1486 perm_rows.append(entry)
1505 perm_rows.append(entry)
1487
1506
1488 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1507 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1489 return perm_rows
1508 return perm_rows
1490
1509
1491 def _get_default_perms(self, user_group, suffix=''):
1510 def _get_default_perms(self, user_group, suffix=''):
1492 from rhodecode.model.permission import PermissionModel
1511 from rhodecode.model.permission import PermissionModel
1493 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1512 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1494
1513
1495 def get_default_perms(self, suffix=''):
1514 def get_default_perms(self, suffix=''):
1496 return self._get_default_perms(self, suffix)
1515 return self._get_default_perms(self, suffix)
1497
1516
1498 def get_api_data(self, with_group_members=True, include_secrets=False):
1517 def get_api_data(self, with_group_members=True, include_secrets=False):
1499 """
1518 """
1500 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1519 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1501 basically forwarded.
1520 basically forwarded.
1502
1521
1503 """
1522 """
1504 user_group = self
1523 user_group = self
1505 data = {
1524 data = {
1506 'users_group_id': user_group.users_group_id,
1525 'users_group_id': user_group.users_group_id,
1507 'group_name': user_group.users_group_name,
1526 'group_name': user_group.users_group_name,
1508 'group_description': user_group.user_group_description,
1527 'group_description': user_group.user_group_description,
1509 'active': user_group.users_group_active,
1528 'active': user_group.users_group_active,
1510 'owner': user_group.user.username,
1529 'owner': user_group.user.username,
1511 'sync': user_group.sync,
1530 'sync': user_group.sync,
1512 'owner_email': user_group.user.email,
1531 'owner_email': user_group.user.email,
1513 }
1532 }
1514
1533
1515 if with_group_members:
1534 if with_group_members:
1516 users = []
1535 users = []
1517 for user in user_group.members:
1536 for user in user_group.members:
1518 user = user.user
1537 user = user.user
1519 users.append(user.get_api_data(include_secrets=include_secrets))
1538 users.append(user.get_api_data(include_secrets=include_secrets))
1520 data['users'] = users
1539 data['users'] = users
1521
1540
1522 return data
1541 return data
1523
1542
1524
1543
1525 class UserGroupMember(Base, BaseModel):
1544 class UserGroupMember(Base, BaseModel):
1526 __tablename__ = 'users_groups_members'
1545 __tablename__ = 'users_groups_members'
1527 __table_args__ = (
1546 __table_args__ = (
1528 base_table_args,
1547 base_table_args,
1529 )
1548 )
1530
1549
1531 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1550 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1532 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1551 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1533 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1552 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1534
1553
1535 user = relationship('User', lazy='joined')
1554 user = relationship('User', lazy='joined')
1536 users_group = relationship('UserGroup')
1555 users_group = relationship('UserGroup')
1537
1556
1538 def __init__(self, gr_id='', u_id=''):
1557 def __init__(self, gr_id='', u_id=''):
1539 self.users_group_id = gr_id
1558 self.users_group_id = gr_id
1540 self.user_id = u_id
1559 self.user_id = u_id
1541
1560
1542
1561
1543 class RepositoryField(Base, BaseModel):
1562 class RepositoryField(Base, BaseModel):
1544 __tablename__ = 'repositories_fields'
1563 __tablename__ = 'repositories_fields'
1545 __table_args__ = (
1564 __table_args__ = (
1546 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1565 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1547 base_table_args,
1566 base_table_args,
1548 )
1567 )
1549
1568
1550 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1569 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1551
1570
1552 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1571 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1553 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1572 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1554 field_key = Column("field_key", String(250))
1573 field_key = Column("field_key", String(250))
1555 field_label = Column("field_label", String(1024), nullable=False)
1574 field_label = Column("field_label", String(1024), nullable=False)
1556 field_value = Column("field_value", String(10000), nullable=False)
1575 field_value = Column("field_value", String(10000), nullable=False)
1557 field_desc = Column("field_desc", String(1024), nullable=False)
1576 field_desc = Column("field_desc", String(1024), nullable=False)
1558 field_type = Column("field_type", String(255), nullable=False, unique=None)
1577 field_type = Column("field_type", String(255), nullable=False, unique=None)
1559 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1578 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1560
1579
1561 repository = relationship('Repository')
1580 repository = relationship('Repository')
1562
1581
1563 @property
1582 @property
1564 def field_key_prefixed(self):
1583 def field_key_prefixed(self):
1565 return 'ex_%s' % self.field_key
1584 return 'ex_%s' % self.field_key
1566
1585
1567 @classmethod
1586 @classmethod
1568 def un_prefix_key(cls, key):
1587 def un_prefix_key(cls, key):
1569 if key.startswith(cls.PREFIX):
1588 if key.startswith(cls.PREFIX):
1570 return key[len(cls.PREFIX):]
1589 return key[len(cls.PREFIX):]
1571 return key
1590 return key
1572
1591
1573 @classmethod
1592 @classmethod
1574 def get_by_key_name(cls, key, repo):
1593 def get_by_key_name(cls, key, repo):
1575 row = cls.query()\
1594 row = cls.query()\
1576 .filter(cls.repository == repo)\
1595 .filter(cls.repository == repo)\
1577 .filter(cls.field_key == key).scalar()
1596 .filter(cls.field_key == key).scalar()
1578 return row
1597 return row
1579
1598
1580
1599
1581 class Repository(Base, BaseModel):
1600 class Repository(Base, BaseModel):
1582 __tablename__ = 'repositories'
1601 __tablename__ = 'repositories'
1583 __table_args__ = (
1602 __table_args__ = (
1584 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1603 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1585 base_table_args,
1604 base_table_args,
1586 )
1605 )
1587 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1606 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1588 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1607 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1589 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1608 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1590
1609
1591 STATE_CREATED = 'repo_state_created'
1610 STATE_CREATED = 'repo_state_created'
1592 STATE_PENDING = 'repo_state_pending'
1611 STATE_PENDING = 'repo_state_pending'
1593 STATE_ERROR = 'repo_state_error'
1612 STATE_ERROR = 'repo_state_error'
1594
1613
1595 LOCK_AUTOMATIC = 'lock_auto'
1614 LOCK_AUTOMATIC = 'lock_auto'
1596 LOCK_API = 'lock_api'
1615 LOCK_API = 'lock_api'
1597 LOCK_WEB = 'lock_web'
1616 LOCK_WEB = 'lock_web'
1598 LOCK_PULL = 'lock_pull'
1617 LOCK_PULL = 'lock_pull'
1599
1618
1600 NAME_SEP = URL_SEP
1619 NAME_SEP = URL_SEP
1601
1620
1602 repo_id = Column(
1621 repo_id = Column(
1603 "repo_id", Integer(), nullable=False, unique=True, default=None,
1622 "repo_id", Integer(), nullable=False, unique=True, default=None,
1604 primary_key=True)
1623 primary_key=True)
1605 _repo_name = Column(
1624 _repo_name = Column(
1606 "repo_name", Text(), nullable=False, default=None)
1625 "repo_name", Text(), nullable=False, default=None)
1607 _repo_name_hash = Column(
1626 _repo_name_hash = Column(
1608 "repo_name_hash", String(255), nullable=False, unique=True)
1627 "repo_name_hash", String(255), nullable=False, unique=True)
1609 repo_state = Column("repo_state", String(255), nullable=True)
1628 repo_state = Column("repo_state", String(255), nullable=True)
1610
1629
1611 clone_uri = Column(
1630 clone_uri = Column(
1612 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1631 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1613 default=None)
1632 default=None)
1614 push_uri = Column(
1633 push_uri = Column(
1615 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1634 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1616 default=None)
1635 default=None)
1617 repo_type = Column(
1636 repo_type = Column(
1618 "repo_type", String(255), nullable=False, unique=False, default=None)
1637 "repo_type", String(255), nullable=False, unique=False, default=None)
1619 user_id = Column(
1638 user_id = Column(
1620 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1639 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1621 unique=False, default=None)
1640 unique=False, default=None)
1622 private = Column(
1641 private = Column(
1623 "private", Boolean(), nullable=True, unique=None, default=None)
1642 "private", Boolean(), nullable=True, unique=None, default=None)
1624 archived = Column(
1643 archived = Column(
1625 "archived", Boolean(), nullable=True, unique=None, default=None)
1644 "archived", Boolean(), nullable=True, unique=None, default=None)
1626 enable_statistics = Column(
1645 enable_statistics = Column(
1627 "statistics", Boolean(), nullable=True, unique=None, default=True)
1646 "statistics", Boolean(), nullable=True, unique=None, default=True)
1628 enable_downloads = Column(
1647 enable_downloads = Column(
1629 "downloads", Boolean(), nullable=True, unique=None, default=True)
1648 "downloads", Boolean(), nullable=True, unique=None, default=True)
1630 description = Column(
1649 description = Column(
1631 "description", String(10000), nullable=True, unique=None, default=None)
1650 "description", String(10000), nullable=True, unique=None, default=None)
1632 created_on = Column(
1651 created_on = Column(
1633 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1652 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1634 default=datetime.datetime.now)
1653 default=datetime.datetime.now)
1635 updated_on = Column(
1654 updated_on = Column(
1636 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1655 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1637 default=datetime.datetime.now)
1656 default=datetime.datetime.now)
1638 _landing_revision = Column(
1657 _landing_revision = Column(
1639 "landing_revision", String(255), nullable=False, unique=False,
1658 "landing_revision", String(255), nullable=False, unique=False,
1640 default=None)
1659 default=None)
1641 enable_locking = Column(
1660 enable_locking = Column(
1642 "enable_locking", Boolean(), nullable=False, unique=None,
1661 "enable_locking", Boolean(), nullable=False, unique=None,
1643 default=False)
1662 default=False)
1644 _locked = Column(
1663 _locked = Column(
1645 "locked", String(255), nullable=True, unique=False, default=None)
1664 "locked", String(255), nullable=True, unique=False, default=None)
1646 _changeset_cache = Column(
1665 _changeset_cache = Column(
1647 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1666 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1648
1667
1649 fork_id = Column(
1668 fork_id = Column(
1650 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1669 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1651 nullable=True, unique=False, default=None)
1670 nullable=True, unique=False, default=None)
1652 group_id = Column(
1671 group_id = Column(
1653 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1672 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1654 unique=False, default=None)
1673 unique=False, default=None)
1655
1674
1656 user = relationship('User', lazy='joined')
1675 user = relationship('User', lazy='joined')
1657 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1676 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1658 group = relationship('RepoGroup', lazy='joined')
1677 group = relationship('RepoGroup', lazy='joined')
1659 repo_to_perm = relationship(
1678 repo_to_perm = relationship(
1660 'UserRepoToPerm', cascade='all',
1679 'UserRepoToPerm', cascade='all',
1661 order_by='UserRepoToPerm.repo_to_perm_id')
1680 order_by='UserRepoToPerm.repo_to_perm_id')
1662 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1681 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1663 stats = relationship('Statistics', cascade='all', uselist=False)
1682 stats = relationship('Statistics', cascade='all', uselist=False)
1664
1683
1665 followers = relationship(
1684 followers = relationship(
1666 'UserFollowing',
1685 'UserFollowing',
1667 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1686 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1668 cascade='all')
1687 cascade='all')
1669 extra_fields = relationship(
1688 extra_fields = relationship(
1670 'RepositoryField', cascade="all, delete-orphan")
1689 'RepositoryField', cascade="all, delete-orphan")
1671 logs = relationship('UserLog')
1690 logs = relationship('UserLog')
1672 comments = relationship(
1691 comments = relationship(
1673 'ChangesetComment', cascade="all, delete-orphan")
1692 'ChangesetComment', cascade="all, delete-orphan")
1674 pull_requests_source = relationship(
1693 pull_requests_source = relationship(
1675 'PullRequest',
1694 'PullRequest',
1676 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1695 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1677 cascade="all, delete-orphan")
1696 cascade="all, delete-orphan")
1678 pull_requests_target = relationship(
1697 pull_requests_target = relationship(
1679 'PullRequest',
1698 'PullRequest',
1680 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1699 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1681 cascade="all, delete-orphan")
1700 cascade="all, delete-orphan")
1682 ui = relationship('RepoRhodeCodeUi', cascade="all")
1701 ui = relationship('RepoRhodeCodeUi', cascade="all")
1683 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1702 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1684 integrations = relationship('Integration', cascade="all, delete-orphan")
1703 integrations = relationship('Integration', cascade="all, delete-orphan")
1685
1704
1686 scoped_tokens = relationship('UserApiKeys', cascade="all")
1705 scoped_tokens = relationship('UserApiKeys', cascade="all")
1687
1706
1688 artifacts = relationship('FileStore', cascade="all")
1707 artifacts = relationship('FileStore', cascade="all")
1689
1708
1690 def __unicode__(self):
1709 def __unicode__(self):
1691 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1710 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1692 safe_unicode(self.repo_name))
1711 safe_unicode(self.repo_name))
1693
1712
1694 @hybrid_property
1713 @hybrid_property
1695 def description_safe(self):
1714 def description_safe(self):
1696 from rhodecode.lib import helpers as h
1715 from rhodecode.lib import helpers as h
1697 return h.escape(self.description)
1716 return h.escape(self.description)
1698
1717
1699 @hybrid_property
1718 @hybrid_property
1700 def landing_rev(self):
1719 def landing_rev(self):
1701 # always should return [rev_type, rev]
1720 # always should return [rev_type, rev]
1702 if self._landing_revision:
1721 if self._landing_revision:
1703 _rev_info = self._landing_revision.split(':')
1722 _rev_info = self._landing_revision.split(':')
1704 if len(_rev_info) < 2:
1723 if len(_rev_info) < 2:
1705 _rev_info.insert(0, 'rev')
1724 _rev_info.insert(0, 'rev')
1706 return [_rev_info[0], _rev_info[1]]
1725 return [_rev_info[0], _rev_info[1]]
1707 return [None, None]
1726 return [None, None]
1708
1727
1709 @landing_rev.setter
1728 @landing_rev.setter
1710 def landing_rev(self, val):
1729 def landing_rev(self, val):
1711 if ':' not in val:
1730 if ':' not in val:
1712 raise ValueError('value must be delimited with `:` and consist '
1731 raise ValueError('value must be delimited with `:` and consist '
1713 'of <rev_type>:<rev>, got %s instead' % val)
1732 'of <rev_type>:<rev>, got %s instead' % val)
1714 self._landing_revision = val
1733 self._landing_revision = val
1715
1734
1716 @hybrid_property
1735 @hybrid_property
1717 def locked(self):
1736 def locked(self):
1718 if self._locked:
1737 if self._locked:
1719 user_id, timelocked, reason = self._locked.split(':')
1738 user_id, timelocked, reason = self._locked.split(':')
1720 lock_values = int(user_id), timelocked, reason
1739 lock_values = int(user_id), timelocked, reason
1721 else:
1740 else:
1722 lock_values = [None, None, None]
1741 lock_values = [None, None, None]
1723 return lock_values
1742 return lock_values
1724
1743
1725 @locked.setter
1744 @locked.setter
1726 def locked(self, val):
1745 def locked(self, val):
1727 if val and isinstance(val, (list, tuple)):
1746 if val and isinstance(val, (list, tuple)):
1728 self._locked = ':'.join(map(str, val))
1747 self._locked = ':'.join(map(str, val))
1729 else:
1748 else:
1730 self._locked = None
1749 self._locked = None
1731
1750
1732 @hybrid_property
1751 @hybrid_property
1733 def changeset_cache(self):
1752 def changeset_cache(self):
1734 from rhodecode.lib.vcs.backends.base import EmptyCommit
1753 from rhodecode.lib.vcs.backends.base import EmptyCommit
1735 dummy = EmptyCommit().__json__()
1754 dummy = EmptyCommit().__json__()
1736 if not self._changeset_cache:
1755 if not self._changeset_cache:
1737 dummy['source_repo_id'] = self.repo_id
1756 dummy['source_repo_id'] = self.repo_id
1738 return json.loads(json.dumps(dummy))
1757 return json.loads(json.dumps(dummy))
1739
1758
1740 try:
1759 try:
1741 return json.loads(self._changeset_cache)
1760 return json.loads(self._changeset_cache)
1742 except TypeError:
1761 except TypeError:
1743 return dummy
1762 return dummy
1744 except Exception:
1763 except Exception:
1745 log.error(traceback.format_exc())
1764 log.error(traceback.format_exc())
1746 return dummy
1765 return dummy
1747
1766
1748 @changeset_cache.setter
1767 @changeset_cache.setter
1749 def changeset_cache(self, val):
1768 def changeset_cache(self, val):
1750 try:
1769 try:
1751 self._changeset_cache = json.dumps(val)
1770 self._changeset_cache = json.dumps(val)
1752 except Exception:
1771 except Exception:
1753 log.error(traceback.format_exc())
1772 log.error(traceback.format_exc())
1754
1773
1755 @hybrid_property
1774 @hybrid_property
1756 def repo_name(self):
1775 def repo_name(self):
1757 return self._repo_name
1776 return self._repo_name
1758
1777
1759 @repo_name.setter
1778 @repo_name.setter
1760 def repo_name(self, value):
1779 def repo_name(self, value):
1761 self._repo_name = value
1780 self._repo_name = value
1762 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1781 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1763
1782
1764 @classmethod
1783 @classmethod
1765 def normalize_repo_name(cls, repo_name):
1784 def normalize_repo_name(cls, repo_name):
1766 """
1785 """
1767 Normalizes os specific repo_name to the format internally stored inside
1786 Normalizes os specific repo_name to the format internally stored inside
1768 database using URL_SEP
1787 database using URL_SEP
1769
1788
1770 :param cls:
1789 :param cls:
1771 :param repo_name:
1790 :param repo_name:
1772 """
1791 """
1773 return cls.NAME_SEP.join(repo_name.split(os.sep))
1792 return cls.NAME_SEP.join(repo_name.split(os.sep))
1774
1793
1775 @classmethod
1794 @classmethod
1776 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1795 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1777 session = Session()
1796 session = Session()
1778 q = session.query(cls).filter(cls.repo_name == repo_name)
1797 q = session.query(cls).filter(cls.repo_name == repo_name)
1779
1798
1780 if cache:
1799 if cache:
1781 if identity_cache:
1800 if identity_cache:
1782 val = cls.identity_cache(session, 'repo_name', repo_name)
1801 val = cls.identity_cache(session, 'repo_name', repo_name)
1783 if val:
1802 if val:
1784 return val
1803 return val
1785 else:
1804 else:
1786 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1805 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1787 q = q.options(
1806 q = q.options(
1788 FromCache("sql_cache_short", cache_key))
1807 FromCache("sql_cache_short", cache_key))
1789
1808
1790 return q.scalar()
1809 return q.scalar()
1791
1810
1792 @classmethod
1811 @classmethod
1793 def get_by_id_or_repo_name(cls, repoid):
1812 def get_by_id_or_repo_name(cls, repoid):
1794 if isinstance(repoid, (int, long)):
1813 if isinstance(repoid, (int, long)):
1795 try:
1814 try:
1796 repo = cls.get(repoid)
1815 repo = cls.get(repoid)
1797 except ValueError:
1816 except ValueError:
1798 repo = None
1817 repo = None
1799 else:
1818 else:
1800 repo = cls.get_by_repo_name(repoid)
1819 repo = cls.get_by_repo_name(repoid)
1801 return repo
1820 return repo
1802
1821
1803 @classmethod
1822 @classmethod
1804 def get_by_full_path(cls, repo_full_path):
1823 def get_by_full_path(cls, repo_full_path):
1805 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1824 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1806 repo_name = cls.normalize_repo_name(repo_name)
1825 repo_name = cls.normalize_repo_name(repo_name)
1807 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1826 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1808
1827
1809 @classmethod
1828 @classmethod
1810 def get_repo_forks(cls, repo_id):
1829 def get_repo_forks(cls, repo_id):
1811 return cls.query().filter(Repository.fork_id == repo_id)
1830 return cls.query().filter(Repository.fork_id == repo_id)
1812
1831
1813 @classmethod
1832 @classmethod
1814 def base_path(cls):
1833 def base_path(cls):
1815 """
1834 """
1816 Returns base path when all repos are stored
1835 Returns base path when all repos are stored
1817
1836
1818 :param cls:
1837 :param cls:
1819 """
1838 """
1820 q = Session().query(RhodeCodeUi)\
1839 q = Session().query(RhodeCodeUi)\
1821 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1840 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1822 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1841 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1823 return q.one().ui_value
1842 return q.one().ui_value
1824
1843
1825 @classmethod
1844 @classmethod
1826 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1845 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1827 case_insensitive=True, archived=False):
1846 case_insensitive=True, archived=False):
1828 q = Repository.query()
1847 q = Repository.query()
1829
1848
1830 if not archived:
1849 if not archived:
1831 q = q.filter(Repository.archived.isnot(true()))
1850 q = q.filter(Repository.archived.isnot(true()))
1832
1851
1833 if not isinstance(user_id, Optional):
1852 if not isinstance(user_id, Optional):
1834 q = q.filter(Repository.user_id == user_id)
1853 q = q.filter(Repository.user_id == user_id)
1835
1854
1836 if not isinstance(group_id, Optional):
1855 if not isinstance(group_id, Optional):
1837 q = q.filter(Repository.group_id == group_id)
1856 q = q.filter(Repository.group_id == group_id)
1838
1857
1839 if case_insensitive:
1858 if case_insensitive:
1840 q = q.order_by(func.lower(Repository.repo_name))
1859 q = q.order_by(func.lower(Repository.repo_name))
1841 else:
1860 else:
1842 q = q.order_by(Repository.repo_name)
1861 q = q.order_by(Repository.repo_name)
1843
1862
1844 return q.all()
1863 return q.all()
1845
1864
1846 @property
1865 @property
1847 def repo_uid(self):
1866 def repo_uid(self):
1848 return '_{}'.format(self.repo_id)
1867 return '_{}'.format(self.repo_id)
1849
1868
1850 @property
1869 @property
1851 def forks(self):
1870 def forks(self):
1852 """
1871 """
1853 Return forks of this repo
1872 Return forks of this repo
1854 """
1873 """
1855 return Repository.get_repo_forks(self.repo_id)
1874 return Repository.get_repo_forks(self.repo_id)
1856
1875
1857 @property
1876 @property
1858 def parent(self):
1877 def parent(self):
1859 """
1878 """
1860 Returns fork parent
1879 Returns fork parent
1861 """
1880 """
1862 return self.fork
1881 return self.fork
1863
1882
1864 @property
1883 @property
1865 def just_name(self):
1884 def just_name(self):
1866 return self.repo_name.split(self.NAME_SEP)[-1]
1885 return self.repo_name.split(self.NAME_SEP)[-1]
1867
1886
1868 @property
1887 @property
1869 def groups_with_parents(self):
1888 def groups_with_parents(self):
1870 groups = []
1889 groups = []
1871 if self.group is None:
1890 if self.group is None:
1872 return groups
1891 return groups
1873
1892
1874 cur_gr = self.group
1893 cur_gr = self.group
1875 groups.insert(0, cur_gr)
1894 groups.insert(0, cur_gr)
1876 while 1:
1895 while 1:
1877 gr = getattr(cur_gr, 'parent_group', None)
1896 gr = getattr(cur_gr, 'parent_group', None)
1878 cur_gr = cur_gr.parent_group
1897 cur_gr = cur_gr.parent_group
1879 if gr is None:
1898 if gr is None:
1880 break
1899 break
1881 groups.insert(0, gr)
1900 groups.insert(0, gr)
1882
1901
1883 return groups
1902 return groups
1884
1903
1885 @property
1904 @property
1886 def groups_and_repo(self):
1905 def groups_and_repo(self):
1887 return self.groups_with_parents, self
1906 return self.groups_with_parents, self
1888
1907
1889 @LazyProperty
1908 @LazyProperty
1890 def repo_path(self):
1909 def repo_path(self):
1891 """
1910 """
1892 Returns base full path for that repository means where it actually
1911 Returns base full path for that repository means where it actually
1893 exists on a filesystem
1912 exists on a filesystem
1894 """
1913 """
1895 q = Session().query(RhodeCodeUi).filter(
1914 q = Session().query(RhodeCodeUi).filter(
1896 RhodeCodeUi.ui_key == self.NAME_SEP)
1915 RhodeCodeUi.ui_key == self.NAME_SEP)
1897 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1916 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1898 return q.one().ui_value
1917 return q.one().ui_value
1899
1918
1900 @property
1919 @property
1901 def repo_full_path(self):
1920 def repo_full_path(self):
1902 p = [self.repo_path]
1921 p = [self.repo_path]
1903 # we need to split the name by / since this is how we store the
1922 # we need to split the name by / since this is how we store the
1904 # names in the database, but that eventually needs to be converted
1923 # names in the database, but that eventually needs to be converted
1905 # into a valid system path
1924 # into a valid system path
1906 p += self.repo_name.split(self.NAME_SEP)
1925 p += self.repo_name.split(self.NAME_SEP)
1907 return os.path.join(*map(safe_unicode, p))
1926 return os.path.join(*map(safe_unicode, p))
1908
1927
1909 @property
1928 @property
1910 def cache_keys(self):
1929 def cache_keys(self):
1911 """
1930 """
1912 Returns associated cache keys for that repo
1931 Returns associated cache keys for that repo
1913 """
1932 """
1914 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
1933 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
1915 repo_id=self.repo_id)
1934 repo_id=self.repo_id)
1916 return CacheKey.query()\
1935 return CacheKey.query()\
1917 .filter(CacheKey.cache_args == invalidation_namespace)\
1936 .filter(CacheKey.cache_args == invalidation_namespace)\
1918 .order_by(CacheKey.cache_key)\
1937 .order_by(CacheKey.cache_key)\
1919 .all()
1938 .all()
1920
1939
1921 @property
1940 @property
1922 def cached_diffs_relative_dir(self):
1941 def cached_diffs_relative_dir(self):
1923 """
1942 """
1924 Return a relative to the repository store path of cached diffs
1943 Return a relative to the repository store path of cached diffs
1925 used for safe display for users, who shouldn't know the absolute store
1944 used for safe display for users, who shouldn't know the absolute store
1926 path
1945 path
1927 """
1946 """
1928 return os.path.join(
1947 return os.path.join(
1929 os.path.dirname(self.repo_name),
1948 os.path.dirname(self.repo_name),
1930 self.cached_diffs_dir.split(os.path.sep)[-1])
1949 self.cached_diffs_dir.split(os.path.sep)[-1])
1931
1950
1932 @property
1951 @property
1933 def cached_diffs_dir(self):
1952 def cached_diffs_dir(self):
1934 path = self.repo_full_path
1953 path = self.repo_full_path
1935 return os.path.join(
1954 return os.path.join(
1936 os.path.dirname(path),
1955 os.path.dirname(path),
1937 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
1956 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
1938
1957
1939 def cached_diffs(self):
1958 def cached_diffs(self):
1940 diff_cache_dir = self.cached_diffs_dir
1959 diff_cache_dir = self.cached_diffs_dir
1941 if os.path.isdir(diff_cache_dir):
1960 if os.path.isdir(diff_cache_dir):
1942 return os.listdir(diff_cache_dir)
1961 return os.listdir(diff_cache_dir)
1943 return []
1962 return []
1944
1963
1945 def shadow_repos(self):
1964 def shadow_repos(self):
1946 shadow_repos_pattern = '.__shadow_repo_{}'.format(self.repo_id)
1965 shadow_repos_pattern = '.__shadow_repo_{}'.format(self.repo_id)
1947 return [
1966 return [
1948 x for x in os.listdir(os.path.dirname(self.repo_full_path))
1967 x for x in os.listdir(os.path.dirname(self.repo_full_path))
1949 if x.startswith(shadow_repos_pattern)]
1968 if x.startswith(shadow_repos_pattern)]
1950
1969
1951 def get_new_name(self, repo_name):
1970 def get_new_name(self, repo_name):
1952 """
1971 """
1953 returns new full repository name based on assigned group and new new
1972 returns new full repository name based on assigned group and new new
1954
1973
1955 :param group_name:
1974 :param group_name:
1956 """
1975 """
1957 path_prefix = self.group.full_path_splitted if self.group else []
1976 path_prefix = self.group.full_path_splitted if self.group else []
1958 return self.NAME_SEP.join(path_prefix + [repo_name])
1977 return self.NAME_SEP.join(path_prefix + [repo_name])
1959
1978
1960 @property
1979 @property
1961 def _config(self):
1980 def _config(self):
1962 """
1981 """
1963 Returns db based config object.
1982 Returns db based config object.
1964 """
1983 """
1965 from rhodecode.lib.utils import make_db_config
1984 from rhodecode.lib.utils import make_db_config
1966 return make_db_config(clear_session=False, repo=self)
1985 return make_db_config(clear_session=False, repo=self)
1967
1986
1968 def permissions(self, with_admins=True, with_owner=True,
1987 def permissions(self, with_admins=True, with_owner=True,
1969 expand_from_user_groups=False):
1988 expand_from_user_groups=False):
1970 """
1989 """
1971 Permissions for repositories
1990 Permissions for repositories
1972 """
1991 """
1973 _admin_perm = 'repository.admin'
1992 _admin_perm = 'repository.admin'
1974
1993
1975 owner_row = []
1994 owner_row = []
1976 if with_owner:
1995 if with_owner:
1977 usr = AttributeDict(self.user.get_dict())
1996 usr = AttributeDict(self.user.get_dict())
1978 usr.owner_row = True
1997 usr.owner_row = True
1979 usr.permission = _admin_perm
1998 usr.permission = _admin_perm
1980 usr.permission_id = None
1999 usr.permission_id = None
1981 owner_row.append(usr)
2000 owner_row.append(usr)
1982
2001
1983 super_admin_ids = []
2002 super_admin_ids = []
1984 super_admin_rows = []
2003 super_admin_rows = []
1985 if with_admins:
2004 if with_admins:
1986 for usr in User.get_all_super_admins():
2005 for usr in User.get_all_super_admins():
1987 super_admin_ids.append(usr.user_id)
2006 super_admin_ids.append(usr.user_id)
1988 # if this admin is also owner, don't double the record
2007 # if this admin is also owner, don't double the record
1989 if usr.user_id == owner_row[0].user_id:
2008 if usr.user_id == owner_row[0].user_id:
1990 owner_row[0].admin_row = True
2009 owner_row[0].admin_row = True
1991 else:
2010 else:
1992 usr = AttributeDict(usr.get_dict())
2011 usr = AttributeDict(usr.get_dict())
1993 usr.admin_row = True
2012 usr.admin_row = True
1994 usr.permission = _admin_perm
2013 usr.permission = _admin_perm
1995 usr.permission_id = None
2014 usr.permission_id = None
1996 super_admin_rows.append(usr)
2015 super_admin_rows.append(usr)
1997
2016
1998 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
2017 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1999 q = q.options(joinedload(UserRepoToPerm.repository),
2018 q = q.options(joinedload(UserRepoToPerm.repository),
2000 joinedload(UserRepoToPerm.user),
2019 joinedload(UserRepoToPerm.user),
2001 joinedload(UserRepoToPerm.permission),)
2020 joinedload(UserRepoToPerm.permission),)
2002
2021
2003 # get owners and admins and permissions. We do a trick of re-writing
2022 # get owners and admins and permissions. We do a trick of re-writing
2004 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2023 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2005 # has a global reference and changing one object propagates to all
2024 # has a global reference and changing one object propagates to all
2006 # others. This means if admin is also an owner admin_row that change
2025 # others. This means if admin is also an owner admin_row that change
2007 # would propagate to both objects
2026 # would propagate to both objects
2008 perm_rows = []
2027 perm_rows = []
2009 for _usr in q.all():
2028 for _usr in q.all():
2010 usr = AttributeDict(_usr.user.get_dict())
2029 usr = AttributeDict(_usr.user.get_dict())
2011 # if this user is also owner/admin, mark as duplicate record
2030 # if this user is also owner/admin, mark as duplicate record
2012 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2031 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2013 usr.duplicate_perm = True
2032 usr.duplicate_perm = True
2014 # also check if this permission is maybe used by branch_permissions
2033 # also check if this permission is maybe used by branch_permissions
2015 if _usr.branch_perm_entry:
2034 if _usr.branch_perm_entry:
2016 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
2035 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
2017
2036
2018 usr.permission = _usr.permission.permission_name
2037 usr.permission = _usr.permission.permission_name
2019 usr.permission_id = _usr.repo_to_perm_id
2038 usr.permission_id = _usr.repo_to_perm_id
2020 perm_rows.append(usr)
2039 perm_rows.append(usr)
2021
2040
2022 # filter the perm rows by 'default' first and then sort them by
2041 # filter the perm rows by 'default' first and then sort them by
2023 # admin,write,read,none permissions sorted again alphabetically in
2042 # admin,write,read,none permissions sorted again alphabetically in
2024 # each group
2043 # each group
2025 perm_rows = sorted(perm_rows, key=display_user_sort)
2044 perm_rows = sorted(perm_rows, key=display_user_sort)
2026
2045
2027 user_groups_rows = []
2046 user_groups_rows = []
2028 if expand_from_user_groups:
2047 if expand_from_user_groups:
2029 for ug in self.permission_user_groups(with_members=True):
2048 for ug in self.permission_user_groups(with_members=True):
2030 for user_data in ug.members:
2049 for user_data in ug.members:
2031 user_groups_rows.append(user_data)
2050 user_groups_rows.append(user_data)
2032
2051
2033 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2052 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2034
2053
2035 def permission_user_groups(self, with_members=True):
2054 def permission_user_groups(self, with_members=True):
2036 q = UserGroupRepoToPerm.query()\
2055 q = UserGroupRepoToPerm.query()\
2037 .filter(UserGroupRepoToPerm.repository == self)
2056 .filter(UserGroupRepoToPerm.repository == self)
2038 q = q.options(joinedload(UserGroupRepoToPerm.repository),
2057 q = q.options(joinedload(UserGroupRepoToPerm.repository),
2039 joinedload(UserGroupRepoToPerm.users_group),
2058 joinedload(UserGroupRepoToPerm.users_group),
2040 joinedload(UserGroupRepoToPerm.permission),)
2059 joinedload(UserGroupRepoToPerm.permission),)
2041
2060
2042 perm_rows = []
2061 perm_rows = []
2043 for _user_group in q.all():
2062 for _user_group in q.all():
2044 entry = AttributeDict(_user_group.users_group.get_dict())
2063 entry = AttributeDict(_user_group.users_group.get_dict())
2045 entry.permission = _user_group.permission.permission_name
2064 entry.permission = _user_group.permission.permission_name
2046 if with_members:
2065 if with_members:
2047 entry.members = [x.user.get_dict()
2066 entry.members = [x.user.get_dict()
2048 for x in _user_group.users_group.members]
2067 for x in _user_group.users_group.members]
2049 perm_rows.append(entry)
2068 perm_rows.append(entry)
2050
2069
2051 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2070 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2052 return perm_rows
2071 return perm_rows
2053
2072
2054 def get_api_data(self, include_secrets=False):
2073 def get_api_data(self, include_secrets=False):
2055 """
2074 """
2056 Common function for generating repo api data
2075 Common function for generating repo api data
2057
2076
2058 :param include_secrets: See :meth:`User.get_api_data`.
2077 :param include_secrets: See :meth:`User.get_api_data`.
2059
2078
2060 """
2079 """
2061 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2080 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2062 # move this methods on models level.
2081 # move this methods on models level.
2063 from rhodecode.model.settings import SettingsModel
2082 from rhodecode.model.settings import SettingsModel
2064 from rhodecode.model.repo import RepoModel
2083 from rhodecode.model.repo import RepoModel
2065
2084
2066 repo = self
2085 repo = self
2067 _user_id, _time, _reason = self.locked
2086 _user_id, _time, _reason = self.locked
2068
2087
2069 data = {
2088 data = {
2070 'repo_id': repo.repo_id,
2089 'repo_id': repo.repo_id,
2071 'repo_name': repo.repo_name,
2090 'repo_name': repo.repo_name,
2072 'repo_type': repo.repo_type,
2091 'repo_type': repo.repo_type,
2073 'clone_uri': repo.clone_uri or '',
2092 'clone_uri': repo.clone_uri or '',
2074 'push_uri': repo.push_uri or '',
2093 'push_uri': repo.push_uri or '',
2075 'url': RepoModel().get_url(self),
2094 'url': RepoModel().get_url(self),
2076 'private': repo.private,
2095 'private': repo.private,
2077 'created_on': repo.created_on,
2096 'created_on': repo.created_on,
2078 'description': repo.description_safe,
2097 'description': repo.description_safe,
2079 'landing_rev': repo.landing_rev,
2098 'landing_rev': repo.landing_rev,
2080 'owner': repo.user.username,
2099 'owner': repo.user.username,
2081 'fork_of': repo.fork.repo_name if repo.fork else None,
2100 'fork_of': repo.fork.repo_name if repo.fork else None,
2082 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2101 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2083 'enable_statistics': repo.enable_statistics,
2102 'enable_statistics': repo.enable_statistics,
2084 'enable_locking': repo.enable_locking,
2103 'enable_locking': repo.enable_locking,
2085 'enable_downloads': repo.enable_downloads,
2104 'enable_downloads': repo.enable_downloads,
2086 'last_changeset': repo.changeset_cache,
2105 'last_changeset': repo.changeset_cache,
2087 'locked_by': User.get(_user_id).get_api_data(
2106 'locked_by': User.get(_user_id).get_api_data(
2088 include_secrets=include_secrets) if _user_id else None,
2107 include_secrets=include_secrets) if _user_id else None,
2089 'locked_date': time_to_datetime(_time) if _time else None,
2108 'locked_date': time_to_datetime(_time) if _time else None,
2090 'lock_reason': _reason if _reason else None,
2109 'lock_reason': _reason if _reason else None,
2091 }
2110 }
2092
2111
2093 # TODO: mikhail: should be per-repo settings here
2112 # TODO: mikhail: should be per-repo settings here
2094 rc_config = SettingsModel().get_all_settings()
2113 rc_config = SettingsModel().get_all_settings()
2095 repository_fields = str2bool(
2114 repository_fields = str2bool(
2096 rc_config.get('rhodecode_repository_fields'))
2115 rc_config.get('rhodecode_repository_fields'))
2097 if repository_fields:
2116 if repository_fields:
2098 for f in self.extra_fields:
2117 for f in self.extra_fields:
2099 data[f.field_key_prefixed] = f.field_value
2118 data[f.field_key_prefixed] = f.field_value
2100
2119
2101 return data
2120 return data
2102
2121
2103 @classmethod
2122 @classmethod
2104 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2123 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2105 if not lock_time:
2124 if not lock_time:
2106 lock_time = time.time()
2125 lock_time = time.time()
2107 if not lock_reason:
2126 if not lock_reason:
2108 lock_reason = cls.LOCK_AUTOMATIC
2127 lock_reason = cls.LOCK_AUTOMATIC
2109 repo.locked = [user_id, lock_time, lock_reason]
2128 repo.locked = [user_id, lock_time, lock_reason]
2110 Session().add(repo)
2129 Session().add(repo)
2111 Session().commit()
2130 Session().commit()
2112
2131
2113 @classmethod
2132 @classmethod
2114 def unlock(cls, repo):
2133 def unlock(cls, repo):
2115 repo.locked = None
2134 repo.locked = None
2116 Session().add(repo)
2135 Session().add(repo)
2117 Session().commit()
2136 Session().commit()
2118
2137
2119 @classmethod
2138 @classmethod
2120 def getlock(cls, repo):
2139 def getlock(cls, repo):
2121 return repo.locked
2140 return repo.locked
2122
2141
2123 def is_user_lock(self, user_id):
2142 def is_user_lock(self, user_id):
2124 if self.lock[0]:
2143 if self.lock[0]:
2125 lock_user_id = safe_int(self.lock[0])
2144 lock_user_id = safe_int(self.lock[0])
2126 user_id = safe_int(user_id)
2145 user_id = safe_int(user_id)
2127 # both are ints, and they are equal
2146 # both are ints, and they are equal
2128 return all([lock_user_id, user_id]) and lock_user_id == user_id
2147 return all([lock_user_id, user_id]) and lock_user_id == user_id
2129
2148
2130 return False
2149 return False
2131
2150
2132 def get_locking_state(self, action, user_id, only_when_enabled=True):
2151 def get_locking_state(self, action, user_id, only_when_enabled=True):
2133 """
2152 """
2134 Checks locking on this repository, if locking is enabled and lock is
2153 Checks locking on this repository, if locking is enabled and lock is
2135 present returns a tuple of make_lock, locked, locked_by.
2154 present returns a tuple of make_lock, locked, locked_by.
2136 make_lock can have 3 states None (do nothing) True, make lock
2155 make_lock can have 3 states None (do nothing) True, make lock
2137 False release lock, This value is later propagated to hooks, which
2156 False release lock, This value is later propagated to hooks, which
2138 do the locking. Think about this as signals passed to hooks what to do.
2157 do the locking. Think about this as signals passed to hooks what to do.
2139
2158
2140 """
2159 """
2141 # TODO: johbo: This is part of the business logic and should be moved
2160 # TODO: johbo: This is part of the business logic and should be moved
2142 # into the RepositoryModel.
2161 # into the RepositoryModel.
2143
2162
2144 if action not in ('push', 'pull'):
2163 if action not in ('push', 'pull'):
2145 raise ValueError("Invalid action value: %s" % repr(action))
2164 raise ValueError("Invalid action value: %s" % repr(action))
2146
2165
2147 # defines if locked error should be thrown to user
2166 # defines if locked error should be thrown to user
2148 currently_locked = False
2167 currently_locked = False
2149 # defines if new lock should be made, tri-state
2168 # defines if new lock should be made, tri-state
2150 make_lock = None
2169 make_lock = None
2151 repo = self
2170 repo = self
2152 user = User.get(user_id)
2171 user = User.get(user_id)
2153
2172
2154 lock_info = repo.locked
2173 lock_info = repo.locked
2155
2174
2156 if repo and (repo.enable_locking or not only_when_enabled):
2175 if repo and (repo.enable_locking or not only_when_enabled):
2157 if action == 'push':
2176 if action == 'push':
2158 # check if it's already locked !, if it is compare users
2177 # check if it's already locked !, if it is compare users
2159 locked_by_user_id = lock_info[0]
2178 locked_by_user_id = lock_info[0]
2160 if user.user_id == locked_by_user_id:
2179 if user.user_id == locked_by_user_id:
2161 log.debug(
2180 log.debug(
2162 'Got `push` action from user %s, now unlocking', user)
2181 'Got `push` action from user %s, now unlocking', user)
2163 # unlock if we have push from user who locked
2182 # unlock if we have push from user who locked
2164 make_lock = False
2183 make_lock = False
2165 else:
2184 else:
2166 # we're not the same user who locked, ban with
2185 # we're not the same user who locked, ban with
2167 # code defined in settings (default is 423 HTTP Locked) !
2186 # code defined in settings (default is 423 HTTP Locked) !
2168 log.debug('Repo %s is currently locked by %s', repo, user)
2187 log.debug('Repo %s is currently locked by %s', repo, user)
2169 currently_locked = True
2188 currently_locked = True
2170 elif action == 'pull':
2189 elif action == 'pull':
2171 # [0] user [1] date
2190 # [0] user [1] date
2172 if lock_info[0] and lock_info[1]:
2191 if lock_info[0] and lock_info[1]:
2173 log.debug('Repo %s is currently locked by %s', repo, user)
2192 log.debug('Repo %s is currently locked by %s', repo, user)
2174 currently_locked = True
2193 currently_locked = True
2175 else:
2194 else:
2176 log.debug('Setting lock on repo %s by %s', repo, user)
2195 log.debug('Setting lock on repo %s by %s', repo, user)
2177 make_lock = True
2196 make_lock = True
2178
2197
2179 else:
2198 else:
2180 log.debug('Repository %s do not have locking enabled', repo)
2199 log.debug('Repository %s do not have locking enabled', repo)
2181
2200
2182 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2201 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2183 make_lock, currently_locked, lock_info)
2202 make_lock, currently_locked, lock_info)
2184
2203
2185 from rhodecode.lib.auth import HasRepoPermissionAny
2204 from rhodecode.lib.auth import HasRepoPermissionAny
2186 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2205 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2187 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2206 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2188 # if we don't have at least write permission we cannot make a lock
2207 # if we don't have at least write permission we cannot make a lock
2189 log.debug('lock state reset back to FALSE due to lack '
2208 log.debug('lock state reset back to FALSE due to lack '
2190 'of at least read permission')
2209 'of at least read permission')
2191 make_lock = False
2210 make_lock = False
2192
2211
2193 return make_lock, currently_locked, lock_info
2212 return make_lock, currently_locked, lock_info
2194
2213
2195 @property
2214 @property
2196 def last_commit_cache_update_diff(self):
2215 def last_commit_cache_update_diff(self):
2197 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2216 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2198
2217
2199 @property
2218 @property
2200 def last_commit_change(self):
2219 def last_commit_change(self):
2201 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2220 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2202 empty_date = datetime.datetime.fromtimestamp(0)
2221 empty_date = datetime.datetime.fromtimestamp(0)
2203 date_latest = self.changeset_cache.get('date', empty_date)
2222 date_latest = self.changeset_cache.get('date', empty_date)
2204 try:
2223 try:
2205 return parse_datetime(date_latest)
2224 return parse_datetime(date_latest)
2206 except Exception:
2225 except Exception:
2207 return empty_date
2226 return empty_date
2208
2227
2209 @property
2228 @property
2210 def last_db_change(self):
2229 def last_db_change(self):
2211 return self.updated_on
2230 return self.updated_on
2212
2231
2213 @property
2232 @property
2214 def clone_uri_hidden(self):
2233 def clone_uri_hidden(self):
2215 clone_uri = self.clone_uri
2234 clone_uri = self.clone_uri
2216 if clone_uri:
2235 if clone_uri:
2217 import urlobject
2236 import urlobject
2218 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2237 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2219 if url_obj.password:
2238 if url_obj.password:
2220 clone_uri = url_obj.with_password('*****')
2239 clone_uri = url_obj.with_password('*****')
2221 return clone_uri
2240 return clone_uri
2222
2241
2223 @property
2242 @property
2224 def push_uri_hidden(self):
2243 def push_uri_hidden(self):
2225 push_uri = self.push_uri
2244 push_uri = self.push_uri
2226 if push_uri:
2245 if push_uri:
2227 import urlobject
2246 import urlobject
2228 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2247 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2229 if url_obj.password:
2248 if url_obj.password:
2230 push_uri = url_obj.with_password('*****')
2249 push_uri = url_obj.with_password('*****')
2231 return push_uri
2250 return push_uri
2232
2251
2233 def clone_url(self, **override):
2252 def clone_url(self, **override):
2234 from rhodecode.model.settings import SettingsModel
2253 from rhodecode.model.settings import SettingsModel
2235
2254
2236 uri_tmpl = None
2255 uri_tmpl = None
2237 if 'with_id' in override:
2256 if 'with_id' in override:
2238 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2257 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2239 del override['with_id']
2258 del override['with_id']
2240
2259
2241 if 'uri_tmpl' in override:
2260 if 'uri_tmpl' in override:
2242 uri_tmpl = override['uri_tmpl']
2261 uri_tmpl = override['uri_tmpl']
2243 del override['uri_tmpl']
2262 del override['uri_tmpl']
2244
2263
2245 ssh = False
2264 ssh = False
2246 if 'ssh' in override:
2265 if 'ssh' in override:
2247 ssh = True
2266 ssh = True
2248 del override['ssh']
2267 del override['ssh']
2249
2268
2250 # we didn't override our tmpl from **overrides
2269 # we didn't override our tmpl from **overrides
2251 request = get_current_request()
2270 request = get_current_request()
2252 if not uri_tmpl:
2271 if not uri_tmpl:
2253 if hasattr(request, 'call_context') and hasattr(request.call_context, 'rc_config'):
2272 if hasattr(request, 'call_context') and hasattr(request.call_context, 'rc_config'):
2254 rc_config = request.call_context.rc_config
2273 rc_config = request.call_context.rc_config
2255 else:
2274 else:
2256 rc_config = SettingsModel().get_all_settings(cache=True)
2275 rc_config = SettingsModel().get_all_settings(cache=True)
2257 if ssh:
2276 if ssh:
2258 uri_tmpl = rc_config.get(
2277 uri_tmpl = rc_config.get(
2259 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2278 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2260 else:
2279 else:
2261 uri_tmpl = rc_config.get(
2280 uri_tmpl = rc_config.get(
2262 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2281 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2263
2282
2264 return get_clone_url(request=request,
2283 return get_clone_url(request=request,
2265 uri_tmpl=uri_tmpl,
2284 uri_tmpl=uri_tmpl,
2266 repo_name=self.repo_name,
2285 repo_name=self.repo_name,
2267 repo_id=self.repo_id, **override)
2286 repo_id=self.repo_id, **override)
2268
2287
2269 def set_state(self, state):
2288 def set_state(self, state):
2270 self.repo_state = state
2289 self.repo_state = state
2271 Session().add(self)
2290 Session().add(self)
2272 #==========================================================================
2291 #==========================================================================
2273 # SCM PROPERTIES
2292 # SCM PROPERTIES
2274 #==========================================================================
2293 #==========================================================================
2275
2294
2276 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2295 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2277 return get_commit_safe(
2296 return get_commit_safe(
2278 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2297 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2279
2298
2280 def get_changeset(self, rev=None, pre_load=None):
2299 def get_changeset(self, rev=None, pre_load=None):
2281 warnings.warn("Use get_commit", DeprecationWarning)
2300 warnings.warn("Use get_commit", DeprecationWarning)
2282 commit_id = None
2301 commit_id = None
2283 commit_idx = None
2302 commit_idx = None
2284 if isinstance(rev, compat.string_types):
2303 if isinstance(rev, compat.string_types):
2285 commit_id = rev
2304 commit_id = rev
2286 else:
2305 else:
2287 commit_idx = rev
2306 commit_idx = rev
2288 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2307 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2289 pre_load=pre_load)
2308 pre_load=pre_load)
2290
2309
2291 def get_landing_commit(self):
2310 def get_landing_commit(self):
2292 """
2311 """
2293 Returns landing commit, or if that doesn't exist returns the tip
2312 Returns landing commit, or if that doesn't exist returns the tip
2294 """
2313 """
2295 _rev_type, _rev = self.landing_rev
2314 _rev_type, _rev = self.landing_rev
2296 commit = self.get_commit(_rev)
2315 commit = self.get_commit(_rev)
2297 if isinstance(commit, EmptyCommit):
2316 if isinstance(commit, EmptyCommit):
2298 return self.get_commit()
2317 return self.get_commit()
2299 return commit
2318 return commit
2300
2319
2301 def flush_commit_cache(self):
2320 def flush_commit_cache(self):
2302 self.update_commit_cache(cs_cache={'raw_id':'0'})
2321 self.update_commit_cache(cs_cache={'raw_id':'0'})
2303 self.update_commit_cache()
2322 self.update_commit_cache()
2304
2323
2305 def update_commit_cache(self, cs_cache=None, config=None):
2324 def update_commit_cache(self, cs_cache=None, config=None):
2306 """
2325 """
2307 Update cache of last commit for repository, keys should be::
2326 Update cache of last commit for repository, keys should be::
2308
2327
2309 source_repo_id
2328 source_repo_id
2310 short_id
2329 short_id
2311 raw_id
2330 raw_id
2312 revision
2331 revision
2313 parents
2332 parents
2314 message
2333 message
2315 date
2334 date
2316 author
2335 author
2317 updated_on
2336 updated_on
2318
2337
2319 """
2338 """
2320 from rhodecode.lib.vcs.backends.base import BaseChangeset
2339 from rhodecode.lib.vcs.backends.base import BaseChangeset
2321 if cs_cache is None:
2340 if cs_cache is None:
2322 # use no-cache version here
2341 # use no-cache version here
2323 scm_repo = self.scm_instance(cache=False, config=config)
2342 scm_repo = self.scm_instance(cache=False, config=config)
2324
2343
2325 empty = scm_repo is None or scm_repo.is_empty()
2344 empty = scm_repo is None or scm_repo.is_empty()
2326 if not empty:
2345 if not empty:
2327 cs_cache = scm_repo.get_commit(
2346 cs_cache = scm_repo.get_commit(
2328 pre_load=["author", "date", "message", "parents", "branch"])
2347 pre_load=["author", "date", "message", "parents", "branch"])
2329 else:
2348 else:
2330 cs_cache = EmptyCommit()
2349 cs_cache = EmptyCommit()
2331
2350
2332 if isinstance(cs_cache, BaseChangeset):
2351 if isinstance(cs_cache, BaseChangeset):
2333 cs_cache = cs_cache.__json__()
2352 cs_cache = cs_cache.__json__()
2334
2353
2335 def is_outdated(new_cs_cache):
2354 def is_outdated(new_cs_cache):
2336 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2355 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2337 new_cs_cache['revision'] != self.changeset_cache['revision']):
2356 new_cs_cache['revision'] != self.changeset_cache['revision']):
2338 return True
2357 return True
2339 return False
2358 return False
2340
2359
2341 # check if we have maybe already latest cached revision
2360 # check if we have maybe already latest cached revision
2342 if is_outdated(cs_cache) or not self.changeset_cache:
2361 if is_outdated(cs_cache) or not self.changeset_cache:
2343 _default = datetime.datetime.utcnow()
2362 _default = datetime.datetime.utcnow()
2344 last_change = cs_cache.get('date') or _default
2363 last_change = cs_cache.get('date') or _default
2345 # we check if last update is newer than the new value
2364 # we check if last update is newer than the new value
2346 # if yes, we use the current timestamp instead. Imagine you get
2365 # if yes, we use the current timestamp instead. Imagine you get
2347 # old commit pushed 1y ago, we'd set last update 1y to ago.
2366 # old commit pushed 1y ago, we'd set last update 1y to ago.
2348 last_change_timestamp = datetime_to_time(last_change)
2367 last_change_timestamp = datetime_to_time(last_change)
2349 current_timestamp = datetime_to_time(last_change)
2368 current_timestamp = datetime_to_time(last_change)
2350 if last_change_timestamp > current_timestamp:
2369 if last_change_timestamp > current_timestamp:
2351 cs_cache['date'] = _default
2370 cs_cache['date'] = _default
2352
2371
2353 cs_cache['updated_on'] = time.time()
2372 cs_cache['updated_on'] = time.time()
2354 self.changeset_cache = cs_cache
2373 self.changeset_cache = cs_cache
2355 self.updated_on = last_change
2374 self.updated_on = last_change
2356 Session().add(self)
2375 Session().add(self)
2357 Session().commit()
2376 Session().commit()
2358
2377
2359 log.debug('updated repo `%s` with new commit cache %s',
2378 log.debug('updated repo `%s` with new commit cache %s',
2360 self.repo_name, cs_cache)
2379 self.repo_name, cs_cache)
2361 else:
2380 else:
2362 cs_cache = self.changeset_cache
2381 cs_cache = self.changeset_cache
2363 cs_cache['updated_on'] = time.time()
2382 cs_cache['updated_on'] = time.time()
2364 self.changeset_cache = cs_cache
2383 self.changeset_cache = cs_cache
2365 Session().add(self)
2384 Session().add(self)
2366 Session().commit()
2385 Session().commit()
2367
2386
2368 log.debug('Skipping update_commit_cache for repo:`%s` '
2387 log.debug('Skipping update_commit_cache for repo:`%s` '
2369 'commit already with latest changes', self.repo_name)
2388 'commit already with latest changes', self.repo_name)
2370
2389
2371 @property
2390 @property
2372 def tip(self):
2391 def tip(self):
2373 return self.get_commit('tip')
2392 return self.get_commit('tip')
2374
2393
2375 @property
2394 @property
2376 def author(self):
2395 def author(self):
2377 return self.tip.author
2396 return self.tip.author
2378
2397
2379 @property
2398 @property
2380 def last_change(self):
2399 def last_change(self):
2381 return self.scm_instance().last_change
2400 return self.scm_instance().last_change
2382
2401
2383 def get_comments(self, revisions=None):
2402 def get_comments(self, revisions=None):
2384 """
2403 """
2385 Returns comments for this repository grouped by revisions
2404 Returns comments for this repository grouped by revisions
2386
2405
2387 :param revisions: filter query by revisions only
2406 :param revisions: filter query by revisions only
2388 """
2407 """
2389 cmts = ChangesetComment.query()\
2408 cmts = ChangesetComment.query()\
2390 .filter(ChangesetComment.repo == self)
2409 .filter(ChangesetComment.repo == self)
2391 if revisions:
2410 if revisions:
2392 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2411 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2393 grouped = collections.defaultdict(list)
2412 grouped = collections.defaultdict(list)
2394 for cmt in cmts.all():
2413 for cmt in cmts.all():
2395 grouped[cmt.revision].append(cmt)
2414 grouped[cmt.revision].append(cmt)
2396 return grouped
2415 return grouped
2397
2416
2398 def statuses(self, revisions=None):
2417 def statuses(self, revisions=None):
2399 """
2418 """
2400 Returns statuses for this repository
2419 Returns statuses for this repository
2401
2420
2402 :param revisions: list of revisions to get statuses for
2421 :param revisions: list of revisions to get statuses for
2403 """
2422 """
2404 statuses = ChangesetStatus.query()\
2423 statuses = ChangesetStatus.query()\
2405 .filter(ChangesetStatus.repo == self)\
2424 .filter(ChangesetStatus.repo == self)\
2406 .filter(ChangesetStatus.version == 0)
2425 .filter(ChangesetStatus.version == 0)
2407
2426
2408 if revisions:
2427 if revisions:
2409 # Try doing the filtering in chunks to avoid hitting limits
2428 # Try doing the filtering in chunks to avoid hitting limits
2410 size = 500
2429 size = 500
2411 status_results = []
2430 status_results = []
2412 for chunk in xrange(0, len(revisions), size):
2431 for chunk in xrange(0, len(revisions), size):
2413 status_results += statuses.filter(
2432 status_results += statuses.filter(
2414 ChangesetStatus.revision.in_(
2433 ChangesetStatus.revision.in_(
2415 revisions[chunk: chunk+size])
2434 revisions[chunk: chunk+size])
2416 ).all()
2435 ).all()
2417 else:
2436 else:
2418 status_results = statuses.all()
2437 status_results = statuses.all()
2419
2438
2420 grouped = {}
2439 grouped = {}
2421
2440
2422 # maybe we have open new pullrequest without a status?
2441 # maybe we have open new pullrequest without a status?
2423 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2442 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2424 status_lbl = ChangesetStatus.get_status_lbl(stat)
2443 status_lbl = ChangesetStatus.get_status_lbl(stat)
2425 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2444 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2426 for rev in pr.revisions:
2445 for rev in pr.revisions:
2427 pr_id = pr.pull_request_id
2446 pr_id = pr.pull_request_id
2428 pr_repo = pr.target_repo.repo_name
2447 pr_repo = pr.target_repo.repo_name
2429 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2448 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2430
2449
2431 for stat in status_results:
2450 for stat in status_results:
2432 pr_id = pr_repo = None
2451 pr_id = pr_repo = None
2433 if stat.pull_request:
2452 if stat.pull_request:
2434 pr_id = stat.pull_request.pull_request_id
2453 pr_id = stat.pull_request.pull_request_id
2435 pr_repo = stat.pull_request.target_repo.repo_name
2454 pr_repo = stat.pull_request.target_repo.repo_name
2436 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2455 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2437 pr_id, pr_repo]
2456 pr_id, pr_repo]
2438 return grouped
2457 return grouped
2439
2458
2440 # ==========================================================================
2459 # ==========================================================================
2441 # SCM CACHE INSTANCE
2460 # SCM CACHE INSTANCE
2442 # ==========================================================================
2461 # ==========================================================================
2443
2462
2444 def scm_instance(self, **kwargs):
2463 def scm_instance(self, **kwargs):
2445 import rhodecode
2464 import rhodecode
2446
2465
2447 # Passing a config will not hit the cache currently only used
2466 # Passing a config will not hit the cache currently only used
2448 # for repo2dbmapper
2467 # for repo2dbmapper
2449 config = kwargs.pop('config', None)
2468 config = kwargs.pop('config', None)
2450 cache = kwargs.pop('cache', None)
2469 cache = kwargs.pop('cache', None)
2451 vcs_full_cache = kwargs.pop('vcs_full_cache', None)
2470 vcs_full_cache = kwargs.pop('vcs_full_cache', None)
2452 if vcs_full_cache is not None:
2471 if vcs_full_cache is not None:
2453 # allows override global config
2472 # allows override global config
2454 full_cache = vcs_full_cache
2473 full_cache = vcs_full_cache
2455 else:
2474 else:
2456 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2475 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2457 # if cache is NOT defined use default global, else we have a full
2476 # if cache is NOT defined use default global, else we have a full
2458 # control over cache behaviour
2477 # control over cache behaviour
2459 if cache is None and full_cache and not config:
2478 if cache is None and full_cache and not config:
2460 log.debug('Initializing pure cached instance for %s', self.repo_path)
2479 log.debug('Initializing pure cached instance for %s', self.repo_path)
2461 return self._get_instance_cached()
2480 return self._get_instance_cached()
2462
2481
2463 # cache here is sent to the "vcs server"
2482 # cache here is sent to the "vcs server"
2464 return self._get_instance(cache=bool(cache), config=config)
2483 return self._get_instance(cache=bool(cache), config=config)
2465
2484
2466 def _get_instance_cached(self):
2485 def _get_instance_cached(self):
2467 from rhodecode.lib import rc_cache
2486 from rhodecode.lib import rc_cache
2468
2487
2469 cache_namespace_uid = 'cache_repo_instance.{}'.format(self.repo_id)
2488 cache_namespace_uid = 'cache_repo_instance.{}'.format(self.repo_id)
2470 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2489 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2471 repo_id=self.repo_id)
2490 repo_id=self.repo_id)
2472 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2491 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2473
2492
2474 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2493 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2475 def get_instance_cached(repo_id, context_id, _cache_state_uid):
2494 def get_instance_cached(repo_id, context_id, _cache_state_uid):
2476 return self._get_instance(repo_state_uid=_cache_state_uid)
2495 return self._get_instance(repo_state_uid=_cache_state_uid)
2477
2496
2478 # we must use thread scoped cache here,
2497 # we must use thread scoped cache here,
2479 # because each thread of gevent needs it's own not shared connection and cache
2498 # because each thread of gevent needs it's own not shared connection and cache
2480 # we also alter `args` so the cache key is individual for every green thread.
2499 # we also alter `args` so the cache key is individual for every green thread.
2481 inv_context_manager = rc_cache.InvalidationContext(
2500 inv_context_manager = rc_cache.InvalidationContext(
2482 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace,
2501 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace,
2483 thread_scoped=True)
2502 thread_scoped=True)
2484 with inv_context_manager as invalidation_context:
2503 with inv_context_manager as invalidation_context:
2485 cache_state_uid = invalidation_context.cache_data['cache_state_uid']
2504 cache_state_uid = invalidation_context.cache_data['cache_state_uid']
2486 args = (self.repo_id, inv_context_manager.cache_key, cache_state_uid)
2505 args = (self.repo_id, inv_context_manager.cache_key, cache_state_uid)
2487
2506
2488 # re-compute and store cache if we get invalidate signal
2507 # re-compute and store cache if we get invalidate signal
2489 if invalidation_context.should_invalidate():
2508 if invalidation_context.should_invalidate():
2490 instance = get_instance_cached.refresh(*args)
2509 instance = get_instance_cached.refresh(*args)
2491 else:
2510 else:
2492 instance = get_instance_cached(*args)
2511 instance = get_instance_cached(*args)
2493
2512
2494 log.debug('Repo instance fetched in %.4fs', inv_context_manager.compute_time)
2513 log.debug('Repo instance fetched in %.4fs', inv_context_manager.compute_time)
2495 return instance
2514 return instance
2496
2515
2497 def _get_instance(self, cache=True, config=None, repo_state_uid=None):
2516 def _get_instance(self, cache=True, config=None, repo_state_uid=None):
2498 log.debug('Initializing %s instance `%s` with cache flag set to: %s',
2517 log.debug('Initializing %s instance `%s` with cache flag set to: %s',
2499 self.repo_type, self.repo_path, cache)
2518 self.repo_type, self.repo_path, cache)
2500 config = config or self._config
2519 config = config or self._config
2501 custom_wire = {
2520 custom_wire = {
2502 'cache': cache, # controls the vcs.remote cache
2521 'cache': cache, # controls the vcs.remote cache
2503 'repo_state_uid': repo_state_uid
2522 'repo_state_uid': repo_state_uid
2504 }
2523 }
2505 repo = get_vcs_instance(
2524 repo = get_vcs_instance(
2506 repo_path=safe_str(self.repo_full_path),
2525 repo_path=safe_str(self.repo_full_path),
2507 config=config,
2526 config=config,
2508 with_wire=custom_wire,
2527 with_wire=custom_wire,
2509 create=False,
2528 create=False,
2510 _vcs_alias=self.repo_type)
2529 _vcs_alias=self.repo_type)
2511 if repo is not None:
2530 if repo is not None:
2512 repo.count() # cache rebuild
2531 repo.count() # cache rebuild
2513 return repo
2532 return repo
2514
2533
2515 def get_shadow_repository_path(self, workspace_id):
2534 def get_shadow_repository_path(self, workspace_id):
2516 from rhodecode.lib.vcs.backends.base import BaseRepository
2535 from rhodecode.lib.vcs.backends.base import BaseRepository
2517 shadow_repo_path = BaseRepository._get_shadow_repository_path(
2536 shadow_repo_path = BaseRepository._get_shadow_repository_path(
2518 self.repo_full_path, self.repo_id, workspace_id)
2537 self.repo_full_path, self.repo_id, workspace_id)
2519 return shadow_repo_path
2538 return shadow_repo_path
2520
2539
2521 def __json__(self):
2540 def __json__(self):
2522 return {'landing_rev': self.landing_rev}
2541 return {'landing_rev': self.landing_rev}
2523
2542
2524 def get_dict(self):
2543 def get_dict(self):
2525
2544
2526 # Since we transformed `repo_name` to a hybrid property, we need to
2545 # Since we transformed `repo_name` to a hybrid property, we need to
2527 # keep compatibility with the code which uses `repo_name` field.
2546 # keep compatibility with the code which uses `repo_name` field.
2528
2547
2529 result = super(Repository, self).get_dict()
2548 result = super(Repository, self).get_dict()
2530 result['repo_name'] = result.pop('_repo_name', None)
2549 result['repo_name'] = result.pop('_repo_name', None)
2531 return result
2550 return result
2532
2551
2533
2552
2534 class RepoGroup(Base, BaseModel):
2553 class RepoGroup(Base, BaseModel):
2535 __tablename__ = 'groups'
2554 __tablename__ = 'groups'
2536 __table_args__ = (
2555 __table_args__ = (
2537 UniqueConstraint('group_name', 'group_parent_id'),
2556 UniqueConstraint('group_name', 'group_parent_id'),
2538 base_table_args,
2557 base_table_args,
2539 )
2558 )
2540 __mapper_args__ = {'order_by': 'group_name'}
2559 __mapper_args__ = {'order_by': 'group_name'}
2541
2560
2542 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2561 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2543
2562
2544 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2563 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2545 _group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2564 _group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2546 group_name_hash = Column("repo_group_name_hash", String(1024), nullable=False, unique=False)
2565 group_name_hash = Column("repo_group_name_hash", String(1024), nullable=False, unique=False)
2547 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2566 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2548 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2567 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2549 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2568 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2550 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2569 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2551 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2570 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2552 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2571 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2553 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2572 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2554 _changeset_cache = Column(
2573 _changeset_cache = Column(
2555 "changeset_cache", LargeBinary(), nullable=True) # JSON data
2574 "changeset_cache", LargeBinary(), nullable=True) # JSON data
2556
2575
2557 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2576 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2558 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2577 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2559 parent_group = relationship('RepoGroup', remote_side=group_id)
2578 parent_group = relationship('RepoGroup', remote_side=group_id)
2560 user = relationship('User')
2579 user = relationship('User')
2561 integrations = relationship('Integration', cascade="all, delete-orphan")
2580 integrations = relationship('Integration', cascade="all, delete-orphan")
2562
2581
2563 def __init__(self, group_name='', parent_group=None):
2582 def __init__(self, group_name='', parent_group=None):
2564 self.group_name = group_name
2583 self.group_name = group_name
2565 self.parent_group = parent_group
2584 self.parent_group = parent_group
2566
2585
2567 def __unicode__(self):
2586 def __unicode__(self):
2568 return u"<%s('id:%s:%s')>" % (
2587 return u"<%s('id:%s:%s')>" % (
2569 self.__class__.__name__, self.group_id, self.group_name)
2588 self.__class__.__name__, self.group_id, self.group_name)
2570
2589
2571 @hybrid_property
2590 @hybrid_property
2572 def group_name(self):
2591 def group_name(self):
2573 return self._group_name
2592 return self._group_name
2574
2593
2575 @group_name.setter
2594 @group_name.setter
2576 def group_name(self, value):
2595 def group_name(self, value):
2577 self._group_name = value
2596 self._group_name = value
2578 self.group_name_hash = self.hash_repo_group_name(value)
2597 self.group_name_hash = self.hash_repo_group_name(value)
2579
2598
2580 @hybrid_property
2599 @hybrid_property
2581 def changeset_cache(self):
2600 def changeset_cache(self):
2582 from rhodecode.lib.vcs.backends.base import EmptyCommit
2601 from rhodecode.lib.vcs.backends.base import EmptyCommit
2583 dummy = EmptyCommit().__json__()
2602 dummy = EmptyCommit().__json__()
2584 if not self._changeset_cache:
2603 if not self._changeset_cache:
2585 dummy['source_repo_id'] = ''
2604 dummy['source_repo_id'] = ''
2586 return json.loads(json.dumps(dummy))
2605 return json.loads(json.dumps(dummy))
2587
2606
2588 try:
2607 try:
2589 return json.loads(self._changeset_cache)
2608 return json.loads(self._changeset_cache)
2590 except TypeError:
2609 except TypeError:
2591 return dummy
2610 return dummy
2592 except Exception:
2611 except Exception:
2593 log.error(traceback.format_exc())
2612 log.error(traceback.format_exc())
2594 return dummy
2613 return dummy
2595
2614
2596 @changeset_cache.setter
2615 @changeset_cache.setter
2597 def changeset_cache(self, val):
2616 def changeset_cache(self, val):
2598 try:
2617 try:
2599 self._changeset_cache = json.dumps(val)
2618 self._changeset_cache = json.dumps(val)
2600 except Exception:
2619 except Exception:
2601 log.error(traceback.format_exc())
2620 log.error(traceback.format_exc())
2602
2621
2603 @validates('group_parent_id')
2622 @validates('group_parent_id')
2604 def validate_group_parent_id(self, key, val):
2623 def validate_group_parent_id(self, key, val):
2605 """
2624 """
2606 Check cycle references for a parent group to self
2625 Check cycle references for a parent group to self
2607 """
2626 """
2608 if self.group_id and val:
2627 if self.group_id and val:
2609 assert val != self.group_id
2628 assert val != self.group_id
2610
2629
2611 return val
2630 return val
2612
2631
2613 @hybrid_property
2632 @hybrid_property
2614 def description_safe(self):
2633 def description_safe(self):
2615 from rhodecode.lib import helpers as h
2634 from rhodecode.lib import helpers as h
2616 return h.escape(self.group_description)
2635 return h.escape(self.group_description)
2617
2636
2618 @classmethod
2637 @classmethod
2619 def hash_repo_group_name(cls, repo_group_name):
2638 def hash_repo_group_name(cls, repo_group_name):
2620 val = remove_formatting(repo_group_name)
2639 val = remove_formatting(repo_group_name)
2621 val = safe_str(val).lower()
2640 val = safe_str(val).lower()
2622 chars = []
2641 chars = []
2623 for c in val:
2642 for c in val:
2624 if c not in string.ascii_letters:
2643 if c not in string.ascii_letters:
2625 c = str(ord(c))
2644 c = str(ord(c))
2626 chars.append(c)
2645 chars.append(c)
2627
2646
2628 return ''.join(chars)
2647 return ''.join(chars)
2629
2648
2630 @classmethod
2649 @classmethod
2631 def _generate_choice(cls, repo_group):
2650 def _generate_choice(cls, repo_group):
2632 from webhelpers.html import literal as _literal
2651 from webhelpers.html import literal as _literal
2633 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2652 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2634 return repo_group.group_id, _name(repo_group.full_path_splitted)
2653 return repo_group.group_id, _name(repo_group.full_path_splitted)
2635
2654
2636 @classmethod
2655 @classmethod
2637 def groups_choices(cls, groups=None, show_empty_group=True):
2656 def groups_choices(cls, groups=None, show_empty_group=True):
2638 if not groups:
2657 if not groups:
2639 groups = cls.query().all()
2658 groups = cls.query().all()
2640
2659
2641 repo_groups = []
2660 repo_groups = []
2642 if show_empty_group:
2661 if show_empty_group:
2643 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2662 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2644
2663
2645 repo_groups.extend([cls._generate_choice(x) for x in groups])
2664 repo_groups.extend([cls._generate_choice(x) for x in groups])
2646
2665
2647 repo_groups = sorted(
2666 repo_groups = sorted(
2648 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2667 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2649 return repo_groups
2668 return repo_groups
2650
2669
2651 @classmethod
2670 @classmethod
2652 def url_sep(cls):
2671 def url_sep(cls):
2653 return URL_SEP
2672 return URL_SEP
2654
2673
2655 @classmethod
2674 @classmethod
2656 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2675 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2657 if case_insensitive:
2676 if case_insensitive:
2658 gr = cls.query().filter(func.lower(cls.group_name)
2677 gr = cls.query().filter(func.lower(cls.group_name)
2659 == func.lower(group_name))
2678 == func.lower(group_name))
2660 else:
2679 else:
2661 gr = cls.query().filter(cls.group_name == group_name)
2680 gr = cls.query().filter(cls.group_name == group_name)
2662 if cache:
2681 if cache:
2663 name_key = _hash_key(group_name)
2682 name_key = _hash_key(group_name)
2664 gr = gr.options(
2683 gr = gr.options(
2665 FromCache("sql_cache_short", "get_group_%s" % name_key))
2684 FromCache("sql_cache_short", "get_group_%s" % name_key))
2666 return gr.scalar()
2685 return gr.scalar()
2667
2686
2668 @classmethod
2687 @classmethod
2669 def get_user_personal_repo_group(cls, user_id):
2688 def get_user_personal_repo_group(cls, user_id):
2670 user = User.get(user_id)
2689 user = User.get(user_id)
2671 if user.username == User.DEFAULT_USER:
2690 if user.username == User.DEFAULT_USER:
2672 return None
2691 return None
2673
2692
2674 return cls.query()\
2693 return cls.query()\
2675 .filter(cls.personal == true()) \
2694 .filter(cls.personal == true()) \
2676 .filter(cls.user == user) \
2695 .filter(cls.user == user) \
2677 .order_by(cls.group_id.asc()) \
2696 .order_by(cls.group_id.asc()) \
2678 .first()
2697 .first()
2679
2698
2680 @classmethod
2699 @classmethod
2681 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2700 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2682 case_insensitive=True):
2701 case_insensitive=True):
2683 q = RepoGroup.query()
2702 q = RepoGroup.query()
2684
2703
2685 if not isinstance(user_id, Optional):
2704 if not isinstance(user_id, Optional):
2686 q = q.filter(RepoGroup.user_id == user_id)
2705 q = q.filter(RepoGroup.user_id == user_id)
2687
2706
2688 if not isinstance(group_id, Optional):
2707 if not isinstance(group_id, Optional):
2689 q = q.filter(RepoGroup.group_parent_id == group_id)
2708 q = q.filter(RepoGroup.group_parent_id == group_id)
2690
2709
2691 if case_insensitive:
2710 if case_insensitive:
2692 q = q.order_by(func.lower(RepoGroup.group_name))
2711 q = q.order_by(func.lower(RepoGroup.group_name))
2693 else:
2712 else:
2694 q = q.order_by(RepoGroup.group_name)
2713 q = q.order_by(RepoGroup.group_name)
2695 return q.all()
2714 return q.all()
2696
2715
2697 @property
2716 @property
2698 def parents(self, parents_recursion_limit = 10):
2717 def parents(self, parents_recursion_limit = 10):
2699 groups = []
2718 groups = []
2700 if self.parent_group is None:
2719 if self.parent_group is None:
2701 return groups
2720 return groups
2702 cur_gr = self.parent_group
2721 cur_gr = self.parent_group
2703 groups.insert(0, cur_gr)
2722 groups.insert(0, cur_gr)
2704 cnt = 0
2723 cnt = 0
2705 while 1:
2724 while 1:
2706 cnt += 1
2725 cnt += 1
2707 gr = getattr(cur_gr, 'parent_group', None)
2726 gr = getattr(cur_gr, 'parent_group', None)
2708 cur_gr = cur_gr.parent_group
2727 cur_gr = cur_gr.parent_group
2709 if gr is None:
2728 if gr is None:
2710 break
2729 break
2711 if cnt == parents_recursion_limit:
2730 if cnt == parents_recursion_limit:
2712 # this will prevent accidental infinit loops
2731 # this will prevent accidental infinit loops
2713 log.error('more than %s parents found for group %s, stopping '
2732 log.error('more than %s parents found for group %s, stopping '
2714 'recursive parent fetching', parents_recursion_limit, self)
2733 'recursive parent fetching', parents_recursion_limit, self)
2715 break
2734 break
2716
2735
2717 groups.insert(0, gr)
2736 groups.insert(0, gr)
2718 return groups
2737 return groups
2719
2738
2720 @property
2739 @property
2721 def last_commit_cache_update_diff(self):
2740 def last_commit_cache_update_diff(self):
2722 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2741 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2723
2742
2724 @property
2743 @property
2725 def last_commit_change(self):
2744 def last_commit_change(self):
2726 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2745 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2727 empty_date = datetime.datetime.fromtimestamp(0)
2746 empty_date = datetime.datetime.fromtimestamp(0)
2728 date_latest = self.changeset_cache.get('date', empty_date)
2747 date_latest = self.changeset_cache.get('date', empty_date)
2729 try:
2748 try:
2730 return parse_datetime(date_latest)
2749 return parse_datetime(date_latest)
2731 except Exception:
2750 except Exception:
2732 return empty_date
2751 return empty_date
2733
2752
2734 @property
2753 @property
2735 def last_db_change(self):
2754 def last_db_change(self):
2736 return self.updated_on
2755 return self.updated_on
2737
2756
2738 @property
2757 @property
2739 def children(self):
2758 def children(self):
2740 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2759 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2741
2760
2742 @property
2761 @property
2743 def name(self):
2762 def name(self):
2744 return self.group_name.split(RepoGroup.url_sep())[-1]
2763 return self.group_name.split(RepoGroup.url_sep())[-1]
2745
2764
2746 @property
2765 @property
2747 def full_path(self):
2766 def full_path(self):
2748 return self.group_name
2767 return self.group_name
2749
2768
2750 @property
2769 @property
2751 def full_path_splitted(self):
2770 def full_path_splitted(self):
2752 return self.group_name.split(RepoGroup.url_sep())
2771 return self.group_name.split(RepoGroup.url_sep())
2753
2772
2754 @property
2773 @property
2755 def repositories(self):
2774 def repositories(self):
2756 return Repository.query()\
2775 return Repository.query()\
2757 .filter(Repository.group == self)\
2776 .filter(Repository.group == self)\
2758 .order_by(Repository.repo_name)
2777 .order_by(Repository.repo_name)
2759
2778
2760 @property
2779 @property
2761 def repositories_recursive_count(self):
2780 def repositories_recursive_count(self):
2762 cnt = self.repositories.count()
2781 cnt = self.repositories.count()
2763
2782
2764 def children_count(group):
2783 def children_count(group):
2765 cnt = 0
2784 cnt = 0
2766 for child in group.children:
2785 for child in group.children:
2767 cnt += child.repositories.count()
2786 cnt += child.repositories.count()
2768 cnt += children_count(child)
2787 cnt += children_count(child)
2769 return cnt
2788 return cnt
2770
2789
2771 return cnt + children_count(self)
2790 return cnt + children_count(self)
2772
2791
2773 def _recursive_objects(self, include_repos=True, include_groups=True):
2792 def _recursive_objects(self, include_repos=True, include_groups=True):
2774 all_ = []
2793 all_ = []
2775
2794
2776 def _get_members(root_gr):
2795 def _get_members(root_gr):
2777 if include_repos:
2796 if include_repos:
2778 for r in root_gr.repositories:
2797 for r in root_gr.repositories:
2779 all_.append(r)
2798 all_.append(r)
2780 childs = root_gr.children.all()
2799 childs = root_gr.children.all()
2781 if childs:
2800 if childs:
2782 for gr in childs:
2801 for gr in childs:
2783 if include_groups:
2802 if include_groups:
2784 all_.append(gr)
2803 all_.append(gr)
2785 _get_members(gr)
2804 _get_members(gr)
2786
2805
2787 root_group = []
2806 root_group = []
2788 if include_groups:
2807 if include_groups:
2789 root_group = [self]
2808 root_group = [self]
2790
2809
2791 _get_members(self)
2810 _get_members(self)
2792 return root_group + all_
2811 return root_group + all_
2793
2812
2794 def recursive_groups_and_repos(self):
2813 def recursive_groups_and_repos(self):
2795 """
2814 """
2796 Recursive return all groups, with repositories in those groups
2815 Recursive return all groups, with repositories in those groups
2797 """
2816 """
2798 return self._recursive_objects()
2817 return self._recursive_objects()
2799
2818
2800 def recursive_groups(self):
2819 def recursive_groups(self):
2801 """
2820 """
2802 Returns all children groups for this group including children of children
2821 Returns all children groups for this group including children of children
2803 """
2822 """
2804 return self._recursive_objects(include_repos=False)
2823 return self._recursive_objects(include_repos=False)
2805
2824
2806 def recursive_repos(self):
2825 def recursive_repos(self):
2807 """
2826 """
2808 Returns all children repositories for this group
2827 Returns all children repositories for this group
2809 """
2828 """
2810 return self._recursive_objects(include_groups=False)
2829 return self._recursive_objects(include_groups=False)
2811
2830
2812 def get_new_name(self, group_name):
2831 def get_new_name(self, group_name):
2813 """
2832 """
2814 returns new full group name based on parent and new name
2833 returns new full group name based on parent and new name
2815
2834
2816 :param group_name:
2835 :param group_name:
2817 """
2836 """
2818 path_prefix = (self.parent_group.full_path_splitted if
2837 path_prefix = (self.parent_group.full_path_splitted if
2819 self.parent_group else [])
2838 self.parent_group else [])
2820 return RepoGroup.url_sep().join(path_prefix + [group_name])
2839 return RepoGroup.url_sep().join(path_prefix + [group_name])
2821
2840
2822 def update_commit_cache(self, config=None):
2841 def update_commit_cache(self, config=None):
2823 """
2842 """
2824 Update cache of last changeset for newest repository inside this group, keys should be::
2843 Update cache of last changeset for newest repository inside this group, keys should be::
2825
2844
2826 source_repo_id
2845 source_repo_id
2827 short_id
2846 short_id
2828 raw_id
2847 raw_id
2829 revision
2848 revision
2830 parents
2849 parents
2831 message
2850 message
2832 date
2851 date
2833 author
2852 author
2834
2853
2835 """
2854 """
2836 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2855 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2837
2856
2838 def repo_groups_and_repos():
2857 def repo_groups_and_repos():
2839 all_entries = OrderedDefaultDict(list)
2858 all_entries = OrderedDefaultDict(list)
2840
2859
2841 def _get_members(root_gr, pos=0):
2860 def _get_members(root_gr, pos=0):
2842
2861
2843 for repo in root_gr.repositories:
2862 for repo in root_gr.repositories:
2844 all_entries[root_gr].append(repo)
2863 all_entries[root_gr].append(repo)
2845
2864
2846 # fill in all parent positions
2865 # fill in all parent positions
2847 for parent_group in root_gr.parents:
2866 for parent_group in root_gr.parents:
2848 all_entries[parent_group].extend(all_entries[root_gr])
2867 all_entries[parent_group].extend(all_entries[root_gr])
2849
2868
2850 children_groups = root_gr.children.all()
2869 children_groups = root_gr.children.all()
2851 if children_groups:
2870 if children_groups:
2852 for cnt, gr in enumerate(children_groups, 1):
2871 for cnt, gr in enumerate(children_groups, 1):
2853 _get_members(gr, pos=pos+cnt)
2872 _get_members(gr, pos=pos+cnt)
2854
2873
2855 _get_members(root_gr=self)
2874 _get_members(root_gr=self)
2856 return all_entries
2875 return all_entries
2857
2876
2858 empty_date = datetime.datetime.fromtimestamp(0)
2877 empty_date = datetime.datetime.fromtimestamp(0)
2859 for repo_group, repos in repo_groups_and_repos().items():
2878 for repo_group, repos in repo_groups_and_repos().items():
2860
2879
2861 latest_repo_cs_cache = {}
2880 latest_repo_cs_cache = {}
2862 _date_latest = empty_date
2881 _date_latest = empty_date
2863 for repo in repos:
2882 for repo in repos:
2864 repo_cs_cache = repo.changeset_cache
2883 repo_cs_cache = repo.changeset_cache
2865 date_latest = latest_repo_cs_cache.get('date', empty_date)
2884 date_latest = latest_repo_cs_cache.get('date', empty_date)
2866 date_current = repo_cs_cache.get('date', empty_date)
2885 date_current = repo_cs_cache.get('date', empty_date)
2867 current_timestamp = datetime_to_time(parse_datetime(date_latest))
2886 current_timestamp = datetime_to_time(parse_datetime(date_latest))
2868 if current_timestamp < datetime_to_time(parse_datetime(date_current)):
2887 if current_timestamp < datetime_to_time(parse_datetime(date_current)):
2869 latest_repo_cs_cache = repo_cs_cache
2888 latest_repo_cs_cache = repo_cs_cache
2870 latest_repo_cs_cache['source_repo_id'] = repo.repo_id
2889 latest_repo_cs_cache['source_repo_id'] = repo.repo_id
2871 _date_latest = parse_datetime(latest_repo_cs_cache['date'])
2890 _date_latest = parse_datetime(latest_repo_cs_cache['date'])
2872
2891
2873 latest_repo_cs_cache['updated_on'] = time.time()
2892 latest_repo_cs_cache['updated_on'] = time.time()
2874 repo_group.changeset_cache = latest_repo_cs_cache
2893 repo_group.changeset_cache = latest_repo_cs_cache
2875 repo_group.updated_on = _date_latest
2894 repo_group.updated_on = _date_latest
2876 Session().add(repo_group)
2895 Session().add(repo_group)
2877 Session().commit()
2896 Session().commit()
2878
2897
2879 log.debug('updated repo group `%s` with new commit cache %s',
2898 log.debug('updated repo group `%s` with new commit cache %s',
2880 repo_group.group_name, latest_repo_cs_cache)
2899 repo_group.group_name, latest_repo_cs_cache)
2881
2900
2882 def permissions(self, with_admins=True, with_owner=True,
2901 def permissions(self, with_admins=True, with_owner=True,
2883 expand_from_user_groups=False):
2902 expand_from_user_groups=False):
2884 """
2903 """
2885 Permissions for repository groups
2904 Permissions for repository groups
2886 """
2905 """
2887 _admin_perm = 'group.admin'
2906 _admin_perm = 'group.admin'
2888
2907
2889 owner_row = []
2908 owner_row = []
2890 if with_owner:
2909 if with_owner:
2891 usr = AttributeDict(self.user.get_dict())
2910 usr = AttributeDict(self.user.get_dict())
2892 usr.owner_row = True
2911 usr.owner_row = True
2893 usr.permission = _admin_perm
2912 usr.permission = _admin_perm
2894 owner_row.append(usr)
2913 owner_row.append(usr)
2895
2914
2896 super_admin_ids = []
2915 super_admin_ids = []
2897 super_admin_rows = []
2916 super_admin_rows = []
2898 if with_admins:
2917 if with_admins:
2899 for usr in User.get_all_super_admins():
2918 for usr in User.get_all_super_admins():
2900 super_admin_ids.append(usr.user_id)
2919 super_admin_ids.append(usr.user_id)
2901 # if this admin is also owner, don't double the record
2920 # if this admin is also owner, don't double the record
2902 if usr.user_id == owner_row[0].user_id:
2921 if usr.user_id == owner_row[0].user_id:
2903 owner_row[0].admin_row = True
2922 owner_row[0].admin_row = True
2904 else:
2923 else:
2905 usr = AttributeDict(usr.get_dict())
2924 usr = AttributeDict(usr.get_dict())
2906 usr.admin_row = True
2925 usr.admin_row = True
2907 usr.permission = _admin_perm
2926 usr.permission = _admin_perm
2908 super_admin_rows.append(usr)
2927 super_admin_rows.append(usr)
2909
2928
2910 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2929 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2911 q = q.options(joinedload(UserRepoGroupToPerm.group),
2930 q = q.options(joinedload(UserRepoGroupToPerm.group),
2912 joinedload(UserRepoGroupToPerm.user),
2931 joinedload(UserRepoGroupToPerm.user),
2913 joinedload(UserRepoGroupToPerm.permission),)
2932 joinedload(UserRepoGroupToPerm.permission),)
2914
2933
2915 # get owners and admins and permissions. We do a trick of re-writing
2934 # get owners and admins and permissions. We do a trick of re-writing
2916 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2935 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2917 # has a global reference and changing one object propagates to all
2936 # has a global reference and changing one object propagates to all
2918 # others. This means if admin is also an owner admin_row that change
2937 # others. This means if admin is also an owner admin_row that change
2919 # would propagate to both objects
2938 # would propagate to both objects
2920 perm_rows = []
2939 perm_rows = []
2921 for _usr in q.all():
2940 for _usr in q.all():
2922 usr = AttributeDict(_usr.user.get_dict())
2941 usr = AttributeDict(_usr.user.get_dict())
2923 # if this user is also owner/admin, mark as duplicate record
2942 # if this user is also owner/admin, mark as duplicate record
2924 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2943 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2925 usr.duplicate_perm = True
2944 usr.duplicate_perm = True
2926 usr.permission = _usr.permission.permission_name
2945 usr.permission = _usr.permission.permission_name
2927 perm_rows.append(usr)
2946 perm_rows.append(usr)
2928
2947
2929 # filter the perm rows by 'default' first and then sort them by
2948 # filter the perm rows by 'default' first and then sort them by
2930 # admin,write,read,none permissions sorted again alphabetically in
2949 # admin,write,read,none permissions sorted again alphabetically in
2931 # each group
2950 # each group
2932 perm_rows = sorted(perm_rows, key=display_user_sort)
2951 perm_rows = sorted(perm_rows, key=display_user_sort)
2933
2952
2934 user_groups_rows = []
2953 user_groups_rows = []
2935 if expand_from_user_groups:
2954 if expand_from_user_groups:
2936 for ug in self.permission_user_groups(with_members=True):
2955 for ug in self.permission_user_groups(with_members=True):
2937 for user_data in ug.members:
2956 for user_data in ug.members:
2938 user_groups_rows.append(user_data)
2957 user_groups_rows.append(user_data)
2939
2958
2940 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2959 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2941
2960
2942 def permission_user_groups(self, with_members=False):
2961 def permission_user_groups(self, with_members=False):
2943 q = UserGroupRepoGroupToPerm.query()\
2962 q = UserGroupRepoGroupToPerm.query()\
2944 .filter(UserGroupRepoGroupToPerm.group == self)
2963 .filter(UserGroupRepoGroupToPerm.group == self)
2945 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2964 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2946 joinedload(UserGroupRepoGroupToPerm.users_group),
2965 joinedload(UserGroupRepoGroupToPerm.users_group),
2947 joinedload(UserGroupRepoGroupToPerm.permission),)
2966 joinedload(UserGroupRepoGroupToPerm.permission),)
2948
2967
2949 perm_rows = []
2968 perm_rows = []
2950 for _user_group in q.all():
2969 for _user_group in q.all():
2951 entry = AttributeDict(_user_group.users_group.get_dict())
2970 entry = AttributeDict(_user_group.users_group.get_dict())
2952 entry.permission = _user_group.permission.permission_name
2971 entry.permission = _user_group.permission.permission_name
2953 if with_members:
2972 if with_members:
2954 entry.members = [x.user.get_dict()
2973 entry.members = [x.user.get_dict()
2955 for x in _user_group.users_group.members]
2974 for x in _user_group.users_group.members]
2956 perm_rows.append(entry)
2975 perm_rows.append(entry)
2957
2976
2958 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2977 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2959 return perm_rows
2978 return perm_rows
2960
2979
2961 def get_api_data(self):
2980 def get_api_data(self):
2962 """
2981 """
2963 Common function for generating api data
2982 Common function for generating api data
2964
2983
2965 """
2984 """
2966 group = self
2985 group = self
2967 data = {
2986 data = {
2968 'group_id': group.group_id,
2987 'group_id': group.group_id,
2969 'group_name': group.group_name,
2988 'group_name': group.group_name,
2970 'group_description': group.description_safe,
2989 'group_description': group.description_safe,
2971 'parent_group': group.parent_group.group_name if group.parent_group else None,
2990 'parent_group': group.parent_group.group_name if group.parent_group else None,
2972 'repositories': [x.repo_name for x in group.repositories],
2991 'repositories': [x.repo_name for x in group.repositories],
2973 'owner': group.user.username,
2992 'owner': group.user.username,
2974 }
2993 }
2975 return data
2994 return data
2976
2995
2977 def get_dict(self):
2996 def get_dict(self):
2978 # Since we transformed `group_name` to a hybrid property, we need to
2997 # Since we transformed `group_name` to a hybrid property, we need to
2979 # keep compatibility with the code which uses `group_name` field.
2998 # keep compatibility with the code which uses `group_name` field.
2980 result = super(RepoGroup, self).get_dict()
2999 result = super(RepoGroup, self).get_dict()
2981 result['group_name'] = result.pop('_group_name', None)
3000 result['group_name'] = result.pop('_group_name', None)
2982 return result
3001 return result
2983
3002
2984
3003
2985 class Permission(Base, BaseModel):
3004 class Permission(Base, BaseModel):
2986 __tablename__ = 'permissions'
3005 __tablename__ = 'permissions'
2987 __table_args__ = (
3006 __table_args__ = (
2988 Index('p_perm_name_idx', 'permission_name'),
3007 Index('p_perm_name_idx', 'permission_name'),
2989 base_table_args,
3008 base_table_args,
2990 )
3009 )
2991
3010
2992 PERMS = [
3011 PERMS = [
2993 ('hg.admin', _('RhodeCode Super Administrator')),
3012 ('hg.admin', _('RhodeCode Super Administrator')),
2994
3013
2995 ('repository.none', _('Repository no access')),
3014 ('repository.none', _('Repository no access')),
2996 ('repository.read', _('Repository read access')),
3015 ('repository.read', _('Repository read access')),
2997 ('repository.write', _('Repository write access')),
3016 ('repository.write', _('Repository write access')),
2998 ('repository.admin', _('Repository admin access')),
3017 ('repository.admin', _('Repository admin access')),
2999
3018
3000 ('group.none', _('Repository group no access')),
3019 ('group.none', _('Repository group no access')),
3001 ('group.read', _('Repository group read access')),
3020 ('group.read', _('Repository group read access')),
3002 ('group.write', _('Repository group write access')),
3021 ('group.write', _('Repository group write access')),
3003 ('group.admin', _('Repository group admin access')),
3022 ('group.admin', _('Repository group admin access')),
3004
3023
3005 ('usergroup.none', _('User group no access')),
3024 ('usergroup.none', _('User group no access')),
3006 ('usergroup.read', _('User group read access')),
3025 ('usergroup.read', _('User group read access')),
3007 ('usergroup.write', _('User group write access')),
3026 ('usergroup.write', _('User group write access')),
3008 ('usergroup.admin', _('User group admin access')),
3027 ('usergroup.admin', _('User group admin access')),
3009
3028
3010 ('branch.none', _('Branch no permissions')),
3029 ('branch.none', _('Branch no permissions')),
3011 ('branch.merge', _('Branch access by web merge')),
3030 ('branch.merge', _('Branch access by web merge')),
3012 ('branch.push', _('Branch access by push')),
3031 ('branch.push', _('Branch access by push')),
3013 ('branch.push_force', _('Branch access by push with force')),
3032 ('branch.push_force', _('Branch access by push with force')),
3014
3033
3015 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
3034 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
3016 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
3035 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
3017
3036
3018 ('hg.usergroup.create.false', _('User Group creation disabled')),
3037 ('hg.usergroup.create.false', _('User Group creation disabled')),
3019 ('hg.usergroup.create.true', _('User Group creation enabled')),
3038 ('hg.usergroup.create.true', _('User Group creation enabled')),
3020
3039
3021 ('hg.create.none', _('Repository creation disabled')),
3040 ('hg.create.none', _('Repository creation disabled')),
3022 ('hg.create.repository', _('Repository creation enabled')),
3041 ('hg.create.repository', _('Repository creation enabled')),
3023 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
3042 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
3024 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
3043 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
3025
3044
3026 ('hg.fork.none', _('Repository forking disabled')),
3045 ('hg.fork.none', _('Repository forking disabled')),
3027 ('hg.fork.repository', _('Repository forking enabled')),
3046 ('hg.fork.repository', _('Repository forking enabled')),
3028
3047
3029 ('hg.register.none', _('Registration disabled')),
3048 ('hg.register.none', _('Registration disabled')),
3030 ('hg.register.manual_activate', _('User Registration with manual account activation')),
3049 ('hg.register.manual_activate', _('User Registration with manual account activation')),
3031 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
3050 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
3032
3051
3033 ('hg.password_reset.enabled', _('Password reset enabled')),
3052 ('hg.password_reset.enabled', _('Password reset enabled')),
3034 ('hg.password_reset.hidden', _('Password reset hidden')),
3053 ('hg.password_reset.hidden', _('Password reset hidden')),
3035 ('hg.password_reset.disabled', _('Password reset disabled')),
3054 ('hg.password_reset.disabled', _('Password reset disabled')),
3036
3055
3037 ('hg.extern_activate.manual', _('Manual activation of external account')),
3056 ('hg.extern_activate.manual', _('Manual activation of external account')),
3038 ('hg.extern_activate.auto', _('Automatic activation of external account')),
3057 ('hg.extern_activate.auto', _('Automatic activation of external account')),
3039
3058
3040 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
3059 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
3041 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
3060 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
3042 ]
3061 ]
3043
3062
3044 # definition of system default permissions for DEFAULT user, created on
3063 # definition of system default permissions for DEFAULT user, created on
3045 # system setup
3064 # system setup
3046 DEFAULT_USER_PERMISSIONS = [
3065 DEFAULT_USER_PERMISSIONS = [
3047 # object perms
3066 # object perms
3048 'repository.read',
3067 'repository.read',
3049 'group.read',
3068 'group.read',
3050 'usergroup.read',
3069 'usergroup.read',
3051 # branch, for backward compat we need same value as before so forced pushed
3070 # branch, for backward compat we need same value as before so forced pushed
3052 'branch.push_force',
3071 'branch.push_force',
3053 # global
3072 # global
3054 'hg.create.repository',
3073 'hg.create.repository',
3055 'hg.repogroup.create.false',
3074 'hg.repogroup.create.false',
3056 'hg.usergroup.create.false',
3075 'hg.usergroup.create.false',
3057 'hg.create.write_on_repogroup.true',
3076 'hg.create.write_on_repogroup.true',
3058 'hg.fork.repository',
3077 'hg.fork.repository',
3059 'hg.register.manual_activate',
3078 'hg.register.manual_activate',
3060 'hg.password_reset.enabled',
3079 'hg.password_reset.enabled',
3061 'hg.extern_activate.auto',
3080 'hg.extern_activate.auto',
3062 'hg.inherit_default_perms.true',
3081 'hg.inherit_default_perms.true',
3063 ]
3082 ]
3064
3083
3065 # defines which permissions are more important higher the more important
3084 # defines which permissions are more important higher the more important
3066 # Weight defines which permissions are more important.
3085 # Weight defines which permissions are more important.
3067 # The higher number the more important.
3086 # The higher number the more important.
3068 PERM_WEIGHTS = {
3087 PERM_WEIGHTS = {
3069 'repository.none': 0,
3088 'repository.none': 0,
3070 'repository.read': 1,
3089 'repository.read': 1,
3071 'repository.write': 3,
3090 'repository.write': 3,
3072 'repository.admin': 4,
3091 'repository.admin': 4,
3073
3092
3074 'group.none': 0,
3093 'group.none': 0,
3075 'group.read': 1,
3094 'group.read': 1,
3076 'group.write': 3,
3095 'group.write': 3,
3077 'group.admin': 4,
3096 'group.admin': 4,
3078
3097
3079 'usergroup.none': 0,
3098 'usergroup.none': 0,
3080 'usergroup.read': 1,
3099 'usergroup.read': 1,
3081 'usergroup.write': 3,
3100 'usergroup.write': 3,
3082 'usergroup.admin': 4,
3101 'usergroup.admin': 4,
3083
3102
3084 'branch.none': 0,
3103 'branch.none': 0,
3085 'branch.merge': 1,
3104 'branch.merge': 1,
3086 'branch.push': 3,
3105 'branch.push': 3,
3087 'branch.push_force': 4,
3106 'branch.push_force': 4,
3088
3107
3089 'hg.repogroup.create.false': 0,
3108 'hg.repogroup.create.false': 0,
3090 'hg.repogroup.create.true': 1,
3109 'hg.repogroup.create.true': 1,
3091
3110
3092 'hg.usergroup.create.false': 0,
3111 'hg.usergroup.create.false': 0,
3093 'hg.usergroup.create.true': 1,
3112 'hg.usergroup.create.true': 1,
3094
3113
3095 'hg.fork.none': 0,
3114 'hg.fork.none': 0,
3096 'hg.fork.repository': 1,
3115 'hg.fork.repository': 1,
3097 'hg.create.none': 0,
3116 'hg.create.none': 0,
3098 'hg.create.repository': 1
3117 'hg.create.repository': 1
3099 }
3118 }
3100
3119
3101 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3120 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3102 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
3121 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
3103 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
3122 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
3104
3123
3105 def __unicode__(self):
3124 def __unicode__(self):
3106 return u"<%s('%s:%s')>" % (
3125 return u"<%s('%s:%s')>" % (
3107 self.__class__.__name__, self.permission_id, self.permission_name
3126 self.__class__.__name__, self.permission_id, self.permission_name
3108 )
3127 )
3109
3128
3110 @classmethod
3129 @classmethod
3111 def get_by_key(cls, key):
3130 def get_by_key(cls, key):
3112 return cls.query().filter(cls.permission_name == key).scalar()
3131 return cls.query().filter(cls.permission_name == key).scalar()
3113
3132
3114 @classmethod
3133 @classmethod
3115 def get_default_repo_perms(cls, user_id, repo_id=None):
3134 def get_default_repo_perms(cls, user_id, repo_id=None):
3116 q = Session().query(UserRepoToPerm, Repository, Permission)\
3135 q = Session().query(UserRepoToPerm, Repository, Permission)\
3117 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
3136 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
3118 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
3137 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
3119 .filter(UserRepoToPerm.user_id == user_id)
3138 .filter(UserRepoToPerm.user_id == user_id)
3120 if repo_id:
3139 if repo_id:
3121 q = q.filter(UserRepoToPerm.repository_id == repo_id)
3140 q = q.filter(UserRepoToPerm.repository_id == repo_id)
3122 return q.all()
3141 return q.all()
3123
3142
3124 @classmethod
3143 @classmethod
3125 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
3144 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
3126 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
3145 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
3127 .join(
3146 .join(
3128 Permission,
3147 Permission,
3129 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
3148 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
3130 .join(
3149 .join(
3131 UserRepoToPerm,
3150 UserRepoToPerm,
3132 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
3151 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
3133 .filter(UserRepoToPerm.user_id == user_id)
3152 .filter(UserRepoToPerm.user_id == user_id)
3134
3153
3135 if repo_id:
3154 if repo_id:
3136 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
3155 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
3137 return q.order_by(UserToRepoBranchPermission.rule_order).all()
3156 return q.order_by(UserToRepoBranchPermission.rule_order).all()
3138
3157
3139 @classmethod
3158 @classmethod
3140 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
3159 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
3141 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
3160 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
3142 .join(
3161 .join(
3143 Permission,
3162 Permission,
3144 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
3163 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
3145 .join(
3164 .join(
3146 Repository,
3165 Repository,
3147 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
3166 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
3148 .join(
3167 .join(
3149 UserGroup,
3168 UserGroup,
3150 UserGroupRepoToPerm.users_group_id ==
3169 UserGroupRepoToPerm.users_group_id ==
3151 UserGroup.users_group_id)\
3170 UserGroup.users_group_id)\
3152 .join(
3171 .join(
3153 UserGroupMember,
3172 UserGroupMember,
3154 UserGroupRepoToPerm.users_group_id ==
3173 UserGroupRepoToPerm.users_group_id ==
3155 UserGroupMember.users_group_id)\
3174 UserGroupMember.users_group_id)\
3156 .filter(
3175 .filter(
3157 UserGroupMember.user_id == user_id,
3176 UserGroupMember.user_id == user_id,
3158 UserGroup.users_group_active == true())
3177 UserGroup.users_group_active == true())
3159 if repo_id:
3178 if repo_id:
3160 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
3179 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
3161 return q.all()
3180 return q.all()
3162
3181
3163 @classmethod
3182 @classmethod
3164 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
3183 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
3165 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
3184 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
3166 .join(
3185 .join(
3167 Permission,
3186 Permission,
3168 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
3187 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
3169 .join(
3188 .join(
3170 UserGroupRepoToPerm,
3189 UserGroupRepoToPerm,
3171 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
3190 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
3172 .join(
3191 .join(
3173 UserGroup,
3192 UserGroup,
3174 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
3193 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
3175 .join(
3194 .join(
3176 UserGroupMember,
3195 UserGroupMember,
3177 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
3196 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
3178 .filter(
3197 .filter(
3179 UserGroupMember.user_id == user_id,
3198 UserGroupMember.user_id == user_id,
3180 UserGroup.users_group_active == true())
3199 UserGroup.users_group_active == true())
3181
3200
3182 if repo_id:
3201 if repo_id:
3183 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
3202 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
3184 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
3203 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
3185
3204
3186 @classmethod
3205 @classmethod
3187 def get_default_group_perms(cls, user_id, repo_group_id=None):
3206 def get_default_group_perms(cls, user_id, repo_group_id=None):
3188 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
3207 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
3189 .join(
3208 .join(
3190 Permission,
3209 Permission,
3191 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
3210 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
3192 .join(
3211 .join(
3193 RepoGroup,
3212 RepoGroup,
3194 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
3213 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
3195 .filter(UserRepoGroupToPerm.user_id == user_id)
3214 .filter(UserRepoGroupToPerm.user_id == user_id)
3196 if repo_group_id:
3215 if repo_group_id:
3197 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
3216 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
3198 return q.all()
3217 return q.all()
3199
3218
3200 @classmethod
3219 @classmethod
3201 def get_default_group_perms_from_user_group(
3220 def get_default_group_perms_from_user_group(
3202 cls, user_id, repo_group_id=None):
3221 cls, user_id, repo_group_id=None):
3203 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
3222 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
3204 .join(
3223 .join(
3205 Permission,
3224 Permission,
3206 UserGroupRepoGroupToPerm.permission_id ==
3225 UserGroupRepoGroupToPerm.permission_id ==
3207 Permission.permission_id)\
3226 Permission.permission_id)\
3208 .join(
3227 .join(
3209 RepoGroup,
3228 RepoGroup,
3210 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
3229 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
3211 .join(
3230 .join(
3212 UserGroup,
3231 UserGroup,
3213 UserGroupRepoGroupToPerm.users_group_id ==
3232 UserGroupRepoGroupToPerm.users_group_id ==
3214 UserGroup.users_group_id)\
3233 UserGroup.users_group_id)\
3215 .join(
3234 .join(
3216 UserGroupMember,
3235 UserGroupMember,
3217 UserGroupRepoGroupToPerm.users_group_id ==
3236 UserGroupRepoGroupToPerm.users_group_id ==
3218 UserGroupMember.users_group_id)\
3237 UserGroupMember.users_group_id)\
3219 .filter(
3238 .filter(
3220 UserGroupMember.user_id == user_id,
3239 UserGroupMember.user_id == user_id,
3221 UserGroup.users_group_active == true())
3240 UserGroup.users_group_active == true())
3222 if repo_group_id:
3241 if repo_group_id:
3223 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
3242 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
3224 return q.all()
3243 return q.all()
3225
3244
3226 @classmethod
3245 @classmethod
3227 def get_default_user_group_perms(cls, user_id, user_group_id=None):
3246 def get_default_user_group_perms(cls, user_id, user_group_id=None):
3228 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
3247 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
3229 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
3248 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
3230 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
3249 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
3231 .filter(UserUserGroupToPerm.user_id == user_id)
3250 .filter(UserUserGroupToPerm.user_id == user_id)
3232 if user_group_id:
3251 if user_group_id:
3233 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
3252 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
3234 return q.all()
3253 return q.all()
3235
3254
3236 @classmethod
3255 @classmethod
3237 def get_default_user_group_perms_from_user_group(
3256 def get_default_user_group_perms_from_user_group(
3238 cls, user_id, user_group_id=None):
3257 cls, user_id, user_group_id=None):
3239 TargetUserGroup = aliased(UserGroup, name='target_user_group')
3258 TargetUserGroup = aliased(UserGroup, name='target_user_group')
3240 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
3259 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
3241 .join(
3260 .join(
3242 Permission,
3261 Permission,
3243 UserGroupUserGroupToPerm.permission_id ==
3262 UserGroupUserGroupToPerm.permission_id ==
3244 Permission.permission_id)\
3263 Permission.permission_id)\
3245 .join(
3264 .join(
3246 TargetUserGroup,
3265 TargetUserGroup,
3247 UserGroupUserGroupToPerm.target_user_group_id ==
3266 UserGroupUserGroupToPerm.target_user_group_id ==
3248 TargetUserGroup.users_group_id)\
3267 TargetUserGroup.users_group_id)\
3249 .join(
3268 .join(
3250 UserGroup,
3269 UserGroup,
3251 UserGroupUserGroupToPerm.user_group_id ==
3270 UserGroupUserGroupToPerm.user_group_id ==
3252 UserGroup.users_group_id)\
3271 UserGroup.users_group_id)\
3253 .join(
3272 .join(
3254 UserGroupMember,
3273 UserGroupMember,
3255 UserGroupUserGroupToPerm.user_group_id ==
3274 UserGroupUserGroupToPerm.user_group_id ==
3256 UserGroupMember.users_group_id)\
3275 UserGroupMember.users_group_id)\
3257 .filter(
3276 .filter(
3258 UserGroupMember.user_id == user_id,
3277 UserGroupMember.user_id == user_id,
3259 UserGroup.users_group_active == true())
3278 UserGroup.users_group_active == true())
3260 if user_group_id:
3279 if user_group_id:
3261 q = q.filter(
3280 q = q.filter(
3262 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3281 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3263
3282
3264 return q.all()
3283 return q.all()
3265
3284
3266
3285
3267 class UserRepoToPerm(Base, BaseModel):
3286 class UserRepoToPerm(Base, BaseModel):
3268 __tablename__ = 'repo_to_perm'
3287 __tablename__ = 'repo_to_perm'
3269 __table_args__ = (
3288 __table_args__ = (
3270 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3289 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3271 base_table_args
3290 base_table_args
3272 )
3291 )
3273
3292
3274 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3293 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3275 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3294 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3276 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3295 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3277 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3296 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3278
3297
3279 user = relationship('User')
3298 user = relationship('User')
3280 repository = relationship('Repository')
3299 repository = relationship('Repository')
3281 permission = relationship('Permission')
3300 permission = relationship('Permission')
3282
3301
3283 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete-orphan", lazy='joined')
3302 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete-orphan", lazy='joined')
3284
3303
3285 @classmethod
3304 @classmethod
3286 def create(cls, user, repository, permission):
3305 def create(cls, user, repository, permission):
3287 n = cls()
3306 n = cls()
3288 n.user = user
3307 n.user = user
3289 n.repository = repository
3308 n.repository = repository
3290 n.permission = permission
3309 n.permission = permission
3291 Session().add(n)
3310 Session().add(n)
3292 return n
3311 return n
3293
3312
3294 def __unicode__(self):
3313 def __unicode__(self):
3295 return u'<%s => %s >' % (self.user, self.repository)
3314 return u'<%s => %s >' % (self.user, self.repository)
3296
3315
3297
3316
3298 class UserUserGroupToPerm(Base, BaseModel):
3317 class UserUserGroupToPerm(Base, BaseModel):
3299 __tablename__ = 'user_user_group_to_perm'
3318 __tablename__ = 'user_user_group_to_perm'
3300 __table_args__ = (
3319 __table_args__ = (
3301 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3320 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3302 base_table_args
3321 base_table_args
3303 )
3322 )
3304
3323
3305 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3324 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3306 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3325 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3307 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3326 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3308 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3327 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3309
3328
3310 user = relationship('User')
3329 user = relationship('User')
3311 user_group = relationship('UserGroup')
3330 user_group = relationship('UserGroup')
3312 permission = relationship('Permission')
3331 permission = relationship('Permission')
3313
3332
3314 @classmethod
3333 @classmethod
3315 def create(cls, user, user_group, permission):
3334 def create(cls, user, user_group, permission):
3316 n = cls()
3335 n = cls()
3317 n.user = user
3336 n.user = user
3318 n.user_group = user_group
3337 n.user_group = user_group
3319 n.permission = permission
3338 n.permission = permission
3320 Session().add(n)
3339 Session().add(n)
3321 return n
3340 return n
3322
3341
3323 def __unicode__(self):
3342 def __unicode__(self):
3324 return u'<%s => %s >' % (self.user, self.user_group)
3343 return u'<%s => %s >' % (self.user, self.user_group)
3325
3344
3326
3345
3327 class UserToPerm(Base, BaseModel):
3346 class UserToPerm(Base, BaseModel):
3328 __tablename__ = 'user_to_perm'
3347 __tablename__ = 'user_to_perm'
3329 __table_args__ = (
3348 __table_args__ = (
3330 UniqueConstraint('user_id', 'permission_id'),
3349 UniqueConstraint('user_id', 'permission_id'),
3331 base_table_args
3350 base_table_args
3332 )
3351 )
3333
3352
3334 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3353 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3335 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3354 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3336 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3355 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3337
3356
3338 user = relationship('User')
3357 user = relationship('User')
3339 permission = relationship('Permission', lazy='joined')
3358 permission = relationship('Permission', lazy='joined')
3340
3359
3341 def __unicode__(self):
3360 def __unicode__(self):
3342 return u'<%s => %s >' % (self.user, self.permission)
3361 return u'<%s => %s >' % (self.user, self.permission)
3343
3362
3344
3363
3345 class UserGroupRepoToPerm(Base, BaseModel):
3364 class UserGroupRepoToPerm(Base, BaseModel):
3346 __tablename__ = 'users_group_repo_to_perm'
3365 __tablename__ = 'users_group_repo_to_perm'
3347 __table_args__ = (
3366 __table_args__ = (
3348 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3367 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3349 base_table_args
3368 base_table_args
3350 )
3369 )
3351
3370
3352 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3371 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3353 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3372 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3354 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3373 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3355 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3374 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3356
3375
3357 users_group = relationship('UserGroup')
3376 users_group = relationship('UserGroup')
3358 permission = relationship('Permission')
3377 permission = relationship('Permission')
3359 repository = relationship('Repository')
3378 repository = relationship('Repository')
3360 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all')
3379 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all')
3361
3380
3362 @classmethod
3381 @classmethod
3363 def create(cls, users_group, repository, permission):
3382 def create(cls, users_group, repository, permission):
3364 n = cls()
3383 n = cls()
3365 n.users_group = users_group
3384 n.users_group = users_group
3366 n.repository = repository
3385 n.repository = repository
3367 n.permission = permission
3386 n.permission = permission
3368 Session().add(n)
3387 Session().add(n)
3369 return n
3388 return n
3370
3389
3371 def __unicode__(self):
3390 def __unicode__(self):
3372 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
3391 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
3373
3392
3374
3393
3375 class UserGroupUserGroupToPerm(Base, BaseModel):
3394 class UserGroupUserGroupToPerm(Base, BaseModel):
3376 __tablename__ = 'user_group_user_group_to_perm'
3395 __tablename__ = 'user_group_user_group_to_perm'
3377 __table_args__ = (
3396 __table_args__ = (
3378 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3397 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3379 CheckConstraint('target_user_group_id != user_group_id'),
3398 CheckConstraint('target_user_group_id != user_group_id'),
3380 base_table_args
3399 base_table_args
3381 )
3400 )
3382
3401
3383 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)
3402 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)
3384 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3403 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3385 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3404 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3386 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3405 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3387
3406
3388 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3407 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3389 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3408 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3390 permission = relationship('Permission')
3409 permission = relationship('Permission')
3391
3410
3392 @classmethod
3411 @classmethod
3393 def create(cls, target_user_group, user_group, permission):
3412 def create(cls, target_user_group, user_group, permission):
3394 n = cls()
3413 n = cls()
3395 n.target_user_group = target_user_group
3414 n.target_user_group = target_user_group
3396 n.user_group = user_group
3415 n.user_group = user_group
3397 n.permission = permission
3416 n.permission = permission
3398 Session().add(n)
3417 Session().add(n)
3399 return n
3418 return n
3400
3419
3401 def __unicode__(self):
3420 def __unicode__(self):
3402 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3421 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3403
3422
3404
3423
3405 class UserGroupToPerm(Base, BaseModel):
3424 class UserGroupToPerm(Base, BaseModel):
3406 __tablename__ = 'users_group_to_perm'
3425 __tablename__ = 'users_group_to_perm'
3407 __table_args__ = (
3426 __table_args__ = (
3408 UniqueConstraint('users_group_id', 'permission_id',),
3427 UniqueConstraint('users_group_id', 'permission_id',),
3409 base_table_args
3428 base_table_args
3410 )
3429 )
3411
3430
3412 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3431 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3413 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3432 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3414 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3433 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3415
3434
3416 users_group = relationship('UserGroup')
3435 users_group = relationship('UserGroup')
3417 permission = relationship('Permission')
3436 permission = relationship('Permission')
3418
3437
3419
3438
3420 class UserRepoGroupToPerm(Base, BaseModel):
3439 class UserRepoGroupToPerm(Base, BaseModel):
3421 __tablename__ = 'user_repo_group_to_perm'
3440 __tablename__ = 'user_repo_group_to_perm'
3422 __table_args__ = (
3441 __table_args__ = (
3423 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3442 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3424 base_table_args
3443 base_table_args
3425 )
3444 )
3426
3445
3427 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3446 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3428 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3447 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3429 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3448 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3430 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3449 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3431
3450
3432 user = relationship('User')
3451 user = relationship('User')
3433 group = relationship('RepoGroup')
3452 group = relationship('RepoGroup')
3434 permission = relationship('Permission')
3453 permission = relationship('Permission')
3435
3454
3436 @classmethod
3455 @classmethod
3437 def create(cls, user, repository_group, permission):
3456 def create(cls, user, repository_group, permission):
3438 n = cls()
3457 n = cls()
3439 n.user = user
3458 n.user = user
3440 n.group = repository_group
3459 n.group = repository_group
3441 n.permission = permission
3460 n.permission = permission
3442 Session().add(n)
3461 Session().add(n)
3443 return n
3462 return n
3444
3463
3445
3464
3446 class UserGroupRepoGroupToPerm(Base, BaseModel):
3465 class UserGroupRepoGroupToPerm(Base, BaseModel):
3447 __tablename__ = 'users_group_repo_group_to_perm'
3466 __tablename__ = 'users_group_repo_group_to_perm'
3448 __table_args__ = (
3467 __table_args__ = (
3449 UniqueConstraint('users_group_id', 'group_id'),
3468 UniqueConstraint('users_group_id', 'group_id'),
3450 base_table_args
3469 base_table_args
3451 )
3470 )
3452
3471
3453 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)
3472 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)
3454 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3473 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3455 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3474 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3456 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3475 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3457
3476
3458 users_group = relationship('UserGroup')
3477 users_group = relationship('UserGroup')
3459 permission = relationship('Permission')
3478 permission = relationship('Permission')
3460 group = relationship('RepoGroup')
3479 group = relationship('RepoGroup')
3461
3480
3462 @classmethod
3481 @classmethod
3463 def create(cls, user_group, repository_group, permission):
3482 def create(cls, user_group, repository_group, permission):
3464 n = cls()
3483 n = cls()
3465 n.users_group = user_group
3484 n.users_group = user_group
3466 n.group = repository_group
3485 n.group = repository_group
3467 n.permission = permission
3486 n.permission = permission
3468 Session().add(n)
3487 Session().add(n)
3469 return n
3488 return n
3470
3489
3471 def __unicode__(self):
3490 def __unicode__(self):
3472 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3491 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3473
3492
3474
3493
3475 class Statistics(Base, BaseModel):
3494 class Statistics(Base, BaseModel):
3476 __tablename__ = 'statistics'
3495 __tablename__ = 'statistics'
3477 __table_args__ = (
3496 __table_args__ = (
3478 base_table_args
3497 base_table_args
3479 )
3498 )
3480
3499
3481 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3500 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3482 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3501 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3483 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3502 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3484 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3503 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3485 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3504 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3486 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3505 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3487
3506
3488 repository = relationship('Repository', single_parent=True)
3507 repository = relationship('Repository', single_parent=True)
3489
3508
3490
3509
3491 class UserFollowing(Base, BaseModel):
3510 class UserFollowing(Base, BaseModel):
3492 __tablename__ = 'user_followings'
3511 __tablename__ = 'user_followings'
3493 __table_args__ = (
3512 __table_args__ = (
3494 UniqueConstraint('user_id', 'follows_repository_id'),
3513 UniqueConstraint('user_id', 'follows_repository_id'),
3495 UniqueConstraint('user_id', 'follows_user_id'),
3514 UniqueConstraint('user_id', 'follows_user_id'),
3496 base_table_args
3515 base_table_args
3497 )
3516 )
3498
3517
3499 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3518 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3500 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3519 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3501 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3520 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3502 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3521 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3503 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3522 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3504
3523
3505 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3524 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3506
3525
3507 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3526 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3508 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3527 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3509
3528
3510 @classmethod
3529 @classmethod
3511 def get_repo_followers(cls, repo_id):
3530 def get_repo_followers(cls, repo_id):
3512 return cls.query().filter(cls.follows_repo_id == repo_id)
3531 return cls.query().filter(cls.follows_repo_id == repo_id)
3513
3532
3514
3533
3515 class CacheKey(Base, BaseModel):
3534 class CacheKey(Base, BaseModel):
3516 __tablename__ = 'cache_invalidation'
3535 __tablename__ = 'cache_invalidation'
3517 __table_args__ = (
3536 __table_args__ = (
3518 UniqueConstraint('cache_key'),
3537 UniqueConstraint('cache_key'),
3519 Index('key_idx', 'cache_key'),
3538 Index('key_idx', 'cache_key'),
3520 base_table_args,
3539 base_table_args,
3521 )
3540 )
3522
3541
3523 CACHE_TYPE_FEED = 'FEED'
3542 CACHE_TYPE_FEED = 'FEED'
3524
3543
3525 # namespaces used to register process/thread aware caches
3544 # namespaces used to register process/thread aware caches
3526 REPO_INVALIDATION_NAMESPACE = 'repo_cache:{repo_id}'
3545 REPO_INVALIDATION_NAMESPACE = 'repo_cache:{repo_id}'
3527 SETTINGS_INVALIDATION_NAMESPACE = 'system_settings'
3546 SETTINGS_INVALIDATION_NAMESPACE = 'system_settings'
3528
3547
3529 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3548 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3530 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3549 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3531 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3550 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3532 cache_state_uid = Column("cache_state_uid", String(255), nullable=True, unique=None, default=None)
3551 cache_state_uid = Column("cache_state_uid", String(255), nullable=True, unique=None, default=None)
3533 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3552 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3534
3553
3535 def __init__(self, cache_key, cache_args='', cache_state_uid=None):
3554 def __init__(self, cache_key, cache_args='', cache_state_uid=None):
3536 self.cache_key = cache_key
3555 self.cache_key = cache_key
3537 self.cache_args = cache_args
3556 self.cache_args = cache_args
3538 self.cache_active = False
3557 self.cache_active = False
3539 # first key should be same for all entries, since all workers should share it
3558 # first key should be same for all entries, since all workers should share it
3540 self.cache_state_uid = cache_state_uid or self.generate_new_state_uid()
3559 self.cache_state_uid = cache_state_uid or self.generate_new_state_uid()
3541
3560
3542 def __unicode__(self):
3561 def __unicode__(self):
3543 return u"<%s('%s:%s[%s]')>" % (
3562 return u"<%s('%s:%s[%s]')>" % (
3544 self.__class__.__name__,
3563 self.__class__.__name__,
3545 self.cache_id, self.cache_key, self.cache_active)
3564 self.cache_id, self.cache_key, self.cache_active)
3546
3565
3547 def _cache_key_partition(self):
3566 def _cache_key_partition(self):
3548 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3567 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3549 return prefix, repo_name, suffix
3568 return prefix, repo_name, suffix
3550
3569
3551 def get_prefix(self):
3570 def get_prefix(self):
3552 """
3571 """
3553 Try to extract prefix from existing cache key. The key could consist
3572 Try to extract prefix from existing cache key. The key could consist
3554 of prefix, repo_name, suffix
3573 of prefix, repo_name, suffix
3555 """
3574 """
3556 # this returns prefix, repo_name, suffix
3575 # this returns prefix, repo_name, suffix
3557 return self._cache_key_partition()[0]
3576 return self._cache_key_partition()[0]
3558
3577
3559 def get_suffix(self):
3578 def get_suffix(self):
3560 """
3579 """
3561 get suffix that might have been used in _get_cache_key to
3580 get suffix that might have been used in _get_cache_key to
3562 generate self.cache_key. Only used for informational purposes
3581 generate self.cache_key. Only used for informational purposes
3563 in repo_edit.mako.
3582 in repo_edit.mako.
3564 """
3583 """
3565 # prefix, repo_name, suffix
3584 # prefix, repo_name, suffix
3566 return self._cache_key_partition()[2]
3585 return self._cache_key_partition()[2]
3567
3586
3568 @classmethod
3587 @classmethod
3569 def generate_new_state_uid(cls, based_on=None):
3588 def generate_new_state_uid(cls, based_on=None):
3570 if based_on:
3589 if based_on:
3571 return str(uuid.uuid5(uuid.NAMESPACE_URL, safe_str(based_on)))
3590 return str(uuid.uuid5(uuid.NAMESPACE_URL, safe_str(based_on)))
3572 else:
3591 else:
3573 return str(uuid.uuid4())
3592 return str(uuid.uuid4())
3574
3593
3575 @classmethod
3594 @classmethod
3576 def delete_all_cache(cls):
3595 def delete_all_cache(cls):
3577 """
3596 """
3578 Delete all cache keys from database.
3597 Delete all cache keys from database.
3579 Should only be run when all instances are down and all entries
3598 Should only be run when all instances are down and all entries
3580 thus stale.
3599 thus stale.
3581 """
3600 """
3582 cls.query().delete()
3601 cls.query().delete()
3583 Session().commit()
3602 Session().commit()
3584
3603
3585 @classmethod
3604 @classmethod
3586 def set_invalidate(cls, cache_uid, delete=False):
3605 def set_invalidate(cls, cache_uid, delete=False):
3587 """
3606 """
3588 Mark all caches of a repo as invalid in the database.
3607 Mark all caches of a repo as invalid in the database.
3589 """
3608 """
3590
3609
3591 try:
3610 try:
3592 qry = Session().query(cls).filter(cls.cache_args == cache_uid)
3611 qry = Session().query(cls).filter(cls.cache_args == cache_uid)
3593 if delete:
3612 if delete:
3594 qry.delete()
3613 qry.delete()
3595 log.debug('cache objects deleted for cache args %s',
3614 log.debug('cache objects deleted for cache args %s',
3596 safe_str(cache_uid))
3615 safe_str(cache_uid))
3597 else:
3616 else:
3598 qry.update({"cache_active": False,
3617 qry.update({"cache_active": False,
3599 "cache_state_uid": cls.generate_new_state_uid()})
3618 "cache_state_uid": cls.generate_new_state_uid()})
3600 log.debug('cache objects marked as invalid for cache args %s',
3619 log.debug('cache objects marked as invalid for cache args %s',
3601 safe_str(cache_uid))
3620 safe_str(cache_uid))
3602
3621
3603 Session().commit()
3622 Session().commit()
3604 except Exception:
3623 except Exception:
3605 log.exception(
3624 log.exception(
3606 'Cache key invalidation failed for cache args %s',
3625 'Cache key invalidation failed for cache args %s',
3607 safe_str(cache_uid))
3626 safe_str(cache_uid))
3608 Session().rollback()
3627 Session().rollback()
3609
3628
3610 @classmethod
3629 @classmethod
3611 def get_active_cache(cls, cache_key):
3630 def get_active_cache(cls, cache_key):
3612 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3631 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3613 if inv_obj:
3632 if inv_obj:
3614 return inv_obj
3633 return inv_obj
3615 return None
3634 return None
3616
3635
3617 @classmethod
3636 @classmethod
3618 def get_namespace_map(cls, namespace):
3637 def get_namespace_map(cls, namespace):
3619 return {
3638 return {
3620 x.cache_key: x
3639 x.cache_key: x
3621 for x in cls.query().filter(cls.cache_args == namespace)}
3640 for x in cls.query().filter(cls.cache_args == namespace)}
3622
3641
3623
3642
3624 class ChangesetComment(Base, BaseModel):
3643 class ChangesetComment(Base, BaseModel):
3625 __tablename__ = 'changeset_comments'
3644 __tablename__ = 'changeset_comments'
3626 __table_args__ = (
3645 __table_args__ = (
3627 Index('cc_revision_idx', 'revision'),
3646 Index('cc_revision_idx', 'revision'),
3628 base_table_args,
3647 base_table_args,
3629 )
3648 )
3630
3649
3631 COMMENT_OUTDATED = u'comment_outdated'
3650 COMMENT_OUTDATED = u'comment_outdated'
3632 COMMENT_TYPE_NOTE = u'note'
3651 COMMENT_TYPE_NOTE = u'note'
3633 COMMENT_TYPE_TODO = u'todo'
3652 COMMENT_TYPE_TODO = u'todo'
3634 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3653 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3635
3654
3636 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3655 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3637 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3656 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3638 revision = Column('revision', String(40), nullable=True)
3657 revision = Column('revision', String(40), nullable=True)
3639 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3658 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3640 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3659 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3641 line_no = Column('line_no', Unicode(10), nullable=True)
3660 line_no = Column('line_no', Unicode(10), nullable=True)
3642 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3661 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3643 f_path = Column('f_path', Unicode(1000), nullable=True)
3662 f_path = Column('f_path', Unicode(1000), nullable=True)
3644 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3663 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3645 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3664 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3646 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3665 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3647 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3666 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3648 renderer = Column('renderer', Unicode(64), nullable=True)
3667 renderer = Column('renderer', Unicode(64), nullable=True)
3649 display_state = Column('display_state', Unicode(128), nullable=True)
3668 display_state = Column('display_state', Unicode(128), nullable=True)
3650
3669
3651 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3670 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3652 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3671 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3653
3672
3654 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3673 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3655 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3674 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3656
3675
3657 author = relationship('User', lazy='joined')
3676 author = relationship('User', lazy='joined')
3658 repo = relationship('Repository')
3677 repo = relationship('Repository')
3659 status_change = relationship('ChangesetStatus', cascade="all, delete-orphan", lazy='joined')
3678 status_change = relationship('ChangesetStatus', cascade="all, delete-orphan", lazy='joined')
3660 pull_request = relationship('PullRequest', lazy='joined')
3679 pull_request = relationship('PullRequest', lazy='joined')
3661 pull_request_version = relationship('PullRequestVersion')
3680 pull_request_version = relationship('PullRequestVersion')
3662
3681
3663 @classmethod
3682 @classmethod
3664 def get_users(cls, revision=None, pull_request_id=None):
3683 def get_users(cls, revision=None, pull_request_id=None):
3665 """
3684 """
3666 Returns user associated with this ChangesetComment. ie those
3685 Returns user associated with this ChangesetComment. ie those
3667 who actually commented
3686 who actually commented
3668
3687
3669 :param cls:
3688 :param cls:
3670 :param revision:
3689 :param revision:
3671 """
3690 """
3672 q = Session().query(User)\
3691 q = Session().query(User)\
3673 .join(ChangesetComment.author)
3692 .join(ChangesetComment.author)
3674 if revision:
3693 if revision:
3675 q = q.filter(cls.revision == revision)
3694 q = q.filter(cls.revision == revision)
3676 elif pull_request_id:
3695 elif pull_request_id:
3677 q = q.filter(cls.pull_request_id == pull_request_id)
3696 q = q.filter(cls.pull_request_id == pull_request_id)
3678 return q.all()
3697 return q.all()
3679
3698
3680 @classmethod
3699 @classmethod
3681 def get_index_from_version(cls, pr_version, versions):
3700 def get_index_from_version(cls, pr_version, versions):
3682 num_versions = [x.pull_request_version_id for x in versions]
3701 num_versions = [x.pull_request_version_id for x in versions]
3683 try:
3702 try:
3684 return num_versions.index(pr_version) +1
3703 return num_versions.index(pr_version) +1
3685 except (IndexError, ValueError):
3704 except (IndexError, ValueError):
3686 return
3705 return
3687
3706
3688 @property
3707 @property
3689 def outdated(self):
3708 def outdated(self):
3690 return self.display_state == self.COMMENT_OUTDATED
3709 return self.display_state == self.COMMENT_OUTDATED
3691
3710
3692 def outdated_at_version(self, version):
3711 def outdated_at_version(self, version):
3693 """
3712 """
3694 Checks if comment is outdated for given pull request version
3713 Checks if comment is outdated for given pull request version
3695 """
3714 """
3696 return self.outdated and self.pull_request_version_id != version
3715 return self.outdated and self.pull_request_version_id != version
3697
3716
3698 def older_than_version(self, version):
3717 def older_than_version(self, version):
3699 """
3718 """
3700 Checks if comment is made from previous version than given
3719 Checks if comment is made from previous version than given
3701 """
3720 """
3702 if version is None:
3721 if version is None:
3703 return self.pull_request_version_id is not None
3722 return self.pull_request_version_id is not None
3704
3723
3705 return self.pull_request_version_id < version
3724 return self.pull_request_version_id < version
3706
3725
3707 @property
3726 @property
3708 def resolved(self):
3727 def resolved(self):
3709 return self.resolved_by[0] if self.resolved_by else None
3728 return self.resolved_by[0] if self.resolved_by else None
3710
3729
3711 @property
3730 @property
3712 def is_todo(self):
3731 def is_todo(self):
3713 return self.comment_type == self.COMMENT_TYPE_TODO
3732 return self.comment_type == self.COMMENT_TYPE_TODO
3714
3733
3715 @property
3734 @property
3716 def is_inline(self):
3735 def is_inline(self):
3717 return self.line_no and self.f_path
3736 return self.line_no and self.f_path
3718
3737
3719 def get_index_version(self, versions):
3738 def get_index_version(self, versions):
3720 return self.get_index_from_version(
3739 return self.get_index_from_version(
3721 self.pull_request_version_id, versions)
3740 self.pull_request_version_id, versions)
3722
3741
3723 def __repr__(self):
3742 def __repr__(self):
3724 if self.comment_id:
3743 if self.comment_id:
3725 return '<DB:Comment #%s>' % self.comment_id
3744 return '<DB:Comment #%s>' % self.comment_id
3726 else:
3745 else:
3727 return '<DB:Comment at %#x>' % id(self)
3746 return '<DB:Comment at %#x>' % id(self)
3728
3747
3729 def get_api_data(self):
3748 def get_api_data(self):
3730 comment = self
3749 comment = self
3731 data = {
3750 data = {
3732 'comment_id': comment.comment_id,
3751 'comment_id': comment.comment_id,
3733 'comment_type': comment.comment_type,
3752 'comment_type': comment.comment_type,
3734 'comment_text': comment.text,
3753 'comment_text': comment.text,
3735 'comment_status': comment.status_change,
3754 'comment_status': comment.status_change,
3736 'comment_f_path': comment.f_path,
3755 'comment_f_path': comment.f_path,
3737 'comment_lineno': comment.line_no,
3756 'comment_lineno': comment.line_no,
3738 'comment_author': comment.author,
3757 'comment_author': comment.author,
3739 'comment_created_on': comment.created_on,
3758 'comment_created_on': comment.created_on,
3740 'comment_resolved_by': self.resolved
3759 'comment_resolved_by': self.resolved
3741 }
3760 }
3742 return data
3761 return data
3743
3762
3744 def __json__(self):
3763 def __json__(self):
3745 data = dict()
3764 data = dict()
3746 data.update(self.get_api_data())
3765 data.update(self.get_api_data())
3747 return data
3766 return data
3748
3767
3749
3768
3750 class ChangesetStatus(Base, BaseModel):
3769 class ChangesetStatus(Base, BaseModel):
3751 __tablename__ = 'changeset_statuses'
3770 __tablename__ = 'changeset_statuses'
3752 __table_args__ = (
3771 __table_args__ = (
3753 Index('cs_revision_idx', 'revision'),
3772 Index('cs_revision_idx', 'revision'),
3754 Index('cs_version_idx', 'version'),
3773 Index('cs_version_idx', 'version'),
3755 UniqueConstraint('repo_id', 'revision', 'version'),
3774 UniqueConstraint('repo_id', 'revision', 'version'),
3756 base_table_args
3775 base_table_args
3757 )
3776 )
3758
3777
3759 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3778 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3760 STATUS_APPROVED = 'approved'
3779 STATUS_APPROVED = 'approved'
3761 STATUS_REJECTED = 'rejected'
3780 STATUS_REJECTED = 'rejected'
3762 STATUS_UNDER_REVIEW = 'under_review'
3781 STATUS_UNDER_REVIEW = 'under_review'
3763
3782
3764 STATUSES = [
3783 STATUSES = [
3765 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3784 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3766 (STATUS_APPROVED, _("Approved")),
3785 (STATUS_APPROVED, _("Approved")),
3767 (STATUS_REJECTED, _("Rejected")),
3786 (STATUS_REJECTED, _("Rejected")),
3768 (STATUS_UNDER_REVIEW, _("Under Review")),
3787 (STATUS_UNDER_REVIEW, _("Under Review")),
3769 ]
3788 ]
3770
3789
3771 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3790 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3772 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3791 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3773 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3792 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3774 revision = Column('revision', String(40), nullable=False)
3793 revision = Column('revision', String(40), nullable=False)
3775 status = Column('status', String(128), nullable=False, default=DEFAULT)
3794 status = Column('status', String(128), nullable=False, default=DEFAULT)
3776 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3795 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3777 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3796 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3778 version = Column('version', Integer(), nullable=False, default=0)
3797 version = Column('version', Integer(), nullable=False, default=0)
3779 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3798 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3780
3799
3781 author = relationship('User', lazy='joined')
3800 author = relationship('User', lazy='joined')
3782 repo = relationship('Repository')
3801 repo = relationship('Repository')
3783 comment = relationship('ChangesetComment', lazy='joined')
3802 comment = relationship('ChangesetComment', lazy='joined')
3784 pull_request = relationship('PullRequest', lazy='joined')
3803 pull_request = relationship('PullRequest', lazy='joined')
3785
3804
3786 def __unicode__(self):
3805 def __unicode__(self):
3787 return u"<%s('%s[v%s]:%s')>" % (
3806 return u"<%s('%s[v%s]:%s')>" % (
3788 self.__class__.__name__,
3807 self.__class__.__name__,
3789 self.status, self.version, self.author
3808 self.status, self.version, self.author
3790 )
3809 )
3791
3810
3792 @classmethod
3811 @classmethod
3793 def get_status_lbl(cls, value):
3812 def get_status_lbl(cls, value):
3794 return dict(cls.STATUSES).get(value)
3813 return dict(cls.STATUSES).get(value)
3795
3814
3796 @property
3815 @property
3797 def status_lbl(self):
3816 def status_lbl(self):
3798 return ChangesetStatus.get_status_lbl(self.status)
3817 return ChangesetStatus.get_status_lbl(self.status)
3799
3818
3800 def get_api_data(self):
3819 def get_api_data(self):
3801 status = self
3820 status = self
3802 data = {
3821 data = {
3803 'status_id': status.changeset_status_id,
3822 'status_id': status.changeset_status_id,
3804 'status': status.status,
3823 'status': status.status,
3805 }
3824 }
3806 return data
3825 return data
3807
3826
3808 def __json__(self):
3827 def __json__(self):
3809 data = dict()
3828 data = dict()
3810 data.update(self.get_api_data())
3829 data.update(self.get_api_data())
3811 return data
3830 return data
3812
3831
3813
3832
3814 class _SetState(object):
3833 class _SetState(object):
3815 """
3834 """
3816 Context processor allowing changing state for sensitive operation such as
3835 Context processor allowing changing state for sensitive operation such as
3817 pull request update or merge
3836 pull request update or merge
3818 """
3837 """
3819
3838
3820 def __init__(self, pull_request, pr_state, back_state=None):
3839 def __init__(self, pull_request, pr_state, back_state=None):
3821 self._pr = pull_request
3840 self._pr = pull_request
3822 self._org_state = back_state or pull_request.pull_request_state
3841 self._org_state = back_state or pull_request.pull_request_state
3823 self._pr_state = pr_state
3842 self._pr_state = pr_state
3824 self._current_state = None
3843 self._current_state = None
3825
3844
3826 def __enter__(self):
3845 def __enter__(self):
3827 log.debug('StateLock: entering set state context, setting state to: `%s`',
3846 log.debug('StateLock: entering set state context, setting state to: `%s`',
3828 self._pr_state)
3847 self._pr_state)
3829 self.set_pr_state(self._pr_state)
3848 self.set_pr_state(self._pr_state)
3830 return self
3849 return self
3831
3850
3832 def __exit__(self, exc_type, exc_val, exc_tb):
3851 def __exit__(self, exc_type, exc_val, exc_tb):
3833 if exc_val is not None:
3852 if exc_val is not None:
3834 log.error(traceback.format_exc(exc_tb))
3853 log.error(traceback.format_exc(exc_tb))
3835 return None
3854 return None
3836
3855
3837 self.set_pr_state(self._org_state)
3856 self.set_pr_state(self._org_state)
3838 log.debug('StateLock: exiting set state context, setting state to: `%s`',
3857 log.debug('StateLock: exiting set state context, setting state to: `%s`',
3839 self._org_state)
3858 self._org_state)
3840 @property
3859 @property
3841 def state(self):
3860 def state(self):
3842 return self._current_state
3861 return self._current_state
3843
3862
3844 def set_pr_state(self, pr_state):
3863 def set_pr_state(self, pr_state):
3845 try:
3864 try:
3846 self._pr.pull_request_state = pr_state
3865 self._pr.pull_request_state = pr_state
3847 Session().add(self._pr)
3866 Session().add(self._pr)
3848 Session().commit()
3867 Session().commit()
3849 self._current_state = pr_state
3868 self._current_state = pr_state
3850 except Exception:
3869 except Exception:
3851 log.exception('Failed to set PullRequest %s state to %s', self._pr, pr_state)
3870 log.exception('Failed to set PullRequest %s state to %s', self._pr, pr_state)
3852 raise
3871 raise
3853
3872
3854 class _PullRequestBase(BaseModel):
3873 class _PullRequestBase(BaseModel):
3855 """
3874 """
3856 Common attributes of pull request and version entries.
3875 Common attributes of pull request and version entries.
3857 """
3876 """
3858
3877
3859 # .status values
3878 # .status values
3860 STATUS_NEW = u'new'
3879 STATUS_NEW = u'new'
3861 STATUS_OPEN = u'open'
3880 STATUS_OPEN = u'open'
3862 STATUS_CLOSED = u'closed'
3881 STATUS_CLOSED = u'closed'
3863
3882
3864 # available states
3883 # available states
3865 STATE_CREATING = u'creating'
3884 STATE_CREATING = u'creating'
3866 STATE_UPDATING = u'updating'
3885 STATE_UPDATING = u'updating'
3867 STATE_MERGING = u'merging'
3886 STATE_MERGING = u'merging'
3868 STATE_CREATED = u'created'
3887 STATE_CREATED = u'created'
3869
3888
3870 title = Column('title', Unicode(255), nullable=True)
3889 title = Column('title', Unicode(255), nullable=True)
3871 description = Column(
3890 description = Column(
3872 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3891 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3873 nullable=True)
3892 nullable=True)
3874 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3893 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3875
3894
3876 # new/open/closed status of pull request (not approve/reject/etc)
3895 # new/open/closed status of pull request (not approve/reject/etc)
3877 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3896 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3878 created_on = Column(
3897 created_on = Column(
3879 'created_on', DateTime(timezone=False), nullable=False,
3898 'created_on', DateTime(timezone=False), nullable=False,
3880 default=datetime.datetime.now)
3899 default=datetime.datetime.now)
3881 updated_on = Column(
3900 updated_on = Column(
3882 'updated_on', DateTime(timezone=False), nullable=False,
3901 'updated_on', DateTime(timezone=False), nullable=False,
3883 default=datetime.datetime.now)
3902 default=datetime.datetime.now)
3884
3903
3885 pull_request_state = Column("pull_request_state", String(255), nullable=True)
3904 pull_request_state = Column("pull_request_state", String(255), nullable=True)
3886
3905
3887 @declared_attr
3906 @declared_attr
3888 def user_id(cls):
3907 def user_id(cls):
3889 return Column(
3908 return Column(
3890 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3909 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3891 unique=None)
3910 unique=None)
3892
3911
3893 # 500 revisions max
3912 # 500 revisions max
3894 _revisions = Column(
3913 _revisions = Column(
3895 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3914 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3896
3915
3897 @declared_attr
3916 @declared_attr
3898 def source_repo_id(cls):
3917 def source_repo_id(cls):
3899 # TODO: dan: rename column to source_repo_id
3918 # TODO: dan: rename column to source_repo_id
3900 return Column(
3919 return Column(
3901 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3920 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3902 nullable=False)
3921 nullable=False)
3903
3922
3904 _source_ref = Column('org_ref', Unicode(255), nullable=False)
3923 _source_ref = Column('org_ref', Unicode(255), nullable=False)
3905
3924
3906 @hybrid_property
3925 @hybrid_property
3907 def source_ref(self):
3926 def source_ref(self):
3908 return self._source_ref
3927 return self._source_ref
3909
3928
3910 @source_ref.setter
3929 @source_ref.setter
3911 def source_ref(self, val):
3930 def source_ref(self, val):
3912 parts = (val or '').split(':')
3931 parts = (val or '').split(':')
3913 if len(parts) != 3:
3932 if len(parts) != 3:
3914 raise ValueError(
3933 raise ValueError(
3915 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3934 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3916 self._source_ref = safe_unicode(val)
3935 self._source_ref = safe_unicode(val)
3917
3936
3918 _target_ref = Column('other_ref', Unicode(255), nullable=False)
3937 _target_ref = Column('other_ref', Unicode(255), nullable=False)
3919
3938
3920 @hybrid_property
3939 @hybrid_property
3921 def target_ref(self):
3940 def target_ref(self):
3922 return self._target_ref
3941 return self._target_ref
3923
3942
3924 @target_ref.setter
3943 @target_ref.setter
3925 def target_ref(self, val):
3944 def target_ref(self, val):
3926 parts = (val or '').split(':')
3945 parts = (val or '').split(':')
3927 if len(parts) != 3:
3946 if len(parts) != 3:
3928 raise ValueError(
3947 raise ValueError(
3929 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3948 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3930 self._target_ref = safe_unicode(val)
3949 self._target_ref = safe_unicode(val)
3931
3950
3932 @declared_attr
3951 @declared_attr
3933 def target_repo_id(cls):
3952 def target_repo_id(cls):
3934 # TODO: dan: rename column to target_repo_id
3953 # TODO: dan: rename column to target_repo_id
3935 return Column(
3954 return Column(
3936 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3955 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3937 nullable=False)
3956 nullable=False)
3938
3957
3939 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3958 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3940
3959
3941 # TODO: dan: rename column to last_merge_source_rev
3960 # TODO: dan: rename column to last_merge_source_rev
3942 _last_merge_source_rev = Column(
3961 _last_merge_source_rev = Column(
3943 'last_merge_org_rev', String(40), nullable=True)
3962 'last_merge_org_rev', String(40), nullable=True)
3944 # TODO: dan: rename column to last_merge_target_rev
3963 # TODO: dan: rename column to last_merge_target_rev
3945 _last_merge_target_rev = Column(
3964 _last_merge_target_rev = Column(
3946 'last_merge_other_rev', String(40), nullable=True)
3965 'last_merge_other_rev', String(40), nullable=True)
3947 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3966 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3948 merge_rev = Column('merge_rev', String(40), nullable=True)
3967 merge_rev = Column('merge_rev', String(40), nullable=True)
3949
3968
3950 reviewer_data = Column(
3969 reviewer_data = Column(
3951 'reviewer_data_json', MutationObj.as_mutable(
3970 'reviewer_data_json', MutationObj.as_mutable(
3952 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3971 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3953
3972
3954 @property
3973 @property
3955 def reviewer_data_json(self):
3974 def reviewer_data_json(self):
3956 return json.dumps(self.reviewer_data)
3975 return json.dumps(self.reviewer_data)
3957
3976
3958 @hybrid_property
3977 @hybrid_property
3959 def description_safe(self):
3978 def description_safe(self):
3960 from rhodecode.lib import helpers as h
3979 from rhodecode.lib import helpers as h
3961 return h.escape(self.description)
3980 return h.escape(self.description)
3962
3981
3963 @hybrid_property
3982 @hybrid_property
3964 def revisions(self):
3983 def revisions(self):
3965 return self._revisions.split(':') if self._revisions else []
3984 return self._revisions.split(':') if self._revisions else []
3966
3985
3967 @revisions.setter
3986 @revisions.setter
3968 def revisions(self, val):
3987 def revisions(self, val):
3969 self._revisions = u':'.join(val)
3988 self._revisions = u':'.join(val)
3970
3989
3971 @hybrid_property
3990 @hybrid_property
3972 def last_merge_status(self):
3991 def last_merge_status(self):
3973 return safe_int(self._last_merge_status)
3992 return safe_int(self._last_merge_status)
3974
3993
3975 @last_merge_status.setter
3994 @last_merge_status.setter
3976 def last_merge_status(self, val):
3995 def last_merge_status(self, val):
3977 self._last_merge_status = val
3996 self._last_merge_status = val
3978
3997
3979 @declared_attr
3998 @declared_attr
3980 def author(cls):
3999 def author(cls):
3981 return relationship('User', lazy='joined')
4000 return relationship('User', lazy='joined')
3982
4001
3983 @declared_attr
4002 @declared_attr
3984 def source_repo(cls):
4003 def source_repo(cls):
3985 return relationship(
4004 return relationship(
3986 'Repository',
4005 'Repository',
3987 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
4006 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3988
4007
3989 @property
4008 @property
3990 def source_ref_parts(self):
4009 def source_ref_parts(self):
3991 return self.unicode_to_reference(self.source_ref)
4010 return self.unicode_to_reference(self.source_ref)
3992
4011
3993 @declared_attr
4012 @declared_attr
3994 def target_repo(cls):
4013 def target_repo(cls):
3995 return relationship(
4014 return relationship(
3996 'Repository',
4015 'Repository',
3997 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
4016 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3998
4017
3999 @property
4018 @property
4000 def target_ref_parts(self):
4019 def target_ref_parts(self):
4001 return self.unicode_to_reference(self.target_ref)
4020 return self.unicode_to_reference(self.target_ref)
4002
4021
4003 @property
4022 @property
4004 def shadow_merge_ref(self):
4023 def shadow_merge_ref(self):
4005 return self.unicode_to_reference(self._shadow_merge_ref)
4024 return self.unicode_to_reference(self._shadow_merge_ref)
4006
4025
4007 @shadow_merge_ref.setter
4026 @shadow_merge_ref.setter
4008 def shadow_merge_ref(self, ref):
4027 def shadow_merge_ref(self, ref):
4009 self._shadow_merge_ref = self.reference_to_unicode(ref)
4028 self._shadow_merge_ref = self.reference_to_unicode(ref)
4010
4029
4011 @staticmethod
4030 @staticmethod
4012 def unicode_to_reference(raw):
4031 def unicode_to_reference(raw):
4013 """
4032 """
4014 Convert a unicode (or string) to a reference object.
4033 Convert a unicode (or string) to a reference object.
4015 If unicode evaluates to False it returns None.
4034 If unicode evaluates to False it returns None.
4016 """
4035 """
4017 if raw:
4036 if raw:
4018 refs = raw.split(':')
4037 refs = raw.split(':')
4019 return Reference(*refs)
4038 return Reference(*refs)
4020 else:
4039 else:
4021 return None
4040 return None
4022
4041
4023 @staticmethod
4042 @staticmethod
4024 def reference_to_unicode(ref):
4043 def reference_to_unicode(ref):
4025 """
4044 """
4026 Convert a reference object to unicode.
4045 Convert a reference object to unicode.
4027 If reference is None it returns None.
4046 If reference is None it returns None.
4028 """
4047 """
4029 if ref:
4048 if ref:
4030 return u':'.join(ref)
4049 return u':'.join(ref)
4031 else:
4050 else:
4032 return None
4051 return None
4033
4052
4034 def get_api_data(self, with_merge_state=True):
4053 def get_api_data(self, with_merge_state=True):
4035 from rhodecode.model.pull_request import PullRequestModel
4054 from rhodecode.model.pull_request import PullRequestModel
4036
4055
4037 pull_request = self
4056 pull_request = self
4038 if with_merge_state:
4057 if with_merge_state:
4039 merge_status = PullRequestModel().merge_status(pull_request)
4058 merge_status = PullRequestModel().merge_status(pull_request)
4040 merge_state = {
4059 merge_state = {
4041 'status': merge_status[0],
4060 'status': merge_status[0],
4042 'message': safe_unicode(merge_status[1]),
4061 'message': safe_unicode(merge_status[1]),
4043 }
4062 }
4044 else:
4063 else:
4045 merge_state = {'status': 'not_available',
4064 merge_state = {'status': 'not_available',
4046 'message': 'not_available'}
4065 'message': 'not_available'}
4047
4066
4048 merge_data = {
4067 merge_data = {
4049 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
4068 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
4050 'reference': (
4069 'reference': (
4051 pull_request.shadow_merge_ref._asdict()
4070 pull_request.shadow_merge_ref._asdict()
4052 if pull_request.shadow_merge_ref else None),
4071 if pull_request.shadow_merge_ref else None),
4053 }
4072 }
4054
4073
4055 data = {
4074 data = {
4056 'pull_request_id': pull_request.pull_request_id,
4075 'pull_request_id': pull_request.pull_request_id,
4057 'url': PullRequestModel().get_url(pull_request),
4076 'url': PullRequestModel().get_url(pull_request),
4058 'title': pull_request.title,
4077 'title': pull_request.title,
4059 'description': pull_request.description,
4078 'description': pull_request.description,
4060 'status': pull_request.status,
4079 'status': pull_request.status,
4061 'state': pull_request.pull_request_state,
4080 'state': pull_request.pull_request_state,
4062 'created_on': pull_request.created_on,
4081 'created_on': pull_request.created_on,
4063 'updated_on': pull_request.updated_on,
4082 'updated_on': pull_request.updated_on,
4064 'commit_ids': pull_request.revisions,
4083 'commit_ids': pull_request.revisions,
4065 'review_status': pull_request.calculated_review_status(),
4084 'review_status': pull_request.calculated_review_status(),
4066 'mergeable': merge_state,
4085 'mergeable': merge_state,
4067 'source': {
4086 'source': {
4068 'clone_url': pull_request.source_repo.clone_url(),
4087 'clone_url': pull_request.source_repo.clone_url(),
4069 'repository': pull_request.source_repo.repo_name,
4088 'repository': pull_request.source_repo.repo_name,
4070 'reference': {
4089 'reference': {
4071 'name': pull_request.source_ref_parts.name,
4090 'name': pull_request.source_ref_parts.name,
4072 'type': pull_request.source_ref_parts.type,
4091 'type': pull_request.source_ref_parts.type,
4073 'commit_id': pull_request.source_ref_parts.commit_id,
4092 'commit_id': pull_request.source_ref_parts.commit_id,
4074 },
4093 },
4075 },
4094 },
4076 'target': {
4095 'target': {
4077 'clone_url': pull_request.target_repo.clone_url(),
4096 'clone_url': pull_request.target_repo.clone_url(),
4078 'repository': pull_request.target_repo.repo_name,
4097 'repository': pull_request.target_repo.repo_name,
4079 'reference': {
4098 'reference': {
4080 'name': pull_request.target_ref_parts.name,
4099 'name': pull_request.target_ref_parts.name,
4081 'type': pull_request.target_ref_parts.type,
4100 'type': pull_request.target_ref_parts.type,
4082 'commit_id': pull_request.target_ref_parts.commit_id,
4101 'commit_id': pull_request.target_ref_parts.commit_id,
4083 },
4102 },
4084 },
4103 },
4085 'merge': merge_data,
4104 'merge': merge_data,
4086 'author': pull_request.author.get_api_data(include_secrets=False,
4105 'author': pull_request.author.get_api_data(include_secrets=False,
4087 details='basic'),
4106 details='basic'),
4088 'reviewers': [
4107 'reviewers': [
4089 {
4108 {
4090 'user': reviewer.get_api_data(include_secrets=False,
4109 'user': reviewer.get_api_data(include_secrets=False,
4091 details='basic'),
4110 details='basic'),
4092 'reasons': reasons,
4111 'reasons': reasons,
4093 'review_status': st[0][1].status if st else 'not_reviewed',
4112 'review_status': st[0][1].status if st else 'not_reviewed',
4094 }
4113 }
4095 for obj, reviewer, reasons, mandatory, st in
4114 for obj, reviewer, reasons, mandatory, st in
4096 pull_request.reviewers_statuses()
4115 pull_request.reviewers_statuses()
4097 ]
4116 ]
4098 }
4117 }
4099
4118
4100 return data
4119 return data
4101
4120
4102 def set_state(self, pull_request_state, final_state=None):
4121 def set_state(self, pull_request_state, final_state=None):
4103 """
4122 """
4104 # goes from initial state to updating to initial state.
4123 # goes from initial state to updating to initial state.
4105 # initial state can be changed by specifying back_state=
4124 # initial state can be changed by specifying back_state=
4106 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
4125 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
4107 pull_request.merge()
4126 pull_request.merge()
4108
4127
4109 :param pull_request_state:
4128 :param pull_request_state:
4110 :param final_state:
4129 :param final_state:
4111
4130
4112 """
4131 """
4113
4132
4114 return _SetState(self, pull_request_state, back_state=final_state)
4133 return _SetState(self, pull_request_state, back_state=final_state)
4115
4134
4116
4135
4117 class PullRequest(Base, _PullRequestBase):
4136 class PullRequest(Base, _PullRequestBase):
4118 __tablename__ = 'pull_requests'
4137 __tablename__ = 'pull_requests'
4119 __table_args__ = (
4138 __table_args__ = (
4120 base_table_args,
4139 base_table_args,
4121 )
4140 )
4122
4141
4123 pull_request_id = Column(
4142 pull_request_id = Column(
4124 'pull_request_id', Integer(), nullable=False, primary_key=True)
4143 'pull_request_id', Integer(), nullable=False, primary_key=True)
4125
4144
4126 def __repr__(self):
4145 def __repr__(self):
4127 if self.pull_request_id:
4146 if self.pull_request_id:
4128 return '<DB:PullRequest #%s>' % self.pull_request_id
4147 return '<DB:PullRequest #%s>' % self.pull_request_id
4129 else:
4148 else:
4130 return '<DB:PullRequest at %#x>' % id(self)
4149 return '<DB:PullRequest at %#x>' % id(self)
4131
4150
4132 reviewers = relationship('PullRequestReviewers',
4151 reviewers = relationship('PullRequestReviewers',
4133 cascade="all, delete-orphan")
4152 cascade="all, delete-orphan")
4134 statuses = relationship('ChangesetStatus',
4153 statuses = relationship('ChangesetStatus',
4135 cascade="all, delete-orphan")
4154 cascade="all, delete-orphan")
4136 comments = relationship('ChangesetComment',
4155 comments = relationship('ChangesetComment',
4137 cascade="all, delete-orphan")
4156 cascade="all, delete-orphan")
4138 versions = relationship('PullRequestVersion',
4157 versions = relationship('PullRequestVersion',
4139 cascade="all, delete-orphan",
4158 cascade="all, delete-orphan",
4140 lazy='dynamic')
4159 lazy='dynamic')
4141
4160
4142 @classmethod
4161 @classmethod
4143 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
4162 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
4144 internal_methods=None):
4163 internal_methods=None):
4145
4164
4146 class PullRequestDisplay(object):
4165 class PullRequestDisplay(object):
4147 """
4166 """
4148 Special object wrapper for showing PullRequest data via Versions
4167 Special object wrapper for showing PullRequest data via Versions
4149 It mimics PR object as close as possible. This is read only object
4168 It mimics PR object as close as possible. This is read only object
4150 just for display
4169 just for display
4151 """
4170 """
4152
4171
4153 def __init__(self, attrs, internal=None):
4172 def __init__(self, attrs, internal=None):
4154 self.attrs = attrs
4173 self.attrs = attrs
4155 # internal have priority over the given ones via attrs
4174 # internal have priority over the given ones via attrs
4156 self.internal = internal or ['versions']
4175 self.internal = internal or ['versions']
4157
4176
4158 def __getattr__(self, item):
4177 def __getattr__(self, item):
4159 if item in self.internal:
4178 if item in self.internal:
4160 return getattr(self, item)
4179 return getattr(self, item)
4161 try:
4180 try:
4162 return self.attrs[item]
4181 return self.attrs[item]
4163 except KeyError:
4182 except KeyError:
4164 raise AttributeError(
4183 raise AttributeError(
4165 '%s object has no attribute %s' % (self, item))
4184 '%s object has no attribute %s' % (self, item))
4166
4185
4167 def __repr__(self):
4186 def __repr__(self):
4168 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
4187 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
4169
4188
4170 def versions(self):
4189 def versions(self):
4171 return pull_request_obj.versions.order_by(
4190 return pull_request_obj.versions.order_by(
4172 PullRequestVersion.pull_request_version_id).all()
4191 PullRequestVersion.pull_request_version_id).all()
4173
4192
4174 def is_closed(self):
4193 def is_closed(self):
4175 return pull_request_obj.is_closed()
4194 return pull_request_obj.is_closed()
4176
4195
4177 @property
4196 @property
4178 def pull_request_version_id(self):
4197 def pull_request_version_id(self):
4179 return getattr(pull_request_obj, 'pull_request_version_id', None)
4198 return getattr(pull_request_obj, 'pull_request_version_id', None)
4180
4199
4181 attrs = StrictAttributeDict(pull_request_obj.get_api_data(with_merge_state=False))
4200 attrs = StrictAttributeDict(pull_request_obj.get_api_data(with_merge_state=False))
4182
4201
4183 attrs.author = StrictAttributeDict(
4202 attrs.author = StrictAttributeDict(
4184 pull_request_obj.author.get_api_data())
4203 pull_request_obj.author.get_api_data())
4185 if pull_request_obj.target_repo:
4204 if pull_request_obj.target_repo:
4186 attrs.target_repo = StrictAttributeDict(
4205 attrs.target_repo = StrictAttributeDict(
4187 pull_request_obj.target_repo.get_api_data())
4206 pull_request_obj.target_repo.get_api_data())
4188 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
4207 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
4189
4208
4190 if pull_request_obj.source_repo:
4209 if pull_request_obj.source_repo:
4191 attrs.source_repo = StrictAttributeDict(
4210 attrs.source_repo = StrictAttributeDict(
4192 pull_request_obj.source_repo.get_api_data())
4211 pull_request_obj.source_repo.get_api_data())
4193 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
4212 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
4194
4213
4195 attrs.source_ref_parts = pull_request_obj.source_ref_parts
4214 attrs.source_ref_parts = pull_request_obj.source_ref_parts
4196 attrs.target_ref_parts = pull_request_obj.target_ref_parts
4215 attrs.target_ref_parts = pull_request_obj.target_ref_parts
4197 attrs.revisions = pull_request_obj.revisions
4216 attrs.revisions = pull_request_obj.revisions
4198
4217
4199 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
4218 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
4200 attrs.reviewer_data = org_pull_request_obj.reviewer_data
4219 attrs.reviewer_data = org_pull_request_obj.reviewer_data
4201 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
4220 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
4202
4221
4203 return PullRequestDisplay(attrs, internal=internal_methods)
4222 return PullRequestDisplay(attrs, internal=internal_methods)
4204
4223
4205 def is_closed(self):
4224 def is_closed(self):
4206 return self.status == self.STATUS_CLOSED
4225 return self.status == self.STATUS_CLOSED
4207
4226
4208 def __json__(self):
4227 def __json__(self):
4209 return {
4228 return {
4210 'revisions': self.revisions,
4229 'revisions': self.revisions,
4211 }
4230 }
4212
4231
4213 def calculated_review_status(self):
4232 def calculated_review_status(self):
4214 from rhodecode.model.changeset_status import ChangesetStatusModel
4233 from rhodecode.model.changeset_status import ChangesetStatusModel
4215 return ChangesetStatusModel().calculated_review_status(self)
4234 return ChangesetStatusModel().calculated_review_status(self)
4216
4235
4217 def reviewers_statuses(self):
4236 def reviewers_statuses(self):
4218 from rhodecode.model.changeset_status import ChangesetStatusModel
4237 from rhodecode.model.changeset_status import ChangesetStatusModel
4219 return ChangesetStatusModel().reviewers_statuses(self)
4238 return ChangesetStatusModel().reviewers_statuses(self)
4220
4239
4221 @property
4240 @property
4222 def workspace_id(self):
4241 def workspace_id(self):
4223 from rhodecode.model.pull_request import PullRequestModel
4242 from rhodecode.model.pull_request import PullRequestModel
4224 return PullRequestModel()._workspace_id(self)
4243 return PullRequestModel()._workspace_id(self)
4225
4244
4226 def get_shadow_repo(self):
4245 def get_shadow_repo(self):
4227 workspace_id = self.workspace_id
4246 workspace_id = self.workspace_id
4228 shadow_repository_path = self.target_repo.get_shadow_repository_path(workspace_id)
4247 shadow_repository_path = self.target_repo.get_shadow_repository_path(workspace_id)
4229 if os.path.isdir(shadow_repository_path):
4248 if os.path.isdir(shadow_repository_path):
4230 vcs_obj = self.target_repo.scm_instance()
4249 vcs_obj = self.target_repo.scm_instance()
4231 return vcs_obj.get_shadow_instance(shadow_repository_path)
4250 return vcs_obj.get_shadow_instance(shadow_repository_path)
4232
4251
4233
4252
4234 class PullRequestVersion(Base, _PullRequestBase):
4253 class PullRequestVersion(Base, _PullRequestBase):
4235 __tablename__ = 'pull_request_versions'
4254 __tablename__ = 'pull_request_versions'
4236 __table_args__ = (
4255 __table_args__ = (
4237 base_table_args,
4256 base_table_args,
4238 )
4257 )
4239
4258
4240 pull_request_version_id = Column(
4259 pull_request_version_id = Column(
4241 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
4260 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
4242 pull_request_id = Column(
4261 pull_request_id = Column(
4243 'pull_request_id', Integer(),
4262 'pull_request_id', Integer(),
4244 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4263 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4245 pull_request = relationship('PullRequest')
4264 pull_request = relationship('PullRequest')
4246
4265
4247 def __repr__(self):
4266 def __repr__(self):
4248 if self.pull_request_version_id:
4267 if self.pull_request_version_id:
4249 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
4268 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
4250 else:
4269 else:
4251 return '<DB:PullRequestVersion at %#x>' % id(self)
4270 return '<DB:PullRequestVersion at %#x>' % id(self)
4252
4271
4253 @property
4272 @property
4254 def reviewers(self):
4273 def reviewers(self):
4255 return self.pull_request.reviewers
4274 return self.pull_request.reviewers
4256
4275
4257 @property
4276 @property
4258 def versions(self):
4277 def versions(self):
4259 return self.pull_request.versions
4278 return self.pull_request.versions
4260
4279
4261 def is_closed(self):
4280 def is_closed(self):
4262 # calculate from original
4281 # calculate from original
4263 return self.pull_request.status == self.STATUS_CLOSED
4282 return self.pull_request.status == self.STATUS_CLOSED
4264
4283
4265 def calculated_review_status(self):
4284 def calculated_review_status(self):
4266 return self.pull_request.calculated_review_status()
4285 return self.pull_request.calculated_review_status()
4267
4286
4268 def reviewers_statuses(self):
4287 def reviewers_statuses(self):
4269 return self.pull_request.reviewers_statuses()
4288 return self.pull_request.reviewers_statuses()
4270
4289
4271
4290
4272 class PullRequestReviewers(Base, BaseModel):
4291 class PullRequestReviewers(Base, BaseModel):
4273 __tablename__ = 'pull_request_reviewers'
4292 __tablename__ = 'pull_request_reviewers'
4274 __table_args__ = (
4293 __table_args__ = (
4275 base_table_args,
4294 base_table_args,
4276 )
4295 )
4277
4296
4278 @hybrid_property
4297 @hybrid_property
4279 def reasons(self):
4298 def reasons(self):
4280 if not self._reasons:
4299 if not self._reasons:
4281 return []
4300 return []
4282 return self._reasons
4301 return self._reasons
4283
4302
4284 @reasons.setter
4303 @reasons.setter
4285 def reasons(self, val):
4304 def reasons(self, val):
4286 val = val or []
4305 val = val or []
4287 if any(not isinstance(x, compat.string_types) for x in val):
4306 if any(not isinstance(x, compat.string_types) for x in val):
4288 raise Exception('invalid reasons type, must be list of strings')
4307 raise Exception('invalid reasons type, must be list of strings')
4289 self._reasons = val
4308 self._reasons = val
4290
4309
4291 pull_requests_reviewers_id = Column(
4310 pull_requests_reviewers_id = Column(
4292 'pull_requests_reviewers_id', Integer(), nullable=False,
4311 'pull_requests_reviewers_id', Integer(), nullable=False,
4293 primary_key=True)
4312 primary_key=True)
4294 pull_request_id = Column(
4313 pull_request_id = Column(
4295 "pull_request_id", Integer(),
4314 "pull_request_id", Integer(),
4296 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4315 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4297 user_id = Column(
4316 user_id = Column(
4298 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4317 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4299 _reasons = Column(
4318 _reasons = Column(
4300 'reason', MutationList.as_mutable(
4319 'reason', MutationList.as_mutable(
4301 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4320 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4302
4321
4303 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4322 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4304 user = relationship('User')
4323 user = relationship('User')
4305 pull_request = relationship('PullRequest')
4324 pull_request = relationship('PullRequest')
4306
4325
4307 rule_data = Column(
4326 rule_data = Column(
4308 'rule_data_json',
4327 'rule_data_json',
4309 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4328 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4310
4329
4311 def rule_user_group_data(self):
4330 def rule_user_group_data(self):
4312 """
4331 """
4313 Returns the voting user group rule data for this reviewer
4332 Returns the voting user group rule data for this reviewer
4314 """
4333 """
4315
4334
4316 if self.rule_data and 'vote_rule' in self.rule_data:
4335 if self.rule_data and 'vote_rule' in self.rule_data:
4317 user_group_data = {}
4336 user_group_data = {}
4318 if 'rule_user_group_entry_id' in self.rule_data:
4337 if 'rule_user_group_entry_id' in self.rule_data:
4319 # means a group with voting rules !
4338 # means a group with voting rules !
4320 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4339 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4321 user_group_data['name'] = self.rule_data['rule_name']
4340 user_group_data['name'] = self.rule_data['rule_name']
4322 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4341 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4323
4342
4324 return user_group_data
4343 return user_group_data
4325
4344
4326 def __unicode__(self):
4345 def __unicode__(self):
4327 return u"<%s('id:%s')>" % (self.__class__.__name__,
4346 return u"<%s('id:%s')>" % (self.__class__.__name__,
4328 self.pull_requests_reviewers_id)
4347 self.pull_requests_reviewers_id)
4329
4348
4330
4349
4331 class Notification(Base, BaseModel):
4350 class Notification(Base, BaseModel):
4332 __tablename__ = 'notifications'
4351 __tablename__ = 'notifications'
4333 __table_args__ = (
4352 __table_args__ = (
4334 Index('notification_type_idx', 'type'),
4353 Index('notification_type_idx', 'type'),
4335 base_table_args,
4354 base_table_args,
4336 )
4355 )
4337
4356
4338 TYPE_CHANGESET_COMMENT = u'cs_comment'
4357 TYPE_CHANGESET_COMMENT = u'cs_comment'
4339 TYPE_MESSAGE = u'message'
4358 TYPE_MESSAGE = u'message'
4340 TYPE_MENTION = u'mention'
4359 TYPE_MENTION = u'mention'
4341 TYPE_REGISTRATION = u'registration'
4360 TYPE_REGISTRATION = u'registration'
4342 TYPE_PULL_REQUEST = u'pull_request'
4361 TYPE_PULL_REQUEST = u'pull_request'
4343 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
4362 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
4344
4363
4345 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4364 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4346 subject = Column('subject', Unicode(512), nullable=True)
4365 subject = Column('subject', Unicode(512), nullable=True)
4347 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4366 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4348 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4367 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4349 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4368 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4350 type_ = Column('type', Unicode(255))
4369 type_ = Column('type', Unicode(255))
4351
4370
4352 created_by_user = relationship('User')
4371 created_by_user = relationship('User')
4353 notifications_to_users = relationship('UserNotification', lazy='joined',
4372 notifications_to_users = relationship('UserNotification', lazy='joined',
4354 cascade="all, delete-orphan")
4373 cascade="all, delete-orphan")
4355
4374
4356 @property
4375 @property
4357 def recipients(self):
4376 def recipients(self):
4358 return [x.user for x in UserNotification.query()\
4377 return [x.user for x in UserNotification.query()\
4359 .filter(UserNotification.notification == self)\
4378 .filter(UserNotification.notification == self)\
4360 .order_by(UserNotification.user_id.asc()).all()]
4379 .order_by(UserNotification.user_id.asc()).all()]
4361
4380
4362 @classmethod
4381 @classmethod
4363 def create(cls, created_by, subject, body, recipients, type_=None):
4382 def create(cls, created_by, subject, body, recipients, type_=None):
4364 if type_ is None:
4383 if type_ is None:
4365 type_ = Notification.TYPE_MESSAGE
4384 type_ = Notification.TYPE_MESSAGE
4366
4385
4367 notification = cls()
4386 notification = cls()
4368 notification.created_by_user = created_by
4387 notification.created_by_user = created_by
4369 notification.subject = subject
4388 notification.subject = subject
4370 notification.body = body
4389 notification.body = body
4371 notification.type_ = type_
4390 notification.type_ = type_
4372 notification.created_on = datetime.datetime.now()
4391 notification.created_on = datetime.datetime.now()
4373
4392
4374 # For each recipient link the created notification to his account
4393 # For each recipient link the created notification to his account
4375 for u in recipients:
4394 for u in recipients:
4376 assoc = UserNotification()
4395 assoc = UserNotification()
4377 assoc.user_id = u.user_id
4396 assoc.user_id = u.user_id
4378 assoc.notification = notification
4397 assoc.notification = notification
4379
4398
4380 # if created_by is inside recipients mark his notification
4399 # if created_by is inside recipients mark his notification
4381 # as read
4400 # as read
4382 if u.user_id == created_by.user_id:
4401 if u.user_id == created_by.user_id:
4383 assoc.read = True
4402 assoc.read = True
4384 Session().add(assoc)
4403 Session().add(assoc)
4385
4404
4386 Session().add(notification)
4405 Session().add(notification)
4387
4406
4388 return notification
4407 return notification
4389
4408
4390
4409
4391 class UserNotification(Base, BaseModel):
4410 class UserNotification(Base, BaseModel):
4392 __tablename__ = 'user_to_notification'
4411 __tablename__ = 'user_to_notification'
4393 __table_args__ = (
4412 __table_args__ = (
4394 UniqueConstraint('user_id', 'notification_id'),
4413 UniqueConstraint('user_id', 'notification_id'),
4395 base_table_args
4414 base_table_args
4396 )
4415 )
4397
4416
4398 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4417 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4399 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4418 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4400 read = Column('read', Boolean, default=False)
4419 read = Column('read', Boolean, default=False)
4401 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4420 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4402
4421
4403 user = relationship('User', lazy="joined")
4422 user = relationship('User', lazy="joined")
4404 notification = relationship('Notification', lazy="joined",
4423 notification = relationship('Notification', lazy="joined",
4405 order_by=lambda: Notification.created_on.desc(),)
4424 order_by=lambda: Notification.created_on.desc(),)
4406
4425
4407 def mark_as_read(self):
4426 def mark_as_read(self):
4408 self.read = True
4427 self.read = True
4409 Session().add(self)
4428 Session().add(self)
4410
4429
4411
4430
4412 class Gist(Base, BaseModel):
4431 class Gist(Base, BaseModel):
4413 __tablename__ = 'gists'
4432 __tablename__ = 'gists'
4414 __table_args__ = (
4433 __table_args__ = (
4415 Index('g_gist_access_id_idx', 'gist_access_id'),
4434 Index('g_gist_access_id_idx', 'gist_access_id'),
4416 Index('g_created_on_idx', 'created_on'),
4435 Index('g_created_on_idx', 'created_on'),
4417 base_table_args
4436 base_table_args
4418 )
4437 )
4419
4438
4420 GIST_PUBLIC = u'public'
4439 GIST_PUBLIC = u'public'
4421 GIST_PRIVATE = u'private'
4440 GIST_PRIVATE = u'private'
4422 DEFAULT_FILENAME = u'gistfile1.txt'
4441 DEFAULT_FILENAME = u'gistfile1.txt'
4423
4442
4424 ACL_LEVEL_PUBLIC = u'acl_public'
4443 ACL_LEVEL_PUBLIC = u'acl_public'
4425 ACL_LEVEL_PRIVATE = u'acl_private'
4444 ACL_LEVEL_PRIVATE = u'acl_private'
4426
4445
4427 gist_id = Column('gist_id', Integer(), primary_key=True)
4446 gist_id = Column('gist_id', Integer(), primary_key=True)
4428 gist_access_id = Column('gist_access_id', Unicode(250))
4447 gist_access_id = Column('gist_access_id', Unicode(250))
4429 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4448 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4430 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4449 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4431 gist_expires = Column('gist_expires', Float(53), nullable=False)
4450 gist_expires = Column('gist_expires', Float(53), nullable=False)
4432 gist_type = Column('gist_type', Unicode(128), nullable=False)
4451 gist_type = Column('gist_type', Unicode(128), nullable=False)
4433 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4452 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4434 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4453 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4435 acl_level = Column('acl_level', Unicode(128), nullable=True)
4454 acl_level = Column('acl_level', Unicode(128), nullable=True)
4436
4455
4437 owner = relationship('User')
4456 owner = relationship('User')
4438
4457
4439 def __repr__(self):
4458 def __repr__(self):
4440 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4459 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4441
4460
4442 @hybrid_property
4461 @hybrid_property
4443 def description_safe(self):
4462 def description_safe(self):
4444 from rhodecode.lib import helpers as h
4463 from rhodecode.lib import helpers as h
4445 return h.escape(self.gist_description)
4464 return h.escape(self.gist_description)
4446
4465
4447 @classmethod
4466 @classmethod
4448 def get_or_404(cls, id_):
4467 def get_or_404(cls, id_):
4449 from pyramid.httpexceptions import HTTPNotFound
4468 from pyramid.httpexceptions import HTTPNotFound
4450
4469
4451 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4470 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4452 if not res:
4471 if not res:
4453 raise HTTPNotFound()
4472 raise HTTPNotFound()
4454 return res
4473 return res
4455
4474
4456 @classmethod
4475 @classmethod
4457 def get_by_access_id(cls, gist_access_id):
4476 def get_by_access_id(cls, gist_access_id):
4458 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4477 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4459
4478
4460 def gist_url(self):
4479 def gist_url(self):
4461 from rhodecode.model.gist import GistModel
4480 from rhodecode.model.gist import GistModel
4462 return GistModel().get_url(self)
4481 return GistModel().get_url(self)
4463
4482
4464 @classmethod
4483 @classmethod
4465 def base_path(cls):
4484 def base_path(cls):
4466 """
4485 """
4467 Returns base path when all gists are stored
4486 Returns base path when all gists are stored
4468
4487
4469 :param cls:
4488 :param cls:
4470 """
4489 """
4471 from rhodecode.model.gist import GIST_STORE_LOC
4490 from rhodecode.model.gist import GIST_STORE_LOC
4472 q = Session().query(RhodeCodeUi)\
4491 q = Session().query(RhodeCodeUi)\
4473 .filter(RhodeCodeUi.ui_key == URL_SEP)
4492 .filter(RhodeCodeUi.ui_key == URL_SEP)
4474 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4493 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4475 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4494 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4476
4495
4477 def get_api_data(self):
4496 def get_api_data(self):
4478 """
4497 """
4479 Common function for generating gist related data for API
4498 Common function for generating gist related data for API
4480 """
4499 """
4481 gist = self
4500 gist = self
4482 data = {
4501 data = {
4483 'gist_id': gist.gist_id,
4502 'gist_id': gist.gist_id,
4484 'type': gist.gist_type,
4503 'type': gist.gist_type,
4485 'access_id': gist.gist_access_id,
4504 'access_id': gist.gist_access_id,
4486 'description': gist.gist_description,
4505 'description': gist.gist_description,
4487 'url': gist.gist_url(),
4506 'url': gist.gist_url(),
4488 'expires': gist.gist_expires,
4507 'expires': gist.gist_expires,
4489 'created_on': gist.created_on,
4508 'created_on': gist.created_on,
4490 'modified_at': gist.modified_at,
4509 'modified_at': gist.modified_at,
4491 'content': None,
4510 'content': None,
4492 'acl_level': gist.acl_level,
4511 'acl_level': gist.acl_level,
4493 }
4512 }
4494 return data
4513 return data
4495
4514
4496 def __json__(self):
4515 def __json__(self):
4497 data = dict(
4516 data = dict(
4498 )
4517 )
4499 data.update(self.get_api_data())
4518 data.update(self.get_api_data())
4500 return data
4519 return data
4501 # SCM functions
4520 # SCM functions
4502
4521
4503 def scm_instance(self, **kwargs):
4522 def scm_instance(self, **kwargs):
4504 """
4523 """
4505 Get an instance of VCS Repository
4524 Get an instance of VCS Repository
4506
4525
4507 :param kwargs:
4526 :param kwargs:
4508 """
4527 """
4509 from rhodecode.model.gist import GistModel
4528 from rhodecode.model.gist import GistModel
4510 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4529 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4511 return get_vcs_instance(
4530 return get_vcs_instance(
4512 repo_path=safe_str(full_repo_path), create=False,
4531 repo_path=safe_str(full_repo_path), create=False,
4513 _vcs_alias=GistModel.vcs_backend)
4532 _vcs_alias=GistModel.vcs_backend)
4514
4533
4515
4534
4516 class ExternalIdentity(Base, BaseModel):
4535 class ExternalIdentity(Base, BaseModel):
4517 __tablename__ = 'external_identities'
4536 __tablename__ = 'external_identities'
4518 __table_args__ = (
4537 __table_args__ = (
4519 Index('local_user_id_idx', 'local_user_id'),
4538 Index('local_user_id_idx', 'local_user_id'),
4520 Index('external_id_idx', 'external_id'),
4539 Index('external_id_idx', 'external_id'),
4521 base_table_args
4540 base_table_args
4522 )
4541 )
4523
4542
4524 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4543 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4525 external_username = Column('external_username', Unicode(1024), default=u'')
4544 external_username = Column('external_username', Unicode(1024), default=u'')
4526 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4545 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4527 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4546 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4528 access_token = Column('access_token', String(1024), default=u'')
4547 access_token = Column('access_token', String(1024), default=u'')
4529 alt_token = Column('alt_token', String(1024), default=u'')
4548 alt_token = Column('alt_token', String(1024), default=u'')
4530 token_secret = Column('token_secret', String(1024), default=u'')
4549 token_secret = Column('token_secret', String(1024), default=u'')
4531
4550
4532 @classmethod
4551 @classmethod
4533 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4552 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4534 """
4553 """
4535 Returns ExternalIdentity instance based on search params
4554 Returns ExternalIdentity instance based on search params
4536
4555
4537 :param external_id:
4556 :param external_id:
4538 :param provider_name:
4557 :param provider_name:
4539 :return: ExternalIdentity
4558 :return: ExternalIdentity
4540 """
4559 """
4541 query = cls.query()
4560 query = cls.query()
4542 query = query.filter(cls.external_id == external_id)
4561 query = query.filter(cls.external_id == external_id)
4543 query = query.filter(cls.provider_name == provider_name)
4562 query = query.filter(cls.provider_name == provider_name)
4544 if local_user_id:
4563 if local_user_id:
4545 query = query.filter(cls.local_user_id == local_user_id)
4564 query = query.filter(cls.local_user_id == local_user_id)
4546 return query.first()
4565 return query.first()
4547
4566
4548 @classmethod
4567 @classmethod
4549 def user_by_external_id_and_provider(cls, external_id, provider_name):
4568 def user_by_external_id_and_provider(cls, external_id, provider_name):
4550 """
4569 """
4551 Returns User instance based on search params
4570 Returns User instance based on search params
4552
4571
4553 :param external_id:
4572 :param external_id:
4554 :param provider_name:
4573 :param provider_name:
4555 :return: User
4574 :return: User
4556 """
4575 """
4557 query = User.query()
4576 query = User.query()
4558 query = query.filter(cls.external_id == external_id)
4577 query = query.filter(cls.external_id == external_id)
4559 query = query.filter(cls.provider_name == provider_name)
4578 query = query.filter(cls.provider_name == provider_name)
4560 query = query.filter(User.user_id == cls.local_user_id)
4579 query = query.filter(User.user_id == cls.local_user_id)
4561 return query.first()
4580 return query.first()
4562
4581
4563 @classmethod
4582 @classmethod
4564 def by_local_user_id(cls, local_user_id):
4583 def by_local_user_id(cls, local_user_id):
4565 """
4584 """
4566 Returns all tokens for user
4585 Returns all tokens for user
4567
4586
4568 :param local_user_id:
4587 :param local_user_id:
4569 :return: ExternalIdentity
4588 :return: ExternalIdentity
4570 """
4589 """
4571 query = cls.query()
4590 query = cls.query()
4572 query = query.filter(cls.local_user_id == local_user_id)
4591 query = query.filter(cls.local_user_id == local_user_id)
4573 return query
4592 return query
4574
4593
4575 @classmethod
4594 @classmethod
4576 def load_provider_plugin(cls, plugin_id):
4595 def load_provider_plugin(cls, plugin_id):
4577 from rhodecode.authentication.base import loadplugin
4596 from rhodecode.authentication.base import loadplugin
4578 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4597 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4579 auth_plugin = loadplugin(_plugin_id)
4598 auth_plugin = loadplugin(_plugin_id)
4580 return auth_plugin
4599 return auth_plugin
4581
4600
4582
4601
4583 class Integration(Base, BaseModel):
4602 class Integration(Base, BaseModel):
4584 __tablename__ = 'integrations'
4603 __tablename__ = 'integrations'
4585 __table_args__ = (
4604 __table_args__ = (
4586 base_table_args
4605 base_table_args
4587 )
4606 )
4588
4607
4589 integration_id = Column('integration_id', Integer(), primary_key=True)
4608 integration_id = Column('integration_id', Integer(), primary_key=True)
4590 integration_type = Column('integration_type', String(255))
4609 integration_type = Column('integration_type', String(255))
4591 enabled = Column('enabled', Boolean(), nullable=False)
4610 enabled = Column('enabled', Boolean(), nullable=False)
4592 name = Column('name', String(255), nullable=False)
4611 name = Column('name', String(255), nullable=False)
4593 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4612 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4594 default=False)
4613 default=False)
4595
4614
4596 settings = Column(
4615 settings = Column(
4597 'settings_json', MutationObj.as_mutable(
4616 'settings_json', MutationObj.as_mutable(
4598 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4617 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4599 repo_id = Column(
4618 repo_id = Column(
4600 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4619 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4601 nullable=True, unique=None, default=None)
4620 nullable=True, unique=None, default=None)
4602 repo = relationship('Repository', lazy='joined')
4621 repo = relationship('Repository', lazy='joined')
4603
4622
4604 repo_group_id = Column(
4623 repo_group_id = Column(
4605 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4624 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4606 nullable=True, unique=None, default=None)
4625 nullable=True, unique=None, default=None)
4607 repo_group = relationship('RepoGroup', lazy='joined')
4626 repo_group = relationship('RepoGroup', lazy='joined')
4608
4627
4609 @property
4628 @property
4610 def scope(self):
4629 def scope(self):
4611 if self.repo:
4630 if self.repo:
4612 return repr(self.repo)
4631 return repr(self.repo)
4613 if self.repo_group:
4632 if self.repo_group:
4614 if self.child_repos_only:
4633 if self.child_repos_only:
4615 return repr(self.repo_group) + ' (child repos only)'
4634 return repr(self.repo_group) + ' (child repos only)'
4616 else:
4635 else:
4617 return repr(self.repo_group) + ' (recursive)'
4636 return repr(self.repo_group) + ' (recursive)'
4618 if self.child_repos_only:
4637 if self.child_repos_only:
4619 return 'root_repos'
4638 return 'root_repos'
4620 return 'global'
4639 return 'global'
4621
4640
4622 def __repr__(self):
4641 def __repr__(self):
4623 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4642 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4624
4643
4625
4644
4626 class RepoReviewRuleUser(Base, BaseModel):
4645 class RepoReviewRuleUser(Base, BaseModel):
4627 __tablename__ = 'repo_review_rules_users'
4646 __tablename__ = 'repo_review_rules_users'
4628 __table_args__ = (
4647 __table_args__ = (
4629 base_table_args
4648 base_table_args
4630 )
4649 )
4631
4650
4632 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4651 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4633 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4652 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4634 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4653 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4635 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4654 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4636 user = relationship('User')
4655 user = relationship('User')
4637
4656
4638 def rule_data(self):
4657 def rule_data(self):
4639 return {
4658 return {
4640 'mandatory': self.mandatory
4659 'mandatory': self.mandatory
4641 }
4660 }
4642
4661
4643
4662
4644 class RepoReviewRuleUserGroup(Base, BaseModel):
4663 class RepoReviewRuleUserGroup(Base, BaseModel):
4645 __tablename__ = 'repo_review_rules_users_groups'
4664 __tablename__ = 'repo_review_rules_users_groups'
4646 __table_args__ = (
4665 __table_args__ = (
4647 base_table_args
4666 base_table_args
4648 )
4667 )
4649
4668
4650 VOTE_RULE_ALL = -1
4669 VOTE_RULE_ALL = -1
4651
4670
4652 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4671 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4653 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4672 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4654 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4673 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4655 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4674 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4656 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4675 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4657 users_group = relationship('UserGroup')
4676 users_group = relationship('UserGroup')
4658
4677
4659 def rule_data(self):
4678 def rule_data(self):
4660 return {
4679 return {
4661 'mandatory': self.mandatory,
4680 'mandatory': self.mandatory,
4662 'vote_rule': self.vote_rule
4681 'vote_rule': self.vote_rule
4663 }
4682 }
4664
4683
4665 @property
4684 @property
4666 def vote_rule_label(self):
4685 def vote_rule_label(self):
4667 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4686 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4668 return 'all must vote'
4687 return 'all must vote'
4669 else:
4688 else:
4670 return 'min. vote {}'.format(self.vote_rule)
4689 return 'min. vote {}'.format(self.vote_rule)
4671
4690
4672
4691
4673 class RepoReviewRule(Base, BaseModel):
4692 class RepoReviewRule(Base, BaseModel):
4674 __tablename__ = 'repo_review_rules'
4693 __tablename__ = 'repo_review_rules'
4675 __table_args__ = (
4694 __table_args__ = (
4676 base_table_args
4695 base_table_args
4677 )
4696 )
4678
4697
4679 repo_review_rule_id = Column(
4698 repo_review_rule_id = Column(
4680 'repo_review_rule_id', Integer(), primary_key=True)
4699 'repo_review_rule_id', Integer(), primary_key=True)
4681 repo_id = Column(
4700 repo_id = Column(
4682 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4701 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4683 repo = relationship('Repository', backref='review_rules')
4702 repo = relationship('Repository', backref='review_rules')
4684
4703
4685 review_rule_name = Column('review_rule_name', String(255))
4704 review_rule_name = Column('review_rule_name', String(255))
4686 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4705 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4687 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4706 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4688 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4707 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4689
4708
4690 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4709 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4691 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4710 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4692 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4711 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4693 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4712 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4694
4713
4695 rule_users = relationship('RepoReviewRuleUser')
4714 rule_users = relationship('RepoReviewRuleUser')
4696 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4715 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4697
4716
4698 def _validate_pattern(self, value):
4717 def _validate_pattern(self, value):
4699 re.compile('^' + glob2re(value) + '$')
4718 re.compile('^' + glob2re(value) + '$')
4700
4719
4701 @hybrid_property
4720 @hybrid_property
4702 def source_branch_pattern(self):
4721 def source_branch_pattern(self):
4703 return self._branch_pattern or '*'
4722 return self._branch_pattern or '*'
4704
4723
4705 @source_branch_pattern.setter
4724 @source_branch_pattern.setter
4706 def source_branch_pattern(self, value):
4725 def source_branch_pattern(self, value):
4707 self._validate_pattern(value)
4726 self._validate_pattern(value)
4708 self._branch_pattern = value or '*'
4727 self._branch_pattern = value or '*'
4709
4728
4710 @hybrid_property
4729 @hybrid_property
4711 def target_branch_pattern(self):
4730 def target_branch_pattern(self):
4712 return self._target_branch_pattern or '*'
4731 return self._target_branch_pattern or '*'
4713
4732
4714 @target_branch_pattern.setter
4733 @target_branch_pattern.setter
4715 def target_branch_pattern(self, value):
4734 def target_branch_pattern(self, value):
4716 self._validate_pattern(value)
4735 self._validate_pattern(value)
4717 self._target_branch_pattern = value or '*'
4736 self._target_branch_pattern = value or '*'
4718
4737
4719 @hybrid_property
4738 @hybrid_property
4720 def file_pattern(self):
4739 def file_pattern(self):
4721 return self._file_pattern or '*'
4740 return self._file_pattern or '*'
4722
4741
4723 @file_pattern.setter
4742 @file_pattern.setter
4724 def file_pattern(self, value):
4743 def file_pattern(self, value):
4725 self._validate_pattern(value)
4744 self._validate_pattern(value)
4726 self._file_pattern = value or '*'
4745 self._file_pattern = value or '*'
4727
4746
4728 def matches(self, source_branch, target_branch, files_changed):
4747 def matches(self, source_branch, target_branch, files_changed):
4729 """
4748 """
4730 Check if this review rule matches a branch/files in a pull request
4749 Check if this review rule matches a branch/files in a pull request
4731
4750
4732 :param source_branch: source branch name for the commit
4751 :param source_branch: source branch name for the commit
4733 :param target_branch: target branch name for the commit
4752 :param target_branch: target branch name for the commit
4734 :param files_changed: list of file paths changed in the pull request
4753 :param files_changed: list of file paths changed in the pull request
4735 """
4754 """
4736
4755
4737 source_branch = source_branch or ''
4756 source_branch = source_branch or ''
4738 target_branch = target_branch or ''
4757 target_branch = target_branch or ''
4739 files_changed = files_changed or []
4758 files_changed = files_changed or []
4740
4759
4741 branch_matches = True
4760 branch_matches = True
4742 if source_branch or target_branch:
4761 if source_branch or target_branch:
4743 if self.source_branch_pattern == '*':
4762 if self.source_branch_pattern == '*':
4744 source_branch_match = True
4763 source_branch_match = True
4745 else:
4764 else:
4746 if self.source_branch_pattern.startswith('re:'):
4765 if self.source_branch_pattern.startswith('re:'):
4747 source_pattern = self.source_branch_pattern[3:]
4766 source_pattern = self.source_branch_pattern[3:]
4748 else:
4767 else:
4749 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4768 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4750 source_branch_regex = re.compile(source_pattern)
4769 source_branch_regex = re.compile(source_pattern)
4751 source_branch_match = bool(source_branch_regex.search(source_branch))
4770 source_branch_match = bool(source_branch_regex.search(source_branch))
4752 if self.target_branch_pattern == '*':
4771 if self.target_branch_pattern == '*':
4753 target_branch_match = True
4772 target_branch_match = True
4754 else:
4773 else:
4755 if self.target_branch_pattern.startswith('re:'):
4774 if self.target_branch_pattern.startswith('re:'):
4756 target_pattern = self.target_branch_pattern[3:]
4775 target_pattern = self.target_branch_pattern[3:]
4757 else:
4776 else:
4758 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4777 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4759 target_branch_regex = re.compile(target_pattern)
4778 target_branch_regex = re.compile(target_pattern)
4760 target_branch_match = bool(target_branch_regex.search(target_branch))
4779 target_branch_match = bool(target_branch_regex.search(target_branch))
4761
4780
4762 branch_matches = source_branch_match and target_branch_match
4781 branch_matches = source_branch_match and target_branch_match
4763
4782
4764 files_matches = True
4783 files_matches = True
4765 if self.file_pattern != '*':
4784 if self.file_pattern != '*':
4766 files_matches = False
4785 files_matches = False
4767 if self.file_pattern.startswith('re:'):
4786 if self.file_pattern.startswith('re:'):
4768 file_pattern = self.file_pattern[3:]
4787 file_pattern = self.file_pattern[3:]
4769 else:
4788 else:
4770 file_pattern = glob2re(self.file_pattern)
4789 file_pattern = glob2re(self.file_pattern)
4771 file_regex = re.compile(file_pattern)
4790 file_regex = re.compile(file_pattern)
4772 for filename in files_changed:
4791 for filename in files_changed:
4773 if file_regex.search(filename):
4792 if file_regex.search(filename):
4774 files_matches = True
4793 files_matches = True
4775 break
4794 break
4776
4795
4777 return branch_matches and files_matches
4796 return branch_matches and files_matches
4778
4797
4779 @property
4798 @property
4780 def review_users(self):
4799 def review_users(self):
4781 """ Returns the users which this rule applies to """
4800 """ Returns the users which this rule applies to """
4782
4801
4783 users = collections.OrderedDict()
4802 users = collections.OrderedDict()
4784
4803
4785 for rule_user in self.rule_users:
4804 for rule_user in self.rule_users:
4786 if rule_user.user.active:
4805 if rule_user.user.active:
4787 if rule_user.user not in users:
4806 if rule_user.user not in users:
4788 users[rule_user.user.username] = {
4807 users[rule_user.user.username] = {
4789 'user': rule_user.user,
4808 'user': rule_user.user,
4790 'source': 'user',
4809 'source': 'user',
4791 'source_data': {},
4810 'source_data': {},
4792 'data': rule_user.rule_data()
4811 'data': rule_user.rule_data()
4793 }
4812 }
4794
4813
4795 for rule_user_group in self.rule_user_groups:
4814 for rule_user_group in self.rule_user_groups:
4796 source_data = {
4815 source_data = {
4797 'user_group_id': rule_user_group.users_group.users_group_id,
4816 'user_group_id': rule_user_group.users_group.users_group_id,
4798 'name': rule_user_group.users_group.users_group_name,
4817 'name': rule_user_group.users_group.users_group_name,
4799 'members': len(rule_user_group.users_group.members)
4818 'members': len(rule_user_group.users_group.members)
4800 }
4819 }
4801 for member in rule_user_group.users_group.members:
4820 for member in rule_user_group.users_group.members:
4802 if member.user.active:
4821 if member.user.active:
4803 key = member.user.username
4822 key = member.user.username
4804 if key in users:
4823 if key in users:
4805 # skip this member as we have him already
4824 # skip this member as we have him already
4806 # this prevents from override the "first" matched
4825 # this prevents from override the "first" matched
4807 # users with duplicates in multiple groups
4826 # users with duplicates in multiple groups
4808 continue
4827 continue
4809
4828
4810 users[key] = {
4829 users[key] = {
4811 'user': member.user,
4830 'user': member.user,
4812 'source': 'user_group',
4831 'source': 'user_group',
4813 'source_data': source_data,
4832 'source_data': source_data,
4814 'data': rule_user_group.rule_data()
4833 'data': rule_user_group.rule_data()
4815 }
4834 }
4816
4835
4817 return users
4836 return users
4818
4837
4819 def user_group_vote_rule(self, user_id):
4838 def user_group_vote_rule(self, user_id):
4820
4839
4821 rules = []
4840 rules = []
4822 if not self.rule_user_groups:
4841 if not self.rule_user_groups:
4823 return rules
4842 return rules
4824
4843
4825 for user_group in self.rule_user_groups:
4844 for user_group in self.rule_user_groups:
4826 user_group_members = [x.user_id for x in user_group.users_group.members]
4845 user_group_members = [x.user_id for x in user_group.users_group.members]
4827 if user_id in user_group_members:
4846 if user_id in user_group_members:
4828 rules.append(user_group)
4847 rules.append(user_group)
4829 return rules
4848 return rules
4830
4849
4831 def __repr__(self):
4850 def __repr__(self):
4832 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4851 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4833 self.repo_review_rule_id, self.repo)
4852 self.repo_review_rule_id, self.repo)
4834
4853
4835
4854
4836 class ScheduleEntry(Base, BaseModel):
4855 class ScheduleEntry(Base, BaseModel):
4837 __tablename__ = 'schedule_entries'
4856 __tablename__ = 'schedule_entries'
4838 __table_args__ = (
4857 __table_args__ = (
4839 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4858 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4840 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4859 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4841 base_table_args,
4860 base_table_args,
4842 )
4861 )
4843
4862
4844 schedule_types = ['crontab', 'timedelta', 'integer']
4863 schedule_types = ['crontab', 'timedelta', 'integer']
4845 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4864 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4846
4865
4847 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4866 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4848 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4867 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4849 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4868 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4850
4869
4851 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4870 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4852 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4871 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4853
4872
4854 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4873 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4855 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4874 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4856
4875
4857 # task
4876 # task
4858 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4877 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4859 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4878 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4860 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4879 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4861 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4880 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4862
4881
4863 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4882 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4864 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4883 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4865
4884
4866 @hybrid_property
4885 @hybrid_property
4867 def schedule_type(self):
4886 def schedule_type(self):
4868 return self._schedule_type
4887 return self._schedule_type
4869
4888
4870 @schedule_type.setter
4889 @schedule_type.setter
4871 def schedule_type(self, val):
4890 def schedule_type(self, val):
4872 if val not in self.schedule_types:
4891 if val not in self.schedule_types:
4873 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4892 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4874 val, self.schedule_type))
4893 val, self.schedule_type))
4875
4894
4876 self._schedule_type = val
4895 self._schedule_type = val
4877
4896
4878 @classmethod
4897 @classmethod
4879 def get_uid(cls, obj):
4898 def get_uid(cls, obj):
4880 args = obj.task_args
4899 args = obj.task_args
4881 kwargs = obj.task_kwargs
4900 kwargs = obj.task_kwargs
4882 if isinstance(args, JsonRaw):
4901 if isinstance(args, JsonRaw):
4883 try:
4902 try:
4884 args = json.loads(args)
4903 args = json.loads(args)
4885 except ValueError:
4904 except ValueError:
4886 args = tuple()
4905 args = tuple()
4887
4906
4888 if isinstance(kwargs, JsonRaw):
4907 if isinstance(kwargs, JsonRaw):
4889 try:
4908 try:
4890 kwargs = json.loads(kwargs)
4909 kwargs = json.loads(kwargs)
4891 except ValueError:
4910 except ValueError:
4892 kwargs = dict()
4911 kwargs = dict()
4893
4912
4894 dot_notation = obj.task_dot_notation
4913 dot_notation = obj.task_dot_notation
4895 val = '.'.join(map(safe_str, [
4914 val = '.'.join(map(safe_str, [
4896 sorted(dot_notation), args, sorted(kwargs.items())]))
4915 sorted(dot_notation), args, sorted(kwargs.items())]))
4897 return hashlib.sha1(val).hexdigest()
4916 return hashlib.sha1(val).hexdigest()
4898
4917
4899 @classmethod
4918 @classmethod
4900 def get_by_schedule_name(cls, schedule_name):
4919 def get_by_schedule_name(cls, schedule_name):
4901 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4920 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4902
4921
4903 @classmethod
4922 @classmethod
4904 def get_by_schedule_id(cls, schedule_id):
4923 def get_by_schedule_id(cls, schedule_id):
4905 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4924 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4906
4925
4907 @property
4926 @property
4908 def task(self):
4927 def task(self):
4909 return self.task_dot_notation
4928 return self.task_dot_notation
4910
4929
4911 @property
4930 @property
4912 def schedule(self):
4931 def schedule(self):
4913 from rhodecode.lib.celerylib.utils import raw_2_schedule
4932 from rhodecode.lib.celerylib.utils import raw_2_schedule
4914 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4933 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4915 return schedule
4934 return schedule
4916
4935
4917 @property
4936 @property
4918 def args(self):
4937 def args(self):
4919 try:
4938 try:
4920 return list(self.task_args or [])
4939 return list(self.task_args or [])
4921 except ValueError:
4940 except ValueError:
4922 return list()
4941 return list()
4923
4942
4924 @property
4943 @property
4925 def kwargs(self):
4944 def kwargs(self):
4926 try:
4945 try:
4927 return dict(self.task_kwargs or {})
4946 return dict(self.task_kwargs or {})
4928 except ValueError:
4947 except ValueError:
4929 return dict()
4948 return dict()
4930
4949
4931 def _as_raw(self, val):
4950 def _as_raw(self, val):
4932 if hasattr(val, 'de_coerce'):
4951 if hasattr(val, 'de_coerce'):
4933 val = val.de_coerce()
4952 val = val.de_coerce()
4934 if val:
4953 if val:
4935 val = json.dumps(val)
4954 val = json.dumps(val)
4936
4955
4937 return val
4956 return val
4938
4957
4939 @property
4958 @property
4940 def schedule_definition_raw(self):
4959 def schedule_definition_raw(self):
4941 return self._as_raw(self.schedule_definition)
4960 return self._as_raw(self.schedule_definition)
4942
4961
4943 @property
4962 @property
4944 def args_raw(self):
4963 def args_raw(self):
4945 return self._as_raw(self.task_args)
4964 return self._as_raw(self.task_args)
4946
4965
4947 @property
4966 @property
4948 def kwargs_raw(self):
4967 def kwargs_raw(self):
4949 return self._as_raw(self.task_kwargs)
4968 return self._as_raw(self.task_kwargs)
4950
4969
4951 def __repr__(self):
4970 def __repr__(self):
4952 return '<DB:ScheduleEntry({}:{})>'.format(
4971 return '<DB:ScheduleEntry({}:{})>'.format(
4953 self.schedule_entry_id, self.schedule_name)
4972 self.schedule_entry_id, self.schedule_name)
4954
4973
4955
4974
4956 @event.listens_for(ScheduleEntry, 'before_update')
4975 @event.listens_for(ScheduleEntry, 'before_update')
4957 def update_task_uid(mapper, connection, target):
4976 def update_task_uid(mapper, connection, target):
4958 target.task_uid = ScheduleEntry.get_uid(target)
4977 target.task_uid = ScheduleEntry.get_uid(target)
4959
4978
4960
4979
4961 @event.listens_for(ScheduleEntry, 'before_insert')
4980 @event.listens_for(ScheduleEntry, 'before_insert')
4962 def set_task_uid(mapper, connection, target):
4981 def set_task_uid(mapper, connection, target):
4963 target.task_uid = ScheduleEntry.get_uid(target)
4982 target.task_uid = ScheduleEntry.get_uid(target)
4964
4983
4965
4984
4966 class _BaseBranchPerms(BaseModel):
4985 class _BaseBranchPerms(BaseModel):
4967 @classmethod
4986 @classmethod
4968 def compute_hash(cls, value):
4987 def compute_hash(cls, value):
4969 return sha1_safe(value)
4988 return sha1_safe(value)
4970
4989
4971 @hybrid_property
4990 @hybrid_property
4972 def branch_pattern(self):
4991 def branch_pattern(self):
4973 return self._branch_pattern or '*'
4992 return self._branch_pattern or '*'
4974
4993
4975 @hybrid_property
4994 @hybrid_property
4976 def branch_hash(self):
4995 def branch_hash(self):
4977 return self._branch_hash
4996 return self._branch_hash
4978
4997
4979 def _validate_glob(self, value):
4998 def _validate_glob(self, value):
4980 re.compile('^' + glob2re(value) + '$')
4999 re.compile('^' + glob2re(value) + '$')
4981
5000
4982 @branch_pattern.setter
5001 @branch_pattern.setter
4983 def branch_pattern(self, value):
5002 def branch_pattern(self, value):
4984 self._validate_glob(value)
5003 self._validate_glob(value)
4985 self._branch_pattern = value or '*'
5004 self._branch_pattern = value or '*'
4986 # set the Hash when setting the branch pattern
5005 # set the Hash when setting the branch pattern
4987 self._branch_hash = self.compute_hash(self._branch_pattern)
5006 self._branch_hash = self.compute_hash(self._branch_pattern)
4988
5007
4989 def matches(self, branch):
5008 def matches(self, branch):
4990 """
5009 """
4991 Check if this the branch matches entry
5010 Check if this the branch matches entry
4992
5011
4993 :param branch: branch name for the commit
5012 :param branch: branch name for the commit
4994 """
5013 """
4995
5014
4996 branch = branch or ''
5015 branch = branch or ''
4997
5016
4998 branch_matches = True
5017 branch_matches = True
4999 if branch:
5018 if branch:
5000 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
5019 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
5001 branch_matches = bool(branch_regex.search(branch))
5020 branch_matches = bool(branch_regex.search(branch))
5002
5021
5003 return branch_matches
5022 return branch_matches
5004
5023
5005
5024
5006 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
5025 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
5007 __tablename__ = 'user_to_repo_branch_permissions'
5026 __tablename__ = 'user_to_repo_branch_permissions'
5008 __table_args__ = (
5027 __table_args__ = (
5009 base_table_args
5028 base_table_args
5010 )
5029 )
5011
5030
5012 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5031 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5013
5032
5014 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5033 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5015 repo = relationship('Repository', backref='user_branch_perms')
5034 repo = relationship('Repository', backref='user_branch_perms')
5016
5035
5017 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5036 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5018 permission = relationship('Permission')
5037 permission = relationship('Permission')
5019
5038
5020 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
5039 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
5021 user_repo_to_perm = relationship('UserRepoToPerm')
5040 user_repo_to_perm = relationship('UserRepoToPerm')
5022
5041
5023 rule_order = Column('rule_order', Integer(), nullable=False)
5042 rule_order = Column('rule_order', Integer(), nullable=False)
5024 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
5043 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
5025 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5044 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5026
5045
5027 def __unicode__(self):
5046 def __unicode__(self):
5028 return u'<UserBranchPermission(%s => %r)>' % (
5047 return u'<UserBranchPermission(%s => %r)>' % (
5029 self.user_repo_to_perm, self.branch_pattern)
5048 self.user_repo_to_perm, self.branch_pattern)
5030
5049
5031
5050
5032 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
5051 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
5033 __tablename__ = 'user_group_to_repo_branch_permissions'
5052 __tablename__ = 'user_group_to_repo_branch_permissions'
5034 __table_args__ = (
5053 __table_args__ = (
5035 base_table_args
5054 base_table_args
5036 )
5055 )
5037
5056
5038 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5057 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5039
5058
5040 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5059 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5041 repo = relationship('Repository', backref='user_group_branch_perms')
5060 repo = relationship('Repository', backref='user_group_branch_perms')
5042
5061
5043 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5062 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5044 permission = relationship('Permission')
5063 permission = relationship('Permission')
5045
5064
5046 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)
5065 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)
5047 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
5066 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
5048
5067
5049 rule_order = Column('rule_order', Integer(), nullable=False)
5068 rule_order = Column('rule_order', Integer(), nullable=False)
5050 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
5069 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
5051 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5070 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5052
5071
5053 def __unicode__(self):
5072 def __unicode__(self):
5054 return u'<UserBranchPermission(%s => %r)>' % (
5073 return u'<UserBranchPermission(%s => %r)>' % (
5055 self.user_group_repo_to_perm, self.branch_pattern)
5074 self.user_group_repo_to_perm, self.branch_pattern)
5056
5075
5057
5076
5058 class UserBookmark(Base, BaseModel):
5077 class UserBookmark(Base, BaseModel):
5059 __tablename__ = 'user_bookmarks'
5078 __tablename__ = 'user_bookmarks'
5060 __table_args__ = (
5079 __table_args__ = (
5061 UniqueConstraint('user_id', 'bookmark_repo_id'),
5080 UniqueConstraint('user_id', 'bookmark_repo_id'),
5062 UniqueConstraint('user_id', 'bookmark_repo_group_id'),
5081 UniqueConstraint('user_id', 'bookmark_repo_group_id'),
5063 UniqueConstraint('user_id', 'bookmark_position'),
5082 UniqueConstraint('user_id', 'bookmark_position'),
5064 base_table_args
5083 base_table_args
5065 )
5084 )
5066
5085
5067 user_bookmark_id = Column("user_bookmark_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
5086 user_bookmark_id = Column("user_bookmark_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
5068 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
5087 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
5069 position = Column("bookmark_position", Integer(), nullable=False)
5088 position = Column("bookmark_position", Integer(), nullable=False)
5070 title = Column("bookmark_title", String(255), nullable=True, unique=None, default=None)
5089 title = Column("bookmark_title", String(255), nullable=True, unique=None, default=None)
5071 redirect_url = Column("bookmark_redirect_url", String(10240), nullable=True, unique=None, default=None)
5090 redirect_url = Column("bookmark_redirect_url", String(10240), nullable=True, unique=None, default=None)
5072 created_on = Column("created_on", DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5091 created_on = Column("created_on", DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5073
5092
5074 bookmark_repo_id = Column("bookmark_repo_id", Integer(), ForeignKey("repositories.repo_id"), nullable=True, unique=None, default=None)
5093 bookmark_repo_id = Column("bookmark_repo_id", Integer(), ForeignKey("repositories.repo_id"), nullable=True, unique=None, default=None)
5075 bookmark_repo_group_id = Column("bookmark_repo_group_id", Integer(), ForeignKey("groups.group_id"), nullable=True, unique=None, default=None)
5094 bookmark_repo_group_id = Column("bookmark_repo_group_id", Integer(), ForeignKey("groups.group_id"), nullable=True, unique=None, default=None)
5076
5095
5077 user = relationship("User")
5096 user = relationship("User")
5078
5097
5079 repository = relationship("Repository")
5098 repository = relationship("Repository")
5080 repository_group = relationship("RepoGroup")
5099 repository_group = relationship("RepoGroup")
5081
5100
5082 @classmethod
5101 @classmethod
5083 def get_by_position_for_user(cls, position, user_id):
5102 def get_by_position_for_user(cls, position, user_id):
5084 return cls.query() \
5103 return cls.query() \
5085 .filter(UserBookmark.user_id == user_id) \
5104 .filter(UserBookmark.user_id == user_id) \
5086 .filter(UserBookmark.position == position).scalar()
5105 .filter(UserBookmark.position == position).scalar()
5087
5106
5088 @classmethod
5107 @classmethod
5089 def get_bookmarks_for_user(cls, user_id):
5108 def get_bookmarks_for_user(cls, user_id):
5090 return cls.query() \
5109 return cls.query() \
5091 .filter(UserBookmark.user_id == user_id) \
5110 .filter(UserBookmark.user_id == user_id) \
5092 .options(joinedload(UserBookmark.repository)) \
5111 .options(joinedload(UserBookmark.repository)) \
5093 .options(joinedload(UserBookmark.repository_group)) \
5112 .options(joinedload(UserBookmark.repository_group)) \
5094 .order_by(UserBookmark.position.asc()) \
5113 .order_by(UserBookmark.position.asc()) \
5095 .all()
5114 .all()
5096
5115
5097 def __unicode__(self):
5116 def __unicode__(self):
5098 return u'<UserBookmark(%s @ %r)>' % (self.position, self.redirect_url)
5117 return u'<UserBookmark(%s @ %r)>' % (self.position, self.redirect_url)
5099
5118
5100
5119
5101 class FileStore(Base, BaseModel):
5120 class FileStore(Base, BaseModel):
5102 __tablename__ = 'file_store'
5121 __tablename__ = 'file_store'
5103 __table_args__ = (
5122 __table_args__ = (
5104 base_table_args
5123 base_table_args
5105 )
5124 )
5106
5125
5107 file_store_id = Column('file_store_id', Integer(), primary_key=True)
5126 file_store_id = Column('file_store_id', Integer(), primary_key=True)
5108 file_uid = Column('file_uid', String(1024), nullable=False)
5127 file_uid = Column('file_uid', String(1024), nullable=False)
5109 file_display_name = Column('file_display_name', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), nullable=True)
5128 file_display_name = Column('file_display_name', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), nullable=True)
5110 file_description = Column('file_description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=True)
5129 file_description = Column('file_description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=True)
5111 file_org_name = Column('file_org_name', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=False)
5130 file_org_name = Column('file_org_name', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=False)
5112
5131
5113 # sha256 hash
5132 # sha256 hash
5114 file_hash = Column('file_hash', String(512), nullable=False)
5133 file_hash = Column('file_hash', String(512), nullable=False)
5115 file_size = Column('file_size', Integer(), nullable=False)
5134 file_size = Column('file_size', Integer(), nullable=False)
5116
5135
5117 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5136 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5118 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True)
5137 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True)
5119 accessed_count = Column('accessed_count', Integer(), default=0)
5138 accessed_count = Column('accessed_count', Integer(), default=0)
5120
5139
5121 enabled = Column('enabled', Boolean(), nullable=False, default=True)
5140 enabled = Column('enabled', Boolean(), nullable=False, default=True)
5122
5141
5123 # if repo/repo_group reference is set, check for permissions
5142 # if repo/repo_group reference is set, check for permissions
5124 check_acl = Column('check_acl', Boolean(), nullable=False, default=True)
5143 check_acl = Column('check_acl', Boolean(), nullable=False, default=True)
5125
5144
5126 # hidden defines an attachment that should be hidden from showing in artifact listing
5145 # hidden defines an attachment that should be hidden from showing in artifact listing
5127 hidden = Column('hidden', Boolean(), nullable=False, default=False)
5146 hidden = Column('hidden', Boolean(), nullable=False, default=False)
5128
5147
5129 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
5148 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
5130 upload_user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.user_id')
5149 upload_user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.user_id')
5131
5150
5132 file_metadata = relationship('FileStoreMetadata', lazy='joined')
5151 file_metadata = relationship('FileStoreMetadata', lazy='joined')
5133
5152
5134 # scope limited to user, which requester have access to
5153 # scope limited to user, which requester have access to
5135 scope_user_id = Column(
5154 scope_user_id = Column(
5136 'scope_user_id', Integer(), ForeignKey('users.user_id'),
5155 'scope_user_id', Integer(), ForeignKey('users.user_id'),
5137 nullable=True, unique=None, default=None)
5156 nullable=True, unique=None, default=None)
5138 user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.scope_user_id')
5157 user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.scope_user_id')
5139
5158
5140 # scope limited to user group, which requester have access to
5159 # scope limited to user group, which requester have access to
5141 scope_user_group_id = Column(
5160 scope_user_group_id = Column(
5142 'scope_user_group_id', Integer(), ForeignKey('users_groups.users_group_id'),
5161 'scope_user_group_id', Integer(), ForeignKey('users_groups.users_group_id'),
5143 nullable=True, unique=None, default=None)
5162 nullable=True, unique=None, default=None)
5144 user_group = relationship('UserGroup', lazy='joined')
5163 user_group = relationship('UserGroup', lazy='joined')
5145
5164
5146 # scope limited to repo, which requester have access to
5165 # scope limited to repo, which requester have access to
5147 scope_repo_id = Column(
5166 scope_repo_id = Column(
5148 'scope_repo_id', Integer(), ForeignKey('repositories.repo_id'),
5167 'scope_repo_id', Integer(), ForeignKey('repositories.repo_id'),
5149 nullable=True, unique=None, default=None)
5168 nullable=True, unique=None, default=None)
5150 repo = relationship('Repository', lazy='joined')
5169 repo = relationship('Repository', lazy='joined')
5151
5170
5152 # scope limited to repo group, which requester have access to
5171 # scope limited to repo group, which requester have access to
5153 scope_repo_group_id = Column(
5172 scope_repo_group_id = Column(
5154 'scope_repo_group_id', Integer(), ForeignKey('groups.group_id'),
5173 'scope_repo_group_id', Integer(), ForeignKey('groups.group_id'),
5155 nullable=True, unique=None, default=None)
5174 nullable=True, unique=None, default=None)
5156 repo_group = relationship('RepoGroup', lazy='joined')
5175 repo_group = relationship('RepoGroup', lazy='joined')
5157
5176
5158 @classmethod
5177 @classmethod
5159 def get_by_store_uid(cls, file_store_uid):
5178 def get_by_store_uid(cls, file_store_uid):
5160 return FileStore.query().filter(FileStore.file_uid == file_store_uid).scalar()
5179 return FileStore.query().filter(FileStore.file_uid == file_store_uid).scalar()
5161
5180
5162 @classmethod
5181 @classmethod
5163 def create(cls, file_uid, filename, file_hash, file_size, file_display_name='',
5182 def create(cls, file_uid, filename, file_hash, file_size, file_display_name='',
5164 file_description='', enabled=True, hidden=False, check_acl=True,
5183 file_description='', enabled=True, hidden=False, check_acl=True,
5165 user_id=None, scope_user_id=None, scope_repo_id=None, scope_repo_group_id=None):
5184 user_id=None, scope_user_id=None, scope_repo_id=None, scope_repo_group_id=None):
5166
5185
5167 store_entry = FileStore()
5186 store_entry = FileStore()
5168 store_entry.file_uid = file_uid
5187 store_entry.file_uid = file_uid
5169 store_entry.file_display_name = file_display_name
5188 store_entry.file_display_name = file_display_name
5170 store_entry.file_org_name = filename
5189 store_entry.file_org_name = filename
5171 store_entry.file_size = file_size
5190 store_entry.file_size = file_size
5172 store_entry.file_hash = file_hash
5191 store_entry.file_hash = file_hash
5173 store_entry.file_description = file_description
5192 store_entry.file_description = file_description
5174
5193
5175 store_entry.check_acl = check_acl
5194 store_entry.check_acl = check_acl
5176 store_entry.enabled = enabled
5195 store_entry.enabled = enabled
5177 store_entry.hidden = hidden
5196 store_entry.hidden = hidden
5178
5197
5179 store_entry.user_id = user_id
5198 store_entry.user_id = user_id
5180 store_entry.scope_user_id = scope_user_id
5199 store_entry.scope_user_id = scope_user_id
5181 store_entry.scope_repo_id = scope_repo_id
5200 store_entry.scope_repo_id = scope_repo_id
5182 store_entry.scope_repo_group_id = scope_repo_group_id
5201 store_entry.scope_repo_group_id = scope_repo_group_id
5183
5202
5184 return store_entry
5203 return store_entry
5185
5204
5186 @classmethod
5205 @classmethod
5187 def store_metadata(cls, file_store_id, args, commit=True):
5206 def store_metadata(cls, file_store_id, args, commit=True):
5188 file_store = FileStore.get(file_store_id)
5207 file_store = FileStore.get(file_store_id)
5189 if file_store is None:
5208 if file_store is None:
5190 return
5209 return
5191
5210
5192 for section, key, value, value_type in args:
5211 for section, key, value, value_type in args:
5193 has_key = FileStoreMetadata().query() \
5212 has_key = FileStoreMetadata().query() \
5194 .filter(FileStoreMetadata.file_store_id == file_store.file_store_id) \
5213 .filter(FileStoreMetadata.file_store_id == file_store.file_store_id) \
5195 .filter(FileStoreMetadata.file_store_meta_section == section) \
5214 .filter(FileStoreMetadata.file_store_meta_section == section) \
5196 .filter(FileStoreMetadata.file_store_meta_key == key) \
5215 .filter(FileStoreMetadata.file_store_meta_key == key) \
5197 .scalar()
5216 .scalar()
5198 if has_key:
5217 if has_key:
5199 msg = 'key `{}` already defined under section `{}` for this file.'\
5218 msg = 'key `{}` already defined under section `{}` for this file.'\
5200 .format(key, section)
5219 .format(key, section)
5201 raise ArtifactMetadataDuplicate(msg, err_section=section, err_key=key)
5220 raise ArtifactMetadataDuplicate(msg, err_section=section, err_key=key)
5202
5221
5203 # NOTE(marcink): raises ArtifactMetadataBadValueType
5222 # NOTE(marcink): raises ArtifactMetadataBadValueType
5204 FileStoreMetadata.valid_value_type(value_type)
5223 FileStoreMetadata.valid_value_type(value_type)
5205
5224
5206 meta_entry = FileStoreMetadata()
5225 meta_entry = FileStoreMetadata()
5207 meta_entry.file_store = file_store
5226 meta_entry.file_store = file_store
5208 meta_entry.file_store_meta_section = section
5227 meta_entry.file_store_meta_section = section
5209 meta_entry.file_store_meta_key = key
5228 meta_entry.file_store_meta_key = key
5210 meta_entry.file_store_meta_value_type = value_type
5229 meta_entry.file_store_meta_value_type = value_type
5211 meta_entry.file_store_meta_value = value
5230 meta_entry.file_store_meta_value = value
5212
5231
5213 Session().add(meta_entry)
5232 Session().add(meta_entry)
5214
5233
5215 try:
5234 try:
5216 if commit:
5235 if commit:
5217 Session().commit()
5236 Session().commit()
5218 except IntegrityError:
5237 except IntegrityError:
5219 Session().rollback()
5238 Session().rollback()
5220 raise ArtifactMetadataDuplicate('Duplicate section/key found for this file.')
5239 raise ArtifactMetadataDuplicate('Duplicate section/key found for this file.')
5221
5240
5222 @classmethod
5241 @classmethod
5223 def bump_access_counter(cls, file_uid, commit=True):
5242 def bump_access_counter(cls, file_uid, commit=True):
5224 FileStore().query()\
5243 FileStore().query()\
5225 .filter(FileStore.file_uid == file_uid)\
5244 .filter(FileStore.file_uid == file_uid)\
5226 .update({FileStore.accessed_count: (FileStore.accessed_count + 1),
5245 .update({FileStore.accessed_count: (FileStore.accessed_count + 1),
5227 FileStore.accessed_on: datetime.datetime.now()})
5246 FileStore.accessed_on: datetime.datetime.now()})
5228 if commit:
5247 if commit:
5229 Session().commit()
5248 Session().commit()
5230
5249
5231 def __json__(self):
5250 def __json__(self):
5232 data = {
5251 data = {
5233 'filename': self.file_display_name,
5252 'filename': self.file_display_name,
5234 'filename_org': self.file_org_name,
5253 'filename_org': self.file_org_name,
5235 'file_uid': self.file_uid,
5254 'file_uid': self.file_uid,
5236 'description': self.file_description,
5255 'description': self.file_description,
5237 'hidden': self.hidden,
5256 'hidden': self.hidden,
5238 'size': self.file_size,
5257 'size': self.file_size,
5239 'created_on': self.created_on,
5258 'created_on': self.created_on,
5240 'uploaded_by': self.upload_user.get_api_data(details='basic'),
5259 'uploaded_by': self.upload_user.get_api_data(details='basic'),
5241 'downloaded_times': self.accessed_count,
5260 'downloaded_times': self.accessed_count,
5242 'sha256': self.file_hash,
5261 'sha256': self.file_hash,
5243 'metadata': self.file_metadata,
5262 'metadata': self.file_metadata,
5244 }
5263 }
5245
5264
5246 return data
5265 return data
5247
5266
5248 def __repr__(self):
5267 def __repr__(self):
5249 return '<FileStore({})>'.format(self.file_store_id)
5268 return '<FileStore({})>'.format(self.file_store_id)
5250
5269
5251
5270
5252 class FileStoreMetadata(Base, BaseModel):
5271 class FileStoreMetadata(Base, BaseModel):
5253 __tablename__ = 'file_store_metadata'
5272 __tablename__ = 'file_store_metadata'
5254 __table_args__ = (
5273 __table_args__ = (
5255 UniqueConstraint('file_store_id', 'file_store_meta_section', 'file_store_meta_key'),
5274 UniqueConstraint('file_store_id', 'file_store_meta_section', 'file_store_meta_key'),
5256 Index('file_store_meta_section_idx', 'file_store_meta_section'),
5275 Index('file_store_meta_section_idx', 'file_store_meta_section'),
5257 Index('file_store_meta_key_idx', 'file_store_meta_key'),
5276 Index('file_store_meta_key_idx', 'file_store_meta_key'),
5258 base_table_args
5277 base_table_args
5259 )
5278 )
5260 SETTINGS_TYPES = {
5279 SETTINGS_TYPES = {
5261 'str': safe_str,
5280 'str': safe_str,
5262 'int': safe_int,
5281 'int': safe_int,
5263 'unicode': safe_unicode,
5282 'unicode': safe_unicode,
5264 'bool': str2bool,
5283 'bool': str2bool,
5265 'list': functools.partial(aslist, sep=',')
5284 'list': functools.partial(aslist, sep=',')
5266 }
5285 }
5267
5286
5268 file_store_meta_id = Column(
5287 file_store_meta_id = Column(
5269 "file_store_meta_id", Integer(), nullable=False, unique=True, default=None,
5288 "file_store_meta_id", Integer(), nullable=False, unique=True, default=None,
5270 primary_key=True)
5289 primary_key=True)
5271 file_store_meta_section = Column(
5290 file_store_meta_section = Column(
5272 "file_store_meta_section", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5291 "file_store_meta_section", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5273 nullable=True, unique=None, default=None)
5292 nullable=True, unique=None, default=None)
5274 file_store_meta_key = Column(
5293 file_store_meta_key = Column(
5275 "file_store_meta_key", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5294 "file_store_meta_key", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5276 nullable=True, unique=None, default=None)
5295 nullable=True, unique=None, default=None)
5277 _file_store_meta_value = Column(
5296 _file_store_meta_value = Column(
5278 "file_store_meta_value", UnicodeText().with_variant(UnicodeText(20480), 'mysql'),
5297 "file_store_meta_value", UnicodeText().with_variant(UnicodeText(20480), 'mysql'),
5279 nullable=True, unique=None, default=None)
5298 nullable=True, unique=None, default=None)
5280 _file_store_meta_value_type = Column(
5299 _file_store_meta_value_type = Column(
5281 "file_store_meta_value_type", String(255), nullable=True, unique=None,
5300 "file_store_meta_value_type", String(255), nullable=True, unique=None,
5282 default='unicode')
5301 default='unicode')
5283
5302
5284 file_store_id = Column(
5303 file_store_id = Column(
5285 'file_store_id', Integer(), ForeignKey('file_store.file_store_id'),
5304 'file_store_id', Integer(), ForeignKey('file_store.file_store_id'),
5286 nullable=True, unique=None, default=None)
5305 nullable=True, unique=None, default=None)
5287
5306
5288 file_store = relationship('FileStore', lazy='joined')
5307 file_store = relationship('FileStore', lazy='joined')
5289
5308
5290 @classmethod
5309 @classmethod
5291 def valid_value_type(cls, value):
5310 def valid_value_type(cls, value):
5292 if value.split('.')[0] not in cls.SETTINGS_TYPES:
5311 if value.split('.')[0] not in cls.SETTINGS_TYPES:
5293 raise ArtifactMetadataBadValueType(
5312 raise ArtifactMetadataBadValueType(
5294 'value_type must be one of %s got %s' % (cls.SETTINGS_TYPES.keys(), value))
5313 'value_type must be one of %s got %s' % (cls.SETTINGS_TYPES.keys(), value))
5295
5314
5296 @hybrid_property
5315 @hybrid_property
5297 def file_store_meta_value(self):
5316 def file_store_meta_value(self):
5298 val = self._file_store_meta_value
5317 val = self._file_store_meta_value
5299
5318
5300 if self._file_store_meta_value_type:
5319 if self._file_store_meta_value_type:
5301 # e.g unicode.encrypted == unicode
5320 # e.g unicode.encrypted == unicode
5302 _type = self._file_store_meta_value_type.split('.')[0]
5321 _type = self._file_store_meta_value_type.split('.')[0]
5303 # decode the encrypted value if it's encrypted field type
5322 # decode the encrypted value if it's encrypted field type
5304 if '.encrypted' in self._file_store_meta_value_type:
5323 if '.encrypted' in self._file_store_meta_value_type:
5305 cipher = EncryptedTextValue()
5324 cipher = EncryptedTextValue()
5306 val = safe_unicode(cipher.process_result_value(val, None))
5325 val = safe_unicode(cipher.process_result_value(val, None))
5307 # do final type conversion
5326 # do final type conversion
5308 converter = self.SETTINGS_TYPES.get(_type) or self.SETTINGS_TYPES['unicode']
5327 converter = self.SETTINGS_TYPES.get(_type) or self.SETTINGS_TYPES['unicode']
5309 val = converter(val)
5328 val = converter(val)
5310
5329
5311 return val
5330 return val
5312
5331
5313 @file_store_meta_value.setter
5332 @file_store_meta_value.setter
5314 def file_store_meta_value(self, val):
5333 def file_store_meta_value(self, val):
5315 val = safe_unicode(val)
5334 val = safe_unicode(val)
5316 # encode the encrypted value
5335 # encode the encrypted value
5317 if '.encrypted' in self.file_store_meta_value_type:
5336 if '.encrypted' in self.file_store_meta_value_type:
5318 cipher = EncryptedTextValue()
5337 cipher = EncryptedTextValue()
5319 val = safe_unicode(cipher.process_bind_param(val, None))
5338 val = safe_unicode(cipher.process_bind_param(val, None))
5320 self._file_store_meta_value = val
5339 self._file_store_meta_value = val
5321
5340
5322 @hybrid_property
5341 @hybrid_property
5323 def file_store_meta_value_type(self):
5342 def file_store_meta_value_type(self):
5324 return self._file_store_meta_value_type
5343 return self._file_store_meta_value_type
5325
5344
5326 @file_store_meta_value_type.setter
5345 @file_store_meta_value_type.setter
5327 def file_store_meta_value_type(self, val):
5346 def file_store_meta_value_type(self, val):
5328 # e.g unicode.encrypted
5347 # e.g unicode.encrypted
5329 self.valid_value_type(val)
5348 self.valid_value_type(val)
5330 self._file_store_meta_value_type = val
5349 self._file_store_meta_value_type = val
5331
5350
5332 def __json__(self):
5351 def __json__(self):
5333 data = {
5352 data = {
5334 'artifact': self.file_store.file_uid,
5353 'artifact': self.file_store.file_uid,
5335 'section': self.file_store_meta_section,
5354 'section': self.file_store_meta_section,
5336 'key': self.file_store_meta_key,
5355 'key': self.file_store_meta_key,
5337 'value': self.file_store_meta_value,
5356 'value': self.file_store_meta_value,
5338 }
5357 }
5339
5358
5340 return data
5359 return data
5341
5360
5342 def __repr__(self):
5361 def __repr__(self):
5343 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.file_store_meta_section,
5362 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.file_store_meta_section,
5344 self.file_store_meta_key, self.file_store_meta_value)
5363 self.file_store_meta_key, self.file_store_meta_value)
5345
5364
5346
5365
5347 class DbMigrateVersion(Base, BaseModel):
5366 class DbMigrateVersion(Base, BaseModel):
5348 __tablename__ = 'db_migrate_version'
5367 __tablename__ = 'db_migrate_version'
5349 __table_args__ = (
5368 __table_args__ = (
5350 base_table_args,
5369 base_table_args,
5351 )
5370 )
5352
5371
5353 repository_id = Column('repository_id', String(250), primary_key=True)
5372 repository_id = Column('repository_id', String(250), primary_key=True)
5354 repository_path = Column('repository_path', Text)
5373 repository_path = Column('repository_path', Text)
5355 version = Column('version', Integer)
5374 version = Column('version', Integer)
5356
5375
5357 @classmethod
5376 @classmethod
5358 def set_version(cls, version):
5377 def set_version(cls, version):
5359 """
5378 """
5360 Helper for forcing a different version, usually for debugging purposes via ishell.
5379 Helper for forcing a different version, usually for debugging purposes via ishell.
5361 """
5380 """
5362 ver = DbMigrateVersion.query().first()
5381 ver = DbMigrateVersion.query().first()
5363 ver.version = version
5382 ver.version = version
5364 Session().commit()
5383 Session().commit()
5365
5384
5366
5385
5367 class DbSession(Base, BaseModel):
5386 class DbSession(Base, BaseModel):
5368 __tablename__ = 'db_session'
5387 __tablename__ = 'db_session'
5369 __table_args__ = (
5388 __table_args__ = (
5370 base_table_args,
5389 base_table_args,
5371 )
5390 )
5372
5391
5373 def __repr__(self):
5392 def __repr__(self):
5374 return '<DB:DbSession({})>'.format(self.id)
5393 return '<DB:DbSession({})>'.format(self.id)
5375
5394
5376 id = Column('id', Integer())
5395 id = Column('id', Integer())
5377 namespace = Column('namespace', String(255), primary_key=True)
5396 namespace = Column('namespace', String(255), primary_key=True)
5378 accessed = Column('accessed', DateTime, nullable=False)
5397 accessed = Column('accessed', DateTime, nullable=False)
5379 created = Column('created', DateTime, nullable=False)
5398 created = Column('created', DateTime, nullable=False)
5380 data = Column('data', PickleType, nullable=False)
5399 data = Column('data', PickleType, nullable=False)
@@ -1,381 +1,382 b''
1
1
2 /******************************************************************************
2 /******************************************************************************
3 * *
3 * *
4 * DO NOT CHANGE THIS FILE MANUALLY *
4 * DO NOT CHANGE THIS FILE MANUALLY *
5 * *
5 * *
6 * *
6 * *
7 * This file is automatically generated when the app starts up with *
7 * This file is automatically generated when the app starts up with *
8 * generate_js_files = true *
8 * generate_js_files = true *
9 * *
9 * *
10 * To add a route here pass jsroute=True to the route definition in the app *
10 * To add a route here pass jsroute=True to the route definition in the app *
11 * *
11 * *
12 ******************************************************************************/
12 ******************************************************************************/
13 function registerRCRoutes() {
13 function registerRCRoutes() {
14 // routes registration
14 // routes registration
15 pyroutes.register('favicon', '/favicon.ico', []);
15 pyroutes.register('favicon', '/favicon.ico', []);
16 pyroutes.register('robots', '/robots.txt', []);
16 pyroutes.register('robots', '/robots.txt', []);
17 pyroutes.register('auth_home', '/_admin/auth*traverse', []);
17 pyroutes.register('auth_home', '/_admin/auth*traverse', []);
18 pyroutes.register('global_integrations_new', '/_admin/integrations/new', []);
18 pyroutes.register('global_integrations_new', '/_admin/integrations/new', []);
19 pyroutes.register('global_integrations_home', '/_admin/integrations', []);
19 pyroutes.register('global_integrations_home', '/_admin/integrations', []);
20 pyroutes.register('global_integrations_list', '/_admin/integrations/%(integration)s', ['integration']);
20 pyroutes.register('global_integrations_list', '/_admin/integrations/%(integration)s', ['integration']);
21 pyroutes.register('global_integrations_create', '/_admin/integrations/%(integration)s/new', ['integration']);
21 pyroutes.register('global_integrations_create', '/_admin/integrations/%(integration)s/new', ['integration']);
22 pyroutes.register('global_integrations_edit', '/_admin/integrations/%(integration)s/%(integration_id)s', ['integration', 'integration_id']);
22 pyroutes.register('global_integrations_edit', '/_admin/integrations/%(integration)s/%(integration_id)s', ['integration', 'integration_id']);
23 pyroutes.register('repo_group_integrations_home', '/%(repo_group_name)s/_settings/integrations', ['repo_group_name']);
23 pyroutes.register('repo_group_integrations_home', '/%(repo_group_name)s/_settings/integrations', ['repo_group_name']);
24 pyroutes.register('repo_group_integrations_new', '/%(repo_group_name)s/_settings/integrations/new', ['repo_group_name']);
24 pyroutes.register('repo_group_integrations_new', '/%(repo_group_name)s/_settings/integrations/new', ['repo_group_name']);
25 pyroutes.register('repo_group_integrations_list', '/%(repo_group_name)s/_settings/integrations/%(integration)s', ['repo_group_name', 'integration']);
25 pyroutes.register('repo_group_integrations_list', '/%(repo_group_name)s/_settings/integrations/%(integration)s', ['repo_group_name', 'integration']);
26 pyroutes.register('repo_group_integrations_create', '/%(repo_group_name)s/_settings/integrations/%(integration)s/new', ['repo_group_name', 'integration']);
26 pyroutes.register('repo_group_integrations_create', '/%(repo_group_name)s/_settings/integrations/%(integration)s/new', ['repo_group_name', 'integration']);
27 pyroutes.register('repo_group_integrations_edit', '/%(repo_group_name)s/_settings/integrations/%(integration)s/%(integration_id)s', ['repo_group_name', 'integration', 'integration_id']);
27 pyroutes.register('repo_group_integrations_edit', '/%(repo_group_name)s/_settings/integrations/%(integration)s/%(integration_id)s', ['repo_group_name', 'integration', 'integration_id']);
28 pyroutes.register('repo_integrations_home', '/%(repo_name)s/settings/integrations', ['repo_name']);
28 pyroutes.register('repo_integrations_home', '/%(repo_name)s/settings/integrations', ['repo_name']);
29 pyroutes.register('repo_integrations_new', '/%(repo_name)s/settings/integrations/new', ['repo_name']);
29 pyroutes.register('repo_integrations_new', '/%(repo_name)s/settings/integrations/new', ['repo_name']);
30 pyroutes.register('repo_integrations_list', '/%(repo_name)s/settings/integrations/%(integration)s', ['repo_name', 'integration']);
30 pyroutes.register('repo_integrations_list', '/%(repo_name)s/settings/integrations/%(integration)s', ['repo_name', 'integration']);
31 pyroutes.register('repo_integrations_create', '/%(repo_name)s/settings/integrations/%(integration)s/new', ['repo_name', 'integration']);
31 pyroutes.register('repo_integrations_create', '/%(repo_name)s/settings/integrations/%(integration)s/new', ['repo_name', 'integration']);
32 pyroutes.register('repo_integrations_edit', '/%(repo_name)s/settings/integrations/%(integration)s/%(integration_id)s', ['repo_name', 'integration', 'integration_id']);
32 pyroutes.register('repo_integrations_edit', '/%(repo_name)s/settings/integrations/%(integration)s/%(integration_id)s', ['repo_name', 'integration', 'integration_id']);
33 pyroutes.register('ops_ping', '/_admin/ops/ping', []);
33 pyroutes.register('ops_ping', '/_admin/ops/ping', []);
34 pyroutes.register('ops_error_test', '/_admin/ops/error', []);
34 pyroutes.register('ops_error_test', '/_admin/ops/error', []);
35 pyroutes.register('ops_redirect_test', '/_admin/ops/redirect', []);
35 pyroutes.register('ops_redirect_test', '/_admin/ops/redirect', []);
36 pyroutes.register('ops_ping_legacy', '/_admin/ping', []);
36 pyroutes.register('ops_ping_legacy', '/_admin/ping', []);
37 pyroutes.register('ops_error_test_legacy', '/_admin/error_test', []);
37 pyroutes.register('ops_error_test_legacy', '/_admin/error_test', []);
38 pyroutes.register('admin_home', '/_admin', []);
38 pyroutes.register('admin_home', '/_admin', []);
39 pyroutes.register('admin_audit_logs', '/_admin/audit_logs', []);
39 pyroutes.register('admin_audit_logs', '/_admin/audit_logs', []);
40 pyroutes.register('admin_audit_log_entry', '/_admin/audit_logs/%(audit_log_id)s', ['audit_log_id']);
40 pyroutes.register('admin_audit_log_entry', '/_admin/audit_logs/%(audit_log_id)s', ['audit_log_id']);
41 pyroutes.register('pull_requests_global_0', '/_admin/pull_requests/%(pull_request_id)s', ['pull_request_id']);
41 pyroutes.register('pull_requests_global_0', '/_admin/pull_requests/%(pull_request_id)s', ['pull_request_id']);
42 pyroutes.register('pull_requests_global_1', '/_admin/pull-requests/%(pull_request_id)s', ['pull_request_id']);
42 pyroutes.register('pull_requests_global_1', '/_admin/pull-requests/%(pull_request_id)s', ['pull_request_id']);
43 pyroutes.register('pull_requests_global', '/_admin/pull-request/%(pull_request_id)s', ['pull_request_id']);
43 pyroutes.register('pull_requests_global', '/_admin/pull-request/%(pull_request_id)s', ['pull_request_id']);
44 pyroutes.register('admin_settings_open_source', '/_admin/settings/open_source', []);
44 pyroutes.register('admin_settings_open_source', '/_admin/settings/open_source', []);
45 pyroutes.register('admin_settings_vcs_svn_generate_cfg', '/_admin/settings/vcs/svn_generate_cfg', []);
45 pyroutes.register('admin_settings_vcs_svn_generate_cfg', '/_admin/settings/vcs/svn_generate_cfg', []);
46 pyroutes.register('admin_settings_system', '/_admin/settings/system', []);
46 pyroutes.register('admin_settings_system', '/_admin/settings/system', []);
47 pyroutes.register('admin_settings_system_update', '/_admin/settings/system/updates', []);
47 pyroutes.register('admin_settings_system_update', '/_admin/settings/system/updates', []);
48 pyroutes.register('admin_settings_exception_tracker', '/_admin/settings/exceptions', []);
48 pyroutes.register('admin_settings_exception_tracker', '/_admin/settings/exceptions', []);
49 pyroutes.register('admin_settings_exception_tracker_delete_all', '/_admin/settings/exceptions/delete', []);
49 pyroutes.register('admin_settings_exception_tracker_delete_all', '/_admin/settings/exceptions/delete', []);
50 pyroutes.register('admin_settings_exception_tracker_show', '/_admin/settings/exceptions/%(exception_id)s', ['exception_id']);
50 pyroutes.register('admin_settings_exception_tracker_show', '/_admin/settings/exceptions/%(exception_id)s', ['exception_id']);
51 pyroutes.register('admin_settings_exception_tracker_delete', '/_admin/settings/exceptions/%(exception_id)s/delete', ['exception_id']);
51 pyroutes.register('admin_settings_exception_tracker_delete', '/_admin/settings/exceptions/%(exception_id)s/delete', ['exception_id']);
52 pyroutes.register('admin_settings_sessions', '/_admin/settings/sessions', []);
52 pyroutes.register('admin_settings_sessions', '/_admin/settings/sessions', []);
53 pyroutes.register('admin_settings_sessions_cleanup', '/_admin/settings/sessions/cleanup', []);
53 pyroutes.register('admin_settings_sessions_cleanup', '/_admin/settings/sessions/cleanup', []);
54 pyroutes.register('admin_settings_process_management', '/_admin/settings/process_management', []);
54 pyroutes.register('admin_settings_process_management', '/_admin/settings/process_management', []);
55 pyroutes.register('admin_settings_process_management_data', '/_admin/settings/process_management/data', []);
55 pyroutes.register('admin_settings_process_management_data', '/_admin/settings/process_management/data', []);
56 pyroutes.register('admin_settings_process_management_signal', '/_admin/settings/process_management/signal', []);
56 pyroutes.register('admin_settings_process_management_signal', '/_admin/settings/process_management/signal', []);
57 pyroutes.register('admin_settings_process_management_master_signal', '/_admin/settings/process_management/master_signal', []);
57 pyroutes.register('admin_settings_process_management_master_signal', '/_admin/settings/process_management/master_signal', []);
58 pyroutes.register('admin_defaults_repositories', '/_admin/defaults/repositories', []);
58 pyroutes.register('admin_defaults_repositories', '/_admin/defaults/repositories', []);
59 pyroutes.register('admin_defaults_repositories_update', '/_admin/defaults/repositories/update', []);
59 pyroutes.register('admin_defaults_repositories_update', '/_admin/defaults/repositories/update', []);
60 pyroutes.register('admin_settings', '/_admin/settings', []);
60 pyroutes.register('admin_settings', '/_admin/settings', []);
61 pyroutes.register('admin_settings_update', '/_admin/settings/update', []);
61 pyroutes.register('admin_settings_update', '/_admin/settings/update', []);
62 pyroutes.register('admin_settings_global', '/_admin/settings/global', []);
62 pyroutes.register('admin_settings_global', '/_admin/settings/global', []);
63 pyroutes.register('admin_settings_global_update', '/_admin/settings/global/update', []);
63 pyroutes.register('admin_settings_global_update', '/_admin/settings/global/update', []);
64 pyroutes.register('admin_settings_vcs', '/_admin/settings/vcs', []);
64 pyroutes.register('admin_settings_vcs', '/_admin/settings/vcs', []);
65 pyroutes.register('admin_settings_vcs_update', '/_admin/settings/vcs/update', []);
65 pyroutes.register('admin_settings_vcs_update', '/_admin/settings/vcs/update', []);
66 pyroutes.register('admin_settings_vcs_svn_pattern_delete', '/_admin/settings/vcs/svn_pattern_delete', []);
66 pyroutes.register('admin_settings_vcs_svn_pattern_delete', '/_admin/settings/vcs/svn_pattern_delete', []);
67 pyroutes.register('admin_settings_mapping', '/_admin/settings/mapping', []);
67 pyroutes.register('admin_settings_mapping', '/_admin/settings/mapping', []);
68 pyroutes.register('admin_settings_mapping_update', '/_admin/settings/mapping/update', []);
68 pyroutes.register('admin_settings_mapping_update', '/_admin/settings/mapping/update', []);
69 pyroutes.register('admin_settings_visual', '/_admin/settings/visual', []);
69 pyroutes.register('admin_settings_visual', '/_admin/settings/visual', []);
70 pyroutes.register('admin_settings_visual_update', '/_admin/settings/visual/update', []);
70 pyroutes.register('admin_settings_visual_update', '/_admin/settings/visual/update', []);
71 pyroutes.register('admin_settings_issuetracker', '/_admin/settings/issue-tracker', []);
71 pyroutes.register('admin_settings_issuetracker', '/_admin/settings/issue-tracker', []);
72 pyroutes.register('admin_settings_issuetracker_update', '/_admin/settings/issue-tracker/update', []);
72 pyroutes.register('admin_settings_issuetracker_update', '/_admin/settings/issue-tracker/update', []);
73 pyroutes.register('admin_settings_issuetracker_test', '/_admin/settings/issue-tracker/test', []);
73 pyroutes.register('admin_settings_issuetracker_test', '/_admin/settings/issue-tracker/test', []);
74 pyroutes.register('admin_settings_issuetracker_delete', '/_admin/settings/issue-tracker/delete', []);
74 pyroutes.register('admin_settings_issuetracker_delete', '/_admin/settings/issue-tracker/delete', []);
75 pyroutes.register('admin_settings_email', '/_admin/settings/email', []);
75 pyroutes.register('admin_settings_email', '/_admin/settings/email', []);
76 pyroutes.register('admin_settings_email_update', '/_admin/settings/email/update', []);
76 pyroutes.register('admin_settings_email_update', '/_admin/settings/email/update', []);
77 pyroutes.register('admin_settings_hooks', '/_admin/settings/hooks', []);
77 pyroutes.register('admin_settings_hooks', '/_admin/settings/hooks', []);
78 pyroutes.register('admin_settings_hooks_update', '/_admin/settings/hooks/update', []);
78 pyroutes.register('admin_settings_hooks_update', '/_admin/settings/hooks/update', []);
79 pyroutes.register('admin_settings_hooks_delete', '/_admin/settings/hooks/delete', []);
79 pyroutes.register('admin_settings_hooks_delete', '/_admin/settings/hooks/delete', []);
80 pyroutes.register('admin_settings_search', '/_admin/settings/search', []);
80 pyroutes.register('admin_settings_search', '/_admin/settings/search', []);
81 pyroutes.register('admin_settings_labs', '/_admin/settings/labs', []);
81 pyroutes.register('admin_settings_labs', '/_admin/settings/labs', []);
82 pyroutes.register('admin_settings_labs_update', '/_admin/settings/labs/update', []);
82 pyroutes.register('admin_settings_labs_update', '/_admin/settings/labs/update', []);
83 pyroutes.register('admin_permissions_application', '/_admin/permissions/application', []);
83 pyroutes.register('admin_permissions_application', '/_admin/permissions/application', []);
84 pyroutes.register('admin_permissions_application_update', '/_admin/permissions/application/update', []);
84 pyroutes.register('admin_permissions_application_update', '/_admin/permissions/application/update', []);
85 pyroutes.register('admin_permissions_global', '/_admin/permissions/global', []);
85 pyroutes.register('admin_permissions_global', '/_admin/permissions/global', []);
86 pyroutes.register('admin_permissions_global_update', '/_admin/permissions/global/update', []);
86 pyroutes.register('admin_permissions_global_update', '/_admin/permissions/global/update', []);
87 pyroutes.register('admin_permissions_object', '/_admin/permissions/object', []);
87 pyroutes.register('admin_permissions_object', '/_admin/permissions/object', []);
88 pyroutes.register('admin_permissions_object_update', '/_admin/permissions/object/update', []);
88 pyroutes.register('admin_permissions_object_update', '/_admin/permissions/object/update', []);
89 pyroutes.register('admin_permissions_ips', '/_admin/permissions/ips', []);
89 pyroutes.register('admin_permissions_ips', '/_admin/permissions/ips', []);
90 pyroutes.register('admin_permissions_overview', '/_admin/permissions/overview', []);
90 pyroutes.register('admin_permissions_overview', '/_admin/permissions/overview', []);
91 pyroutes.register('admin_permissions_auth_token_access', '/_admin/permissions/auth_token_access', []);
91 pyroutes.register('admin_permissions_auth_token_access', '/_admin/permissions/auth_token_access', []);
92 pyroutes.register('admin_permissions_ssh_keys', '/_admin/permissions/ssh_keys', []);
92 pyroutes.register('admin_permissions_ssh_keys', '/_admin/permissions/ssh_keys', []);
93 pyroutes.register('admin_permissions_ssh_keys_data', '/_admin/permissions/ssh_keys/data', []);
93 pyroutes.register('admin_permissions_ssh_keys_data', '/_admin/permissions/ssh_keys/data', []);
94 pyroutes.register('admin_permissions_ssh_keys_update', '/_admin/permissions/ssh_keys/update', []);
94 pyroutes.register('admin_permissions_ssh_keys_update', '/_admin/permissions/ssh_keys/update', []);
95 pyroutes.register('users', '/_admin/users', []);
95 pyroutes.register('users', '/_admin/users', []);
96 pyroutes.register('users_data', '/_admin/users_data', []);
96 pyroutes.register('users_data', '/_admin/users_data', []);
97 pyroutes.register('users_create', '/_admin/users/create', []);
97 pyroutes.register('users_create', '/_admin/users/create', []);
98 pyroutes.register('users_new', '/_admin/users/new', []);
98 pyroutes.register('users_new', '/_admin/users/new', []);
99 pyroutes.register('user_edit', '/_admin/users/%(user_id)s/edit', ['user_id']);
99 pyroutes.register('user_edit', '/_admin/users/%(user_id)s/edit', ['user_id']);
100 pyroutes.register('user_edit_advanced', '/_admin/users/%(user_id)s/edit/advanced', ['user_id']);
100 pyroutes.register('user_edit_advanced', '/_admin/users/%(user_id)s/edit/advanced', ['user_id']);
101 pyroutes.register('user_edit_global_perms', '/_admin/users/%(user_id)s/edit/global_permissions', ['user_id']);
101 pyroutes.register('user_edit_global_perms', '/_admin/users/%(user_id)s/edit/global_permissions', ['user_id']);
102 pyroutes.register('user_edit_global_perms_update', '/_admin/users/%(user_id)s/edit/global_permissions/update', ['user_id']);
102 pyroutes.register('user_edit_global_perms_update', '/_admin/users/%(user_id)s/edit/global_permissions/update', ['user_id']);
103 pyroutes.register('user_update', '/_admin/users/%(user_id)s/update', ['user_id']);
103 pyroutes.register('user_update', '/_admin/users/%(user_id)s/update', ['user_id']);
104 pyroutes.register('user_delete', '/_admin/users/%(user_id)s/delete', ['user_id']);
104 pyroutes.register('user_delete', '/_admin/users/%(user_id)s/delete', ['user_id']);
105 pyroutes.register('user_enable_force_password_reset', '/_admin/users/%(user_id)s/password_reset_enable', ['user_id']);
105 pyroutes.register('user_enable_force_password_reset', '/_admin/users/%(user_id)s/password_reset_enable', ['user_id']);
106 pyroutes.register('user_disable_force_password_reset', '/_admin/users/%(user_id)s/password_reset_disable', ['user_id']);
106 pyroutes.register('user_disable_force_password_reset', '/_admin/users/%(user_id)s/password_reset_disable', ['user_id']);
107 pyroutes.register('user_create_personal_repo_group', '/_admin/users/%(user_id)s/create_repo_group', ['user_id']);
107 pyroutes.register('user_create_personal_repo_group', '/_admin/users/%(user_id)s/create_repo_group', ['user_id']);
108 pyroutes.register('edit_user_auth_tokens_delete', '/_admin/users/%(user_id)s/edit/auth_tokens/delete', ['user_id']);
108 pyroutes.register('edit_user_auth_tokens_delete', '/_admin/users/%(user_id)s/edit/auth_tokens/delete', ['user_id']);
109 pyroutes.register('edit_user_ssh_keys', '/_admin/users/%(user_id)s/edit/ssh_keys', ['user_id']);
109 pyroutes.register('edit_user_ssh_keys', '/_admin/users/%(user_id)s/edit/ssh_keys', ['user_id']);
110 pyroutes.register('edit_user_ssh_keys_generate_keypair', '/_admin/users/%(user_id)s/edit/ssh_keys/generate', ['user_id']);
110 pyroutes.register('edit_user_ssh_keys_generate_keypair', '/_admin/users/%(user_id)s/edit/ssh_keys/generate', ['user_id']);
111 pyroutes.register('edit_user_ssh_keys_add', '/_admin/users/%(user_id)s/edit/ssh_keys/new', ['user_id']);
111 pyroutes.register('edit_user_ssh_keys_add', '/_admin/users/%(user_id)s/edit/ssh_keys/new', ['user_id']);
112 pyroutes.register('edit_user_ssh_keys_delete', '/_admin/users/%(user_id)s/edit/ssh_keys/delete', ['user_id']);
112 pyroutes.register('edit_user_ssh_keys_delete', '/_admin/users/%(user_id)s/edit/ssh_keys/delete', ['user_id']);
113 pyroutes.register('edit_user_emails', '/_admin/users/%(user_id)s/edit/emails', ['user_id']);
113 pyroutes.register('edit_user_emails', '/_admin/users/%(user_id)s/edit/emails', ['user_id']);
114 pyroutes.register('edit_user_emails_add', '/_admin/users/%(user_id)s/edit/emails/new', ['user_id']);
114 pyroutes.register('edit_user_emails_add', '/_admin/users/%(user_id)s/edit/emails/new', ['user_id']);
115 pyroutes.register('edit_user_emails_delete', '/_admin/users/%(user_id)s/edit/emails/delete', ['user_id']);
115 pyroutes.register('edit_user_emails_delete', '/_admin/users/%(user_id)s/edit/emails/delete', ['user_id']);
116 pyroutes.register('edit_user_ips', '/_admin/users/%(user_id)s/edit/ips', ['user_id']);
116 pyroutes.register('edit_user_ips', '/_admin/users/%(user_id)s/edit/ips', ['user_id']);
117 pyroutes.register('edit_user_ips_add', '/_admin/users/%(user_id)s/edit/ips/new', ['user_id']);
117 pyroutes.register('edit_user_ips_add', '/_admin/users/%(user_id)s/edit/ips/new', ['user_id']);
118 pyroutes.register('edit_user_ips_delete', '/_admin/users/%(user_id)s/edit/ips/delete', ['user_id']);
118 pyroutes.register('edit_user_ips_delete', '/_admin/users/%(user_id)s/edit/ips/delete', ['user_id']);
119 pyroutes.register('edit_user_perms_summary', '/_admin/users/%(user_id)s/edit/permissions_summary', ['user_id']);
119 pyroutes.register('edit_user_perms_summary', '/_admin/users/%(user_id)s/edit/permissions_summary', ['user_id']);
120 pyroutes.register('edit_user_perms_summary_json', '/_admin/users/%(user_id)s/edit/permissions_summary/json', ['user_id']);
120 pyroutes.register('edit_user_perms_summary_json', '/_admin/users/%(user_id)s/edit/permissions_summary/json', ['user_id']);
121 pyroutes.register('edit_user_groups_management', '/_admin/users/%(user_id)s/edit/groups_management', ['user_id']);
121 pyroutes.register('edit_user_groups_management', '/_admin/users/%(user_id)s/edit/groups_management', ['user_id']);
122 pyroutes.register('edit_user_groups_management_updates', '/_admin/users/%(user_id)s/edit/edit_user_groups_management/updates', ['user_id']);
122 pyroutes.register('edit_user_groups_management_updates', '/_admin/users/%(user_id)s/edit/edit_user_groups_management/updates', ['user_id']);
123 pyroutes.register('edit_user_audit_logs', '/_admin/users/%(user_id)s/edit/audit', ['user_id']);
123 pyroutes.register('edit_user_audit_logs', '/_admin/users/%(user_id)s/edit/audit', ['user_id']);
124 pyroutes.register('edit_user_audit_logs_download', '/_admin/users/%(user_id)s/edit/audit/download', ['user_id']);
124 pyroutes.register('edit_user_audit_logs_download', '/_admin/users/%(user_id)s/edit/audit/download', ['user_id']);
125 pyroutes.register('edit_user_caches', '/_admin/users/%(user_id)s/edit/caches', ['user_id']);
125 pyroutes.register('edit_user_caches', '/_admin/users/%(user_id)s/edit/caches', ['user_id']);
126 pyroutes.register('edit_user_caches_update', '/_admin/users/%(user_id)s/edit/caches/update', ['user_id']);
126 pyroutes.register('edit_user_caches_update', '/_admin/users/%(user_id)s/edit/caches/update', ['user_id']);
127 pyroutes.register('user_groups', '/_admin/user_groups', []);
127 pyroutes.register('user_groups', '/_admin/user_groups', []);
128 pyroutes.register('user_groups_data', '/_admin/user_groups_data', []);
128 pyroutes.register('user_groups_data', '/_admin/user_groups_data', []);
129 pyroutes.register('user_groups_new', '/_admin/user_groups/new', []);
129 pyroutes.register('user_groups_new', '/_admin/user_groups/new', []);
130 pyroutes.register('user_groups_create', '/_admin/user_groups/create', []);
130 pyroutes.register('user_groups_create', '/_admin/user_groups/create', []);
131 pyroutes.register('repos', '/_admin/repos', []);
131 pyroutes.register('repos', '/_admin/repos', []);
132 pyroutes.register('repo_new', '/_admin/repos/new', []);
132 pyroutes.register('repo_new', '/_admin/repos/new', []);
133 pyroutes.register('repo_create', '/_admin/repos/create', []);
133 pyroutes.register('repo_create', '/_admin/repos/create', []);
134 pyroutes.register('repo_groups', '/_admin/repo_groups', []);
134 pyroutes.register('repo_groups', '/_admin/repo_groups', []);
135 pyroutes.register('repo_groups_data', '/_admin/repo_groups_data', []);
135 pyroutes.register('repo_groups_data', '/_admin/repo_groups_data', []);
136 pyroutes.register('repo_group_new', '/_admin/repo_group/new', []);
136 pyroutes.register('repo_group_new', '/_admin/repo_group/new', []);
137 pyroutes.register('repo_group_create', '/_admin/repo_group/create', []);
137 pyroutes.register('repo_group_create', '/_admin/repo_group/create', []);
138 pyroutes.register('channelstream_connect', '/_admin/channelstream/connect', []);
138 pyroutes.register('channelstream_connect', '/_admin/channelstream/connect', []);
139 pyroutes.register('channelstream_subscribe', '/_admin/channelstream/subscribe', []);
139 pyroutes.register('channelstream_subscribe', '/_admin/channelstream/subscribe', []);
140 pyroutes.register('channelstream_proxy', '/_channelstream', []);
140 pyroutes.register('channelstream_proxy', '/_channelstream', []);
141 pyroutes.register('upload_file', '/_file_store/upload', []);
141 pyroutes.register('upload_file', '/_file_store/upload', []);
142 pyroutes.register('download_file', '/_file_store/download/%(fid)s', ['fid']);
142 pyroutes.register('download_file', '/_file_store/download/%(fid)s', ['fid']);
143 pyroutes.register('download_file_by_token', '/_file_store/token-download/%(_auth_token)s/%(fid)s', ['_auth_token', 'fid']);
143 pyroutes.register('logout', '/_admin/logout', []);
144 pyroutes.register('logout', '/_admin/logout', []);
144 pyroutes.register('reset_password', '/_admin/password_reset', []);
145 pyroutes.register('reset_password', '/_admin/password_reset', []);
145 pyroutes.register('reset_password_confirmation', '/_admin/password_reset_confirmation', []);
146 pyroutes.register('reset_password_confirmation', '/_admin/password_reset_confirmation', []);
146 pyroutes.register('home', '/', []);
147 pyroutes.register('home', '/', []);
147 pyroutes.register('user_autocomplete_data', '/_users', []);
148 pyroutes.register('user_autocomplete_data', '/_users', []);
148 pyroutes.register('user_group_autocomplete_data', '/_user_groups', []);
149 pyroutes.register('user_group_autocomplete_data', '/_user_groups', []);
149 pyroutes.register('repo_list_data', '/_repos', []);
150 pyroutes.register('repo_list_data', '/_repos', []);
150 pyroutes.register('repo_group_list_data', '/_repo_groups', []);
151 pyroutes.register('repo_group_list_data', '/_repo_groups', []);
151 pyroutes.register('goto_switcher_data', '/_goto_data', []);
152 pyroutes.register('goto_switcher_data', '/_goto_data', []);
152 pyroutes.register('markup_preview', '/_markup_preview', []);
153 pyroutes.register('markup_preview', '/_markup_preview', []);
153 pyroutes.register('file_preview', '/_file_preview', []);
154 pyroutes.register('file_preview', '/_file_preview', []);
154 pyroutes.register('store_user_session_value', '/_store_session_attr', []);
155 pyroutes.register('store_user_session_value', '/_store_session_attr', []);
155 pyroutes.register('journal', '/_admin/journal', []);
156 pyroutes.register('journal', '/_admin/journal', []);
156 pyroutes.register('journal_rss', '/_admin/journal/rss', []);
157 pyroutes.register('journal_rss', '/_admin/journal/rss', []);
157 pyroutes.register('journal_atom', '/_admin/journal/atom', []);
158 pyroutes.register('journal_atom', '/_admin/journal/atom', []);
158 pyroutes.register('journal_public', '/_admin/public_journal', []);
159 pyroutes.register('journal_public', '/_admin/public_journal', []);
159 pyroutes.register('journal_public_atom', '/_admin/public_journal/atom', []);
160 pyroutes.register('journal_public_atom', '/_admin/public_journal/atom', []);
160 pyroutes.register('journal_public_atom_old', '/_admin/public_journal_atom', []);
161 pyroutes.register('journal_public_atom_old', '/_admin/public_journal_atom', []);
161 pyroutes.register('journal_public_rss', '/_admin/public_journal/rss', []);
162 pyroutes.register('journal_public_rss', '/_admin/public_journal/rss', []);
162 pyroutes.register('journal_public_rss_old', '/_admin/public_journal_rss', []);
163 pyroutes.register('journal_public_rss_old', '/_admin/public_journal_rss', []);
163 pyroutes.register('toggle_following', '/_admin/toggle_following', []);
164 pyroutes.register('toggle_following', '/_admin/toggle_following', []);
164 pyroutes.register('repo_creating', '/%(repo_name)s/repo_creating', ['repo_name']);
165 pyroutes.register('repo_creating', '/%(repo_name)s/repo_creating', ['repo_name']);
165 pyroutes.register('repo_creating_check', '/%(repo_name)s/repo_creating_check', ['repo_name']);
166 pyroutes.register('repo_creating_check', '/%(repo_name)s/repo_creating_check', ['repo_name']);
166 pyroutes.register('repo_summary_explicit', '/%(repo_name)s/summary', ['repo_name']);
167 pyroutes.register('repo_summary_explicit', '/%(repo_name)s/summary', ['repo_name']);
167 pyroutes.register('repo_summary_commits', '/%(repo_name)s/summary-commits', ['repo_name']);
168 pyroutes.register('repo_summary_commits', '/%(repo_name)s/summary-commits', ['repo_name']);
168 pyroutes.register('repo_commit', '/%(repo_name)s/changeset/%(commit_id)s', ['repo_name', 'commit_id']);
169 pyroutes.register('repo_commit', '/%(repo_name)s/changeset/%(commit_id)s', ['repo_name', 'commit_id']);
169 pyroutes.register('repo_commit_children', '/%(repo_name)s/changeset_children/%(commit_id)s', ['repo_name', 'commit_id']);
170 pyroutes.register('repo_commit_children', '/%(repo_name)s/changeset_children/%(commit_id)s', ['repo_name', 'commit_id']);
170 pyroutes.register('repo_commit_parents', '/%(repo_name)s/changeset_parents/%(commit_id)s', ['repo_name', 'commit_id']);
171 pyroutes.register('repo_commit_parents', '/%(repo_name)s/changeset_parents/%(commit_id)s', ['repo_name', 'commit_id']);
171 pyroutes.register('repo_commit_raw', '/%(repo_name)s/changeset-diff/%(commit_id)s', ['repo_name', 'commit_id']);
172 pyroutes.register('repo_commit_raw', '/%(repo_name)s/changeset-diff/%(commit_id)s', ['repo_name', 'commit_id']);
172 pyroutes.register('repo_commit_patch', '/%(repo_name)s/changeset-patch/%(commit_id)s', ['repo_name', 'commit_id']);
173 pyroutes.register('repo_commit_patch', '/%(repo_name)s/changeset-patch/%(commit_id)s', ['repo_name', 'commit_id']);
173 pyroutes.register('repo_commit_download', '/%(repo_name)s/changeset-download/%(commit_id)s', ['repo_name', 'commit_id']);
174 pyroutes.register('repo_commit_download', '/%(repo_name)s/changeset-download/%(commit_id)s', ['repo_name', 'commit_id']);
174 pyroutes.register('repo_commit_data', '/%(repo_name)s/changeset-data/%(commit_id)s', ['repo_name', 'commit_id']);
175 pyroutes.register('repo_commit_data', '/%(repo_name)s/changeset-data/%(commit_id)s', ['repo_name', 'commit_id']);
175 pyroutes.register('repo_commit_comment_create', '/%(repo_name)s/changeset/%(commit_id)s/comment/create', ['repo_name', 'commit_id']);
176 pyroutes.register('repo_commit_comment_create', '/%(repo_name)s/changeset/%(commit_id)s/comment/create', ['repo_name', 'commit_id']);
176 pyroutes.register('repo_commit_comment_preview', '/%(repo_name)s/changeset/%(commit_id)s/comment/preview', ['repo_name', 'commit_id']);
177 pyroutes.register('repo_commit_comment_preview', '/%(repo_name)s/changeset/%(commit_id)s/comment/preview', ['repo_name', 'commit_id']);
177 pyroutes.register('repo_commit_comment_attachment_upload', '/%(repo_name)s/changeset/%(commit_id)s/comment/attachment_upload', ['repo_name', 'commit_id']);
178 pyroutes.register('repo_commit_comment_attachment_upload', '/%(repo_name)s/changeset/%(commit_id)s/comment/attachment_upload', ['repo_name', 'commit_id']);
178 pyroutes.register('repo_commit_comment_delete', '/%(repo_name)s/changeset/%(commit_id)s/comment/%(comment_id)s/delete', ['repo_name', 'commit_id', 'comment_id']);
179 pyroutes.register('repo_commit_comment_delete', '/%(repo_name)s/changeset/%(commit_id)s/comment/%(comment_id)s/delete', ['repo_name', 'commit_id', 'comment_id']);
179 pyroutes.register('repo_commit_raw_deprecated', '/%(repo_name)s/raw-changeset/%(commit_id)s', ['repo_name', 'commit_id']);
180 pyroutes.register('repo_commit_raw_deprecated', '/%(repo_name)s/raw-changeset/%(commit_id)s', ['repo_name', 'commit_id']);
180 pyroutes.register('repo_archivefile', '/%(repo_name)s/archive/%(fname)s', ['repo_name', 'fname']);
181 pyroutes.register('repo_archivefile', '/%(repo_name)s/archive/%(fname)s', ['repo_name', 'fname']);
181 pyroutes.register('repo_files_diff', '/%(repo_name)s/diff/%(f_path)s', ['repo_name', 'f_path']);
182 pyroutes.register('repo_files_diff', '/%(repo_name)s/diff/%(f_path)s', ['repo_name', 'f_path']);
182 pyroutes.register('repo_files_diff_2way_redirect', '/%(repo_name)s/diff-2way/%(f_path)s', ['repo_name', 'f_path']);
183 pyroutes.register('repo_files_diff_2way_redirect', '/%(repo_name)s/diff-2way/%(f_path)s', ['repo_name', 'f_path']);
183 pyroutes.register('repo_files', '/%(repo_name)s/files/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
184 pyroutes.register('repo_files', '/%(repo_name)s/files/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
184 pyroutes.register('repo_files:default_path', '/%(repo_name)s/files/%(commit_id)s/', ['repo_name', 'commit_id']);
185 pyroutes.register('repo_files:default_path', '/%(repo_name)s/files/%(commit_id)s/', ['repo_name', 'commit_id']);
185 pyroutes.register('repo_files:default_commit', '/%(repo_name)s/files', ['repo_name']);
186 pyroutes.register('repo_files:default_commit', '/%(repo_name)s/files', ['repo_name']);
186 pyroutes.register('repo_files:rendered', '/%(repo_name)s/render/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
187 pyroutes.register('repo_files:rendered', '/%(repo_name)s/render/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
187 pyroutes.register('repo_files:annotated', '/%(repo_name)s/annotate/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
188 pyroutes.register('repo_files:annotated', '/%(repo_name)s/annotate/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
188 pyroutes.register('repo_files:annotated_previous', '/%(repo_name)s/annotate-previous/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
189 pyroutes.register('repo_files:annotated_previous', '/%(repo_name)s/annotate-previous/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
189 pyroutes.register('repo_nodetree_full', '/%(repo_name)s/nodetree_full/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
190 pyroutes.register('repo_nodetree_full', '/%(repo_name)s/nodetree_full/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
190 pyroutes.register('repo_nodetree_full:default_path', '/%(repo_name)s/nodetree_full/%(commit_id)s/', ['repo_name', 'commit_id']);
191 pyroutes.register('repo_nodetree_full:default_path', '/%(repo_name)s/nodetree_full/%(commit_id)s/', ['repo_name', 'commit_id']);
191 pyroutes.register('repo_files_nodelist', '/%(repo_name)s/nodelist/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
192 pyroutes.register('repo_files_nodelist', '/%(repo_name)s/nodelist/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
192 pyroutes.register('repo_file_raw', '/%(repo_name)s/raw/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
193 pyroutes.register('repo_file_raw', '/%(repo_name)s/raw/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
193 pyroutes.register('repo_file_download', '/%(repo_name)s/download/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
194 pyroutes.register('repo_file_download', '/%(repo_name)s/download/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
194 pyroutes.register('repo_file_download:legacy', '/%(repo_name)s/rawfile/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
195 pyroutes.register('repo_file_download:legacy', '/%(repo_name)s/rawfile/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
195 pyroutes.register('repo_file_history', '/%(repo_name)s/history/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
196 pyroutes.register('repo_file_history', '/%(repo_name)s/history/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
196 pyroutes.register('repo_file_authors', '/%(repo_name)s/authors/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
197 pyroutes.register('repo_file_authors', '/%(repo_name)s/authors/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
197 pyroutes.register('repo_files_remove_file', '/%(repo_name)s/remove_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
198 pyroutes.register('repo_files_remove_file', '/%(repo_name)s/remove_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
198 pyroutes.register('repo_files_delete_file', '/%(repo_name)s/delete_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
199 pyroutes.register('repo_files_delete_file', '/%(repo_name)s/delete_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
199 pyroutes.register('repo_files_edit_file', '/%(repo_name)s/edit_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
200 pyroutes.register('repo_files_edit_file', '/%(repo_name)s/edit_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
200 pyroutes.register('repo_files_update_file', '/%(repo_name)s/update_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
201 pyroutes.register('repo_files_update_file', '/%(repo_name)s/update_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
201 pyroutes.register('repo_files_add_file', '/%(repo_name)s/add_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
202 pyroutes.register('repo_files_add_file', '/%(repo_name)s/add_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
202 pyroutes.register('repo_files_upload_file', '/%(repo_name)s/upload_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
203 pyroutes.register('repo_files_upload_file', '/%(repo_name)s/upload_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
203 pyroutes.register('repo_files_create_file', '/%(repo_name)s/create_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
204 pyroutes.register('repo_files_create_file', '/%(repo_name)s/create_file/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
204 pyroutes.register('repo_refs_data', '/%(repo_name)s/refs-data', ['repo_name']);
205 pyroutes.register('repo_refs_data', '/%(repo_name)s/refs-data', ['repo_name']);
205 pyroutes.register('repo_refs_changelog_data', '/%(repo_name)s/refs-data-changelog', ['repo_name']);
206 pyroutes.register('repo_refs_changelog_data', '/%(repo_name)s/refs-data-changelog', ['repo_name']);
206 pyroutes.register('repo_stats', '/%(repo_name)s/repo_stats/%(commit_id)s', ['repo_name', 'commit_id']);
207 pyroutes.register('repo_stats', '/%(repo_name)s/repo_stats/%(commit_id)s', ['repo_name', 'commit_id']);
207 pyroutes.register('repo_commits', '/%(repo_name)s/commits', ['repo_name']);
208 pyroutes.register('repo_commits', '/%(repo_name)s/commits', ['repo_name']);
208 pyroutes.register('repo_commits_file', '/%(repo_name)s/commits/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
209 pyroutes.register('repo_commits_file', '/%(repo_name)s/commits/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
209 pyroutes.register('repo_commits_elements', '/%(repo_name)s/commits_elements', ['repo_name']);
210 pyroutes.register('repo_commits_elements', '/%(repo_name)s/commits_elements', ['repo_name']);
210 pyroutes.register('repo_commits_elements_file', '/%(repo_name)s/commits_elements/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
211 pyroutes.register('repo_commits_elements_file', '/%(repo_name)s/commits_elements/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
211 pyroutes.register('repo_changelog', '/%(repo_name)s/changelog', ['repo_name']);
212 pyroutes.register('repo_changelog', '/%(repo_name)s/changelog', ['repo_name']);
212 pyroutes.register('repo_changelog_file', '/%(repo_name)s/changelog/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
213 pyroutes.register('repo_changelog_file', '/%(repo_name)s/changelog/%(commit_id)s/%(f_path)s', ['repo_name', 'commit_id', 'f_path']);
213 pyroutes.register('repo_compare_select', '/%(repo_name)s/compare', ['repo_name']);
214 pyroutes.register('repo_compare_select', '/%(repo_name)s/compare', ['repo_name']);
214 pyroutes.register('repo_compare', '/%(repo_name)s/compare/%(source_ref_type)s@%(source_ref)s...%(target_ref_type)s@%(target_ref)s', ['repo_name', 'source_ref_type', 'source_ref', 'target_ref_type', 'target_ref']);
215 pyroutes.register('repo_compare', '/%(repo_name)s/compare/%(source_ref_type)s@%(source_ref)s...%(target_ref_type)s@%(target_ref)s', ['repo_name', 'source_ref_type', 'source_ref', 'target_ref_type', 'target_ref']);
215 pyroutes.register('tags_home', '/%(repo_name)s/tags', ['repo_name']);
216 pyroutes.register('tags_home', '/%(repo_name)s/tags', ['repo_name']);
216 pyroutes.register('branches_home', '/%(repo_name)s/branches', ['repo_name']);
217 pyroutes.register('branches_home', '/%(repo_name)s/branches', ['repo_name']);
217 pyroutes.register('bookmarks_home', '/%(repo_name)s/bookmarks', ['repo_name']);
218 pyroutes.register('bookmarks_home', '/%(repo_name)s/bookmarks', ['repo_name']);
218 pyroutes.register('repo_fork_new', '/%(repo_name)s/fork', ['repo_name']);
219 pyroutes.register('repo_fork_new', '/%(repo_name)s/fork', ['repo_name']);
219 pyroutes.register('repo_fork_create', '/%(repo_name)s/fork/create', ['repo_name']);
220 pyroutes.register('repo_fork_create', '/%(repo_name)s/fork/create', ['repo_name']);
220 pyroutes.register('repo_forks_show_all', '/%(repo_name)s/forks', ['repo_name']);
221 pyroutes.register('repo_forks_show_all', '/%(repo_name)s/forks', ['repo_name']);
221 pyroutes.register('repo_forks_data', '/%(repo_name)s/forks/data', ['repo_name']);
222 pyroutes.register('repo_forks_data', '/%(repo_name)s/forks/data', ['repo_name']);
222 pyroutes.register('pullrequest_show', '/%(repo_name)s/pull-request/%(pull_request_id)s', ['repo_name', 'pull_request_id']);
223 pyroutes.register('pullrequest_show', '/%(repo_name)s/pull-request/%(pull_request_id)s', ['repo_name', 'pull_request_id']);
223 pyroutes.register('pullrequest_show_all', '/%(repo_name)s/pull-request', ['repo_name']);
224 pyroutes.register('pullrequest_show_all', '/%(repo_name)s/pull-request', ['repo_name']);
224 pyroutes.register('pullrequest_show_all_data', '/%(repo_name)s/pull-request-data', ['repo_name']);
225 pyroutes.register('pullrequest_show_all_data', '/%(repo_name)s/pull-request-data', ['repo_name']);
225 pyroutes.register('pullrequest_repo_refs', '/%(repo_name)s/pull-request/refs/%(target_repo_name)s', ['repo_name', 'target_repo_name']);
226 pyroutes.register('pullrequest_repo_refs', '/%(repo_name)s/pull-request/refs/%(target_repo_name)s', ['repo_name', 'target_repo_name']);
226 pyroutes.register('pullrequest_repo_targets', '/%(repo_name)s/pull-request/repo-targets', ['repo_name']);
227 pyroutes.register('pullrequest_repo_targets', '/%(repo_name)s/pull-request/repo-targets', ['repo_name']);
227 pyroutes.register('pullrequest_new', '/%(repo_name)s/pull-request/new', ['repo_name']);
228 pyroutes.register('pullrequest_new', '/%(repo_name)s/pull-request/new', ['repo_name']);
228 pyroutes.register('pullrequest_create', '/%(repo_name)s/pull-request/create', ['repo_name']);
229 pyroutes.register('pullrequest_create', '/%(repo_name)s/pull-request/create', ['repo_name']);
229 pyroutes.register('pullrequest_update', '/%(repo_name)s/pull-request/%(pull_request_id)s/update', ['repo_name', 'pull_request_id']);
230 pyroutes.register('pullrequest_update', '/%(repo_name)s/pull-request/%(pull_request_id)s/update', ['repo_name', 'pull_request_id']);
230 pyroutes.register('pullrequest_merge', '/%(repo_name)s/pull-request/%(pull_request_id)s/merge', ['repo_name', 'pull_request_id']);
231 pyroutes.register('pullrequest_merge', '/%(repo_name)s/pull-request/%(pull_request_id)s/merge', ['repo_name', 'pull_request_id']);
231 pyroutes.register('pullrequest_delete', '/%(repo_name)s/pull-request/%(pull_request_id)s/delete', ['repo_name', 'pull_request_id']);
232 pyroutes.register('pullrequest_delete', '/%(repo_name)s/pull-request/%(pull_request_id)s/delete', ['repo_name', 'pull_request_id']);
232 pyroutes.register('pullrequest_comment_create', '/%(repo_name)s/pull-request/%(pull_request_id)s/comment', ['repo_name', 'pull_request_id']);
233 pyroutes.register('pullrequest_comment_create', '/%(repo_name)s/pull-request/%(pull_request_id)s/comment', ['repo_name', 'pull_request_id']);
233 pyroutes.register('pullrequest_comment_delete', '/%(repo_name)s/pull-request/%(pull_request_id)s/comment/%(comment_id)s/delete', ['repo_name', 'pull_request_id', 'comment_id']);
234 pyroutes.register('pullrequest_comment_delete', '/%(repo_name)s/pull-request/%(pull_request_id)s/comment/%(comment_id)s/delete', ['repo_name', 'pull_request_id', 'comment_id']);
234 pyroutes.register('edit_repo', '/%(repo_name)s/settings', ['repo_name']);
235 pyroutes.register('edit_repo', '/%(repo_name)s/settings', ['repo_name']);
235 pyroutes.register('edit_repo_advanced', '/%(repo_name)s/settings/advanced', ['repo_name']);
236 pyroutes.register('edit_repo_advanced', '/%(repo_name)s/settings/advanced', ['repo_name']);
236 pyroutes.register('edit_repo_advanced_archive', '/%(repo_name)s/settings/advanced/archive', ['repo_name']);
237 pyroutes.register('edit_repo_advanced_archive', '/%(repo_name)s/settings/advanced/archive', ['repo_name']);
237 pyroutes.register('edit_repo_advanced_delete', '/%(repo_name)s/settings/advanced/delete', ['repo_name']);
238 pyroutes.register('edit_repo_advanced_delete', '/%(repo_name)s/settings/advanced/delete', ['repo_name']);
238 pyroutes.register('edit_repo_advanced_locking', '/%(repo_name)s/settings/advanced/locking', ['repo_name']);
239 pyroutes.register('edit_repo_advanced_locking', '/%(repo_name)s/settings/advanced/locking', ['repo_name']);
239 pyroutes.register('edit_repo_advanced_journal', '/%(repo_name)s/settings/advanced/journal', ['repo_name']);
240 pyroutes.register('edit_repo_advanced_journal', '/%(repo_name)s/settings/advanced/journal', ['repo_name']);
240 pyroutes.register('edit_repo_advanced_fork', '/%(repo_name)s/settings/advanced/fork', ['repo_name']);
241 pyroutes.register('edit_repo_advanced_fork', '/%(repo_name)s/settings/advanced/fork', ['repo_name']);
241 pyroutes.register('edit_repo_advanced_hooks', '/%(repo_name)s/settings/advanced/hooks', ['repo_name']);
242 pyroutes.register('edit_repo_advanced_hooks', '/%(repo_name)s/settings/advanced/hooks', ['repo_name']);
242 pyroutes.register('edit_repo_caches', '/%(repo_name)s/settings/caches', ['repo_name']);
243 pyroutes.register('edit_repo_caches', '/%(repo_name)s/settings/caches', ['repo_name']);
243 pyroutes.register('edit_repo_perms', '/%(repo_name)s/settings/permissions', ['repo_name']);
244 pyroutes.register('edit_repo_perms', '/%(repo_name)s/settings/permissions', ['repo_name']);
244 pyroutes.register('edit_repo_perms_set_private', '/%(repo_name)s/settings/permissions/set_private', ['repo_name']);
245 pyroutes.register('edit_repo_perms_set_private', '/%(repo_name)s/settings/permissions/set_private', ['repo_name']);
245 pyroutes.register('edit_repo_maintenance', '/%(repo_name)s/settings/maintenance', ['repo_name']);
246 pyroutes.register('edit_repo_maintenance', '/%(repo_name)s/settings/maintenance', ['repo_name']);
246 pyroutes.register('edit_repo_maintenance_execute', '/%(repo_name)s/settings/maintenance/execute', ['repo_name']);
247 pyroutes.register('edit_repo_maintenance_execute', '/%(repo_name)s/settings/maintenance/execute', ['repo_name']);
247 pyroutes.register('edit_repo_fields', '/%(repo_name)s/settings/fields', ['repo_name']);
248 pyroutes.register('edit_repo_fields', '/%(repo_name)s/settings/fields', ['repo_name']);
248 pyroutes.register('edit_repo_fields_create', '/%(repo_name)s/settings/fields/create', ['repo_name']);
249 pyroutes.register('edit_repo_fields_create', '/%(repo_name)s/settings/fields/create', ['repo_name']);
249 pyroutes.register('edit_repo_fields_delete', '/%(repo_name)s/settings/fields/%(field_id)s/delete', ['repo_name', 'field_id']);
250 pyroutes.register('edit_repo_fields_delete', '/%(repo_name)s/settings/fields/%(field_id)s/delete', ['repo_name', 'field_id']);
250 pyroutes.register('repo_edit_toggle_locking', '/%(repo_name)s/settings/toggle_locking', ['repo_name']);
251 pyroutes.register('repo_edit_toggle_locking', '/%(repo_name)s/settings/toggle_locking', ['repo_name']);
251 pyroutes.register('edit_repo_remote', '/%(repo_name)s/settings/remote', ['repo_name']);
252 pyroutes.register('edit_repo_remote', '/%(repo_name)s/settings/remote', ['repo_name']);
252 pyroutes.register('edit_repo_remote_pull', '/%(repo_name)s/settings/remote/pull', ['repo_name']);
253 pyroutes.register('edit_repo_remote_pull', '/%(repo_name)s/settings/remote/pull', ['repo_name']);
253 pyroutes.register('edit_repo_statistics', '/%(repo_name)s/settings/statistics', ['repo_name']);
254 pyroutes.register('edit_repo_statistics', '/%(repo_name)s/settings/statistics', ['repo_name']);
254 pyroutes.register('edit_repo_statistics_reset', '/%(repo_name)s/settings/statistics/update', ['repo_name']);
255 pyroutes.register('edit_repo_statistics_reset', '/%(repo_name)s/settings/statistics/update', ['repo_name']);
255 pyroutes.register('edit_repo_issuetracker', '/%(repo_name)s/settings/issue_trackers', ['repo_name']);
256 pyroutes.register('edit_repo_issuetracker', '/%(repo_name)s/settings/issue_trackers', ['repo_name']);
256 pyroutes.register('edit_repo_issuetracker_test', '/%(repo_name)s/settings/issue_trackers/test', ['repo_name']);
257 pyroutes.register('edit_repo_issuetracker_test', '/%(repo_name)s/settings/issue_trackers/test', ['repo_name']);
257 pyroutes.register('edit_repo_issuetracker_delete', '/%(repo_name)s/settings/issue_trackers/delete', ['repo_name']);
258 pyroutes.register('edit_repo_issuetracker_delete', '/%(repo_name)s/settings/issue_trackers/delete', ['repo_name']);
258 pyroutes.register('edit_repo_issuetracker_update', '/%(repo_name)s/settings/issue_trackers/update', ['repo_name']);
259 pyroutes.register('edit_repo_issuetracker_update', '/%(repo_name)s/settings/issue_trackers/update', ['repo_name']);
259 pyroutes.register('edit_repo_vcs', '/%(repo_name)s/settings/vcs', ['repo_name']);
260 pyroutes.register('edit_repo_vcs', '/%(repo_name)s/settings/vcs', ['repo_name']);
260 pyroutes.register('edit_repo_vcs_update', '/%(repo_name)s/settings/vcs/update', ['repo_name']);
261 pyroutes.register('edit_repo_vcs_update', '/%(repo_name)s/settings/vcs/update', ['repo_name']);
261 pyroutes.register('edit_repo_vcs_svn_pattern_delete', '/%(repo_name)s/settings/vcs/svn_pattern/delete', ['repo_name']);
262 pyroutes.register('edit_repo_vcs_svn_pattern_delete', '/%(repo_name)s/settings/vcs/svn_pattern/delete', ['repo_name']);
262 pyroutes.register('repo_reviewers', '/%(repo_name)s/settings/review/rules', ['repo_name']);
263 pyroutes.register('repo_reviewers', '/%(repo_name)s/settings/review/rules', ['repo_name']);
263 pyroutes.register('repo_default_reviewers_data', '/%(repo_name)s/settings/review/default-reviewers', ['repo_name']);
264 pyroutes.register('repo_default_reviewers_data', '/%(repo_name)s/settings/review/default-reviewers', ['repo_name']);
264 pyroutes.register('edit_repo_strip', '/%(repo_name)s/settings/strip', ['repo_name']);
265 pyroutes.register('edit_repo_strip', '/%(repo_name)s/settings/strip', ['repo_name']);
265 pyroutes.register('strip_check', '/%(repo_name)s/settings/strip_check', ['repo_name']);
266 pyroutes.register('strip_check', '/%(repo_name)s/settings/strip_check', ['repo_name']);
266 pyroutes.register('strip_execute', '/%(repo_name)s/settings/strip_execute', ['repo_name']);
267 pyroutes.register('strip_execute', '/%(repo_name)s/settings/strip_execute', ['repo_name']);
267 pyroutes.register('edit_repo_audit_logs', '/%(repo_name)s/settings/audit_logs', ['repo_name']);
268 pyroutes.register('edit_repo_audit_logs', '/%(repo_name)s/settings/audit_logs', ['repo_name']);
268 pyroutes.register('rss_feed_home', '/%(repo_name)s/feed-rss', ['repo_name']);
269 pyroutes.register('rss_feed_home', '/%(repo_name)s/feed-rss', ['repo_name']);
269 pyroutes.register('atom_feed_home', '/%(repo_name)s/feed-atom', ['repo_name']);
270 pyroutes.register('atom_feed_home', '/%(repo_name)s/feed-atom', ['repo_name']);
270 pyroutes.register('rss_feed_home_old', '/%(repo_name)s/feed/rss', ['repo_name']);
271 pyroutes.register('rss_feed_home_old', '/%(repo_name)s/feed/rss', ['repo_name']);
271 pyroutes.register('atom_feed_home_old', '/%(repo_name)s/feed/atom', ['repo_name']);
272 pyroutes.register('atom_feed_home_old', '/%(repo_name)s/feed/atom', ['repo_name']);
272 pyroutes.register('repo_summary', '/%(repo_name)s', ['repo_name']);
273 pyroutes.register('repo_summary', '/%(repo_name)s', ['repo_name']);
273 pyroutes.register('repo_summary_slash', '/%(repo_name)s/', ['repo_name']);
274 pyroutes.register('repo_summary_slash', '/%(repo_name)s/', ['repo_name']);
274 pyroutes.register('edit_repo_group', '/%(repo_group_name)s/_edit', ['repo_group_name']);
275 pyroutes.register('edit_repo_group', '/%(repo_group_name)s/_edit', ['repo_group_name']);
275 pyroutes.register('edit_repo_group_advanced', '/%(repo_group_name)s/_settings/advanced', ['repo_group_name']);
276 pyroutes.register('edit_repo_group_advanced', '/%(repo_group_name)s/_settings/advanced', ['repo_group_name']);
276 pyroutes.register('edit_repo_group_advanced_delete', '/%(repo_group_name)s/_settings/advanced/delete', ['repo_group_name']);
277 pyroutes.register('edit_repo_group_advanced_delete', '/%(repo_group_name)s/_settings/advanced/delete', ['repo_group_name']);
277 pyroutes.register('edit_repo_group_perms', '/%(repo_group_name)s/_settings/permissions', ['repo_group_name']);
278 pyroutes.register('edit_repo_group_perms', '/%(repo_group_name)s/_settings/permissions', ['repo_group_name']);
278 pyroutes.register('edit_repo_group_perms_update', '/%(repo_group_name)s/_settings/permissions/update', ['repo_group_name']);
279 pyroutes.register('edit_repo_group_perms_update', '/%(repo_group_name)s/_settings/permissions/update', ['repo_group_name']);
279 pyroutes.register('repo_group_home', '/%(repo_group_name)s', ['repo_group_name']);
280 pyroutes.register('repo_group_home', '/%(repo_group_name)s', ['repo_group_name']);
280 pyroutes.register('repo_group_home_slash', '/%(repo_group_name)s/', ['repo_group_name']);
281 pyroutes.register('repo_group_home_slash', '/%(repo_group_name)s/', ['repo_group_name']);
281 pyroutes.register('user_group_members_data', '/_admin/user_groups/%(user_group_id)s/members', ['user_group_id']);
282 pyroutes.register('user_group_members_data', '/_admin/user_groups/%(user_group_id)s/members', ['user_group_id']);
282 pyroutes.register('edit_user_group_perms_summary', '/_admin/user_groups/%(user_group_id)s/edit/permissions_summary', ['user_group_id']);
283 pyroutes.register('edit_user_group_perms_summary', '/_admin/user_groups/%(user_group_id)s/edit/permissions_summary', ['user_group_id']);
283 pyroutes.register('edit_user_group_perms_summary_json', '/_admin/user_groups/%(user_group_id)s/edit/permissions_summary/json', ['user_group_id']);
284 pyroutes.register('edit_user_group_perms_summary_json', '/_admin/user_groups/%(user_group_id)s/edit/permissions_summary/json', ['user_group_id']);
284 pyroutes.register('edit_user_group', '/_admin/user_groups/%(user_group_id)s/edit', ['user_group_id']);
285 pyroutes.register('edit_user_group', '/_admin/user_groups/%(user_group_id)s/edit', ['user_group_id']);
285 pyroutes.register('user_groups_update', '/_admin/user_groups/%(user_group_id)s/update', ['user_group_id']);
286 pyroutes.register('user_groups_update', '/_admin/user_groups/%(user_group_id)s/update', ['user_group_id']);
286 pyroutes.register('edit_user_group_global_perms', '/_admin/user_groups/%(user_group_id)s/edit/global_permissions', ['user_group_id']);
287 pyroutes.register('edit_user_group_global_perms', '/_admin/user_groups/%(user_group_id)s/edit/global_permissions', ['user_group_id']);
287 pyroutes.register('edit_user_group_global_perms_update', '/_admin/user_groups/%(user_group_id)s/edit/global_permissions/update', ['user_group_id']);
288 pyroutes.register('edit_user_group_global_perms_update', '/_admin/user_groups/%(user_group_id)s/edit/global_permissions/update', ['user_group_id']);
288 pyroutes.register('edit_user_group_perms', '/_admin/user_groups/%(user_group_id)s/edit/permissions', ['user_group_id']);
289 pyroutes.register('edit_user_group_perms', '/_admin/user_groups/%(user_group_id)s/edit/permissions', ['user_group_id']);
289 pyroutes.register('edit_user_group_perms_update', '/_admin/user_groups/%(user_group_id)s/edit/permissions/update', ['user_group_id']);
290 pyroutes.register('edit_user_group_perms_update', '/_admin/user_groups/%(user_group_id)s/edit/permissions/update', ['user_group_id']);
290 pyroutes.register('edit_user_group_advanced', '/_admin/user_groups/%(user_group_id)s/edit/advanced', ['user_group_id']);
291 pyroutes.register('edit_user_group_advanced', '/_admin/user_groups/%(user_group_id)s/edit/advanced', ['user_group_id']);
291 pyroutes.register('edit_user_group_advanced_sync', '/_admin/user_groups/%(user_group_id)s/edit/advanced/sync', ['user_group_id']);
292 pyroutes.register('edit_user_group_advanced_sync', '/_admin/user_groups/%(user_group_id)s/edit/advanced/sync', ['user_group_id']);
292 pyroutes.register('user_groups_delete', '/_admin/user_groups/%(user_group_id)s/delete', ['user_group_id']);
293 pyroutes.register('user_groups_delete', '/_admin/user_groups/%(user_group_id)s/delete', ['user_group_id']);
293 pyroutes.register('search', '/_admin/search', []);
294 pyroutes.register('search', '/_admin/search', []);
294 pyroutes.register('search_repo', '/%(repo_name)s/_search', ['repo_name']);
295 pyroutes.register('search_repo', '/%(repo_name)s/_search', ['repo_name']);
295 pyroutes.register('search_repo_alt', '/%(repo_name)s/search', ['repo_name']);
296 pyroutes.register('search_repo_alt', '/%(repo_name)s/search', ['repo_name']);
296 pyroutes.register('search_repo_group', '/%(repo_group_name)s/_search', ['repo_group_name']);
297 pyroutes.register('search_repo_group', '/%(repo_group_name)s/_search', ['repo_group_name']);
297 pyroutes.register('user_profile', '/_profiles/%(username)s', ['username']);
298 pyroutes.register('user_profile', '/_profiles/%(username)s', ['username']);
298 pyroutes.register('user_group_profile', '/_profile_user_group/%(user_group_name)s', ['user_group_name']);
299 pyroutes.register('user_group_profile', '/_profile_user_group/%(user_group_name)s', ['user_group_name']);
299 pyroutes.register('my_account_profile', '/_admin/my_account/profile', []);
300 pyroutes.register('my_account_profile', '/_admin/my_account/profile', []);
300 pyroutes.register('my_account_edit', '/_admin/my_account/edit', []);
301 pyroutes.register('my_account_edit', '/_admin/my_account/edit', []);
301 pyroutes.register('my_account_update', '/_admin/my_account/update', []);
302 pyroutes.register('my_account_update', '/_admin/my_account/update', []);
302 pyroutes.register('my_account_password', '/_admin/my_account/password', []);
303 pyroutes.register('my_account_password', '/_admin/my_account/password', []);
303 pyroutes.register('my_account_password_update', '/_admin/my_account/password/update', []);
304 pyroutes.register('my_account_password_update', '/_admin/my_account/password/update', []);
304 pyroutes.register('my_account_auth_tokens_delete', '/_admin/my_account/auth_tokens/delete', []);
305 pyroutes.register('my_account_auth_tokens_delete', '/_admin/my_account/auth_tokens/delete', []);
305 pyroutes.register('my_account_ssh_keys', '/_admin/my_account/ssh_keys', []);
306 pyroutes.register('my_account_ssh_keys', '/_admin/my_account/ssh_keys', []);
306 pyroutes.register('my_account_ssh_keys_generate', '/_admin/my_account/ssh_keys/generate', []);
307 pyroutes.register('my_account_ssh_keys_generate', '/_admin/my_account/ssh_keys/generate', []);
307 pyroutes.register('my_account_ssh_keys_add', '/_admin/my_account/ssh_keys/new', []);
308 pyroutes.register('my_account_ssh_keys_add', '/_admin/my_account/ssh_keys/new', []);
308 pyroutes.register('my_account_ssh_keys_delete', '/_admin/my_account/ssh_keys/delete', []);
309 pyroutes.register('my_account_ssh_keys_delete', '/_admin/my_account/ssh_keys/delete', []);
309 pyroutes.register('my_account_user_group_membership', '/_admin/my_account/user_group_membership', []);
310 pyroutes.register('my_account_user_group_membership', '/_admin/my_account/user_group_membership', []);
310 pyroutes.register('my_account_emails', '/_admin/my_account/emails', []);
311 pyroutes.register('my_account_emails', '/_admin/my_account/emails', []);
311 pyroutes.register('my_account_emails_add', '/_admin/my_account/emails/new', []);
312 pyroutes.register('my_account_emails_add', '/_admin/my_account/emails/new', []);
312 pyroutes.register('my_account_emails_delete', '/_admin/my_account/emails/delete', []);
313 pyroutes.register('my_account_emails_delete', '/_admin/my_account/emails/delete', []);
313 pyroutes.register('my_account_repos', '/_admin/my_account/repos', []);
314 pyroutes.register('my_account_repos', '/_admin/my_account/repos', []);
314 pyroutes.register('my_account_watched', '/_admin/my_account/watched', []);
315 pyroutes.register('my_account_watched', '/_admin/my_account/watched', []);
315 pyroutes.register('my_account_bookmarks', '/_admin/my_account/bookmarks', []);
316 pyroutes.register('my_account_bookmarks', '/_admin/my_account/bookmarks', []);
316 pyroutes.register('my_account_bookmarks_update', '/_admin/my_account/bookmarks/update', []);
317 pyroutes.register('my_account_bookmarks_update', '/_admin/my_account/bookmarks/update', []);
317 pyroutes.register('my_account_goto_bookmark', '/_admin/my_account/bookmark/%(bookmark_id)s', ['bookmark_id']);
318 pyroutes.register('my_account_goto_bookmark', '/_admin/my_account/bookmark/%(bookmark_id)s', ['bookmark_id']);
318 pyroutes.register('my_account_perms', '/_admin/my_account/perms', []);
319 pyroutes.register('my_account_perms', '/_admin/my_account/perms', []);
319 pyroutes.register('my_account_notifications', '/_admin/my_account/notifications', []);
320 pyroutes.register('my_account_notifications', '/_admin/my_account/notifications', []);
320 pyroutes.register('my_account_notifications_toggle_visibility', '/_admin/my_account/toggle_visibility', []);
321 pyroutes.register('my_account_notifications_toggle_visibility', '/_admin/my_account/toggle_visibility', []);
321 pyroutes.register('my_account_pullrequests', '/_admin/my_account/pull_requests', []);
322 pyroutes.register('my_account_pullrequests', '/_admin/my_account/pull_requests', []);
322 pyroutes.register('my_account_pullrequests_data', '/_admin/my_account/pull_requests/data', []);
323 pyroutes.register('my_account_pullrequests_data', '/_admin/my_account/pull_requests/data', []);
323 pyroutes.register('notifications_show_all', '/_admin/notifications', []);
324 pyroutes.register('notifications_show_all', '/_admin/notifications', []);
324 pyroutes.register('notifications_mark_all_read', '/_admin/notifications/mark_all_read', []);
325 pyroutes.register('notifications_mark_all_read', '/_admin/notifications/mark_all_read', []);
325 pyroutes.register('notifications_show', '/_admin/notifications/%(notification_id)s', ['notification_id']);
326 pyroutes.register('notifications_show', '/_admin/notifications/%(notification_id)s', ['notification_id']);
326 pyroutes.register('notifications_update', '/_admin/notifications/%(notification_id)s/update', ['notification_id']);
327 pyroutes.register('notifications_update', '/_admin/notifications/%(notification_id)s/update', ['notification_id']);
327 pyroutes.register('notifications_delete', '/_admin/notifications/%(notification_id)s/delete', ['notification_id']);
328 pyroutes.register('notifications_delete', '/_admin/notifications/%(notification_id)s/delete', ['notification_id']);
328 pyroutes.register('my_account_notifications_test_channelstream', '/_admin/my_account/test_channelstream', []);
329 pyroutes.register('my_account_notifications_test_channelstream', '/_admin/my_account/test_channelstream', []);
329 pyroutes.register('gists_show', '/_admin/gists', []);
330 pyroutes.register('gists_show', '/_admin/gists', []);
330 pyroutes.register('gists_new', '/_admin/gists/new', []);
331 pyroutes.register('gists_new', '/_admin/gists/new', []);
331 pyroutes.register('gists_create', '/_admin/gists/create', []);
332 pyroutes.register('gists_create', '/_admin/gists/create', []);
332 pyroutes.register('gist_show', '/_admin/gists/%(gist_id)s', ['gist_id']);
333 pyroutes.register('gist_show', '/_admin/gists/%(gist_id)s', ['gist_id']);
333 pyroutes.register('gist_delete', '/_admin/gists/%(gist_id)s/delete', ['gist_id']);
334 pyroutes.register('gist_delete', '/_admin/gists/%(gist_id)s/delete', ['gist_id']);
334 pyroutes.register('gist_edit', '/_admin/gists/%(gist_id)s/edit', ['gist_id']);
335 pyroutes.register('gist_edit', '/_admin/gists/%(gist_id)s/edit', ['gist_id']);
335 pyroutes.register('gist_edit_check_revision', '/_admin/gists/%(gist_id)s/edit/check_revision', ['gist_id']);
336 pyroutes.register('gist_edit_check_revision', '/_admin/gists/%(gist_id)s/edit/check_revision', ['gist_id']);
336 pyroutes.register('gist_update', '/_admin/gists/%(gist_id)s/update', ['gist_id']);
337 pyroutes.register('gist_update', '/_admin/gists/%(gist_id)s/update', ['gist_id']);
337 pyroutes.register('gist_show_rev', '/_admin/gists/%(gist_id)s/%(revision)s', ['gist_id', 'revision']);
338 pyroutes.register('gist_show_rev', '/_admin/gists/%(gist_id)s/%(revision)s', ['gist_id', 'revision']);
338 pyroutes.register('gist_show_formatted', '/_admin/gists/%(gist_id)s/%(revision)s/%(format)s', ['gist_id', 'revision', 'format']);
339 pyroutes.register('gist_show_formatted', '/_admin/gists/%(gist_id)s/%(revision)s/%(format)s', ['gist_id', 'revision', 'format']);
339 pyroutes.register('gist_show_formatted_path', '/_admin/gists/%(gist_id)s/%(revision)s/%(format)s/%(f_path)s', ['gist_id', 'revision', 'format', 'f_path']);
340 pyroutes.register('gist_show_formatted_path', '/_admin/gists/%(gist_id)s/%(revision)s/%(format)s/%(f_path)s', ['gist_id', 'revision', 'format', 'f_path']);
340 pyroutes.register('debug_style_home', '/_admin/debug_style', []);
341 pyroutes.register('debug_style_home', '/_admin/debug_style', []);
341 pyroutes.register('debug_style_template', '/_admin/debug_style/t/%(t_path)s', ['t_path']);
342 pyroutes.register('debug_style_template', '/_admin/debug_style/t/%(t_path)s', ['t_path']);
342 pyroutes.register('apiv2', '/_admin/api', []);
343 pyroutes.register('apiv2', '/_admin/api', []);
343 pyroutes.register('admin_settings_license', '/_admin/settings/license', []);
344 pyroutes.register('admin_settings_license', '/_admin/settings/license', []);
344 pyroutes.register('admin_settings_license_unlock', '/_admin/settings/license_unlock', []);
345 pyroutes.register('admin_settings_license_unlock', '/_admin/settings/license_unlock', []);
345 pyroutes.register('login', '/_admin/login', []);
346 pyroutes.register('login', '/_admin/login', []);
346 pyroutes.register('register', '/_admin/register', []);
347 pyroutes.register('register', '/_admin/register', []);
347 pyroutes.register('repo_reviewers_review_rule_new', '/%(repo_name)s/settings/review/rules/new', ['repo_name']);
348 pyroutes.register('repo_reviewers_review_rule_new', '/%(repo_name)s/settings/review/rules/new', ['repo_name']);
348 pyroutes.register('repo_reviewers_review_rule_edit', '/%(repo_name)s/settings/review/rules/%(rule_id)s', ['repo_name', 'rule_id']);
349 pyroutes.register('repo_reviewers_review_rule_edit', '/%(repo_name)s/settings/review/rules/%(rule_id)s', ['repo_name', 'rule_id']);
349 pyroutes.register('repo_reviewers_review_rule_delete', '/%(repo_name)s/settings/review/rules/%(rule_id)s/delete', ['repo_name', 'rule_id']);
350 pyroutes.register('repo_reviewers_review_rule_delete', '/%(repo_name)s/settings/review/rules/%(rule_id)s/delete', ['repo_name', 'rule_id']);
350 pyroutes.register('plugin_admin_chat', '/_admin/plugin_admin_chat/%(action)s', ['action']);
351 pyroutes.register('plugin_admin_chat', '/_admin/plugin_admin_chat/%(action)s', ['action']);
351 pyroutes.register('edit_user_auth_tokens', '/_admin/users/%(user_id)s/edit/auth_tokens', ['user_id']);
352 pyroutes.register('edit_user_auth_tokens', '/_admin/users/%(user_id)s/edit/auth_tokens', ['user_id']);
352 pyroutes.register('edit_user_auth_tokens_add', '/_admin/users/%(user_id)s/edit/auth_tokens/new', ['user_id']);
353 pyroutes.register('edit_user_auth_tokens_add', '/_admin/users/%(user_id)s/edit/auth_tokens/new', ['user_id']);
353 pyroutes.register('admin_settings_scheduler_show_tasks', '/_admin/settings/scheduler/_tasks', []);
354 pyroutes.register('admin_settings_scheduler_show_tasks', '/_admin/settings/scheduler/_tasks', []);
354 pyroutes.register('admin_settings_scheduler_show_all', '/_admin/settings/scheduler', []);
355 pyroutes.register('admin_settings_scheduler_show_all', '/_admin/settings/scheduler', []);
355 pyroutes.register('admin_settings_scheduler_new', '/_admin/settings/scheduler/new', []);
356 pyroutes.register('admin_settings_scheduler_new', '/_admin/settings/scheduler/new', []);
356 pyroutes.register('admin_settings_scheduler_create', '/_admin/settings/scheduler/create', []);
357 pyroutes.register('admin_settings_scheduler_create', '/_admin/settings/scheduler/create', []);
357 pyroutes.register('admin_settings_scheduler_edit', '/_admin/settings/scheduler/%(schedule_id)s', ['schedule_id']);
358 pyroutes.register('admin_settings_scheduler_edit', '/_admin/settings/scheduler/%(schedule_id)s', ['schedule_id']);
358 pyroutes.register('admin_settings_scheduler_update', '/_admin/settings/scheduler/%(schedule_id)s/update', ['schedule_id']);
359 pyroutes.register('admin_settings_scheduler_update', '/_admin/settings/scheduler/%(schedule_id)s/update', ['schedule_id']);
359 pyroutes.register('admin_settings_scheduler_delete', '/_admin/settings/scheduler/%(schedule_id)s/delete', ['schedule_id']);
360 pyroutes.register('admin_settings_scheduler_delete', '/_admin/settings/scheduler/%(schedule_id)s/delete', ['schedule_id']);
360 pyroutes.register('admin_settings_scheduler_execute', '/_admin/settings/scheduler/%(schedule_id)s/execute', ['schedule_id']);
361 pyroutes.register('admin_settings_scheduler_execute', '/_admin/settings/scheduler/%(schedule_id)s/execute', ['schedule_id']);
361 pyroutes.register('admin_settings_automation', '/_admin/settings/automation', []);
362 pyroutes.register('admin_settings_automation', '/_admin/settings/automation', []);
362 pyroutes.register('admin_settings_automation_update', '/_admin/settings/automation/%(entry_id)s/update', ['entry_id']);
363 pyroutes.register('admin_settings_automation_update', '/_admin/settings/automation/%(entry_id)s/update', ['entry_id']);
363 pyroutes.register('admin_permissions_branch', '/_admin/permissions/branch', []);
364 pyroutes.register('admin_permissions_branch', '/_admin/permissions/branch', []);
364 pyroutes.register('admin_permissions_branch_update', '/_admin/permissions/branch/update', []);
365 pyroutes.register('admin_permissions_branch_update', '/_admin/permissions/branch/update', []);
365 pyroutes.register('my_account_auth_tokens', '/_admin/my_account/auth_tokens', []);
366 pyroutes.register('my_account_auth_tokens', '/_admin/my_account/auth_tokens', []);
366 pyroutes.register('my_account_auth_tokens_add', '/_admin/my_account/auth_tokens/new', []);
367 pyroutes.register('my_account_auth_tokens_add', '/_admin/my_account/auth_tokens/new', []);
367 pyroutes.register('my_account_external_identity', '/_admin/my_account/external-identity', []);
368 pyroutes.register('my_account_external_identity', '/_admin/my_account/external-identity', []);
368 pyroutes.register('my_account_external_identity_delete', '/_admin/my_account/external-identity/delete', []);
369 pyroutes.register('my_account_external_identity_delete', '/_admin/my_account/external-identity/delete', []);
369 pyroutes.register('repo_artifacts_list', '/%(repo_name)s/artifacts', ['repo_name']);
370 pyroutes.register('repo_artifacts_list', '/%(repo_name)s/artifacts', ['repo_name']);
370 pyroutes.register('repo_artifacts_data', '/%(repo_name)s/artifacts_data', ['repo_name']);
371 pyroutes.register('repo_artifacts_data', '/%(repo_name)s/artifacts_data', ['repo_name']);
371 pyroutes.register('repo_artifacts_new', '/%(repo_name)s/artifacts/new', ['repo_name']);
372 pyroutes.register('repo_artifacts_new', '/%(repo_name)s/artifacts/new', ['repo_name']);
372 pyroutes.register('repo_artifacts_get', '/%(repo_name)s/artifacts/download/%(uid)s', ['repo_name', 'uid']);
373 pyroutes.register('repo_artifacts_get', '/%(repo_name)s/artifacts/download/%(uid)s', ['repo_name', 'uid']);
373 pyroutes.register('repo_artifacts_store', '/%(repo_name)s/artifacts/store', ['repo_name']);
374 pyroutes.register('repo_artifacts_store', '/%(repo_name)s/artifacts/store', ['repo_name']);
374 pyroutes.register('repo_artifacts_info', '/%(repo_name)s/artifacts/info/%(uid)s', ['repo_name', 'uid']);
375 pyroutes.register('repo_artifacts_info', '/%(repo_name)s/artifacts/info/%(uid)s', ['repo_name', 'uid']);
375 pyroutes.register('repo_artifacts_delete', '/%(repo_name)s/artifacts/delete/%(uid)s', ['repo_name', 'uid']);
376 pyroutes.register('repo_artifacts_delete', '/%(repo_name)s/artifacts/delete/%(uid)s', ['repo_name', 'uid']);
376 pyroutes.register('repo_automation', '/%(repo_name)s/settings/automation', ['repo_name']);
377 pyroutes.register('repo_automation', '/%(repo_name)s/settings/automation', ['repo_name']);
377 pyroutes.register('repo_automation_update', '/%(repo_name)s/settings/automation/%(entry_id)s/update', ['repo_name', 'entry_id']);
378 pyroutes.register('repo_automation_update', '/%(repo_name)s/settings/automation/%(entry_id)s/update', ['repo_name', 'entry_id']);
378 pyroutes.register('edit_repo_remote_push', '/%(repo_name)s/settings/remote/push', ['repo_name']);
379 pyroutes.register('edit_repo_remote_push', '/%(repo_name)s/settings/remote/push', ['repo_name']);
379 pyroutes.register('edit_repo_perms_branch', '/%(repo_name)s/settings/branch_permissions', ['repo_name']);
380 pyroutes.register('edit_repo_perms_branch', '/%(repo_name)s/settings/branch_permissions', ['repo_name']);
380 pyroutes.register('edit_repo_perms_branch_delete', '/%(repo_name)s/settings/branch_permissions/%(rule_id)s/delete', ['repo_name', 'rule_id']);
381 pyroutes.register('edit_repo_perms_branch_delete', '/%(repo_name)s/settings/branch_permissions/%(rule_id)s/delete', ['repo_name', 'rule_id']);
381 }
382 }
General Comments 0
You need to be logged in to leave comments. Login now