##// END OF EJS Templates
fix(encryption): rely on default config based strict mode if not explicitly given into function params
super-admin -
r5376:63f7e8c6 default
parent child Browse files
Show More
@@ -1,49 +1,76 b''
1 # Copyright (C) 2011-2023 RhodeCode GmbH
2 #
3 # This program is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU Affero General Public License, version 3
5 # (only), as published by the Free Software Foundation.
6 #
7 # This program is distributed in the hope that it will be useful,
8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 # GNU General Public License for more details.
11 #
12 # You should have received a copy of the GNU Affero General Public License
13 # along with this program. If not, see <http://www.gnu.org/licenses/>.
14 #
15 # This program is dual-licensed. If you wish to learn more about the
16 # RhodeCode Enterprise Edition, including its added features, Support services,
17 # and proprietary license terms, please see https://rhodecode.com/licenses/
18
1 from rhodecode.lib.str_utils import safe_bytes
19 from rhodecode.lib.str_utils import safe_bytes
2 from rhodecode.lib.encrypt import encrypt_data, validate_and_decrypt_data
20 from rhodecode.lib.encrypt import encrypt_data, validate_and_decrypt_data
3 from rhodecode.lib.encrypt2 import Encryptor
21 from rhodecode.lib.encrypt2 import Encryptor
4
22
5 ALLOWED_ALGOS = ['aes', 'fernet']
23 ALLOWED_ALGOS = ['aes', 'fernet']
6
24
7
25
8 def get_default_algo():
26 def get_default_algo():
9 import rhodecode
27 import rhodecode
10 return rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
28 return rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
11
29
30 def get_strict_mode():
31 import rhodecode
32 return rhodecode.ConfigGet().get_bool('rhodecode.encrypted_values.strict') or False
33
12
34
13 def encrypt_value(value: bytes, enc_key: bytes, algo: str = ''):
35 def encrypt_value(value: bytes, enc_key: bytes, algo: str = ''):
14 if not algo:
36 if not algo:
15 # not explicit algo, just use what's set by config
37 # not explicit algo, just use what's set by config
16 algo = get_default_algo()
38 algo = get_default_algo()
17
39
18 if algo not in ALLOWED_ALGOS:
40 if algo not in ALLOWED_ALGOS:
19 ValueError(f'Bad encryption algorithm, should be {ALLOWED_ALGOS}, got: {algo}')
41 ValueError(f'Bad encryption algorithm, should be {ALLOWED_ALGOS}, got: {algo}')
20
42
21 enc_key = safe_bytes(enc_key)
43 enc_key = safe_bytes(enc_key)
22 value = safe_bytes(value)
44 value = safe_bytes(value)
23
45
24 if algo == 'aes':
46 if algo == 'aes':
25 return encrypt_data(value, enc_key=enc_key)
47 return encrypt_data(value, enc_key=enc_key)
26 if algo == 'fernet':
48 if algo == 'fernet':
27 return Encryptor(enc_key).encrypt(value)
49 return Encryptor(enc_key).encrypt(value)
28
50
29 return value
51 return value
30
52
31
53
32 def decrypt_value(value: bytes, enc_key: bytes, algo: str = '', strict_mode: bool = False):
54 def decrypt_value(value: bytes, enc_key: bytes, algo: str = '', strict_mode: bool | None = None):
55
56 if strict_mode is None:
57 # we use config value rather then explicit True/False
58 strict_mode = get_strict_mode()
59
33 enc_key = safe_bytes(enc_key)
60 enc_key = safe_bytes(enc_key)
34 value = safe_bytes(value)
61 value = safe_bytes(value)
35
62
36 if not algo:
63 if not algo:
37 # not explicit algo, just use what's set by config
64 # not explicit algo, just use what's set by config
38 algo = Encryptor.detect_enc_algo(value) or get_default_algo()
65 algo = Encryptor.detect_enc_algo(value) or get_default_algo()
39 if algo not in ALLOWED_ALGOS:
66 if algo not in ALLOWED_ALGOS:
40 ValueError(f'Bad encryption algorithm, should be {ALLOWED_ALGOS}, got: {algo}')
67 ValueError(f'Bad encryption algorithm, should be {ALLOWED_ALGOS}, got: {algo}')
41
68
42 safe = not strict_mode
69 safe = not strict_mode
43
70
44 if algo == 'aes':
71 if algo == 'aes':
45 return validate_and_decrypt_data(value, enc_key, safe=safe)
72 return validate_and_decrypt_data(value, enc_key, safe=safe)
46 if algo == 'fernet':
73 if algo == 'fernet':
47 return Encryptor(enc_key).decrypt(value, safe=safe)
74 return Encryptor(enc_key).decrypt(value, safe=safe)
48
75
49 return value
76 return value
@@ -1,6043 +1,6038 b''
1 # Copyright (C) 2010-2023 RhodeCode GmbH
1 # Copyright (C) 2010-2023 RhodeCode GmbH
2 #
2 #
3 # This program is free software: you can redistribute it and/or modify
3 # This program is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU Affero General Public License, version 3
4 # it under the terms of the GNU Affero General Public License, version 3
5 # (only), as published by the Free Software Foundation.
5 # (only), as published by the Free Software Foundation.
6 #
6 #
7 # This program is distributed in the hope that it will be useful,
7 # This program is distributed in the hope that it will be useful,
8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 # GNU General Public License for more details.
10 # GNU General Public License for more details.
11 #
11 #
12 # You should have received a copy of the GNU Affero General Public License
12 # You should have received a copy of the GNU Affero General Public License
13 # along with this program. If not, see <http://www.gnu.org/licenses/>.
13 # along with this program. If not, see <http://www.gnu.org/licenses/>.
14 #
14 #
15 # This program is dual-licensed. If you wish to learn more about the
15 # This program is dual-licensed. If you wish to learn more about the
16 # RhodeCode Enterprise Edition, including its added features, Support services,
16 # RhodeCode Enterprise Edition, including its added features, Support services,
17 # and proprietary license terms, please see https://rhodecode.com/licenses/
17 # and proprietary license terms, please see https://rhodecode.com/licenses/
18
18
19 """
19 """
20 Database Models for RhodeCode Enterprise
20 Database Models for RhodeCode Enterprise
21 """
21 """
22
22
23 import re
23 import re
24 import os
24 import os
25 import time
25 import time
26 import string
26 import string
27 import logging
27 import logging
28 import datetime
28 import datetime
29 import uuid
29 import uuid
30 import warnings
30 import warnings
31 import ipaddress
31 import ipaddress
32 import functools
32 import functools
33 import traceback
33 import traceback
34 import collections
34 import collections
35
35
36 import pyotp
36 import pyotp
37 from sqlalchemy import (
37 from sqlalchemy import (
38 or_, and_, not_, func, cast, TypeDecorator, event, select,
38 or_, and_, not_, func, cast, TypeDecorator, event, select,
39 true, false, null, union_all,
39 true, false, null, union_all,
40 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
40 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
41 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
41 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
42 Text, Float, PickleType, BigInteger)
42 Text, Float, PickleType, BigInteger)
43 from sqlalchemy.sql.expression import case
43 from sqlalchemy.sql.expression import case
44 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
44 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
45 from sqlalchemy.orm import (
45 from sqlalchemy.orm import (
46 relationship, lazyload, joinedload, class_mapper, validates, aliased, load_only)
46 relationship, lazyload, joinedload, class_mapper, validates, aliased, load_only)
47 from sqlalchemy.ext.declarative import declared_attr
47 from sqlalchemy.ext.declarative import declared_attr
48 from sqlalchemy.ext.hybrid import hybrid_property
48 from sqlalchemy.ext.hybrid import hybrid_property
49 from sqlalchemy.exc import IntegrityError # pragma: no cover
49 from sqlalchemy.exc import IntegrityError # pragma: no cover
50 from sqlalchemy.dialects.mysql import LONGTEXT
50 from sqlalchemy.dialects.mysql import LONGTEXT
51 from zope.cachedescriptors.property import Lazy as LazyProperty
51 from zope.cachedescriptors.property import Lazy as LazyProperty
52 from pyramid.threadlocal import get_current_request
52 from pyramid.threadlocal import get_current_request
53 from webhelpers2.text import remove_formatting
53 from webhelpers2.text import remove_formatting
54
54
55 from rhodecode import ConfigGet
55 from rhodecode import ConfigGet
56 from rhodecode.lib.str_utils import safe_bytes
56 from rhodecode.lib.str_utils import safe_bytes
57 from rhodecode.translation import _
57 from rhodecode.translation import _
58 from rhodecode.lib.vcs import get_vcs_instance, VCSError
58 from rhodecode.lib.vcs import get_vcs_instance, VCSError
59 from rhodecode.lib.vcs.backends.base import (
59 from rhodecode.lib.vcs.backends.base import (
60 EmptyCommit, Reference, unicode_to_reference, reference_to_unicode)
60 EmptyCommit, Reference, unicode_to_reference, reference_to_unicode)
61 from rhodecode.lib.utils2 import (
61 from rhodecode.lib.utils2 import (
62 str2bool, safe_str, get_commit_safe, sha1_safe,
62 str2bool, safe_str, get_commit_safe, sha1_safe,
63 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
63 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
64 glob2re, StrictAttributeDict, cleaned_uri, datetime_to_time)
64 glob2re, StrictAttributeDict, cleaned_uri, datetime_to_time)
65 from rhodecode.lib.jsonalchemy import (
65 from rhodecode.lib.jsonalchemy import (
66 MutationObj, MutationList, JsonType, JsonRaw)
66 MutationObj, MutationList, JsonType, JsonRaw)
67 from rhodecode.lib.hash_utils import sha1
67 from rhodecode.lib.hash_utils import sha1
68 from rhodecode.lib import ext_json
68 from rhodecode.lib import ext_json
69 from rhodecode.lib import enc_utils
69 from rhodecode.lib import enc_utils
70 from rhodecode.lib.ext_json import json, str_json
70 from rhodecode.lib.ext_json import json, str_json
71 from rhodecode.lib.caching_query import FromCache
71 from rhodecode.lib.caching_query import FromCache
72 from rhodecode.lib.exceptions import (
72 from rhodecode.lib.exceptions import (
73 ArtifactMetadataDuplicate, ArtifactMetadataBadValueType)
73 ArtifactMetadataDuplicate, ArtifactMetadataBadValueType)
74 from rhodecode.model.meta import Base, Session
74 from rhodecode.model.meta import Base, Session
75
75
76 URL_SEP = '/'
76 URL_SEP = '/'
77 log = logging.getLogger(__name__)
77 log = logging.getLogger(__name__)
78
78
79 # =============================================================================
79 # =============================================================================
80 # BASE CLASSES
80 # BASE CLASSES
81 # =============================================================================
81 # =============================================================================
82
82
83 # this is propagated from .ini file rhodecode.encrypted_values.secret or
83 # this is propagated from .ini file rhodecode.encrypted_values.secret or
84 # beaker.session.secret if first is not set.
84 # beaker.session.secret if first is not set.
85 # and initialized at environment.py
85 # and initialized at environment.py
86 ENCRYPTION_KEY: bytes = b''
86 ENCRYPTION_KEY: bytes = b''
87
87
88 # used to sort permissions by types, '#' used here is not allowed to be in
88 # used to sort permissions by types, '#' used here is not allowed to be in
89 # usernames, and it's very early in sorted string.printable table.
89 # usernames, and it's very early in sorted string.printable table.
90 PERMISSION_TYPE_SORT = {
90 PERMISSION_TYPE_SORT = {
91 'admin': '####',
91 'admin': '####',
92 'write': '###',
92 'write': '###',
93 'read': '##',
93 'read': '##',
94 'none': '#',
94 'none': '#',
95 }
95 }
96
96
97
97
98 def display_user_sort(obj):
98 def display_user_sort(obj):
99 """
99 """
100 Sort function used to sort permissions in .permissions() function of
100 Sort function used to sort permissions in .permissions() function of
101 Repository, RepoGroup, UserGroup. Also it put the default user in front
101 Repository, RepoGroup, UserGroup. Also it put the default user in front
102 of all other resources
102 of all other resources
103 """
103 """
104
104
105 if obj.username == User.DEFAULT_USER:
105 if obj.username == User.DEFAULT_USER:
106 return '#####'
106 return '#####'
107 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
107 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
108 extra_sort_num = '1' # default
108 extra_sort_num = '1' # default
109
109
110 # NOTE(dan): inactive duplicates goes last
110 # NOTE(dan): inactive duplicates goes last
111 if getattr(obj, 'duplicate_perm', None):
111 if getattr(obj, 'duplicate_perm', None):
112 extra_sort_num = '9'
112 extra_sort_num = '9'
113 return prefix + extra_sort_num + obj.username
113 return prefix + extra_sort_num + obj.username
114
114
115
115
116 def display_user_group_sort(obj):
116 def display_user_group_sort(obj):
117 """
117 """
118 Sort function used to sort permissions in .permissions() function of
118 Sort function used to sort permissions in .permissions() function of
119 Repository, RepoGroup, UserGroup. Also it put the default user in front
119 Repository, RepoGroup, UserGroup. Also it put the default user in front
120 of all other resources
120 of all other resources
121 """
121 """
122
122
123 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
123 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
124 return prefix + obj.users_group_name
124 return prefix + obj.users_group_name
125
125
126
126
127 def _hash_key(k):
127 def _hash_key(k):
128 return sha1_safe(k)
128 return sha1_safe(k)
129
129
130
130
131 def in_filter_generator(qry, items, limit=500):
131 def in_filter_generator(qry, items, limit=500):
132 """
132 """
133 Splits IN() into multiple with OR
133 Splits IN() into multiple with OR
134 e.g.::
134 e.g.::
135 cnt = Repository.query().filter(
135 cnt = Repository.query().filter(
136 or_(
136 or_(
137 *in_filter_generator(Repository.repo_id, range(100000))
137 *in_filter_generator(Repository.repo_id, range(100000))
138 )).count()
138 )).count()
139 """
139 """
140 if not items:
140 if not items:
141 # empty list will cause empty query which might cause security issues
141 # empty list will cause empty query which might cause security issues
142 # this can lead to hidden unpleasant results
142 # this can lead to hidden unpleasant results
143 items = [-1]
143 items = [-1]
144
144
145 parts = []
145 parts = []
146 for chunk in range(0, len(items), limit):
146 for chunk in range(0, len(items), limit):
147 parts.append(
147 parts.append(
148 qry.in_(items[chunk: chunk + limit])
148 qry.in_(items[chunk: chunk + limit])
149 )
149 )
150
150
151 return parts
151 return parts
152
152
153
153
154 base_table_args = {
154 base_table_args = {
155 'extend_existing': True,
155 'extend_existing': True,
156 'mysql_engine': 'InnoDB',
156 'mysql_engine': 'InnoDB',
157 'mysql_charset': 'utf8',
157 'mysql_charset': 'utf8',
158 'sqlite_autoincrement': True
158 'sqlite_autoincrement': True
159 }
159 }
160
160
161
161
162 class EncryptedTextValue(TypeDecorator):
162 class EncryptedTextValue(TypeDecorator):
163 """
163 """
164 Special column for encrypted long text data, use like::
164 Special column for encrypted long text data, use like::
165
165
166 value = Column("encrypted_value", EncryptedValue(), nullable=False)
166 value = Column("encrypted_value", EncryptedValue(), nullable=False)
167
167
168 This column is intelligent so if value is in unencrypted form it return
168 This column is intelligent so if value is in unencrypted form it return
169 unencrypted form, but on save it always encrypts
169 unencrypted form, but on save it always encrypts
170 """
170 """
171 cache_ok = True
171 cache_ok = True
172 impl = Text
172 impl = Text
173
173
174 def process_bind_param(self, value, dialect):
174 def process_bind_param(self, value, dialect):
175 """
175 """
176 Setter for storing value
176 Setter for storing value
177 """
177 """
178 import rhodecode
178 import rhodecode
179 if not value:
179 if not value:
180 return value
180 return value
181
181
182 # protect against double encrypting if values is already encrypted
182 # protect against double encrypting if values is already encrypted
183 if value.startswith('enc$aes$') \
183 if value.startswith('enc$aes$') \
184 or value.startswith('enc$aes_hmac$') \
184 or value.startswith('enc$aes_hmac$') \
185 or value.startswith('enc2$'):
185 or value.startswith('enc2$'):
186 raise ValueError('value needs to be in unencrypted format, '
186 raise ValueError('value needs to be in unencrypted format, '
187 'ie. not starting with enc$ or enc2$')
187 'ie. not starting with enc$ or enc2$')
188
188
189 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
189 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
190 bytes_val = enc_utils.encrypt_value(value, enc_key=ENCRYPTION_KEY, algo=algo)
190 bytes_val = enc_utils.encrypt_value(value, enc_key=ENCRYPTION_KEY, algo=algo)
191 return safe_str(bytes_val)
191 return safe_str(bytes_val)
192
192
193 def process_result_value(self, value, dialect):
193 def process_result_value(self, value, dialect):
194 """
194 """
195 Getter for retrieving value
195 Getter for retrieving value
196 """
196 """
197
197
198 import rhodecode
198 import rhodecode
199 if not value:
199 if not value:
200 return value
200 return value
201
201
202 enc_strict_mode = rhodecode.ConfigGet().get_bool('rhodecode.encrypted_values.strict', missing=True)
202 bytes_val = enc_utils.decrypt_value(value, enc_key=ENCRYPTION_KEY)
203
204 bytes_val = enc_utils.decrypt_value(value, enc_key=ENCRYPTION_KEY, strict_mode=enc_strict_mode)
205
203
206 return safe_str(bytes_val)
204 return safe_str(bytes_val)
207
205
208
206
209 class BaseModel(object):
207 class BaseModel(object):
210 """
208 """
211 Base Model for all classes
209 Base Model for all classes
212 """
210 """
213
211
214 @classmethod
212 @classmethod
215 def _get_keys(cls):
213 def _get_keys(cls):
216 """return column names for this model """
214 """return column names for this model """
217 return class_mapper(cls).c.keys()
215 return class_mapper(cls).c.keys()
218
216
219 def get_dict(self):
217 def get_dict(self):
220 """
218 """
221 return dict with keys and values corresponding
219 return dict with keys and values corresponding
222 to this model data """
220 to this model data """
223
221
224 d = {}
222 d = {}
225 for k in self._get_keys():
223 for k in self._get_keys():
226 d[k] = getattr(self, k)
224 d[k] = getattr(self, k)
227
225
228 # also use __json__() if present to get additional fields
226 # also use __json__() if present to get additional fields
229 _json_attr = getattr(self, '__json__', None)
227 _json_attr = getattr(self, '__json__', None)
230 if _json_attr:
228 if _json_attr:
231 # update with attributes from __json__
229 # update with attributes from __json__
232 if callable(_json_attr):
230 if callable(_json_attr):
233 _json_attr = _json_attr()
231 _json_attr = _json_attr()
234 for k, val in _json_attr.items():
232 for k, val in _json_attr.items():
235 d[k] = val
233 d[k] = val
236 return d
234 return d
237
235
238 def get_appstruct(self):
236 def get_appstruct(self):
239 """return list with keys and values tuples corresponding
237 """return list with keys and values tuples corresponding
240 to this model data """
238 to this model data """
241
239
242 lst = []
240 lst = []
243 for k in self._get_keys():
241 for k in self._get_keys():
244 lst.append((k, getattr(self, k),))
242 lst.append((k, getattr(self, k),))
245 return lst
243 return lst
246
244
247 def populate_obj(self, populate_dict):
245 def populate_obj(self, populate_dict):
248 """populate model with data from given populate_dict"""
246 """populate model with data from given populate_dict"""
249
247
250 for k in self._get_keys():
248 for k in self._get_keys():
251 if k in populate_dict:
249 if k in populate_dict:
252 setattr(self, k, populate_dict[k])
250 setattr(self, k, populate_dict[k])
253
251
254 @classmethod
252 @classmethod
255 def query(cls):
253 def query(cls):
256 return Session().query(cls)
254 return Session().query(cls)
257
255
258 @classmethod
256 @classmethod
259 def select(cls, custom_cls=None):
257 def select(cls, custom_cls=None):
260 """
258 """
261 stmt = cls.select().where(cls.user_id==1)
259 stmt = cls.select().where(cls.user_id==1)
262 # optionally
260 # optionally
263 stmt = cls.select(User.user_id).where(cls.user_id==1)
261 stmt = cls.select(User.user_id).where(cls.user_id==1)
264 result = cls.execute(stmt) | cls.scalars(stmt)
262 result = cls.execute(stmt) | cls.scalars(stmt)
265 """
263 """
266
264
267 if custom_cls:
265 if custom_cls:
268 stmt = select(custom_cls)
266 stmt = select(custom_cls)
269 else:
267 else:
270 stmt = select(cls)
268 stmt = select(cls)
271 return stmt
269 return stmt
272
270
273 @classmethod
271 @classmethod
274 def execute(cls, stmt):
272 def execute(cls, stmt):
275 return Session().execute(stmt)
273 return Session().execute(stmt)
276
274
277 @classmethod
275 @classmethod
278 def scalars(cls, stmt):
276 def scalars(cls, stmt):
279 return Session().scalars(stmt)
277 return Session().scalars(stmt)
280
278
281 @classmethod
279 @classmethod
282 def get(cls, id_):
280 def get(cls, id_):
283 if id_:
281 if id_:
284 return cls.query().get(id_)
282 return cls.query().get(id_)
285
283
286 @classmethod
284 @classmethod
287 def get_or_404(cls, id_):
285 def get_or_404(cls, id_):
288 from pyramid.httpexceptions import HTTPNotFound
286 from pyramid.httpexceptions import HTTPNotFound
289
287
290 try:
288 try:
291 id_ = int(id_)
289 id_ = int(id_)
292 except (TypeError, ValueError):
290 except (TypeError, ValueError):
293 raise HTTPNotFound()
291 raise HTTPNotFound()
294
292
295 res = cls.query().get(id_)
293 res = cls.query().get(id_)
296 if not res:
294 if not res:
297 raise HTTPNotFound()
295 raise HTTPNotFound()
298 return res
296 return res
299
297
300 @classmethod
298 @classmethod
301 def getAll(cls):
299 def getAll(cls):
302 # deprecated and left for backward compatibility
300 # deprecated and left for backward compatibility
303 return cls.get_all()
301 return cls.get_all()
304
302
305 @classmethod
303 @classmethod
306 def get_all(cls):
304 def get_all(cls):
307 return cls.query().all()
305 return cls.query().all()
308
306
309 @classmethod
307 @classmethod
310 def delete(cls, id_):
308 def delete(cls, id_):
311 obj = cls.query().get(id_)
309 obj = cls.query().get(id_)
312 Session().delete(obj)
310 Session().delete(obj)
313
311
314 @classmethod
312 @classmethod
315 def identity_cache(cls, session, attr_name, value):
313 def identity_cache(cls, session, attr_name, value):
316 exist_in_session = []
314 exist_in_session = []
317 for (item_cls, pkey), instance in session.identity_map.items():
315 for (item_cls, pkey), instance in session.identity_map.items():
318 if cls == item_cls and getattr(instance, attr_name) == value:
316 if cls == item_cls and getattr(instance, attr_name) == value:
319 exist_in_session.append(instance)
317 exist_in_session.append(instance)
320 if exist_in_session:
318 if exist_in_session:
321 if len(exist_in_session) == 1:
319 if len(exist_in_session) == 1:
322 return exist_in_session[0]
320 return exist_in_session[0]
323 log.exception(
321 log.exception(
324 'multiple objects with attr %s and '
322 'multiple objects with attr %s and '
325 'value %s found with same name: %r',
323 'value %s found with same name: %r',
326 attr_name, value, exist_in_session)
324 attr_name, value, exist_in_session)
327
325
328 @property
326 @property
329 def cls_name(self):
327 def cls_name(self):
330 return self.__class__.__name__
328 return self.__class__.__name__
331
329
332 def __repr__(self):
330 def __repr__(self):
333 return f'<DB:{self.cls_name}>'
331 return f'<DB:{self.cls_name}>'
334
332
335
333
336 class RhodeCodeSetting(Base, BaseModel):
334 class RhodeCodeSetting(Base, BaseModel):
337 __tablename__ = 'rhodecode_settings'
335 __tablename__ = 'rhodecode_settings'
338 __table_args__ = (
336 __table_args__ = (
339 UniqueConstraint('app_settings_name'),
337 UniqueConstraint('app_settings_name'),
340 base_table_args
338 base_table_args
341 )
339 )
342
340
343 SETTINGS_TYPES = {
341 SETTINGS_TYPES = {
344 'str': safe_str,
342 'str': safe_str,
345 'int': safe_int,
343 'int': safe_int,
346 'unicode': safe_str,
344 'unicode': safe_str,
347 'bool': str2bool,
345 'bool': str2bool,
348 'list': functools.partial(aslist, sep=',')
346 'list': functools.partial(aslist, sep=',')
349 }
347 }
350 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
348 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
351 GLOBAL_CONF_KEY = 'app_settings'
349 GLOBAL_CONF_KEY = 'app_settings'
352
350
353 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
351 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
354 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
352 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
355 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
353 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
356 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
354 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
357
355
358 def __init__(self, key='', val='', type='unicode'):
356 def __init__(self, key='', val='', type='unicode'):
359 self.app_settings_name = key
357 self.app_settings_name = key
360 self.app_settings_type = type
358 self.app_settings_type = type
361 self.app_settings_value = val
359 self.app_settings_value = val
362
360
363 @validates('_app_settings_value')
361 @validates('_app_settings_value')
364 def validate_settings_value(self, key, val):
362 def validate_settings_value(self, key, val):
365 assert type(val) == str
363 assert type(val) == str
366 return val
364 return val
367
365
368 @hybrid_property
366 @hybrid_property
369 def app_settings_value(self):
367 def app_settings_value(self):
370 v = self._app_settings_value
368 v = self._app_settings_value
371 _type = self.app_settings_type
369 _type = self.app_settings_type
372 if _type:
370 if _type:
373 _type = self.app_settings_type.split('.')[0]
371 _type = self.app_settings_type.split('.')[0]
374 # decode the encrypted value
372 # decode the encrypted value
375 if 'encrypted' in self.app_settings_type:
373 if 'encrypted' in self.app_settings_type:
376 cipher = EncryptedTextValue()
374 cipher = EncryptedTextValue()
377 v = safe_str(cipher.process_result_value(v, None))
375 v = safe_str(cipher.process_result_value(v, None))
378
376
379 converter = self.SETTINGS_TYPES.get(_type) or \
377 converter = self.SETTINGS_TYPES.get(_type) or \
380 self.SETTINGS_TYPES['unicode']
378 self.SETTINGS_TYPES['unicode']
381 return converter(v)
379 return converter(v)
382
380
383 @app_settings_value.setter
381 @app_settings_value.setter
384 def app_settings_value(self, val):
382 def app_settings_value(self, val):
385 """
383 """
386 Setter that will always make sure we use unicode in app_settings_value
384 Setter that will always make sure we use unicode in app_settings_value
387
385
388 :param val:
386 :param val:
389 """
387 """
390 val = safe_str(val)
388 val = safe_str(val)
391 # encode the encrypted value
389 # encode the encrypted value
392 if 'encrypted' in self.app_settings_type:
390 if 'encrypted' in self.app_settings_type:
393 cipher = EncryptedTextValue()
391 cipher = EncryptedTextValue()
394 val = safe_str(cipher.process_bind_param(val, None))
392 val = safe_str(cipher.process_bind_param(val, None))
395 self._app_settings_value = val
393 self._app_settings_value = val
396
394
397 @hybrid_property
395 @hybrid_property
398 def app_settings_type(self):
396 def app_settings_type(self):
399 return self._app_settings_type
397 return self._app_settings_type
400
398
401 @app_settings_type.setter
399 @app_settings_type.setter
402 def app_settings_type(self, val):
400 def app_settings_type(self, val):
403 if val.split('.')[0] not in self.SETTINGS_TYPES:
401 if val.split('.')[0] not in self.SETTINGS_TYPES:
404 raise Exception('type must be one of %s got %s'
402 raise Exception('type must be one of %s got %s'
405 % (self.SETTINGS_TYPES.keys(), val))
403 % (self.SETTINGS_TYPES.keys(), val))
406 self._app_settings_type = val
404 self._app_settings_type = val
407
405
408 @classmethod
406 @classmethod
409 def get_by_prefix(cls, prefix):
407 def get_by_prefix(cls, prefix):
410 return RhodeCodeSetting.query()\
408 return RhodeCodeSetting.query()\
411 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
409 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
412 .all()
410 .all()
413
411
414 def __repr__(self):
412 def __repr__(self):
415 return "<%s('%s:%s[%s]')>" % (
413 return "<%s('%s:%s[%s]')>" % (
416 self.cls_name,
414 self.cls_name,
417 self.app_settings_name, self.app_settings_value,
415 self.app_settings_name, self.app_settings_value,
418 self.app_settings_type
416 self.app_settings_type
419 )
417 )
420
418
421
419
422 class RhodeCodeUi(Base, BaseModel):
420 class RhodeCodeUi(Base, BaseModel):
423 __tablename__ = 'rhodecode_ui'
421 __tablename__ = 'rhodecode_ui'
424 __table_args__ = (
422 __table_args__ = (
425 UniqueConstraint('ui_key'),
423 UniqueConstraint('ui_key'),
426 base_table_args
424 base_table_args
427 )
425 )
428 # Sync those values with vcsserver.config.hooks
426 # Sync those values with vcsserver.config.hooks
429
427
430 HOOK_REPO_SIZE = 'changegroup.repo_size'
428 HOOK_REPO_SIZE = 'changegroup.repo_size'
431 # HG
429 # HG
432 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
430 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
433 HOOK_PULL = 'outgoing.pull_logger'
431 HOOK_PULL = 'outgoing.pull_logger'
434 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
432 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
435 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
433 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
436 HOOK_PUSH = 'changegroup.push_logger'
434 HOOK_PUSH = 'changegroup.push_logger'
437 HOOK_PUSH_KEY = 'pushkey.key_push'
435 HOOK_PUSH_KEY = 'pushkey.key_push'
438
436
439 HOOKS_BUILTIN = [
437 HOOKS_BUILTIN = [
440 HOOK_PRE_PULL,
438 HOOK_PRE_PULL,
441 HOOK_PULL,
439 HOOK_PULL,
442 HOOK_PRE_PUSH,
440 HOOK_PRE_PUSH,
443 HOOK_PRETX_PUSH,
441 HOOK_PRETX_PUSH,
444 HOOK_PUSH,
442 HOOK_PUSH,
445 HOOK_PUSH_KEY,
443 HOOK_PUSH_KEY,
446 ]
444 ]
447
445
448 # TODO: johbo: Unify way how hooks are configured for git and hg,
446 # TODO: johbo: Unify way how hooks are configured for git and hg,
449 # git part is currently hardcoded.
447 # git part is currently hardcoded.
450
448
451 # SVN PATTERNS
449 # SVN PATTERNS
452 SVN_BRANCH_ID = 'vcs_svn_branch'
450 SVN_BRANCH_ID = 'vcs_svn_branch'
453 SVN_TAG_ID = 'vcs_svn_tag'
451 SVN_TAG_ID = 'vcs_svn_tag'
454
452
455 ui_id = Column(
453 ui_id = Column(
456 "ui_id", Integer(), nullable=False, unique=True, default=None,
454 "ui_id", Integer(), nullable=False, unique=True, default=None,
457 primary_key=True)
455 primary_key=True)
458 ui_section = Column(
456 ui_section = Column(
459 "ui_section", String(255), nullable=True, unique=None, default=None)
457 "ui_section", String(255), nullable=True, unique=None, default=None)
460 ui_key = Column(
458 ui_key = Column(
461 "ui_key", String(255), nullable=True, unique=None, default=None)
459 "ui_key", String(255), nullable=True, unique=None, default=None)
462 ui_value = Column(
460 ui_value = Column(
463 "ui_value", String(255), nullable=True, unique=None, default=None)
461 "ui_value", String(255), nullable=True, unique=None, default=None)
464 ui_active = Column(
462 ui_active = Column(
465 "ui_active", Boolean(), nullable=True, unique=None, default=True)
463 "ui_active", Boolean(), nullable=True, unique=None, default=True)
466
464
467 def __repr__(self):
465 def __repr__(self):
468 return '<%s[%s]%s=>%s]>' % (self.cls_name, self.ui_section,
466 return '<%s[%s]%s=>%s]>' % (self.cls_name, self.ui_section,
469 self.ui_key, self.ui_value)
467 self.ui_key, self.ui_value)
470
468
471
469
472 class RepoRhodeCodeSetting(Base, BaseModel):
470 class RepoRhodeCodeSetting(Base, BaseModel):
473 __tablename__ = 'repo_rhodecode_settings'
471 __tablename__ = 'repo_rhodecode_settings'
474 __table_args__ = (
472 __table_args__ = (
475 UniqueConstraint(
473 UniqueConstraint(
476 'app_settings_name', 'repository_id',
474 'app_settings_name', 'repository_id',
477 name='uq_repo_rhodecode_setting_name_repo_id'),
475 name='uq_repo_rhodecode_setting_name_repo_id'),
478 base_table_args
476 base_table_args
479 )
477 )
480
478
481 repository_id = Column(
479 repository_id = Column(
482 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
480 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
483 nullable=False)
481 nullable=False)
484 app_settings_id = Column(
482 app_settings_id = Column(
485 "app_settings_id", Integer(), nullable=False, unique=True,
483 "app_settings_id", Integer(), nullable=False, unique=True,
486 default=None, primary_key=True)
484 default=None, primary_key=True)
487 app_settings_name = Column(
485 app_settings_name = Column(
488 "app_settings_name", String(255), nullable=True, unique=None,
486 "app_settings_name", String(255), nullable=True, unique=None,
489 default=None)
487 default=None)
490 _app_settings_value = Column(
488 _app_settings_value = Column(
491 "app_settings_value", String(4096), nullable=True, unique=None,
489 "app_settings_value", String(4096), nullable=True, unique=None,
492 default=None)
490 default=None)
493 _app_settings_type = Column(
491 _app_settings_type = Column(
494 "app_settings_type", String(255), nullable=True, unique=None,
492 "app_settings_type", String(255), nullable=True, unique=None,
495 default=None)
493 default=None)
496
494
497 repository = relationship('Repository', viewonly=True)
495 repository = relationship('Repository', viewonly=True)
498
496
499 def __init__(self, repository_id, key='', val='', type='unicode'):
497 def __init__(self, repository_id, key='', val='', type='unicode'):
500 self.repository_id = repository_id
498 self.repository_id = repository_id
501 self.app_settings_name = key
499 self.app_settings_name = key
502 self.app_settings_type = type
500 self.app_settings_type = type
503 self.app_settings_value = val
501 self.app_settings_value = val
504
502
505 @validates('_app_settings_value')
503 @validates('_app_settings_value')
506 def validate_settings_value(self, key, val):
504 def validate_settings_value(self, key, val):
507 assert type(val) == str
505 assert type(val) == str
508 return val
506 return val
509
507
510 @hybrid_property
508 @hybrid_property
511 def app_settings_value(self):
509 def app_settings_value(self):
512 v = self._app_settings_value
510 v = self._app_settings_value
513 type_ = self.app_settings_type
511 type_ = self.app_settings_type
514 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
512 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
515 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
513 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
516 return converter(v)
514 return converter(v)
517
515
518 @app_settings_value.setter
516 @app_settings_value.setter
519 def app_settings_value(self, val):
517 def app_settings_value(self, val):
520 """
518 """
521 Setter that will always make sure we use unicode in app_settings_value
519 Setter that will always make sure we use unicode in app_settings_value
522
520
523 :param val:
521 :param val:
524 """
522 """
525 self._app_settings_value = safe_str(val)
523 self._app_settings_value = safe_str(val)
526
524
527 @hybrid_property
525 @hybrid_property
528 def app_settings_type(self):
526 def app_settings_type(self):
529 return self._app_settings_type
527 return self._app_settings_type
530
528
531 @app_settings_type.setter
529 @app_settings_type.setter
532 def app_settings_type(self, val):
530 def app_settings_type(self, val):
533 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
531 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
534 if val not in SETTINGS_TYPES:
532 if val not in SETTINGS_TYPES:
535 raise Exception('type must be one of %s got %s'
533 raise Exception('type must be one of %s got %s'
536 % (SETTINGS_TYPES.keys(), val))
534 % (SETTINGS_TYPES.keys(), val))
537 self._app_settings_type = val
535 self._app_settings_type = val
538
536
539 def __repr__(self):
537 def __repr__(self):
540 return "<%s('%s:%s:%s[%s]')>" % (
538 return "<%s('%s:%s:%s[%s]')>" % (
541 self.cls_name, self.repository.repo_name,
539 self.cls_name, self.repository.repo_name,
542 self.app_settings_name, self.app_settings_value,
540 self.app_settings_name, self.app_settings_value,
543 self.app_settings_type
541 self.app_settings_type
544 )
542 )
545
543
546
544
547 class RepoRhodeCodeUi(Base, BaseModel):
545 class RepoRhodeCodeUi(Base, BaseModel):
548 __tablename__ = 'repo_rhodecode_ui'
546 __tablename__ = 'repo_rhodecode_ui'
549 __table_args__ = (
547 __table_args__ = (
550 UniqueConstraint(
548 UniqueConstraint(
551 'repository_id', 'ui_section', 'ui_key',
549 'repository_id', 'ui_section', 'ui_key',
552 name='uq_repo_rhodecode_ui_repository_id_section_key'),
550 name='uq_repo_rhodecode_ui_repository_id_section_key'),
553 base_table_args
551 base_table_args
554 )
552 )
555
553
556 repository_id = Column(
554 repository_id = Column(
557 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
555 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
558 nullable=False)
556 nullable=False)
559 ui_id = Column(
557 ui_id = Column(
560 "ui_id", Integer(), nullable=False, unique=True, default=None,
558 "ui_id", Integer(), nullable=False, unique=True, default=None,
561 primary_key=True)
559 primary_key=True)
562 ui_section = Column(
560 ui_section = Column(
563 "ui_section", String(255), nullable=True, unique=None, default=None)
561 "ui_section", String(255), nullable=True, unique=None, default=None)
564 ui_key = Column(
562 ui_key = Column(
565 "ui_key", String(255), nullable=True, unique=None, default=None)
563 "ui_key", String(255), nullable=True, unique=None, default=None)
566 ui_value = Column(
564 ui_value = Column(
567 "ui_value", String(255), nullable=True, unique=None, default=None)
565 "ui_value", String(255), nullable=True, unique=None, default=None)
568 ui_active = Column(
566 ui_active = Column(
569 "ui_active", Boolean(), nullable=True, unique=None, default=True)
567 "ui_active", Boolean(), nullable=True, unique=None, default=True)
570
568
571 repository = relationship('Repository', viewonly=True)
569 repository = relationship('Repository', viewonly=True)
572
570
573 def __repr__(self):
571 def __repr__(self):
574 return '<%s[%s:%s]%s=>%s]>' % (
572 return '<%s[%s:%s]%s=>%s]>' % (
575 self.cls_name, self.repository.repo_name,
573 self.cls_name, self.repository.repo_name,
576 self.ui_section, self.ui_key, self.ui_value)
574 self.ui_section, self.ui_key, self.ui_value)
577
575
578
576
579 class User(Base, BaseModel):
577 class User(Base, BaseModel):
580 __tablename__ = 'users'
578 __tablename__ = 'users'
581 __table_args__ = (
579 __table_args__ = (
582 UniqueConstraint('username'), UniqueConstraint('email'),
580 UniqueConstraint('username'), UniqueConstraint('email'),
583 Index('u_username_idx', 'username'),
581 Index('u_username_idx', 'username'),
584 Index('u_email_idx', 'email'),
582 Index('u_email_idx', 'email'),
585 base_table_args
583 base_table_args
586 )
584 )
587
585
588 DEFAULT_USER = 'default'
586 DEFAULT_USER = 'default'
589 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
587 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
590 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
588 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
591 RECOVERY_CODES_COUNT = 10
589 RECOVERY_CODES_COUNT = 10
592
590
593 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
591 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
594 username = Column("username", String(255), nullable=True, unique=None, default=None)
592 username = Column("username", String(255), nullable=True, unique=None, default=None)
595 password = Column("password", String(255), nullable=True, unique=None, default=None)
593 password = Column("password", String(255), nullable=True, unique=None, default=None)
596 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
594 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
597 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
595 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
598 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
596 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
599 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
597 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
600 _email = Column("email", String(255), nullable=True, unique=None, default=None)
598 _email = Column("email", String(255), nullable=True, unique=None, default=None)
601 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
599 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
602 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
600 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
603 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
601 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
604
602
605 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
603 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
606 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
604 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
607 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
605 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
608 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
606 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
609 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
607 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
610 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
608 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
611
609
612 user_log = relationship('UserLog', back_populates='user')
610 user_log = relationship('UserLog', back_populates='user')
613 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all, delete-orphan')
611 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all, delete-orphan')
614
612
615 repositories = relationship('Repository', back_populates='user')
613 repositories = relationship('Repository', back_populates='user')
616 repository_groups = relationship('RepoGroup', back_populates='user')
614 repository_groups = relationship('RepoGroup', back_populates='user')
617 user_groups = relationship('UserGroup', back_populates='user')
615 user_groups = relationship('UserGroup', back_populates='user')
618
616
619 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all', back_populates='follows_user')
617 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all', back_populates='follows_user')
620 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all', back_populates='user')
618 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all', back_populates='user')
621
619
622 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all, delete-orphan')
620 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all, delete-orphan')
623 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan', back_populates='user')
621 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan', back_populates='user')
624 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan', back_populates='user')
622 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan', back_populates='user')
625
623
626 group_member = relationship('UserGroupMember', cascade='all', back_populates='user')
624 group_member = relationship('UserGroupMember', cascade='all', back_populates='user')
627
625
628 notifications = relationship('UserNotification', cascade='all', back_populates='user')
626 notifications = relationship('UserNotification', cascade='all', back_populates='user')
629 # notifications assigned to this user
627 # notifications assigned to this user
630 user_created_notifications = relationship('Notification', cascade='all', back_populates='created_by_user')
628 user_created_notifications = relationship('Notification', cascade='all', back_populates='created_by_user')
631 # comments created by this user
629 # comments created by this user
632 user_comments = relationship('ChangesetComment', cascade='all', back_populates='author')
630 user_comments = relationship('ChangesetComment', cascade='all', back_populates='author')
633 # user profile extra info
631 # user profile extra info
634 user_emails = relationship('UserEmailMap', cascade='all', back_populates='user')
632 user_emails = relationship('UserEmailMap', cascade='all', back_populates='user')
635 user_ip_map = relationship('UserIpMap', cascade='all', back_populates='user')
633 user_ip_map = relationship('UserIpMap', cascade='all', back_populates='user')
636 user_auth_tokens = relationship('UserApiKeys', cascade='all', back_populates='user')
634 user_auth_tokens = relationship('UserApiKeys', cascade='all', back_populates='user')
637 user_ssh_keys = relationship('UserSshKeys', cascade='all', back_populates='user')
635 user_ssh_keys = relationship('UserSshKeys', cascade='all', back_populates='user')
638
636
639 # gists
637 # gists
640 user_gists = relationship('Gist', cascade='all', back_populates='owner')
638 user_gists = relationship('Gist', cascade='all', back_populates='owner')
641 # user pull requests
639 # user pull requests
642 user_pull_requests = relationship('PullRequest', cascade='all', back_populates='author')
640 user_pull_requests = relationship('PullRequest', cascade='all', back_populates='author')
643
641
644 # external identities
642 # external identities
645 external_identities = relationship('ExternalIdentity', primaryjoin="User.user_id==ExternalIdentity.local_user_id", cascade='all')
643 external_identities = relationship('ExternalIdentity', primaryjoin="User.user_id==ExternalIdentity.local_user_id", cascade='all')
646 # review rules
644 # review rules
647 user_review_rules = relationship('RepoReviewRuleUser', cascade='all', back_populates='user')
645 user_review_rules = relationship('RepoReviewRuleUser', cascade='all', back_populates='user')
648
646
649 # artifacts owned
647 # artifacts owned
650 artifacts = relationship('FileStore', primaryjoin='FileStore.user_id==User.user_id', back_populates='upload_user')
648 artifacts = relationship('FileStore', primaryjoin='FileStore.user_id==User.user_id', back_populates='upload_user')
651
649
652 # no cascade, set NULL
650 # no cascade, set NULL
653 scope_artifacts = relationship('FileStore', primaryjoin='FileStore.scope_user_id==User.user_id', cascade='', back_populates='user')
651 scope_artifacts = relationship('FileStore', primaryjoin='FileStore.scope_user_id==User.user_id', cascade='', back_populates='user')
654
652
655 def __repr__(self):
653 def __repr__(self):
656 return f"<{self.cls_name}('id={self.user_id}, username={self.username}')>"
654 return f"<{self.cls_name}('id={self.user_id}, username={self.username}')>"
657
655
658 @hybrid_property
656 @hybrid_property
659 def email(self):
657 def email(self):
660 return self._email
658 return self._email
661
659
662 @email.setter
660 @email.setter
663 def email(self, val):
661 def email(self, val):
664 self._email = val.lower() if val else None
662 self._email = val.lower() if val else None
665
663
666 @hybrid_property
664 @hybrid_property
667 def first_name(self):
665 def first_name(self):
668 from rhodecode.lib import helpers as h
666 from rhodecode.lib import helpers as h
669 if self.name:
667 if self.name:
670 return h.escape(self.name)
668 return h.escape(self.name)
671 return self.name
669 return self.name
672
670
673 @hybrid_property
671 @hybrid_property
674 def last_name(self):
672 def last_name(self):
675 from rhodecode.lib import helpers as h
673 from rhodecode.lib import helpers as h
676 if self.lastname:
674 if self.lastname:
677 return h.escape(self.lastname)
675 return h.escape(self.lastname)
678 return self.lastname
676 return self.lastname
679
677
680 @hybrid_property
678 @hybrid_property
681 def api_key(self):
679 def api_key(self):
682 """
680 """
683 Fetch if exist an auth-token with role ALL connected to this user
681 Fetch if exist an auth-token with role ALL connected to this user
684 """
682 """
685 user_auth_token = UserApiKeys.query()\
683 user_auth_token = UserApiKeys.query()\
686 .filter(UserApiKeys.user_id == self.user_id)\
684 .filter(UserApiKeys.user_id == self.user_id)\
687 .filter(or_(UserApiKeys.expires == -1,
685 .filter(or_(UserApiKeys.expires == -1,
688 UserApiKeys.expires >= time.time()))\
686 UserApiKeys.expires >= time.time()))\
689 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
687 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
690 if user_auth_token:
688 if user_auth_token:
691 user_auth_token = user_auth_token.api_key
689 user_auth_token = user_auth_token.api_key
692
690
693 return user_auth_token
691 return user_auth_token
694
692
695 @api_key.setter
693 @api_key.setter
696 def api_key(self, val):
694 def api_key(self, val):
697 # don't allow to set API key this is deprecated for now
695 # don't allow to set API key this is deprecated for now
698 self._api_key = None
696 self._api_key = None
699
697
700 @property
698 @property
701 def reviewer_pull_requests(self):
699 def reviewer_pull_requests(self):
702 return PullRequestReviewers.query() \
700 return PullRequestReviewers.query() \
703 .options(joinedload(PullRequestReviewers.pull_request)) \
701 .options(joinedload(PullRequestReviewers.pull_request)) \
704 .filter(PullRequestReviewers.user_id == self.user_id) \
702 .filter(PullRequestReviewers.user_id == self.user_id) \
705 .all()
703 .all()
706
704
707 @property
705 @property
708 def firstname(self):
706 def firstname(self):
709 # alias for future
707 # alias for future
710 return self.name
708 return self.name
711
709
712 @property
710 @property
713 def emails(self):
711 def emails(self):
714 other = UserEmailMap.query()\
712 other = UserEmailMap.query()\
715 .filter(UserEmailMap.user == self) \
713 .filter(UserEmailMap.user == self) \
716 .order_by(UserEmailMap.email_id.asc()) \
714 .order_by(UserEmailMap.email_id.asc()) \
717 .all()
715 .all()
718 return [self.email] + [x.email for x in other]
716 return [self.email] + [x.email for x in other]
719
717
720 def emails_cached(self):
718 def emails_cached(self):
721 emails = []
719 emails = []
722 if self.user_id != self.get_default_user_id():
720 if self.user_id != self.get_default_user_id():
723 emails = UserEmailMap.query()\
721 emails = UserEmailMap.query()\
724 .filter(UserEmailMap.user == self) \
722 .filter(UserEmailMap.user == self) \
725 .order_by(UserEmailMap.email_id.asc())
723 .order_by(UserEmailMap.email_id.asc())
726
724
727 emails = emails.options(
725 emails = emails.options(
728 FromCache("sql_cache_short", f"get_user_{self.user_id}_emails")
726 FromCache("sql_cache_short", f"get_user_{self.user_id}_emails")
729 )
727 )
730
728
731 return [self.email] + [x.email for x in emails]
729 return [self.email] + [x.email for x in emails]
732
730
733 @property
731 @property
734 def auth_tokens(self):
732 def auth_tokens(self):
735 auth_tokens = self.get_auth_tokens()
733 auth_tokens = self.get_auth_tokens()
736 return [x.api_key for x in auth_tokens]
734 return [x.api_key for x in auth_tokens]
737
735
738 def get_auth_tokens(self):
736 def get_auth_tokens(self):
739 return UserApiKeys.query()\
737 return UserApiKeys.query()\
740 .filter(UserApiKeys.user == self)\
738 .filter(UserApiKeys.user == self)\
741 .order_by(UserApiKeys.user_api_key_id.asc())\
739 .order_by(UserApiKeys.user_api_key_id.asc())\
742 .all()
740 .all()
743
741
744 @LazyProperty
742 @LazyProperty
745 def feed_token(self):
743 def feed_token(self):
746 return self.get_feed_token()
744 return self.get_feed_token()
747
745
748 def get_feed_token(self, cache=True):
746 def get_feed_token(self, cache=True):
749 feed_tokens = UserApiKeys.query()\
747 feed_tokens = UserApiKeys.query()\
750 .filter(UserApiKeys.user == self)\
748 .filter(UserApiKeys.user == self)\
751 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
749 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
752 if cache:
750 if cache:
753 feed_tokens = feed_tokens.options(
751 feed_tokens = feed_tokens.options(
754 FromCache("sql_cache_short", f"get_user_feed_token_{self.user_id}"))
752 FromCache("sql_cache_short", f"get_user_feed_token_{self.user_id}"))
755
753
756 feed_tokens = feed_tokens.all()
754 feed_tokens = feed_tokens.all()
757 if feed_tokens:
755 if feed_tokens:
758 return feed_tokens[0].api_key
756 return feed_tokens[0].api_key
759 return 'NO_FEED_TOKEN_AVAILABLE'
757 return 'NO_FEED_TOKEN_AVAILABLE'
760
758
761 @LazyProperty
759 @LazyProperty
762 def artifact_token(self):
760 def artifact_token(self):
763 return self.get_artifact_token()
761 return self.get_artifact_token()
764
762
765 def get_artifact_token(self, cache=True):
763 def get_artifact_token(self, cache=True):
766 artifacts_tokens = UserApiKeys.query()\
764 artifacts_tokens = UserApiKeys.query()\
767 .filter(UserApiKeys.user == self) \
765 .filter(UserApiKeys.user == self) \
768 .filter(or_(UserApiKeys.expires == -1,
766 .filter(or_(UserApiKeys.expires == -1,
769 UserApiKeys.expires >= time.time())) \
767 UserApiKeys.expires >= time.time())) \
770 .filter(UserApiKeys.role == UserApiKeys.ROLE_ARTIFACT_DOWNLOAD)
768 .filter(UserApiKeys.role == UserApiKeys.ROLE_ARTIFACT_DOWNLOAD)
771
769
772 if cache:
770 if cache:
773 artifacts_tokens = artifacts_tokens.options(
771 artifacts_tokens = artifacts_tokens.options(
774 FromCache("sql_cache_short", f"get_user_artifact_token_{self.user_id}"))
772 FromCache("sql_cache_short", f"get_user_artifact_token_{self.user_id}"))
775
773
776 artifacts_tokens = artifacts_tokens.all()
774 artifacts_tokens = artifacts_tokens.all()
777 if artifacts_tokens:
775 if artifacts_tokens:
778 return artifacts_tokens[0].api_key
776 return artifacts_tokens[0].api_key
779 return 'NO_ARTIFACT_TOKEN_AVAILABLE'
777 return 'NO_ARTIFACT_TOKEN_AVAILABLE'
780
778
781 def get_or_create_artifact_token(self):
779 def get_or_create_artifact_token(self):
782 artifacts_tokens = UserApiKeys.query()\
780 artifacts_tokens = UserApiKeys.query()\
783 .filter(UserApiKeys.user == self) \
781 .filter(UserApiKeys.user == self) \
784 .filter(or_(UserApiKeys.expires == -1,
782 .filter(or_(UserApiKeys.expires == -1,
785 UserApiKeys.expires >= time.time())) \
783 UserApiKeys.expires >= time.time())) \
786 .filter(UserApiKeys.role == UserApiKeys.ROLE_ARTIFACT_DOWNLOAD)
784 .filter(UserApiKeys.role == UserApiKeys.ROLE_ARTIFACT_DOWNLOAD)
787
785
788 artifacts_tokens = artifacts_tokens.all()
786 artifacts_tokens = artifacts_tokens.all()
789 if artifacts_tokens:
787 if artifacts_tokens:
790 return artifacts_tokens[0].api_key
788 return artifacts_tokens[0].api_key
791 else:
789 else:
792 from rhodecode.model.auth_token import AuthTokenModel
790 from rhodecode.model.auth_token import AuthTokenModel
793 artifact_token = AuthTokenModel().create(
791 artifact_token = AuthTokenModel().create(
794 self, 'auto-generated-artifact-token',
792 self, 'auto-generated-artifact-token',
795 lifetime=-1, role=UserApiKeys.ROLE_ARTIFACT_DOWNLOAD)
793 lifetime=-1, role=UserApiKeys.ROLE_ARTIFACT_DOWNLOAD)
796 Session.commit()
794 Session.commit()
797 return artifact_token.api_key
795 return artifact_token.api_key
798
796
799 def is_totp_valid(self, received_code, secret):
797 def is_totp_valid(self, received_code, secret):
800 totp = pyotp.TOTP(secret)
798 totp = pyotp.TOTP(secret)
801 return totp.verify(received_code)
799 return totp.verify(received_code)
802
800
803 def is_2fa_recovery_code_valid(self, received_code, secret):
801 def is_2fa_recovery_code_valid(self, received_code, secret):
804 encrypted_recovery_codes = self.user_data.get('recovery_codes_2fa', [])
802 encrypted_recovery_codes = self.user_data.get('recovery_codes_2fa', [])
805 recovery_codes = self.get_2fa_recovery_codes()
803 recovery_codes = self.get_2fa_recovery_codes()
806 if received_code in recovery_codes:
804 if received_code in recovery_codes:
807 encrypted_recovery_codes.pop(recovery_codes.index(received_code))
805 encrypted_recovery_codes.pop(recovery_codes.index(received_code))
808 self.update_userdata(recovery_codes_2fa=encrypted_recovery_codes)
806 self.update_userdata(recovery_codes_2fa=encrypted_recovery_codes)
809 return True
807 return True
810 return False
808 return False
811
809
812 @hybrid_property
810 @hybrid_property
813 def has_forced_2fa(self):
811 def has_forced_2fa(self):
814 """
812 """
815 Checks if 2fa was forced for ALL users (including current one)
813 Checks if 2fa was forced for ALL users (including current one)
816 """
814 """
817 from rhodecode.model.settings import SettingsModel
815 from rhodecode.model.settings import SettingsModel
818 # So now we're supporting only auth_rhodecode_global_2f
816 # So now we're supporting only auth_rhodecode_global_2f
819 if value := SettingsModel().get_setting_by_name('auth_rhodecode_global_2fa'):
817 if value := SettingsModel().get_setting_by_name('auth_rhodecode_global_2fa'):
820 return value.app_settings_value
818 return value.app_settings_value
821 return False
819 return False
822
820
823 @hybrid_property
821 @hybrid_property
824 def has_enabled_2fa(self):
822 def has_enabled_2fa(self):
825 """
823 """
826 Checks if user enabled 2fa
824 Checks if user enabled 2fa
827 """
825 """
828 if value := self.has_forced_2fa:
826 if value := self.has_forced_2fa:
829 return value
827 return value
830 return self.user_data.get('enabled_2fa', False)
828 return self.user_data.get('enabled_2fa', False)
831
829
832 @has_enabled_2fa.setter
830 @has_enabled_2fa.setter
833 def has_enabled_2fa(self, val):
831 def has_enabled_2fa(self, val):
834 val = str2bool(val)
832 val = str2bool(val)
835 self.update_userdata(enabled_2fa=val)
833 self.update_userdata(enabled_2fa=val)
836 if not val:
834 if not val:
837 # NOTE: setting to false we clear the user_data to not store any 2fa artifacts
835 # NOTE: setting to false we clear the user_data to not store any 2fa artifacts
838 self.update_userdata(secret_2fa=None, recovery_codes_2fa=[], check_2fa=False)
836 self.update_userdata(secret_2fa=None, recovery_codes_2fa=[], check_2fa=False)
839 Session().commit()
837 Session().commit()
840
838
841 @hybrid_property
839 @hybrid_property
842 def check_2fa_required(self):
840 def check_2fa_required(self):
843 """
841 """
844 Check if check 2fa flag is set for this user
842 Check if check 2fa flag is set for this user
845 """
843 """
846 value = self.user_data.get('check_2fa', False)
844 value = self.user_data.get('check_2fa', False)
847 return value
845 return value
848
846
849 @check_2fa_required.setter
847 @check_2fa_required.setter
850 def check_2fa_required(self, val):
848 def check_2fa_required(self, val):
851 val = str2bool(val)
849 val = str2bool(val)
852 self.update_userdata(check_2fa=val)
850 self.update_userdata(check_2fa=val)
853 Session().commit()
851 Session().commit()
854
852
855 @hybrid_property
853 @hybrid_property
856 def has_seen_2fa_codes(self):
854 def has_seen_2fa_codes(self):
857 """
855 """
858 get the flag about if user has seen 2fa recovery codes
856 get the flag about if user has seen 2fa recovery codes
859 """
857 """
860 value = self.user_data.get('recovery_codes_2fa_seen', False)
858 value = self.user_data.get('recovery_codes_2fa_seen', False)
861 return value
859 return value
862
860
863 @has_seen_2fa_codes.setter
861 @has_seen_2fa_codes.setter
864 def has_seen_2fa_codes(self, val):
862 def has_seen_2fa_codes(self, val):
865 val = str2bool(val)
863 val = str2bool(val)
866 self.update_userdata(recovery_codes_2fa_seen=val)
864 self.update_userdata(recovery_codes_2fa_seen=val)
867 Session().commit()
865 Session().commit()
868
866
869 @hybrid_property
867 @hybrid_property
870 def needs_2fa_configure(self):
868 def needs_2fa_configure(self):
871 """
869 """
872 Determines if setup2fa has completed for this user. Means he has all needed data for 2fa to work.
870 Determines if setup2fa has completed for this user. Means he has all needed data for 2fa to work.
873
871
874 Currently this is 2fa enabled and secret exists
872 Currently this is 2fa enabled and secret exists
875 """
873 """
876 if self.has_enabled_2fa:
874 if self.has_enabled_2fa:
877 return not self.user_data.get('secret_2fa')
875 return not self.user_data.get('secret_2fa')
878 return False
876 return False
879
877
880 def init_2fa_recovery_codes(self, persist=True, force=False):
878 def init_2fa_recovery_codes(self, persist=True, force=False):
881 """
879 """
882 Creates 2fa recovery codes
880 Creates 2fa recovery codes
883 """
881 """
884 recovery_codes = self.user_data.get('recovery_codes_2fa', [])
882 recovery_codes = self.user_data.get('recovery_codes_2fa', [])
885 encrypted_codes = []
883 encrypted_codes = []
886 if not recovery_codes or force:
884 if not recovery_codes or force:
887 for _ in range(self.RECOVERY_CODES_COUNT):
885 for _ in range(self.RECOVERY_CODES_COUNT):
888 recovery_code = pyotp.random_base32()
886 recovery_code = pyotp.random_base32()
889 recovery_codes.append(recovery_code)
887 recovery_codes.append(recovery_code)
890 encrypted_code = enc_utils.encrypt_value(safe_bytes(recovery_code), enc_key=ENCRYPTION_KEY)
888 encrypted_code = enc_utils.encrypt_value(safe_bytes(recovery_code), enc_key=ENCRYPTION_KEY)
891 encrypted_codes.append(safe_str(encrypted_code))
889 encrypted_codes.append(safe_str(encrypted_code))
892 if persist:
890 if persist:
893 self.update_userdata(recovery_codes_2fa=encrypted_codes, recovery_codes_2fa_seen=False)
891 self.update_userdata(recovery_codes_2fa=encrypted_codes, recovery_codes_2fa_seen=False)
894 return recovery_codes
892 return recovery_codes
895 # User should not check the same recovery codes more than once
893 # User should not check the same recovery codes more than once
896 return []
894 return []
897
895
898 def get_2fa_recovery_codes(self):
896 def get_2fa_recovery_codes(self):
899 encrypted_recovery_codes = self.user_data.get('recovery_codes_2fa', [])
897 encrypted_recovery_codes = self.user_data.get('recovery_codes_2fa', [])
900 strict_mode = ConfigGet().get_bool('rhodecode.encrypted_values.strict', missing=True)
901
898
902 recovery_codes = list(map(
899 recovery_codes = list(map(
903 lambda val: safe_str(
900 lambda val: safe_str(
904 enc_utils.decrypt_value(
901 enc_utils.decrypt_value(
905 val,
902 val,
906 enc_key=ENCRYPTION_KEY,
903 enc_key=ENCRYPTION_KEY
907 strict_mode=strict_mode
908 )),
904 )),
909 encrypted_recovery_codes))
905 encrypted_recovery_codes))
910 return recovery_codes
906 return recovery_codes
911
907
912 def init_secret_2fa(self, persist=True, force=False):
908 def init_secret_2fa(self, persist=True, force=False):
913 secret_2fa = self.user_data.get('secret_2fa')
909 secret_2fa = self.user_data.get('secret_2fa')
914 if not secret_2fa or force:
910 if not secret_2fa or force:
915 secret = pyotp.random_base32()
911 secret = pyotp.random_base32()
916 if persist:
912 if persist:
917 self.update_userdata(secret_2fa=safe_str(enc_utils.encrypt_value(safe_bytes(secret), enc_key=ENCRYPTION_KEY)))
913 self.update_userdata(secret_2fa=safe_str(enc_utils.encrypt_value(safe_bytes(secret), enc_key=ENCRYPTION_KEY)))
918 return secret
914 return secret
919 return ''
915 return ''
920
916
921 @hybrid_property
917 @hybrid_property
922 def secret_2fa(self) -> str:
918 def secret_2fa(self) -> str:
923 """
919 """
924 get stored secret for 2fa
920 get stored secret for 2fa
925 """
921 """
926 secret_2fa = self.user_data.get('secret_2fa')
922 secret_2fa = self.user_data.get('secret_2fa')
927 if secret_2fa:
923 if secret_2fa:
928 strict_mode = ConfigGet().get_bool('rhodecode.encrypted_values.strict', missing=True)
929 return safe_str(
924 return safe_str(
930 enc_utils.decrypt_value(secret_2fa, enc_key=ENCRYPTION_KEY, strict_mode=strict_mode))
925 enc_utils.decrypt_value(secret_2fa, enc_key=ENCRYPTION_KEY))
931 return ''
926 return ''
932
927
933 @secret_2fa.setter
928 @secret_2fa.setter
934 def secret_2fa(self, value: str) -> None:
929 def secret_2fa(self, value: str) -> None:
935 encrypted_value = enc_utils.encrypt_value(safe_bytes(value), enc_key=ENCRYPTION_KEY)
930 encrypted_value = enc_utils.encrypt_value(safe_bytes(value), enc_key=ENCRYPTION_KEY)
936 self.update_userdata(secret_2fa=safe_str(encrypted_value))
931 self.update_userdata(secret_2fa=safe_str(encrypted_value))
937
932
938 def regenerate_2fa_recovery_codes(self):
933 def regenerate_2fa_recovery_codes(self):
939 """
934 """
940 Regenerates 2fa recovery codes upon request
935 Regenerates 2fa recovery codes upon request
941 """
936 """
942 new_recovery_codes = self.init_2fa_recovery_codes(force=True)
937 new_recovery_codes = self.init_2fa_recovery_codes(force=True)
943 Session().commit()
938 Session().commit()
944 return new_recovery_codes
939 return new_recovery_codes
945
940
946 @classmethod
941 @classmethod
947 def extra_valid_auth_tokens(cls, user, role=None):
942 def extra_valid_auth_tokens(cls, user, role=None):
948 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
943 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
949 .filter(or_(UserApiKeys.expires == -1,
944 .filter(or_(UserApiKeys.expires == -1,
950 UserApiKeys.expires >= time.time()))
945 UserApiKeys.expires >= time.time()))
951 if role:
946 if role:
952 tokens = tokens.filter(or_(UserApiKeys.role == role,
947 tokens = tokens.filter(or_(UserApiKeys.role == role,
953 UserApiKeys.role == UserApiKeys.ROLE_ALL))
948 UserApiKeys.role == UserApiKeys.ROLE_ALL))
954 return tokens.all()
949 return tokens.all()
955
950
956 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
951 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
957 from rhodecode.lib import auth
952 from rhodecode.lib import auth
958
953
959 log.debug('Trying to authenticate user: %s via auth-token, '
954 log.debug('Trying to authenticate user: %s via auth-token, '
960 'and roles: %s', self, roles)
955 'and roles: %s', self, roles)
961
956
962 if not auth_token:
957 if not auth_token:
963 return False
958 return False
964
959
965 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
960 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
966 tokens_q = UserApiKeys.query()\
961 tokens_q = UserApiKeys.query()\
967 .filter(UserApiKeys.user_id == self.user_id)\
962 .filter(UserApiKeys.user_id == self.user_id)\
968 .filter(or_(UserApiKeys.expires == -1,
963 .filter(or_(UserApiKeys.expires == -1,
969 UserApiKeys.expires >= time.time()))
964 UserApiKeys.expires >= time.time()))
970
965
971 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
966 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
972
967
973 crypto_backend = auth.crypto_backend()
968 crypto_backend = auth.crypto_backend()
974 enc_token_map = {}
969 enc_token_map = {}
975 plain_token_map = {}
970 plain_token_map = {}
976 for token in tokens_q:
971 for token in tokens_q:
977 if token.api_key.startswith(crypto_backend.ENC_PREF):
972 if token.api_key.startswith(crypto_backend.ENC_PREF):
978 enc_token_map[token.api_key] = token
973 enc_token_map[token.api_key] = token
979 else:
974 else:
980 plain_token_map[token.api_key] = token
975 plain_token_map[token.api_key] = token
981 log.debug(
976 log.debug(
982 'Found %s plain and %s encrypted tokens to check for authentication for this user',
977 'Found %s plain and %s encrypted tokens to check for authentication for this user',
983 len(plain_token_map), len(enc_token_map))
978 len(plain_token_map), len(enc_token_map))
984
979
985 # plain token match comes first
980 # plain token match comes first
986 match = plain_token_map.get(auth_token)
981 match = plain_token_map.get(auth_token)
987
982
988 # check encrypted tokens now
983 # check encrypted tokens now
989 if not match:
984 if not match:
990 for token_hash, token in enc_token_map.items():
985 for token_hash, token in enc_token_map.items():
991 # NOTE(marcink): this is expensive to calculate, but most secure
986 # NOTE(marcink): this is expensive to calculate, but most secure
992 if crypto_backend.hash_check(auth_token, token_hash):
987 if crypto_backend.hash_check(auth_token, token_hash):
993 match = token
988 match = token
994 break
989 break
995
990
996 if match:
991 if match:
997 log.debug('Found matching token %s', match)
992 log.debug('Found matching token %s', match)
998 if match.repo_id:
993 if match.repo_id:
999 log.debug('Found scope, checking for scope match of token %s', match)
994 log.debug('Found scope, checking for scope match of token %s', match)
1000 if match.repo_id == scope_repo_id:
995 if match.repo_id == scope_repo_id:
1001 return True
996 return True
1002 else:
997 else:
1003 log.debug(
998 log.debug(
1004 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
999 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
1005 'and calling scope is:%s, skipping further checks',
1000 'and calling scope is:%s, skipping further checks',
1006 match.repo, scope_repo_id)
1001 match.repo, scope_repo_id)
1007 return False
1002 return False
1008 else:
1003 else:
1009 return True
1004 return True
1010
1005
1011 return False
1006 return False
1012
1007
1013 @property
1008 @property
1014 def ip_addresses(self):
1009 def ip_addresses(self):
1015 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
1010 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
1016 return [x.ip_addr for x in ret]
1011 return [x.ip_addr for x in ret]
1017
1012
1018 @property
1013 @property
1019 def username_and_name(self):
1014 def username_and_name(self):
1020 return f'{self.username} ({self.first_name} {self.last_name})'
1015 return f'{self.username} ({self.first_name} {self.last_name})'
1021
1016
1022 @property
1017 @property
1023 def username_or_name_or_email(self):
1018 def username_or_name_or_email(self):
1024 full_name = self.full_name if self.full_name != ' ' else None
1019 full_name = self.full_name if self.full_name != ' ' else None
1025 return self.username or full_name or self.email
1020 return self.username or full_name or self.email
1026
1021
1027 @property
1022 @property
1028 def full_name(self):
1023 def full_name(self):
1029 return f'{self.first_name} {self.last_name}'
1024 return f'{self.first_name} {self.last_name}'
1030
1025
1031 @property
1026 @property
1032 def full_name_or_username(self):
1027 def full_name_or_username(self):
1033 return (f'{self.first_name} {self.last_name}'
1028 return (f'{self.first_name} {self.last_name}'
1034 if (self.first_name and self.last_name) else self.username)
1029 if (self.first_name and self.last_name) else self.username)
1035
1030
1036 @property
1031 @property
1037 def full_contact(self):
1032 def full_contact(self):
1038 return f'{self.first_name} {self.last_name} <{self.email}>'
1033 return f'{self.first_name} {self.last_name} <{self.email}>'
1039
1034
1040 @property
1035 @property
1041 def short_contact(self):
1036 def short_contact(self):
1042 return f'{self.first_name} {self.last_name}'
1037 return f'{self.first_name} {self.last_name}'
1043
1038
1044 @property
1039 @property
1045 def is_admin(self):
1040 def is_admin(self):
1046 return self.admin
1041 return self.admin
1047
1042
1048 @property
1043 @property
1049 def language(self):
1044 def language(self):
1050 return self.user_data.get('language')
1045 return self.user_data.get('language')
1051
1046
1052 def AuthUser(self, **kwargs):
1047 def AuthUser(self, **kwargs):
1053 """
1048 """
1054 Returns instance of AuthUser for this user
1049 Returns instance of AuthUser for this user
1055 """
1050 """
1056 from rhodecode.lib.auth import AuthUser
1051 from rhodecode.lib.auth import AuthUser
1057 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
1052 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
1058
1053
1059 @hybrid_property
1054 @hybrid_property
1060 def user_data(self):
1055 def user_data(self):
1061 if not self._user_data:
1056 if not self._user_data:
1062 return {}
1057 return {}
1063
1058
1064 try:
1059 try:
1065 return json.loads(self._user_data) or {}
1060 return json.loads(self._user_data) or {}
1066 except TypeError:
1061 except TypeError:
1067 return {}
1062 return {}
1068
1063
1069 @user_data.setter
1064 @user_data.setter
1070 def user_data(self, val):
1065 def user_data(self, val):
1071 if not isinstance(val, dict):
1066 if not isinstance(val, dict):
1072 raise Exception(f'user_data must be dict, got {type(val)}')
1067 raise Exception(f'user_data must be dict, got {type(val)}')
1073 try:
1068 try:
1074 self._user_data = safe_bytes(json.dumps(val))
1069 self._user_data = safe_bytes(json.dumps(val))
1075 except Exception:
1070 except Exception:
1076 log.error(traceback.format_exc())
1071 log.error(traceback.format_exc())
1077
1072
1078 @classmethod
1073 @classmethod
1079 def get(cls, user_id, cache=False):
1074 def get(cls, user_id, cache=False):
1080 if not user_id:
1075 if not user_id:
1081 return
1076 return
1082
1077
1083 user = cls.query()
1078 user = cls.query()
1084 if cache:
1079 if cache:
1085 user = user.options(
1080 user = user.options(
1086 FromCache("sql_cache_short", f"get_users_{user_id}"))
1081 FromCache("sql_cache_short", f"get_users_{user_id}"))
1087 return user.get(user_id)
1082 return user.get(user_id)
1088
1083
1089 @classmethod
1084 @classmethod
1090 def get_by_username(cls, username, case_insensitive=False,
1085 def get_by_username(cls, username, case_insensitive=False,
1091 cache=False):
1086 cache=False):
1092
1087
1093 if case_insensitive:
1088 if case_insensitive:
1094 q = cls.select().where(
1089 q = cls.select().where(
1095 func.lower(cls.username) == func.lower(username))
1090 func.lower(cls.username) == func.lower(username))
1096 else:
1091 else:
1097 q = cls.select().where(cls.username == username)
1092 q = cls.select().where(cls.username == username)
1098
1093
1099 if cache:
1094 if cache:
1100 hash_key = _hash_key(username)
1095 hash_key = _hash_key(username)
1101 q = q.options(
1096 q = q.options(
1102 FromCache("sql_cache_short", f"get_user_by_name_{hash_key}"))
1097 FromCache("sql_cache_short", f"get_user_by_name_{hash_key}"))
1103
1098
1104 return cls.execute(q).scalar_one_or_none()
1099 return cls.execute(q).scalar_one_or_none()
1105
1100
1106 @classmethod
1101 @classmethod
1107 def get_by_username_or_primary_email(cls, user_identifier):
1102 def get_by_username_or_primary_email(cls, user_identifier):
1108 qs = union_all(cls.select().where(func.lower(cls.username) == func.lower(user_identifier)),
1103 qs = union_all(cls.select().where(func.lower(cls.username) == func.lower(user_identifier)),
1109 cls.select().where(func.lower(cls.email) == func.lower(user_identifier)))
1104 cls.select().where(func.lower(cls.email) == func.lower(user_identifier)))
1110 return cls.execute(cls.select(User).from_statement(qs)).scalar_one_or_none()
1105 return cls.execute(cls.select(User).from_statement(qs)).scalar_one_or_none()
1111
1106
1112 @classmethod
1107 @classmethod
1113 def get_by_auth_token(cls, auth_token, cache=False):
1108 def get_by_auth_token(cls, auth_token, cache=False):
1114
1109
1115 q = cls.select(User)\
1110 q = cls.select(User)\
1116 .join(UserApiKeys)\
1111 .join(UserApiKeys)\
1117 .where(UserApiKeys.api_key == auth_token)\
1112 .where(UserApiKeys.api_key == auth_token)\
1118 .where(or_(UserApiKeys.expires == -1,
1113 .where(or_(UserApiKeys.expires == -1,
1119 UserApiKeys.expires >= time.time()))
1114 UserApiKeys.expires >= time.time()))
1120
1115
1121 if cache:
1116 if cache:
1122 q = q.options(
1117 q = q.options(
1123 FromCache("sql_cache_short", f"get_auth_token_{auth_token}"))
1118 FromCache("sql_cache_short", f"get_auth_token_{auth_token}"))
1124
1119
1125 matched_user = cls.execute(q).scalar_one_or_none()
1120 matched_user = cls.execute(q).scalar_one_or_none()
1126
1121
1127 return matched_user
1122 return matched_user
1128
1123
1129 @classmethod
1124 @classmethod
1130 def get_by_email(cls, email, case_insensitive=False, cache=False):
1125 def get_by_email(cls, email, case_insensitive=False, cache=False):
1131
1126
1132 if case_insensitive:
1127 if case_insensitive:
1133 q = cls.select().where(func.lower(cls.email) == func.lower(email))
1128 q = cls.select().where(func.lower(cls.email) == func.lower(email))
1134 else:
1129 else:
1135 q = cls.select().where(cls.email == email)
1130 q = cls.select().where(cls.email == email)
1136
1131
1137 if cache:
1132 if cache:
1138 email_key = _hash_key(email)
1133 email_key = _hash_key(email)
1139 q = q.options(
1134 q = q.options(
1140 FromCache("sql_cache_short", f"get_email_key_{email_key}"))
1135 FromCache("sql_cache_short", f"get_email_key_{email_key}"))
1141
1136
1142 ret = cls.execute(q).scalar_one_or_none()
1137 ret = cls.execute(q).scalar_one_or_none()
1143
1138
1144 if ret is None:
1139 if ret is None:
1145 q = cls.select(UserEmailMap)
1140 q = cls.select(UserEmailMap)
1146 # try fetching in alternate email map
1141 # try fetching in alternate email map
1147 if case_insensitive:
1142 if case_insensitive:
1148 q = q.where(func.lower(UserEmailMap.email) == func.lower(email))
1143 q = q.where(func.lower(UserEmailMap.email) == func.lower(email))
1149 else:
1144 else:
1150 q = q.where(UserEmailMap.email == email)
1145 q = q.where(UserEmailMap.email == email)
1151 q = q.options(joinedload(UserEmailMap.user))
1146 q = q.options(joinedload(UserEmailMap.user))
1152 if cache:
1147 if cache:
1153 q = q.options(
1148 q = q.options(
1154 FromCache("sql_cache_short", f"get_email_map_key_{email_key}"))
1149 FromCache("sql_cache_short", f"get_email_map_key_{email_key}"))
1155
1150
1156 result = cls.execute(q).scalar_one_or_none()
1151 result = cls.execute(q).scalar_one_or_none()
1157 ret = getattr(result, 'user', None)
1152 ret = getattr(result, 'user', None)
1158
1153
1159 return ret
1154 return ret
1160
1155
1161 @classmethod
1156 @classmethod
1162 def get_from_cs_author(cls, author):
1157 def get_from_cs_author(cls, author):
1163 """
1158 """
1164 Tries to get User objects out of commit author string
1159 Tries to get User objects out of commit author string
1165
1160
1166 :param author:
1161 :param author:
1167 """
1162 """
1168 from rhodecode.lib.helpers import email, author_name
1163 from rhodecode.lib.helpers import email, author_name
1169 # Valid email in the attribute passed, see if they're in the system
1164 # Valid email in the attribute passed, see if they're in the system
1170 _email = email(author)
1165 _email = email(author)
1171 if _email:
1166 if _email:
1172 user = cls.get_by_email(_email, case_insensitive=True)
1167 user = cls.get_by_email(_email, case_insensitive=True)
1173 if user:
1168 if user:
1174 return user
1169 return user
1175 # Maybe we can match by username?
1170 # Maybe we can match by username?
1176 _author = author_name(author)
1171 _author = author_name(author)
1177 user = cls.get_by_username(_author, case_insensitive=True)
1172 user = cls.get_by_username(_author, case_insensitive=True)
1178 if user:
1173 if user:
1179 return user
1174 return user
1180
1175
1181 def update_userdata(self, **kwargs):
1176 def update_userdata(self, **kwargs):
1182 usr = self
1177 usr = self
1183 old = usr.user_data
1178 old = usr.user_data
1184 old.update(**kwargs)
1179 old.update(**kwargs)
1185 usr.user_data = old
1180 usr.user_data = old
1186 Session().add(usr)
1181 Session().add(usr)
1187 log.debug('updated userdata with %s', kwargs)
1182 log.debug('updated userdata with %s', kwargs)
1188
1183
1189 def update_lastlogin(self):
1184 def update_lastlogin(self):
1190 """Update user lastlogin"""
1185 """Update user lastlogin"""
1191 self.last_login = datetime.datetime.now()
1186 self.last_login = datetime.datetime.now()
1192 Session().add(self)
1187 Session().add(self)
1193 log.debug('updated user %s lastlogin', self.username)
1188 log.debug('updated user %s lastlogin', self.username)
1194
1189
1195 def update_password(self, new_password):
1190 def update_password(self, new_password):
1196 from rhodecode.lib.auth import get_crypt_password
1191 from rhodecode.lib.auth import get_crypt_password
1197
1192
1198 self.password = get_crypt_password(new_password)
1193 self.password = get_crypt_password(new_password)
1199 Session().add(self)
1194 Session().add(self)
1200
1195
1201 @classmethod
1196 @classmethod
1202 def get_first_super_admin(cls):
1197 def get_first_super_admin(cls):
1203 stmt = cls.select().where(User.admin == true()).order_by(User.user_id.asc())
1198 stmt = cls.select().where(User.admin == true()).order_by(User.user_id.asc())
1204 user = cls.scalars(stmt).first()
1199 user = cls.scalars(stmt).first()
1205
1200
1206 if user is None:
1201 if user is None:
1207 raise Exception('FATAL: Missing administrative account!')
1202 raise Exception('FATAL: Missing administrative account!')
1208 return user
1203 return user
1209
1204
1210 @classmethod
1205 @classmethod
1211 def get_all_super_admins(cls, only_active=False):
1206 def get_all_super_admins(cls, only_active=False):
1212 """
1207 """
1213 Returns all admin accounts sorted by username
1208 Returns all admin accounts sorted by username
1214 """
1209 """
1215 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
1210 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
1216 if only_active:
1211 if only_active:
1217 qry = qry.filter(User.active == true())
1212 qry = qry.filter(User.active == true())
1218 return qry.all()
1213 return qry.all()
1219
1214
1220 @classmethod
1215 @classmethod
1221 def get_all_user_ids(cls, only_active=True):
1216 def get_all_user_ids(cls, only_active=True):
1222 """
1217 """
1223 Returns all users IDs
1218 Returns all users IDs
1224 """
1219 """
1225 qry = Session().query(User.user_id)
1220 qry = Session().query(User.user_id)
1226
1221
1227 if only_active:
1222 if only_active:
1228 qry = qry.filter(User.active == true())
1223 qry = qry.filter(User.active == true())
1229 return [x.user_id for x in qry]
1224 return [x.user_id for x in qry]
1230
1225
1231 @classmethod
1226 @classmethod
1232 def get_default_user(cls, cache=False, refresh=False):
1227 def get_default_user(cls, cache=False, refresh=False):
1233 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
1228 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
1234 if user is None:
1229 if user is None:
1235 raise Exception('FATAL: Missing default account!')
1230 raise Exception('FATAL: Missing default account!')
1236 if refresh:
1231 if refresh:
1237 # The default user might be based on outdated state which
1232 # The default user might be based on outdated state which
1238 # has been loaded from the cache.
1233 # has been loaded from the cache.
1239 # A call to refresh() ensures that the
1234 # A call to refresh() ensures that the
1240 # latest state from the database is used.
1235 # latest state from the database is used.
1241 Session().refresh(user)
1236 Session().refresh(user)
1242
1237
1243 return user
1238 return user
1244
1239
1245 @classmethod
1240 @classmethod
1246 def get_default_user_id(cls):
1241 def get_default_user_id(cls):
1247 import rhodecode
1242 import rhodecode
1248 return rhodecode.CONFIG['default_user_id']
1243 return rhodecode.CONFIG['default_user_id']
1249
1244
1250 def _get_default_perms(self, user, suffix=''):
1245 def _get_default_perms(self, user, suffix=''):
1251 from rhodecode.model.permission import PermissionModel
1246 from rhodecode.model.permission import PermissionModel
1252 return PermissionModel().get_default_perms(user.user_perms, suffix)
1247 return PermissionModel().get_default_perms(user.user_perms, suffix)
1253
1248
1254 def get_default_perms(self, suffix=''):
1249 def get_default_perms(self, suffix=''):
1255 return self._get_default_perms(self, suffix)
1250 return self._get_default_perms(self, suffix)
1256
1251
1257 def get_api_data(self, include_secrets=False, details='full'):
1252 def get_api_data(self, include_secrets=False, details='full'):
1258 """
1253 """
1259 Common function for generating user related data for API
1254 Common function for generating user related data for API
1260
1255
1261 :param include_secrets: By default secrets in the API data will be replaced
1256 :param include_secrets: By default secrets in the API data will be replaced
1262 by a placeholder value to prevent exposing this data by accident. In case
1257 by a placeholder value to prevent exposing this data by accident. In case
1263 this data shall be exposed, set this flag to ``True``.
1258 this data shall be exposed, set this flag to ``True``.
1264
1259
1265 :param details: details can be 'basic|full' basic gives only a subset of
1260 :param details: details can be 'basic|full' basic gives only a subset of
1266 the available user information that includes user_id, name and emails.
1261 the available user information that includes user_id, name and emails.
1267 """
1262 """
1268 user = self
1263 user = self
1269 user_data = self.user_data
1264 user_data = self.user_data
1270 data = {
1265 data = {
1271 'user_id': user.user_id,
1266 'user_id': user.user_id,
1272 'username': user.username,
1267 'username': user.username,
1273 'firstname': user.name,
1268 'firstname': user.name,
1274 'lastname': user.lastname,
1269 'lastname': user.lastname,
1275 'description': user.description,
1270 'description': user.description,
1276 'email': user.email,
1271 'email': user.email,
1277 'emails': user.emails,
1272 'emails': user.emails,
1278 }
1273 }
1279 if details == 'basic':
1274 if details == 'basic':
1280 return data
1275 return data
1281
1276
1282 auth_token_length = 40
1277 auth_token_length = 40
1283 auth_token_replacement = '*' * auth_token_length
1278 auth_token_replacement = '*' * auth_token_length
1284
1279
1285 extras = {
1280 extras = {
1286 'auth_tokens': [auth_token_replacement],
1281 'auth_tokens': [auth_token_replacement],
1287 'active': user.active,
1282 'active': user.active,
1288 'admin': user.admin,
1283 'admin': user.admin,
1289 'extern_type': user.extern_type,
1284 'extern_type': user.extern_type,
1290 'extern_name': user.extern_name,
1285 'extern_name': user.extern_name,
1291 'last_login': user.last_login,
1286 'last_login': user.last_login,
1292 'last_activity': user.last_activity,
1287 'last_activity': user.last_activity,
1293 'ip_addresses': user.ip_addresses,
1288 'ip_addresses': user.ip_addresses,
1294 'language': user_data.get('language')
1289 'language': user_data.get('language')
1295 }
1290 }
1296 data.update(extras)
1291 data.update(extras)
1297
1292
1298 if include_secrets:
1293 if include_secrets:
1299 data['auth_tokens'] = user.auth_tokens
1294 data['auth_tokens'] = user.auth_tokens
1300 return data
1295 return data
1301
1296
1302 def __json__(self):
1297 def __json__(self):
1303 data = {
1298 data = {
1304 'full_name': self.full_name,
1299 'full_name': self.full_name,
1305 'full_name_or_username': self.full_name_or_username,
1300 'full_name_or_username': self.full_name_or_username,
1306 'short_contact': self.short_contact,
1301 'short_contact': self.short_contact,
1307 'full_contact': self.full_contact,
1302 'full_contact': self.full_contact,
1308 }
1303 }
1309 data.update(self.get_api_data())
1304 data.update(self.get_api_data())
1310 return data
1305 return data
1311
1306
1312
1307
1313 class UserApiKeys(Base, BaseModel):
1308 class UserApiKeys(Base, BaseModel):
1314 __tablename__ = 'user_api_keys'
1309 __tablename__ = 'user_api_keys'
1315 __table_args__ = (
1310 __table_args__ = (
1316 Index('uak_api_key_idx', 'api_key'),
1311 Index('uak_api_key_idx', 'api_key'),
1317 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1312 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1318 base_table_args
1313 base_table_args
1319 )
1314 )
1320
1315
1321 # ApiKey role
1316 # ApiKey role
1322 ROLE_ALL = 'token_role_all'
1317 ROLE_ALL = 'token_role_all'
1323 ROLE_VCS = 'token_role_vcs'
1318 ROLE_VCS = 'token_role_vcs'
1324 ROLE_API = 'token_role_api'
1319 ROLE_API = 'token_role_api'
1325 ROLE_HTTP = 'token_role_http'
1320 ROLE_HTTP = 'token_role_http'
1326 ROLE_FEED = 'token_role_feed'
1321 ROLE_FEED = 'token_role_feed'
1327 ROLE_ARTIFACT_DOWNLOAD = 'role_artifact_download'
1322 ROLE_ARTIFACT_DOWNLOAD = 'role_artifact_download'
1328 # The last one is ignored in the list as we only
1323 # The last one is ignored in the list as we only
1329 # use it for one action, and cannot be created by users
1324 # use it for one action, and cannot be created by users
1330 ROLE_PASSWORD_RESET = 'token_password_reset'
1325 ROLE_PASSWORD_RESET = 'token_password_reset'
1331
1326
1332 ROLES = [ROLE_ALL, ROLE_VCS, ROLE_API, ROLE_HTTP, ROLE_FEED, ROLE_ARTIFACT_DOWNLOAD]
1327 ROLES = [ROLE_ALL, ROLE_VCS, ROLE_API, ROLE_HTTP, ROLE_FEED, ROLE_ARTIFACT_DOWNLOAD]
1333
1328
1334 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1329 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1335 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1330 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1336 api_key = Column("api_key", String(255), nullable=False, unique=True)
1331 api_key = Column("api_key", String(255), nullable=False, unique=True)
1337 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1332 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1338 expires = Column('expires', Float(53), nullable=False)
1333 expires = Column('expires', Float(53), nullable=False)
1339 role = Column('role', String(255), nullable=True)
1334 role = Column('role', String(255), nullable=True)
1340 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1335 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1341
1336
1342 # scope columns
1337 # scope columns
1343 repo_id = Column(
1338 repo_id = Column(
1344 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1339 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1345 nullable=True, unique=None, default=None)
1340 nullable=True, unique=None, default=None)
1346 repo = relationship('Repository', lazy='joined', back_populates='scoped_tokens')
1341 repo = relationship('Repository', lazy='joined', back_populates='scoped_tokens')
1347
1342
1348 repo_group_id = Column(
1343 repo_group_id = Column(
1349 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1344 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1350 nullable=True, unique=None, default=None)
1345 nullable=True, unique=None, default=None)
1351 repo_group = relationship('RepoGroup', lazy='joined')
1346 repo_group = relationship('RepoGroup', lazy='joined')
1352
1347
1353 user = relationship('User', lazy='joined', back_populates='user_auth_tokens')
1348 user = relationship('User', lazy='joined', back_populates='user_auth_tokens')
1354
1349
1355 def __repr__(self):
1350 def __repr__(self):
1356 return f"<{self.cls_name}('{self.role}')>"
1351 return f"<{self.cls_name}('{self.role}')>"
1357
1352
1358 def __json__(self):
1353 def __json__(self):
1359 data = {
1354 data = {
1360 'auth_token': self.api_key,
1355 'auth_token': self.api_key,
1361 'role': self.role,
1356 'role': self.role,
1362 'scope': self.scope_humanized,
1357 'scope': self.scope_humanized,
1363 'expired': self.expired
1358 'expired': self.expired
1364 }
1359 }
1365 return data
1360 return data
1366
1361
1367 def get_api_data(self, include_secrets=False):
1362 def get_api_data(self, include_secrets=False):
1368 data = self.__json__()
1363 data = self.__json__()
1369 if include_secrets:
1364 if include_secrets:
1370 return data
1365 return data
1371 else:
1366 else:
1372 data['auth_token'] = self.token_obfuscated
1367 data['auth_token'] = self.token_obfuscated
1373 return data
1368 return data
1374
1369
1375 @hybrid_property
1370 @hybrid_property
1376 def description_safe(self):
1371 def description_safe(self):
1377 from rhodecode.lib import helpers as h
1372 from rhodecode.lib import helpers as h
1378 return h.escape(self.description)
1373 return h.escape(self.description)
1379
1374
1380 @property
1375 @property
1381 def expired(self):
1376 def expired(self):
1382 if self.expires == -1:
1377 if self.expires == -1:
1383 return False
1378 return False
1384 return time.time() > self.expires
1379 return time.time() > self.expires
1385
1380
1386 @classmethod
1381 @classmethod
1387 def _get_role_name(cls, role):
1382 def _get_role_name(cls, role):
1388 return {
1383 return {
1389 cls.ROLE_ALL: _('all'),
1384 cls.ROLE_ALL: _('all'),
1390 cls.ROLE_HTTP: _('http/web interface'),
1385 cls.ROLE_HTTP: _('http/web interface'),
1391 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1386 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1392 cls.ROLE_API: _('api calls'),
1387 cls.ROLE_API: _('api calls'),
1393 cls.ROLE_FEED: _('feed access'),
1388 cls.ROLE_FEED: _('feed access'),
1394 cls.ROLE_ARTIFACT_DOWNLOAD: _('artifacts downloads'),
1389 cls.ROLE_ARTIFACT_DOWNLOAD: _('artifacts downloads'),
1395 }.get(role, role)
1390 }.get(role, role)
1396
1391
1397 @classmethod
1392 @classmethod
1398 def _get_role_description(cls, role):
1393 def _get_role_description(cls, role):
1399 return {
1394 return {
1400 cls.ROLE_ALL: _('Token for all actions.'),
1395 cls.ROLE_ALL: _('Token for all actions.'),
1401 cls.ROLE_HTTP: _('Token to access RhodeCode pages via web interface without '
1396 cls.ROLE_HTTP: _('Token to access RhodeCode pages via web interface without '
1402 'login using `api_access_controllers_whitelist` functionality.'),
1397 'login using `api_access_controllers_whitelist` functionality.'),
1403 cls.ROLE_VCS: _('Token to interact over git/hg/svn protocols. '
1398 cls.ROLE_VCS: _('Token to interact over git/hg/svn protocols. '
1404 'Requires auth_token authentication plugin to be active. <br/>'
1399 'Requires auth_token authentication plugin to be active. <br/>'
1405 'Such Token should be used then instead of a password to '
1400 'Such Token should be used then instead of a password to '
1406 'interact with a repository, and additionally can be '
1401 'interact with a repository, and additionally can be '
1407 'limited to single repository using repo scope.'),
1402 'limited to single repository using repo scope.'),
1408 cls.ROLE_API: _('Token limited to api calls.'),
1403 cls.ROLE_API: _('Token limited to api calls.'),
1409 cls.ROLE_FEED: _('Token to read RSS/ATOM feed.'),
1404 cls.ROLE_FEED: _('Token to read RSS/ATOM feed.'),
1410 cls.ROLE_ARTIFACT_DOWNLOAD: _('Token for artifacts downloads.'),
1405 cls.ROLE_ARTIFACT_DOWNLOAD: _('Token for artifacts downloads.'),
1411 }.get(role, role)
1406 }.get(role, role)
1412
1407
1413 @property
1408 @property
1414 def role_humanized(self):
1409 def role_humanized(self):
1415 return self._get_role_name(self.role)
1410 return self._get_role_name(self.role)
1416
1411
1417 def _get_scope(self):
1412 def _get_scope(self):
1418 if self.repo:
1413 if self.repo:
1419 return 'Repository: {}'.format(self.repo.repo_name)
1414 return 'Repository: {}'.format(self.repo.repo_name)
1420 if self.repo_group:
1415 if self.repo_group:
1421 return 'RepositoryGroup: {} (recursive)'.format(self.repo_group.group_name)
1416 return 'RepositoryGroup: {} (recursive)'.format(self.repo_group.group_name)
1422 return 'Global'
1417 return 'Global'
1423
1418
1424 @property
1419 @property
1425 def scope_humanized(self):
1420 def scope_humanized(self):
1426 return self._get_scope()
1421 return self._get_scope()
1427
1422
1428 @property
1423 @property
1429 def token_obfuscated(self):
1424 def token_obfuscated(self):
1430 if self.api_key:
1425 if self.api_key:
1431 return self.api_key[:4] + "****"
1426 return self.api_key[:4] + "****"
1432
1427
1433
1428
1434 class UserEmailMap(Base, BaseModel):
1429 class UserEmailMap(Base, BaseModel):
1435 __tablename__ = 'user_email_map'
1430 __tablename__ = 'user_email_map'
1436 __table_args__ = (
1431 __table_args__ = (
1437 Index('uem_email_idx', 'email'),
1432 Index('uem_email_idx', 'email'),
1438 Index('uem_user_id_idx', 'user_id'),
1433 Index('uem_user_id_idx', 'user_id'),
1439 UniqueConstraint('email'),
1434 UniqueConstraint('email'),
1440 base_table_args
1435 base_table_args
1441 )
1436 )
1442
1437
1443 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1438 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1444 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1439 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1445 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1440 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1446 user = relationship('User', lazy='joined', back_populates='user_emails')
1441 user = relationship('User', lazy='joined', back_populates='user_emails')
1447
1442
1448 @validates('_email')
1443 @validates('_email')
1449 def validate_email(self, key, email):
1444 def validate_email(self, key, email):
1450 # check if this email is not main one
1445 # check if this email is not main one
1451 main_email = Session().query(User).filter(User.email == email).scalar()
1446 main_email = Session().query(User).filter(User.email == email).scalar()
1452 if main_email is not None:
1447 if main_email is not None:
1453 raise AttributeError('email %s is present is user table' % email)
1448 raise AttributeError('email %s is present is user table' % email)
1454 return email
1449 return email
1455
1450
1456 @hybrid_property
1451 @hybrid_property
1457 def email(self):
1452 def email(self):
1458 return self._email
1453 return self._email
1459
1454
1460 @email.setter
1455 @email.setter
1461 def email(self, val):
1456 def email(self, val):
1462 self._email = val.lower() if val else None
1457 self._email = val.lower() if val else None
1463
1458
1464
1459
1465 class UserIpMap(Base, BaseModel):
1460 class UserIpMap(Base, BaseModel):
1466 __tablename__ = 'user_ip_map'
1461 __tablename__ = 'user_ip_map'
1467 __table_args__ = (
1462 __table_args__ = (
1468 UniqueConstraint('user_id', 'ip_addr'),
1463 UniqueConstraint('user_id', 'ip_addr'),
1469 base_table_args
1464 base_table_args
1470 )
1465 )
1471
1466
1472 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1467 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1473 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1468 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1474 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1469 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1475 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1470 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1476 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1471 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1477 user = relationship('User', lazy='joined', back_populates='user_ip_map')
1472 user = relationship('User', lazy='joined', back_populates='user_ip_map')
1478
1473
1479 @hybrid_property
1474 @hybrid_property
1480 def description_safe(self):
1475 def description_safe(self):
1481 from rhodecode.lib import helpers as h
1476 from rhodecode.lib import helpers as h
1482 return h.escape(self.description)
1477 return h.escape(self.description)
1483
1478
1484 @classmethod
1479 @classmethod
1485 def _get_ip_range(cls, ip_addr):
1480 def _get_ip_range(cls, ip_addr):
1486 net = ipaddress.ip_network(safe_str(ip_addr), strict=False)
1481 net = ipaddress.ip_network(safe_str(ip_addr), strict=False)
1487 return [str(net.network_address), str(net.broadcast_address)]
1482 return [str(net.network_address), str(net.broadcast_address)]
1488
1483
1489 def __json__(self):
1484 def __json__(self):
1490 return {
1485 return {
1491 'ip_addr': self.ip_addr,
1486 'ip_addr': self.ip_addr,
1492 'ip_range': self._get_ip_range(self.ip_addr),
1487 'ip_range': self._get_ip_range(self.ip_addr),
1493 }
1488 }
1494
1489
1495 def __repr__(self):
1490 def __repr__(self):
1496 return f"<{self.cls_name}('user_id={self.user_id} => ip={self.ip_addr}')>"
1491 return f"<{self.cls_name}('user_id={self.user_id} => ip={self.ip_addr}')>"
1497
1492
1498
1493
1499 class UserSshKeys(Base, BaseModel):
1494 class UserSshKeys(Base, BaseModel):
1500 __tablename__ = 'user_ssh_keys'
1495 __tablename__ = 'user_ssh_keys'
1501 __table_args__ = (
1496 __table_args__ = (
1502 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1497 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1503
1498
1504 UniqueConstraint('ssh_key_fingerprint'),
1499 UniqueConstraint('ssh_key_fingerprint'),
1505
1500
1506 base_table_args
1501 base_table_args
1507 )
1502 )
1508
1503
1509 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1504 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1510 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1505 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1511 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1506 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1512
1507
1513 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1508 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1514
1509
1515 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1510 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1516 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1511 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1517 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1512 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1518
1513
1519 user = relationship('User', lazy='joined', back_populates='user_ssh_keys')
1514 user = relationship('User', lazy='joined', back_populates='user_ssh_keys')
1520
1515
1521 def __json__(self):
1516 def __json__(self):
1522 data = {
1517 data = {
1523 'ssh_fingerprint': self.ssh_key_fingerprint,
1518 'ssh_fingerprint': self.ssh_key_fingerprint,
1524 'description': self.description,
1519 'description': self.description,
1525 'created_on': self.created_on
1520 'created_on': self.created_on
1526 }
1521 }
1527 return data
1522 return data
1528
1523
1529 def get_api_data(self):
1524 def get_api_data(self):
1530 data = self.__json__()
1525 data = self.__json__()
1531 return data
1526 return data
1532
1527
1533
1528
1534 class UserLog(Base, BaseModel):
1529 class UserLog(Base, BaseModel):
1535 __tablename__ = 'user_logs'
1530 __tablename__ = 'user_logs'
1536 __table_args__ = (
1531 __table_args__ = (
1537 base_table_args,
1532 base_table_args,
1538 )
1533 )
1539
1534
1540 VERSION_1 = 'v1'
1535 VERSION_1 = 'v1'
1541 VERSION_2 = 'v2'
1536 VERSION_2 = 'v2'
1542 VERSIONS = [VERSION_1, VERSION_2]
1537 VERSIONS = [VERSION_1, VERSION_2]
1543
1538
1544 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1539 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1545 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1540 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1546 username = Column("username", String(255), nullable=True, unique=None, default=None)
1541 username = Column("username", String(255), nullable=True, unique=None, default=None)
1547 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1542 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1548 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1543 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1549 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1544 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1550 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1545 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1551 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1546 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1552
1547
1553 version = Column("version", String(255), nullable=True, default=VERSION_1)
1548 version = Column("version", String(255), nullable=True, default=VERSION_1)
1554 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1549 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1555 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1550 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1556 user = relationship('User', cascade='', back_populates='user_log')
1551 user = relationship('User', cascade='', back_populates='user_log')
1557 repository = relationship('Repository', cascade='', back_populates='logs')
1552 repository = relationship('Repository', cascade='', back_populates='logs')
1558
1553
1559 def __repr__(self):
1554 def __repr__(self):
1560 return f"<{self.cls_name}('id:{self.repository_name}:{self.action}')>"
1555 return f"<{self.cls_name}('id:{self.repository_name}:{self.action}')>"
1561
1556
1562 def __json__(self):
1557 def __json__(self):
1563 return {
1558 return {
1564 'user_id': self.user_id,
1559 'user_id': self.user_id,
1565 'username': self.username,
1560 'username': self.username,
1566 'repository_id': self.repository_id,
1561 'repository_id': self.repository_id,
1567 'repository_name': self.repository_name,
1562 'repository_name': self.repository_name,
1568 'user_ip': self.user_ip,
1563 'user_ip': self.user_ip,
1569 'action_date': self.action_date,
1564 'action_date': self.action_date,
1570 'action': self.action,
1565 'action': self.action,
1571 }
1566 }
1572
1567
1573 @hybrid_property
1568 @hybrid_property
1574 def entry_id(self):
1569 def entry_id(self):
1575 return self.user_log_id
1570 return self.user_log_id
1576
1571
1577 @property
1572 @property
1578 def action_as_day(self):
1573 def action_as_day(self):
1579 return datetime.date(*self.action_date.timetuple()[:3])
1574 return datetime.date(*self.action_date.timetuple()[:3])
1580
1575
1581
1576
1582 class UserGroup(Base, BaseModel):
1577 class UserGroup(Base, BaseModel):
1583 __tablename__ = 'users_groups'
1578 __tablename__ = 'users_groups'
1584 __table_args__ = (
1579 __table_args__ = (
1585 base_table_args,
1580 base_table_args,
1586 )
1581 )
1587
1582
1588 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1583 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1589 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1584 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1590 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1585 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1591 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1586 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1592 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1587 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1593 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1588 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1594 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1589 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1595 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1590 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1596
1591
1597 members = relationship('UserGroupMember', cascade="all, delete-orphan", lazy="joined", back_populates='users_group')
1592 members = relationship('UserGroupMember', cascade="all, delete-orphan", lazy="joined", back_populates='users_group')
1598 users_group_to_perm = relationship('UserGroupToPerm', cascade='all', back_populates='users_group')
1593 users_group_to_perm = relationship('UserGroupToPerm', cascade='all', back_populates='users_group')
1599 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all', back_populates='users_group')
1594 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all', back_populates='users_group')
1600 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all', back_populates='users_group')
1595 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all', back_populates='users_group')
1601 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all', back_populates='user_group')
1596 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all', back_populates='user_group')
1602
1597
1603 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all', back_populates='target_user_group')
1598 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all', back_populates='target_user_group')
1604
1599
1605 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all', back_populates='users_group')
1600 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all', back_populates='users_group')
1606 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id", back_populates='user_groups')
1601 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id", back_populates='user_groups')
1607
1602
1608 @classmethod
1603 @classmethod
1609 def _load_group_data(cls, column):
1604 def _load_group_data(cls, column):
1610 if not column:
1605 if not column:
1611 return {}
1606 return {}
1612
1607
1613 try:
1608 try:
1614 return json.loads(column) or {}
1609 return json.loads(column) or {}
1615 except TypeError:
1610 except TypeError:
1616 return {}
1611 return {}
1617
1612
1618 @hybrid_property
1613 @hybrid_property
1619 def description_safe(self):
1614 def description_safe(self):
1620 from rhodecode.lib import helpers as h
1615 from rhodecode.lib import helpers as h
1621 return h.escape(self.user_group_description)
1616 return h.escape(self.user_group_description)
1622
1617
1623 @hybrid_property
1618 @hybrid_property
1624 def group_data(self):
1619 def group_data(self):
1625 return self._load_group_data(self._group_data)
1620 return self._load_group_data(self._group_data)
1626
1621
1627 @group_data.expression
1622 @group_data.expression
1628 def group_data(self, **kwargs):
1623 def group_data(self, **kwargs):
1629 return self._group_data
1624 return self._group_data
1630
1625
1631 @group_data.setter
1626 @group_data.setter
1632 def group_data(self, val):
1627 def group_data(self, val):
1633 try:
1628 try:
1634 self._group_data = json.dumps(val)
1629 self._group_data = json.dumps(val)
1635 except Exception:
1630 except Exception:
1636 log.error(traceback.format_exc())
1631 log.error(traceback.format_exc())
1637
1632
1638 @classmethod
1633 @classmethod
1639 def _load_sync(cls, group_data):
1634 def _load_sync(cls, group_data):
1640 if group_data:
1635 if group_data:
1641 return group_data.get('extern_type')
1636 return group_data.get('extern_type')
1642
1637
1643 @property
1638 @property
1644 def sync(self):
1639 def sync(self):
1645 return self._load_sync(self.group_data)
1640 return self._load_sync(self.group_data)
1646
1641
1647 def __repr__(self):
1642 def __repr__(self):
1648 return f"<{self.cls_name}('id:{self.users_group_id}:{self.users_group_name}')>"
1643 return f"<{self.cls_name}('id:{self.users_group_id}:{self.users_group_name}')>"
1649
1644
1650 @classmethod
1645 @classmethod
1651 def get_by_group_name(cls, group_name, cache=False,
1646 def get_by_group_name(cls, group_name, cache=False,
1652 case_insensitive=False):
1647 case_insensitive=False):
1653 if case_insensitive:
1648 if case_insensitive:
1654 q = cls.query().filter(func.lower(cls.users_group_name) ==
1649 q = cls.query().filter(func.lower(cls.users_group_name) ==
1655 func.lower(group_name))
1650 func.lower(group_name))
1656
1651
1657 else:
1652 else:
1658 q = cls.query().filter(cls.users_group_name == group_name)
1653 q = cls.query().filter(cls.users_group_name == group_name)
1659 if cache:
1654 if cache:
1660 name_key = _hash_key(group_name)
1655 name_key = _hash_key(group_name)
1661 q = q.options(
1656 q = q.options(
1662 FromCache("sql_cache_short", f"get_group_{name_key}"))
1657 FromCache("sql_cache_short", f"get_group_{name_key}"))
1663 return q.scalar()
1658 return q.scalar()
1664
1659
1665 @classmethod
1660 @classmethod
1666 def get(cls, user_group_id, cache=False):
1661 def get(cls, user_group_id, cache=False):
1667 if not user_group_id:
1662 if not user_group_id:
1668 return
1663 return
1669
1664
1670 user_group = cls.query()
1665 user_group = cls.query()
1671 if cache:
1666 if cache:
1672 user_group = user_group.options(
1667 user_group = user_group.options(
1673 FromCache("sql_cache_short", f"get_users_group_{user_group_id}"))
1668 FromCache("sql_cache_short", f"get_users_group_{user_group_id}"))
1674 return user_group.get(user_group_id)
1669 return user_group.get(user_group_id)
1675
1670
1676 def permissions(self, with_admins=True, with_owner=True,
1671 def permissions(self, with_admins=True, with_owner=True,
1677 expand_from_user_groups=False):
1672 expand_from_user_groups=False):
1678 """
1673 """
1679 Permissions for user groups
1674 Permissions for user groups
1680 """
1675 """
1681 _admin_perm = 'usergroup.admin'
1676 _admin_perm = 'usergroup.admin'
1682
1677
1683 owner_row = []
1678 owner_row = []
1684 if with_owner:
1679 if with_owner:
1685 usr = AttributeDict(self.user.get_dict())
1680 usr = AttributeDict(self.user.get_dict())
1686 usr.owner_row = True
1681 usr.owner_row = True
1687 usr.permission = _admin_perm
1682 usr.permission = _admin_perm
1688 owner_row.append(usr)
1683 owner_row.append(usr)
1689
1684
1690 super_admin_ids = []
1685 super_admin_ids = []
1691 super_admin_rows = []
1686 super_admin_rows = []
1692 if with_admins:
1687 if with_admins:
1693 for usr in User.get_all_super_admins():
1688 for usr in User.get_all_super_admins():
1694 super_admin_ids.append(usr.user_id)
1689 super_admin_ids.append(usr.user_id)
1695 # if this admin is also owner, don't double the record
1690 # if this admin is also owner, don't double the record
1696 if usr.user_id == owner_row[0].user_id:
1691 if usr.user_id == owner_row[0].user_id:
1697 owner_row[0].admin_row = True
1692 owner_row[0].admin_row = True
1698 else:
1693 else:
1699 usr = AttributeDict(usr.get_dict())
1694 usr = AttributeDict(usr.get_dict())
1700 usr.admin_row = True
1695 usr.admin_row = True
1701 usr.permission = _admin_perm
1696 usr.permission = _admin_perm
1702 super_admin_rows.append(usr)
1697 super_admin_rows.append(usr)
1703
1698
1704 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1699 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1705 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1700 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1706 joinedload(UserUserGroupToPerm.user),
1701 joinedload(UserUserGroupToPerm.user),
1707 joinedload(UserUserGroupToPerm.permission),)
1702 joinedload(UserUserGroupToPerm.permission),)
1708
1703
1709 # get owners and admins and permissions. We do a trick of re-writing
1704 # get owners and admins and permissions. We do a trick of re-writing
1710 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1705 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1711 # has a global reference and changing one object propagates to all
1706 # has a global reference and changing one object propagates to all
1712 # others. This means if admin is also an owner admin_row that change
1707 # others. This means if admin is also an owner admin_row that change
1713 # would propagate to both objects
1708 # would propagate to both objects
1714 perm_rows = []
1709 perm_rows = []
1715 for _usr in q.all():
1710 for _usr in q.all():
1716 usr = AttributeDict(_usr.user.get_dict())
1711 usr = AttributeDict(_usr.user.get_dict())
1717 # if this user is also owner/admin, mark as duplicate record
1712 # if this user is also owner/admin, mark as duplicate record
1718 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1713 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1719 usr.duplicate_perm = True
1714 usr.duplicate_perm = True
1720 usr.permission = _usr.permission.permission_name
1715 usr.permission = _usr.permission.permission_name
1721 perm_rows.append(usr)
1716 perm_rows.append(usr)
1722
1717
1723 # filter the perm rows by 'default' first and then sort them by
1718 # filter the perm rows by 'default' first and then sort them by
1724 # admin,write,read,none permissions sorted again alphabetically in
1719 # admin,write,read,none permissions sorted again alphabetically in
1725 # each group
1720 # each group
1726 perm_rows = sorted(perm_rows, key=display_user_sort)
1721 perm_rows = sorted(perm_rows, key=display_user_sort)
1727
1722
1728 user_groups_rows = []
1723 user_groups_rows = []
1729 if expand_from_user_groups:
1724 if expand_from_user_groups:
1730 for ug in self.permission_user_groups(with_members=True):
1725 for ug in self.permission_user_groups(with_members=True):
1731 for user_data in ug.members:
1726 for user_data in ug.members:
1732 user_groups_rows.append(user_data)
1727 user_groups_rows.append(user_data)
1733
1728
1734 return super_admin_rows + owner_row + perm_rows + user_groups_rows
1729 return super_admin_rows + owner_row + perm_rows + user_groups_rows
1735
1730
1736 def permission_user_groups(self, with_members=False):
1731 def permission_user_groups(self, with_members=False):
1737 q = UserGroupUserGroupToPerm.query()\
1732 q = UserGroupUserGroupToPerm.query()\
1738 .filter(UserGroupUserGroupToPerm.target_user_group == self)
1733 .filter(UserGroupUserGroupToPerm.target_user_group == self)
1739 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1734 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1740 joinedload(UserGroupUserGroupToPerm.target_user_group),
1735 joinedload(UserGroupUserGroupToPerm.target_user_group),
1741 joinedload(UserGroupUserGroupToPerm.permission),)
1736 joinedload(UserGroupUserGroupToPerm.permission),)
1742
1737
1743 perm_rows = []
1738 perm_rows = []
1744 for _user_group in q.all():
1739 for _user_group in q.all():
1745 entry = AttributeDict(_user_group.user_group.get_dict())
1740 entry = AttributeDict(_user_group.user_group.get_dict())
1746 entry.permission = _user_group.permission.permission_name
1741 entry.permission = _user_group.permission.permission_name
1747 if with_members:
1742 if with_members:
1748 entry.members = [x.user.get_dict()
1743 entry.members = [x.user.get_dict()
1749 for x in _user_group.user_group.members]
1744 for x in _user_group.user_group.members]
1750 perm_rows.append(entry)
1745 perm_rows.append(entry)
1751
1746
1752 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1747 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1753 return perm_rows
1748 return perm_rows
1754
1749
1755 def _get_default_perms(self, user_group, suffix=''):
1750 def _get_default_perms(self, user_group, suffix=''):
1756 from rhodecode.model.permission import PermissionModel
1751 from rhodecode.model.permission import PermissionModel
1757 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1752 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1758
1753
1759 def get_default_perms(self, suffix=''):
1754 def get_default_perms(self, suffix=''):
1760 return self._get_default_perms(self, suffix)
1755 return self._get_default_perms(self, suffix)
1761
1756
1762 def get_api_data(self, with_group_members=True, include_secrets=False):
1757 def get_api_data(self, with_group_members=True, include_secrets=False):
1763 """
1758 """
1764 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1759 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1765 basically forwarded.
1760 basically forwarded.
1766
1761
1767 """
1762 """
1768 user_group = self
1763 user_group = self
1769 data = {
1764 data = {
1770 'users_group_id': user_group.users_group_id,
1765 'users_group_id': user_group.users_group_id,
1771 'group_name': user_group.users_group_name,
1766 'group_name': user_group.users_group_name,
1772 'group_description': user_group.user_group_description,
1767 'group_description': user_group.user_group_description,
1773 'active': user_group.users_group_active,
1768 'active': user_group.users_group_active,
1774 'owner': user_group.user.username,
1769 'owner': user_group.user.username,
1775 'sync': user_group.sync,
1770 'sync': user_group.sync,
1776 'owner_email': user_group.user.email,
1771 'owner_email': user_group.user.email,
1777 }
1772 }
1778
1773
1779 if with_group_members:
1774 if with_group_members:
1780 users = []
1775 users = []
1781 for user in user_group.members:
1776 for user in user_group.members:
1782 user = user.user
1777 user = user.user
1783 users.append(user.get_api_data(include_secrets=include_secrets))
1778 users.append(user.get_api_data(include_secrets=include_secrets))
1784 data['users'] = users
1779 data['users'] = users
1785
1780
1786 return data
1781 return data
1787
1782
1788
1783
1789 class UserGroupMember(Base, BaseModel):
1784 class UserGroupMember(Base, BaseModel):
1790 __tablename__ = 'users_groups_members'
1785 __tablename__ = 'users_groups_members'
1791 __table_args__ = (
1786 __table_args__ = (
1792 base_table_args,
1787 base_table_args,
1793 )
1788 )
1794
1789
1795 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1790 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1796 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1791 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1797 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1792 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1798
1793
1799 user = relationship('User', lazy='joined', back_populates='group_member')
1794 user = relationship('User', lazy='joined', back_populates='group_member')
1800 users_group = relationship('UserGroup', back_populates='members')
1795 users_group = relationship('UserGroup', back_populates='members')
1801
1796
1802 def __init__(self, gr_id='', u_id=''):
1797 def __init__(self, gr_id='', u_id=''):
1803 self.users_group_id = gr_id
1798 self.users_group_id = gr_id
1804 self.user_id = u_id
1799 self.user_id = u_id
1805
1800
1806
1801
1807 class RepositoryField(Base, BaseModel):
1802 class RepositoryField(Base, BaseModel):
1808 __tablename__ = 'repositories_fields'
1803 __tablename__ = 'repositories_fields'
1809 __table_args__ = (
1804 __table_args__ = (
1810 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1805 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1811 base_table_args,
1806 base_table_args,
1812 )
1807 )
1813
1808
1814 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1809 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1815
1810
1816 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1811 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1817 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1812 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1818 field_key = Column("field_key", String(250))
1813 field_key = Column("field_key", String(250))
1819 field_label = Column("field_label", String(1024), nullable=False)
1814 field_label = Column("field_label", String(1024), nullable=False)
1820 field_value = Column("field_value", String(10000), nullable=False)
1815 field_value = Column("field_value", String(10000), nullable=False)
1821 field_desc = Column("field_desc", String(1024), nullable=False)
1816 field_desc = Column("field_desc", String(1024), nullable=False)
1822 field_type = Column("field_type", String(255), nullable=False, unique=None)
1817 field_type = Column("field_type", String(255), nullable=False, unique=None)
1823 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1818 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1824
1819
1825 repository = relationship('Repository', back_populates='extra_fields')
1820 repository = relationship('Repository', back_populates='extra_fields')
1826
1821
1827 @property
1822 @property
1828 def field_key_prefixed(self):
1823 def field_key_prefixed(self):
1829 return 'ex_%s' % self.field_key
1824 return 'ex_%s' % self.field_key
1830
1825
1831 @classmethod
1826 @classmethod
1832 def un_prefix_key(cls, key):
1827 def un_prefix_key(cls, key):
1833 if key.startswith(cls.PREFIX):
1828 if key.startswith(cls.PREFIX):
1834 return key[len(cls.PREFIX):]
1829 return key[len(cls.PREFIX):]
1835 return key
1830 return key
1836
1831
1837 @classmethod
1832 @classmethod
1838 def get_by_key_name(cls, key, repo):
1833 def get_by_key_name(cls, key, repo):
1839 row = cls.query()\
1834 row = cls.query()\
1840 .filter(cls.repository == repo)\
1835 .filter(cls.repository == repo)\
1841 .filter(cls.field_key == key).scalar()
1836 .filter(cls.field_key == key).scalar()
1842 return row
1837 return row
1843
1838
1844
1839
1845 class Repository(Base, BaseModel):
1840 class Repository(Base, BaseModel):
1846 __tablename__ = 'repositories'
1841 __tablename__ = 'repositories'
1847 __table_args__ = (
1842 __table_args__ = (
1848 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1843 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1849 base_table_args,
1844 base_table_args,
1850 )
1845 )
1851 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1846 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1852 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1847 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1853 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1848 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1854
1849
1855 STATE_CREATED = 'repo_state_created'
1850 STATE_CREATED = 'repo_state_created'
1856 STATE_PENDING = 'repo_state_pending'
1851 STATE_PENDING = 'repo_state_pending'
1857 STATE_ERROR = 'repo_state_error'
1852 STATE_ERROR = 'repo_state_error'
1858
1853
1859 LOCK_AUTOMATIC = 'lock_auto'
1854 LOCK_AUTOMATIC = 'lock_auto'
1860 LOCK_API = 'lock_api'
1855 LOCK_API = 'lock_api'
1861 LOCK_WEB = 'lock_web'
1856 LOCK_WEB = 'lock_web'
1862 LOCK_PULL = 'lock_pull'
1857 LOCK_PULL = 'lock_pull'
1863
1858
1864 NAME_SEP = URL_SEP
1859 NAME_SEP = URL_SEP
1865
1860
1866 repo_id = Column(
1861 repo_id = Column(
1867 "repo_id", Integer(), nullable=False, unique=True, default=None,
1862 "repo_id", Integer(), nullable=False, unique=True, default=None,
1868 primary_key=True)
1863 primary_key=True)
1869 _repo_name = Column(
1864 _repo_name = Column(
1870 "repo_name", Text(), nullable=False, default=None)
1865 "repo_name", Text(), nullable=False, default=None)
1871 repo_name_hash = Column(
1866 repo_name_hash = Column(
1872 "repo_name_hash", String(255), nullable=False, unique=True)
1867 "repo_name_hash", String(255), nullable=False, unique=True)
1873 repo_state = Column("repo_state", String(255), nullable=True)
1868 repo_state = Column("repo_state", String(255), nullable=True)
1874
1869
1875 clone_uri = Column(
1870 clone_uri = Column(
1876 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1871 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1877 default=None)
1872 default=None)
1878 push_uri = Column(
1873 push_uri = Column(
1879 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1874 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1880 default=None)
1875 default=None)
1881 repo_type = Column(
1876 repo_type = Column(
1882 "repo_type", String(255), nullable=False, unique=False, default=None)
1877 "repo_type", String(255), nullable=False, unique=False, default=None)
1883 user_id = Column(
1878 user_id = Column(
1884 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1879 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1885 unique=False, default=None)
1880 unique=False, default=None)
1886 private = Column(
1881 private = Column(
1887 "private", Boolean(), nullable=True, unique=None, default=None)
1882 "private", Boolean(), nullable=True, unique=None, default=None)
1888 archived = Column(
1883 archived = Column(
1889 "archived", Boolean(), nullable=True, unique=None, default=None)
1884 "archived", Boolean(), nullable=True, unique=None, default=None)
1890 enable_statistics = Column(
1885 enable_statistics = Column(
1891 "statistics", Boolean(), nullable=True, unique=None, default=True)
1886 "statistics", Boolean(), nullable=True, unique=None, default=True)
1892 enable_downloads = Column(
1887 enable_downloads = Column(
1893 "downloads", Boolean(), nullable=True, unique=None, default=True)
1888 "downloads", Boolean(), nullable=True, unique=None, default=True)
1894 description = Column(
1889 description = Column(
1895 "description", String(10000), nullable=True, unique=None, default=None)
1890 "description", String(10000), nullable=True, unique=None, default=None)
1896 created_on = Column(
1891 created_on = Column(
1897 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1892 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1898 default=datetime.datetime.now)
1893 default=datetime.datetime.now)
1899 updated_on = Column(
1894 updated_on = Column(
1900 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1895 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1901 default=datetime.datetime.now)
1896 default=datetime.datetime.now)
1902 _landing_revision = Column(
1897 _landing_revision = Column(
1903 "landing_revision", String(255), nullable=False, unique=False,
1898 "landing_revision", String(255), nullable=False, unique=False,
1904 default=None)
1899 default=None)
1905 enable_locking = Column(
1900 enable_locking = Column(
1906 "enable_locking", Boolean(), nullable=False, unique=None,
1901 "enable_locking", Boolean(), nullable=False, unique=None,
1907 default=False)
1902 default=False)
1908 _locked = Column(
1903 _locked = Column(
1909 "locked", String(255), nullable=True, unique=False, default=None)
1904 "locked", String(255), nullable=True, unique=False, default=None)
1910 _changeset_cache = Column(
1905 _changeset_cache = Column(
1911 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1906 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1912
1907
1913 fork_id = Column(
1908 fork_id = Column(
1914 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1909 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1915 nullable=True, unique=False, default=None)
1910 nullable=True, unique=False, default=None)
1916 group_id = Column(
1911 group_id = Column(
1917 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1912 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1918 unique=False, default=None)
1913 unique=False, default=None)
1919
1914
1920 user = relationship('User', lazy='joined', back_populates='repositories')
1915 user = relationship('User', lazy='joined', back_populates='repositories')
1921 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1916 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1922 group = relationship('RepoGroup', lazy='joined')
1917 group = relationship('RepoGroup', lazy='joined')
1923 repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
1918 repo_to_perm = relationship('UserRepoToPerm', cascade='all', order_by='UserRepoToPerm.repo_to_perm_id')
1924 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all', back_populates='repository')
1919 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all', back_populates='repository')
1925 stats = relationship('Statistics', cascade='all', uselist=False)
1920 stats = relationship('Statistics', cascade='all', uselist=False)
1926
1921
1927 followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id', cascade='all', back_populates='follows_repository')
1922 followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id', cascade='all', back_populates='follows_repository')
1928 extra_fields = relationship('RepositoryField', cascade="all, delete-orphan", back_populates='repository')
1923 extra_fields = relationship('RepositoryField', cascade="all, delete-orphan", back_populates='repository')
1929
1924
1930 logs = relationship('UserLog', back_populates='repository')
1925 logs = relationship('UserLog', back_populates='repository')
1931
1926
1932 comments = relationship('ChangesetComment', cascade="all, delete-orphan", back_populates='repo')
1927 comments = relationship('ChangesetComment', cascade="all, delete-orphan", back_populates='repo')
1933
1928
1934 pull_requests_source = relationship(
1929 pull_requests_source = relationship(
1935 'PullRequest',
1930 'PullRequest',
1936 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1931 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1937 cascade="all, delete-orphan",
1932 cascade="all, delete-orphan",
1938 overlaps="source_repo"
1933 overlaps="source_repo"
1939 )
1934 )
1940 pull_requests_target = relationship(
1935 pull_requests_target = relationship(
1941 'PullRequest',
1936 'PullRequest',
1942 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1937 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1943 cascade="all, delete-orphan",
1938 cascade="all, delete-orphan",
1944 overlaps="target_repo"
1939 overlaps="target_repo"
1945 )
1940 )
1946
1941
1947 ui = relationship('RepoRhodeCodeUi', cascade="all")
1942 ui = relationship('RepoRhodeCodeUi', cascade="all")
1948 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1943 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1949 integrations = relationship('Integration', cascade="all, delete-orphan", back_populates='repo')
1944 integrations = relationship('Integration', cascade="all, delete-orphan", back_populates='repo')
1950
1945
1951 scoped_tokens = relationship('UserApiKeys', cascade="all", back_populates='repo')
1946 scoped_tokens = relationship('UserApiKeys', cascade="all", back_populates='repo')
1952
1947
1953 # no cascade, set NULL
1948 # no cascade, set NULL
1954 artifacts = relationship('FileStore', primaryjoin='FileStore.scope_repo_id==Repository.repo_id', viewonly=True)
1949 artifacts = relationship('FileStore', primaryjoin='FileStore.scope_repo_id==Repository.repo_id', viewonly=True)
1955
1950
1956 review_rules = relationship('RepoReviewRule')
1951 review_rules = relationship('RepoReviewRule')
1957 user_branch_perms = relationship('UserToRepoBranchPermission')
1952 user_branch_perms = relationship('UserToRepoBranchPermission')
1958 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission')
1953 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission')
1959
1954
1960 def __repr__(self):
1955 def __repr__(self):
1961 return "<%s('%s:%s')>" % (self.cls_name, self.repo_id, self.repo_name)
1956 return "<%s('%s:%s')>" % (self.cls_name, self.repo_id, self.repo_name)
1962
1957
1963 @hybrid_property
1958 @hybrid_property
1964 def description_safe(self):
1959 def description_safe(self):
1965 from rhodecode.lib import helpers as h
1960 from rhodecode.lib import helpers as h
1966 return h.escape(self.description)
1961 return h.escape(self.description)
1967
1962
1968 @hybrid_property
1963 @hybrid_property
1969 def landing_rev(self):
1964 def landing_rev(self):
1970 # always should return [rev_type, rev], e.g ['branch', 'master']
1965 # always should return [rev_type, rev], e.g ['branch', 'master']
1971 if self._landing_revision:
1966 if self._landing_revision:
1972 _rev_info = self._landing_revision.split(':')
1967 _rev_info = self._landing_revision.split(':')
1973 if len(_rev_info) < 2:
1968 if len(_rev_info) < 2:
1974 _rev_info.insert(0, 'rev')
1969 _rev_info.insert(0, 'rev')
1975 return [_rev_info[0], _rev_info[1]]
1970 return [_rev_info[0], _rev_info[1]]
1976 return [None, None]
1971 return [None, None]
1977
1972
1978 @property
1973 @property
1979 def landing_ref_type(self):
1974 def landing_ref_type(self):
1980 return self.landing_rev[0]
1975 return self.landing_rev[0]
1981
1976
1982 @property
1977 @property
1983 def landing_ref_name(self):
1978 def landing_ref_name(self):
1984 return self.landing_rev[1]
1979 return self.landing_rev[1]
1985
1980
1986 @landing_rev.setter
1981 @landing_rev.setter
1987 def landing_rev(self, val):
1982 def landing_rev(self, val):
1988 if ':' not in val:
1983 if ':' not in val:
1989 raise ValueError('value must be delimited with `:` and consist '
1984 raise ValueError('value must be delimited with `:` and consist '
1990 'of <rev_type>:<rev>, got %s instead' % val)
1985 'of <rev_type>:<rev>, got %s instead' % val)
1991 self._landing_revision = val
1986 self._landing_revision = val
1992
1987
1993 @hybrid_property
1988 @hybrid_property
1994 def locked(self):
1989 def locked(self):
1995 if self._locked:
1990 if self._locked:
1996 user_id, timelocked, reason = self._locked.split(':')
1991 user_id, timelocked, reason = self._locked.split(':')
1997 lock_values = int(user_id), timelocked, reason
1992 lock_values = int(user_id), timelocked, reason
1998 else:
1993 else:
1999 lock_values = [None, None, None]
1994 lock_values = [None, None, None]
2000 return lock_values
1995 return lock_values
2001
1996
2002 @locked.setter
1997 @locked.setter
2003 def locked(self, val):
1998 def locked(self, val):
2004 if val and isinstance(val, (list, tuple)):
1999 if val and isinstance(val, (list, tuple)):
2005 self._locked = ':'.join(map(str, val))
2000 self._locked = ':'.join(map(str, val))
2006 else:
2001 else:
2007 self._locked = None
2002 self._locked = None
2008
2003
2009 @classmethod
2004 @classmethod
2010 def _load_changeset_cache(cls, repo_id, changeset_cache_raw):
2005 def _load_changeset_cache(cls, repo_id, changeset_cache_raw):
2011 from rhodecode.lib.vcs.backends.base import EmptyCommit
2006 from rhodecode.lib.vcs.backends.base import EmptyCommit
2012 dummy = EmptyCommit().__json__()
2007 dummy = EmptyCommit().__json__()
2013 if not changeset_cache_raw:
2008 if not changeset_cache_raw:
2014 dummy['source_repo_id'] = repo_id
2009 dummy['source_repo_id'] = repo_id
2015 return json.loads(json.dumps(dummy))
2010 return json.loads(json.dumps(dummy))
2016
2011
2017 try:
2012 try:
2018 return json.loads(changeset_cache_raw)
2013 return json.loads(changeset_cache_raw)
2019 except TypeError:
2014 except TypeError:
2020 return dummy
2015 return dummy
2021 except Exception:
2016 except Exception:
2022 log.error(traceback.format_exc())
2017 log.error(traceback.format_exc())
2023 return dummy
2018 return dummy
2024
2019
2025 @hybrid_property
2020 @hybrid_property
2026 def changeset_cache(self):
2021 def changeset_cache(self):
2027 return self._load_changeset_cache(self.repo_id, self._changeset_cache)
2022 return self._load_changeset_cache(self.repo_id, self._changeset_cache)
2028
2023
2029 @changeset_cache.setter
2024 @changeset_cache.setter
2030 def changeset_cache(self, val):
2025 def changeset_cache(self, val):
2031 try:
2026 try:
2032 self._changeset_cache = json.dumps(val)
2027 self._changeset_cache = json.dumps(val)
2033 except Exception:
2028 except Exception:
2034 log.error(traceback.format_exc())
2029 log.error(traceback.format_exc())
2035
2030
2036 @hybrid_property
2031 @hybrid_property
2037 def repo_name(self):
2032 def repo_name(self):
2038 return self._repo_name
2033 return self._repo_name
2039
2034
2040 @repo_name.setter
2035 @repo_name.setter
2041 def repo_name(self, value):
2036 def repo_name(self, value):
2042 self._repo_name = value
2037 self._repo_name = value
2043 self.repo_name_hash = sha1(safe_bytes(value))
2038 self.repo_name_hash = sha1(safe_bytes(value))
2044
2039
2045 @classmethod
2040 @classmethod
2046 def normalize_repo_name(cls, repo_name):
2041 def normalize_repo_name(cls, repo_name):
2047 """
2042 """
2048 Normalizes os specific repo_name to the format internally stored inside
2043 Normalizes os specific repo_name to the format internally stored inside
2049 database using URL_SEP
2044 database using URL_SEP
2050
2045
2051 :param cls:
2046 :param cls:
2052 :param repo_name:
2047 :param repo_name:
2053 """
2048 """
2054 return cls.NAME_SEP.join(repo_name.split(os.sep))
2049 return cls.NAME_SEP.join(repo_name.split(os.sep))
2055
2050
2056 @classmethod
2051 @classmethod
2057 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
2052 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
2058 session = Session()
2053 session = Session()
2059 q = session.query(cls).filter(cls.repo_name == repo_name)
2054 q = session.query(cls).filter(cls.repo_name == repo_name)
2060
2055
2061 if cache:
2056 if cache:
2062 if identity_cache:
2057 if identity_cache:
2063 val = cls.identity_cache(session, 'repo_name', repo_name)
2058 val = cls.identity_cache(session, 'repo_name', repo_name)
2064 if val:
2059 if val:
2065 return val
2060 return val
2066 else:
2061 else:
2067 cache_key = f"get_repo_by_name_{_hash_key(repo_name)}"
2062 cache_key = f"get_repo_by_name_{_hash_key(repo_name)}"
2068 q = q.options(
2063 q = q.options(
2069 FromCache("sql_cache_short", cache_key))
2064 FromCache("sql_cache_short", cache_key))
2070
2065
2071 return q.scalar()
2066 return q.scalar()
2072
2067
2073 @classmethod
2068 @classmethod
2074 def get_by_id_or_repo_name(cls, repoid):
2069 def get_by_id_or_repo_name(cls, repoid):
2075 if isinstance(repoid, int):
2070 if isinstance(repoid, int):
2076 try:
2071 try:
2077 repo = cls.get(repoid)
2072 repo = cls.get(repoid)
2078 except ValueError:
2073 except ValueError:
2079 repo = None
2074 repo = None
2080 else:
2075 else:
2081 repo = cls.get_by_repo_name(repoid)
2076 repo = cls.get_by_repo_name(repoid)
2082 return repo
2077 return repo
2083
2078
2084 @classmethod
2079 @classmethod
2085 def get_by_full_path(cls, repo_full_path):
2080 def get_by_full_path(cls, repo_full_path):
2086 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
2081 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
2087 repo_name = cls.normalize_repo_name(repo_name)
2082 repo_name = cls.normalize_repo_name(repo_name)
2088 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
2083 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
2089
2084
2090 @classmethod
2085 @classmethod
2091 def get_repo_forks(cls, repo_id):
2086 def get_repo_forks(cls, repo_id):
2092 return cls.query().filter(Repository.fork_id == repo_id)
2087 return cls.query().filter(Repository.fork_id == repo_id)
2093
2088
2094 @classmethod
2089 @classmethod
2095 def base_path(cls):
2090 def base_path(cls):
2096 """
2091 """
2097 Returns base path when all repos are stored
2092 Returns base path when all repos are stored
2098
2093
2099 :param cls:
2094 :param cls:
2100 """
2095 """
2101 from rhodecode.lib.utils import get_rhodecode_repo_store_path
2096 from rhodecode.lib.utils import get_rhodecode_repo_store_path
2102 return get_rhodecode_repo_store_path()
2097 return get_rhodecode_repo_store_path()
2103
2098
2104 @classmethod
2099 @classmethod
2105 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
2100 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
2106 case_insensitive=True, archived=False):
2101 case_insensitive=True, archived=False):
2107 q = Repository.query()
2102 q = Repository.query()
2108
2103
2109 if not archived:
2104 if not archived:
2110 q = q.filter(Repository.archived.isnot(true()))
2105 q = q.filter(Repository.archived.isnot(true()))
2111
2106
2112 if not isinstance(user_id, Optional):
2107 if not isinstance(user_id, Optional):
2113 q = q.filter(Repository.user_id == user_id)
2108 q = q.filter(Repository.user_id == user_id)
2114
2109
2115 if not isinstance(group_id, Optional):
2110 if not isinstance(group_id, Optional):
2116 q = q.filter(Repository.group_id == group_id)
2111 q = q.filter(Repository.group_id == group_id)
2117
2112
2118 if case_insensitive:
2113 if case_insensitive:
2119 q = q.order_by(func.lower(Repository.repo_name))
2114 q = q.order_by(func.lower(Repository.repo_name))
2120 else:
2115 else:
2121 q = q.order_by(Repository.repo_name)
2116 q = q.order_by(Repository.repo_name)
2122
2117
2123 return q.all()
2118 return q.all()
2124
2119
2125 @property
2120 @property
2126 def repo_uid(self):
2121 def repo_uid(self):
2127 return '_{}'.format(self.repo_id)
2122 return '_{}'.format(self.repo_id)
2128
2123
2129 @property
2124 @property
2130 def forks(self):
2125 def forks(self):
2131 """
2126 """
2132 Return forks of this repo
2127 Return forks of this repo
2133 """
2128 """
2134 return Repository.get_repo_forks(self.repo_id)
2129 return Repository.get_repo_forks(self.repo_id)
2135
2130
2136 @property
2131 @property
2137 def parent(self):
2132 def parent(self):
2138 """
2133 """
2139 Returns fork parent
2134 Returns fork parent
2140 """
2135 """
2141 return self.fork
2136 return self.fork
2142
2137
2143 @property
2138 @property
2144 def just_name(self):
2139 def just_name(self):
2145 return self.repo_name.split(self.NAME_SEP)[-1]
2140 return self.repo_name.split(self.NAME_SEP)[-1]
2146
2141
2147 @property
2142 @property
2148 def groups_with_parents(self):
2143 def groups_with_parents(self):
2149 groups = []
2144 groups = []
2150 if self.group is None:
2145 if self.group is None:
2151 return groups
2146 return groups
2152
2147
2153 cur_gr = self.group
2148 cur_gr = self.group
2154 groups.insert(0, cur_gr)
2149 groups.insert(0, cur_gr)
2155 while 1:
2150 while 1:
2156 gr = getattr(cur_gr, 'parent_group', None)
2151 gr = getattr(cur_gr, 'parent_group', None)
2157 cur_gr = cur_gr.parent_group
2152 cur_gr = cur_gr.parent_group
2158 if gr is None:
2153 if gr is None:
2159 break
2154 break
2160 groups.insert(0, gr)
2155 groups.insert(0, gr)
2161
2156
2162 return groups
2157 return groups
2163
2158
2164 @property
2159 @property
2165 def groups_and_repo(self):
2160 def groups_and_repo(self):
2166 return self.groups_with_parents, self
2161 return self.groups_with_parents, self
2167
2162
2168 @property
2163 @property
2169 def repo_path(self):
2164 def repo_path(self):
2170 """
2165 """
2171 Returns base full path for that repository means where it actually
2166 Returns base full path for that repository means where it actually
2172 exists on a filesystem
2167 exists on a filesystem
2173 """
2168 """
2174 return self.base_path()
2169 return self.base_path()
2175
2170
2176 @property
2171 @property
2177 def repo_full_path(self):
2172 def repo_full_path(self):
2178 p = [self.repo_path]
2173 p = [self.repo_path]
2179 # we need to split the name by / since this is how we store the
2174 # we need to split the name by / since this is how we store the
2180 # names in the database, but that eventually needs to be converted
2175 # names in the database, but that eventually needs to be converted
2181 # into a valid system path
2176 # into a valid system path
2182 p += self.repo_name.split(self.NAME_SEP)
2177 p += self.repo_name.split(self.NAME_SEP)
2183 return os.path.join(*map(safe_str, p))
2178 return os.path.join(*map(safe_str, p))
2184
2179
2185 @property
2180 @property
2186 def cache_keys(self):
2181 def cache_keys(self):
2187 """
2182 """
2188 Returns associated cache keys for that repo
2183 Returns associated cache keys for that repo
2189 """
2184 """
2190 repo_namespace_key = CacheKey.REPO_INVALIDATION_NAMESPACE.format(repo_id=self.repo_id)
2185 repo_namespace_key = CacheKey.REPO_INVALIDATION_NAMESPACE.format(repo_id=self.repo_id)
2191 return CacheKey.query()\
2186 return CacheKey.query()\
2192 .filter(CacheKey.cache_key == repo_namespace_key)\
2187 .filter(CacheKey.cache_key == repo_namespace_key)\
2193 .order_by(CacheKey.cache_key)\
2188 .order_by(CacheKey.cache_key)\
2194 .all()
2189 .all()
2195
2190
2196 @property
2191 @property
2197 def cached_diffs_relative_dir(self):
2192 def cached_diffs_relative_dir(self):
2198 """
2193 """
2199 Return a relative to the repository store path of cached diffs
2194 Return a relative to the repository store path of cached diffs
2200 used for safe display for users, who shouldn't know the absolute store
2195 used for safe display for users, who shouldn't know the absolute store
2201 path
2196 path
2202 """
2197 """
2203 return os.path.join(
2198 return os.path.join(
2204 os.path.dirname(self.repo_name),
2199 os.path.dirname(self.repo_name),
2205 self.cached_diffs_dir.split(os.path.sep)[-1])
2200 self.cached_diffs_dir.split(os.path.sep)[-1])
2206
2201
2207 @property
2202 @property
2208 def cached_diffs_dir(self):
2203 def cached_diffs_dir(self):
2209 path = self.repo_full_path
2204 path = self.repo_full_path
2210 return os.path.join(
2205 return os.path.join(
2211 os.path.dirname(path),
2206 os.path.dirname(path),
2212 f'.__shadow_diff_cache_repo_{self.repo_id}')
2207 f'.__shadow_diff_cache_repo_{self.repo_id}')
2213
2208
2214 def cached_diffs(self):
2209 def cached_diffs(self):
2215 diff_cache_dir = self.cached_diffs_dir
2210 diff_cache_dir = self.cached_diffs_dir
2216 if os.path.isdir(diff_cache_dir):
2211 if os.path.isdir(diff_cache_dir):
2217 return os.listdir(diff_cache_dir)
2212 return os.listdir(diff_cache_dir)
2218 return []
2213 return []
2219
2214
2220 def shadow_repos(self):
2215 def shadow_repos(self):
2221 shadow_repos_pattern = f'.__shadow_repo_{self.repo_id}'
2216 shadow_repos_pattern = f'.__shadow_repo_{self.repo_id}'
2222 return [
2217 return [
2223 x for x in os.listdir(os.path.dirname(self.repo_full_path))
2218 x for x in os.listdir(os.path.dirname(self.repo_full_path))
2224 if x.startswith(shadow_repos_pattern)
2219 if x.startswith(shadow_repos_pattern)
2225 ]
2220 ]
2226
2221
2227 def get_new_name(self, repo_name):
2222 def get_new_name(self, repo_name):
2228 """
2223 """
2229 returns new full repository name based on assigned group and new new
2224 returns new full repository name based on assigned group and new new
2230
2225
2231 :param repo_name:
2226 :param repo_name:
2232 """
2227 """
2233 path_prefix = self.group.full_path_splitted if self.group else []
2228 path_prefix = self.group.full_path_splitted if self.group else []
2234 return self.NAME_SEP.join(path_prefix + [repo_name])
2229 return self.NAME_SEP.join(path_prefix + [repo_name])
2235
2230
2236 @property
2231 @property
2237 def _config(self):
2232 def _config(self):
2238 """
2233 """
2239 Returns db based config object.
2234 Returns db based config object.
2240 """
2235 """
2241 from rhodecode.lib.utils import make_db_config
2236 from rhodecode.lib.utils import make_db_config
2242 return make_db_config(clear_session=False, repo=self)
2237 return make_db_config(clear_session=False, repo=self)
2243
2238
2244 def permissions(self, with_admins=True, with_owner=True,
2239 def permissions(self, with_admins=True, with_owner=True,
2245 expand_from_user_groups=False):
2240 expand_from_user_groups=False):
2246 """
2241 """
2247 Permissions for repositories
2242 Permissions for repositories
2248 """
2243 """
2249 _admin_perm = 'repository.admin'
2244 _admin_perm = 'repository.admin'
2250
2245
2251 owner_row = []
2246 owner_row = []
2252 if with_owner:
2247 if with_owner:
2253 usr = AttributeDict(self.user.get_dict())
2248 usr = AttributeDict(self.user.get_dict())
2254 usr.owner_row = True
2249 usr.owner_row = True
2255 usr.permission = _admin_perm
2250 usr.permission = _admin_perm
2256 usr.permission_id = None
2251 usr.permission_id = None
2257 owner_row.append(usr)
2252 owner_row.append(usr)
2258
2253
2259 super_admin_ids = []
2254 super_admin_ids = []
2260 super_admin_rows = []
2255 super_admin_rows = []
2261 if with_admins:
2256 if with_admins:
2262 for usr in User.get_all_super_admins():
2257 for usr in User.get_all_super_admins():
2263 super_admin_ids.append(usr.user_id)
2258 super_admin_ids.append(usr.user_id)
2264 # if this admin is also owner, don't double the record
2259 # if this admin is also owner, don't double the record
2265 if usr.user_id == owner_row[0].user_id:
2260 if usr.user_id == owner_row[0].user_id:
2266 owner_row[0].admin_row = True
2261 owner_row[0].admin_row = True
2267 else:
2262 else:
2268 usr = AttributeDict(usr.get_dict())
2263 usr = AttributeDict(usr.get_dict())
2269 usr.admin_row = True
2264 usr.admin_row = True
2270 usr.permission = _admin_perm
2265 usr.permission = _admin_perm
2271 usr.permission_id = None
2266 usr.permission_id = None
2272 super_admin_rows.append(usr)
2267 super_admin_rows.append(usr)
2273
2268
2274 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
2269 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
2275 q = q.options(joinedload(UserRepoToPerm.repository),
2270 q = q.options(joinedload(UserRepoToPerm.repository),
2276 joinedload(UserRepoToPerm.user),
2271 joinedload(UserRepoToPerm.user),
2277 joinedload(UserRepoToPerm.permission),)
2272 joinedload(UserRepoToPerm.permission),)
2278
2273
2279 # get owners and admins and permissions. We do a trick of re-writing
2274 # get owners and admins and permissions. We do a trick of re-writing
2280 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2275 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2281 # has a global reference and changing one object propagates to all
2276 # has a global reference and changing one object propagates to all
2282 # others. This means if admin is also an owner admin_row that change
2277 # others. This means if admin is also an owner admin_row that change
2283 # would propagate to both objects
2278 # would propagate to both objects
2284 perm_rows = []
2279 perm_rows = []
2285 for _usr in q.all():
2280 for _usr in q.all():
2286 usr = AttributeDict(_usr.user.get_dict())
2281 usr = AttributeDict(_usr.user.get_dict())
2287 # if this user is also owner/admin, mark as duplicate record
2282 # if this user is also owner/admin, mark as duplicate record
2288 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2283 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2289 usr.duplicate_perm = True
2284 usr.duplicate_perm = True
2290 # also check if this permission is maybe used by branch_permissions
2285 # also check if this permission is maybe used by branch_permissions
2291 if _usr.branch_perm_entry:
2286 if _usr.branch_perm_entry:
2292 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
2287 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
2293
2288
2294 usr.permission = _usr.permission.permission_name
2289 usr.permission = _usr.permission.permission_name
2295 usr.permission_id = _usr.repo_to_perm_id
2290 usr.permission_id = _usr.repo_to_perm_id
2296 perm_rows.append(usr)
2291 perm_rows.append(usr)
2297
2292
2298 # filter the perm rows by 'default' first and then sort them by
2293 # filter the perm rows by 'default' first and then sort them by
2299 # admin,write,read,none permissions sorted again alphabetically in
2294 # admin,write,read,none permissions sorted again alphabetically in
2300 # each group
2295 # each group
2301 perm_rows = sorted(perm_rows, key=display_user_sort)
2296 perm_rows = sorted(perm_rows, key=display_user_sort)
2302
2297
2303 user_groups_rows = []
2298 user_groups_rows = []
2304 if expand_from_user_groups:
2299 if expand_from_user_groups:
2305 for ug in self.permission_user_groups(with_members=True):
2300 for ug in self.permission_user_groups(with_members=True):
2306 for user_data in ug.members:
2301 for user_data in ug.members:
2307 user_groups_rows.append(user_data)
2302 user_groups_rows.append(user_data)
2308
2303
2309 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2304 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2310
2305
2311 def permission_user_groups(self, with_members=True):
2306 def permission_user_groups(self, with_members=True):
2312 q = UserGroupRepoToPerm.query()\
2307 q = UserGroupRepoToPerm.query()\
2313 .filter(UserGroupRepoToPerm.repository == self)
2308 .filter(UserGroupRepoToPerm.repository == self)
2314 q = q.options(joinedload(UserGroupRepoToPerm.repository),
2309 q = q.options(joinedload(UserGroupRepoToPerm.repository),
2315 joinedload(UserGroupRepoToPerm.users_group),
2310 joinedload(UserGroupRepoToPerm.users_group),
2316 joinedload(UserGroupRepoToPerm.permission),)
2311 joinedload(UserGroupRepoToPerm.permission),)
2317
2312
2318 perm_rows = []
2313 perm_rows = []
2319 for _user_group in q.all():
2314 for _user_group in q.all():
2320 entry = AttributeDict(_user_group.users_group.get_dict())
2315 entry = AttributeDict(_user_group.users_group.get_dict())
2321 entry.permission = _user_group.permission.permission_name
2316 entry.permission = _user_group.permission.permission_name
2322 if with_members:
2317 if with_members:
2323 entry.members = [x.user.get_dict()
2318 entry.members = [x.user.get_dict()
2324 for x in _user_group.users_group.members]
2319 for x in _user_group.users_group.members]
2325 perm_rows.append(entry)
2320 perm_rows.append(entry)
2326
2321
2327 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2322 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2328 return perm_rows
2323 return perm_rows
2329
2324
2330 def get_api_data(self, include_secrets=False):
2325 def get_api_data(self, include_secrets=False):
2331 """
2326 """
2332 Common function for generating repo api data
2327 Common function for generating repo api data
2333
2328
2334 :param include_secrets: See :meth:`User.get_api_data`.
2329 :param include_secrets: See :meth:`User.get_api_data`.
2335
2330
2336 """
2331 """
2337 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2332 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2338 # move this methods on models level.
2333 # move this methods on models level.
2339 from rhodecode.model.settings import SettingsModel
2334 from rhodecode.model.settings import SettingsModel
2340 from rhodecode.model.repo import RepoModel
2335 from rhodecode.model.repo import RepoModel
2341
2336
2342 repo = self
2337 repo = self
2343 _user_id, _time, _reason = self.locked
2338 _user_id, _time, _reason = self.locked
2344
2339
2345 data = {
2340 data = {
2346 'repo_id': repo.repo_id,
2341 'repo_id': repo.repo_id,
2347 'repo_name': repo.repo_name,
2342 'repo_name': repo.repo_name,
2348 'repo_type': repo.repo_type,
2343 'repo_type': repo.repo_type,
2349 'clone_uri': repo.clone_uri or '',
2344 'clone_uri': repo.clone_uri or '',
2350 'push_uri': repo.push_uri or '',
2345 'push_uri': repo.push_uri or '',
2351 'url': RepoModel().get_url(self),
2346 'url': RepoModel().get_url(self),
2352 'private': repo.private,
2347 'private': repo.private,
2353 'created_on': repo.created_on,
2348 'created_on': repo.created_on,
2354 'description': repo.description_safe,
2349 'description': repo.description_safe,
2355 'landing_rev': repo.landing_rev,
2350 'landing_rev': repo.landing_rev,
2356 'owner': repo.user.username,
2351 'owner': repo.user.username,
2357 'fork_of': repo.fork.repo_name if repo.fork else None,
2352 'fork_of': repo.fork.repo_name if repo.fork else None,
2358 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2353 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2359 'enable_statistics': repo.enable_statistics,
2354 'enable_statistics': repo.enable_statistics,
2360 'enable_locking': repo.enable_locking,
2355 'enable_locking': repo.enable_locking,
2361 'enable_downloads': repo.enable_downloads,
2356 'enable_downloads': repo.enable_downloads,
2362 'last_changeset': repo.changeset_cache,
2357 'last_changeset': repo.changeset_cache,
2363 'locked_by': User.get(_user_id).get_api_data(
2358 'locked_by': User.get(_user_id).get_api_data(
2364 include_secrets=include_secrets) if _user_id else None,
2359 include_secrets=include_secrets) if _user_id else None,
2365 'locked_date': time_to_datetime(_time) if _time else None,
2360 'locked_date': time_to_datetime(_time) if _time else None,
2366 'lock_reason': _reason if _reason else None,
2361 'lock_reason': _reason if _reason else None,
2367 }
2362 }
2368
2363
2369 # TODO: mikhail: should be per-repo settings here
2364 # TODO: mikhail: should be per-repo settings here
2370 rc_config = SettingsModel().get_all_settings()
2365 rc_config = SettingsModel().get_all_settings()
2371 repository_fields = str2bool(
2366 repository_fields = str2bool(
2372 rc_config.get('rhodecode_repository_fields'))
2367 rc_config.get('rhodecode_repository_fields'))
2373 if repository_fields:
2368 if repository_fields:
2374 for f in self.extra_fields:
2369 for f in self.extra_fields:
2375 data[f.field_key_prefixed] = f.field_value
2370 data[f.field_key_prefixed] = f.field_value
2376
2371
2377 return data
2372 return data
2378
2373
2379 @classmethod
2374 @classmethod
2380 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2375 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2381 if not lock_time:
2376 if not lock_time:
2382 lock_time = time.time()
2377 lock_time = time.time()
2383 if not lock_reason:
2378 if not lock_reason:
2384 lock_reason = cls.LOCK_AUTOMATIC
2379 lock_reason = cls.LOCK_AUTOMATIC
2385 repo.locked = [user_id, lock_time, lock_reason]
2380 repo.locked = [user_id, lock_time, lock_reason]
2386 Session().add(repo)
2381 Session().add(repo)
2387 Session().commit()
2382 Session().commit()
2388
2383
2389 @classmethod
2384 @classmethod
2390 def unlock(cls, repo):
2385 def unlock(cls, repo):
2391 repo.locked = None
2386 repo.locked = None
2392 Session().add(repo)
2387 Session().add(repo)
2393 Session().commit()
2388 Session().commit()
2394
2389
2395 @classmethod
2390 @classmethod
2396 def getlock(cls, repo):
2391 def getlock(cls, repo):
2397 return repo.locked
2392 return repo.locked
2398
2393
2399 def get_locking_state(self, action, user_id, only_when_enabled=True):
2394 def get_locking_state(self, action, user_id, only_when_enabled=True):
2400 """
2395 """
2401 Checks locking on this repository, if locking is enabled and lock is
2396 Checks locking on this repository, if locking is enabled and lock is
2402 present returns a tuple of make_lock, locked, locked_by.
2397 present returns a tuple of make_lock, locked, locked_by.
2403 make_lock can have 3 states None (do nothing) True, make lock
2398 make_lock can have 3 states None (do nothing) True, make lock
2404 False release lock, This value is later propagated to hooks, which
2399 False release lock, This value is later propagated to hooks, which
2405 do the locking. Think about this as signals passed to hooks what to do.
2400 do the locking. Think about this as signals passed to hooks what to do.
2406
2401
2407 """
2402 """
2408 # TODO: johbo: This is part of the business logic and should be moved
2403 # TODO: johbo: This is part of the business logic and should be moved
2409 # into the RepositoryModel.
2404 # into the RepositoryModel.
2410
2405
2411 if action not in ('push', 'pull'):
2406 if action not in ('push', 'pull'):
2412 raise ValueError("Invalid action value: %s" % repr(action))
2407 raise ValueError("Invalid action value: %s" % repr(action))
2413
2408
2414 # defines if locked error should be thrown to user
2409 # defines if locked error should be thrown to user
2415 currently_locked = False
2410 currently_locked = False
2416 # defines if new lock should be made, tri-state
2411 # defines if new lock should be made, tri-state
2417 make_lock = None
2412 make_lock = None
2418 repo = self
2413 repo = self
2419 user = User.get(user_id)
2414 user = User.get(user_id)
2420
2415
2421 lock_info = repo.locked
2416 lock_info = repo.locked
2422
2417
2423 if repo and (repo.enable_locking or not only_when_enabled):
2418 if repo and (repo.enable_locking or not only_when_enabled):
2424 if action == 'push':
2419 if action == 'push':
2425 # check if it's already locked !, if it is compare users
2420 # check if it's already locked !, if it is compare users
2426 locked_by_user_id = lock_info[0]
2421 locked_by_user_id = lock_info[0]
2427 if user.user_id == locked_by_user_id:
2422 if user.user_id == locked_by_user_id:
2428 log.debug(
2423 log.debug(
2429 'Got `push` action from user %s, now unlocking', user)
2424 'Got `push` action from user %s, now unlocking', user)
2430 # unlock if we have push from user who locked
2425 # unlock if we have push from user who locked
2431 make_lock = False
2426 make_lock = False
2432 else:
2427 else:
2433 # we're not the same user who locked, ban with
2428 # we're not the same user who locked, ban with
2434 # code defined in settings (default is 423 HTTP Locked) !
2429 # code defined in settings (default is 423 HTTP Locked) !
2435 log.debug('Repo %s is currently locked by %s', repo, user)
2430 log.debug('Repo %s is currently locked by %s', repo, user)
2436 currently_locked = True
2431 currently_locked = True
2437 elif action == 'pull':
2432 elif action == 'pull':
2438 # [0] user [1] date
2433 # [0] user [1] date
2439 if lock_info[0] and lock_info[1]:
2434 if lock_info[0] and lock_info[1]:
2440 log.debug('Repo %s is currently locked by %s', repo, user)
2435 log.debug('Repo %s is currently locked by %s', repo, user)
2441 currently_locked = True
2436 currently_locked = True
2442 else:
2437 else:
2443 log.debug('Setting lock on repo %s by %s', repo, user)
2438 log.debug('Setting lock on repo %s by %s', repo, user)
2444 make_lock = True
2439 make_lock = True
2445
2440
2446 else:
2441 else:
2447 log.debug('Repository %s do not have locking enabled', repo)
2442 log.debug('Repository %s do not have locking enabled', repo)
2448
2443
2449 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2444 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2450 make_lock, currently_locked, lock_info)
2445 make_lock, currently_locked, lock_info)
2451
2446
2452 from rhodecode.lib.auth import HasRepoPermissionAny
2447 from rhodecode.lib.auth import HasRepoPermissionAny
2453 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2448 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2454 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2449 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2455 # if we don't have at least write permission we cannot make a lock
2450 # if we don't have at least write permission we cannot make a lock
2456 log.debug('lock state reset back to FALSE due to lack '
2451 log.debug('lock state reset back to FALSE due to lack '
2457 'of at least read permission')
2452 'of at least read permission')
2458 make_lock = False
2453 make_lock = False
2459
2454
2460 return make_lock, currently_locked, lock_info
2455 return make_lock, currently_locked, lock_info
2461
2456
2462 @property
2457 @property
2463 def last_commit_cache_update_diff(self):
2458 def last_commit_cache_update_diff(self):
2464 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2459 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2465
2460
2466 @classmethod
2461 @classmethod
2467 def _load_commit_change(cls, last_commit_cache):
2462 def _load_commit_change(cls, last_commit_cache):
2468 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2463 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2469 empty_date = datetime.datetime.fromtimestamp(0)
2464 empty_date = datetime.datetime.fromtimestamp(0)
2470 date_latest = last_commit_cache.get('date', empty_date)
2465 date_latest = last_commit_cache.get('date', empty_date)
2471 try:
2466 try:
2472 return parse_datetime(date_latest)
2467 return parse_datetime(date_latest)
2473 except Exception:
2468 except Exception:
2474 return empty_date
2469 return empty_date
2475
2470
2476 @property
2471 @property
2477 def last_commit_change(self):
2472 def last_commit_change(self):
2478 return self._load_commit_change(self.changeset_cache)
2473 return self._load_commit_change(self.changeset_cache)
2479
2474
2480 @property
2475 @property
2481 def last_db_change(self):
2476 def last_db_change(self):
2482 return self.updated_on
2477 return self.updated_on
2483
2478
2484 @property
2479 @property
2485 def clone_uri_hidden(self):
2480 def clone_uri_hidden(self):
2486 clone_uri = self.clone_uri
2481 clone_uri = self.clone_uri
2487 if clone_uri:
2482 if clone_uri:
2488 import urlobject
2483 import urlobject
2489 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2484 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2490 if url_obj.password:
2485 if url_obj.password:
2491 clone_uri = url_obj.with_password('*****')
2486 clone_uri = url_obj.with_password('*****')
2492 return clone_uri
2487 return clone_uri
2493
2488
2494 @property
2489 @property
2495 def push_uri_hidden(self):
2490 def push_uri_hidden(self):
2496 push_uri = self.push_uri
2491 push_uri = self.push_uri
2497 if push_uri:
2492 if push_uri:
2498 import urlobject
2493 import urlobject
2499 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2494 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2500 if url_obj.password:
2495 if url_obj.password:
2501 push_uri = url_obj.with_password('*****')
2496 push_uri = url_obj.with_password('*****')
2502 return push_uri
2497 return push_uri
2503
2498
2504 def clone_url(self, **override):
2499 def clone_url(self, **override):
2505 from rhodecode.model.settings import SettingsModel
2500 from rhodecode.model.settings import SettingsModel
2506
2501
2507 uri_tmpl = None
2502 uri_tmpl = None
2508 if 'with_id' in override:
2503 if 'with_id' in override:
2509 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2504 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2510 del override['with_id']
2505 del override['with_id']
2511
2506
2512 if 'uri_tmpl' in override:
2507 if 'uri_tmpl' in override:
2513 uri_tmpl = override['uri_tmpl']
2508 uri_tmpl = override['uri_tmpl']
2514 del override['uri_tmpl']
2509 del override['uri_tmpl']
2515
2510
2516 ssh = False
2511 ssh = False
2517 if 'ssh' in override:
2512 if 'ssh' in override:
2518 ssh = True
2513 ssh = True
2519 del override['ssh']
2514 del override['ssh']
2520
2515
2521 # we didn't override our tmpl from **overrides
2516 # we didn't override our tmpl from **overrides
2522 request = get_current_request()
2517 request = get_current_request()
2523 if not uri_tmpl:
2518 if not uri_tmpl:
2524 if hasattr(request, 'call_context') and hasattr(request.call_context, 'rc_config'):
2519 if hasattr(request, 'call_context') and hasattr(request.call_context, 'rc_config'):
2525 rc_config = request.call_context.rc_config
2520 rc_config = request.call_context.rc_config
2526 else:
2521 else:
2527 rc_config = SettingsModel().get_all_settings(cache=True)
2522 rc_config = SettingsModel().get_all_settings(cache=True)
2528
2523
2529 if ssh:
2524 if ssh:
2530 uri_tmpl = rc_config.get(
2525 uri_tmpl = rc_config.get(
2531 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2526 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2532
2527
2533 else:
2528 else:
2534 uri_tmpl = rc_config.get(
2529 uri_tmpl = rc_config.get(
2535 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2530 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2536
2531
2537 return get_clone_url(request=request,
2532 return get_clone_url(request=request,
2538 uri_tmpl=uri_tmpl,
2533 uri_tmpl=uri_tmpl,
2539 repo_name=self.repo_name,
2534 repo_name=self.repo_name,
2540 repo_id=self.repo_id,
2535 repo_id=self.repo_id,
2541 repo_type=self.repo_type,
2536 repo_type=self.repo_type,
2542 **override)
2537 **override)
2543
2538
2544 def set_state(self, state):
2539 def set_state(self, state):
2545 self.repo_state = state
2540 self.repo_state = state
2546 Session().add(self)
2541 Session().add(self)
2547 #==========================================================================
2542 #==========================================================================
2548 # SCM PROPERTIES
2543 # SCM PROPERTIES
2549 #==========================================================================
2544 #==========================================================================
2550
2545
2551 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None, maybe_unreachable=False, reference_obj=None):
2546 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None, maybe_unreachable=False, reference_obj=None):
2552 return get_commit_safe(
2547 return get_commit_safe(
2553 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load,
2548 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load,
2554 maybe_unreachable=maybe_unreachable, reference_obj=reference_obj)
2549 maybe_unreachable=maybe_unreachable, reference_obj=reference_obj)
2555
2550
2556 def get_changeset(self, rev=None, pre_load=None):
2551 def get_changeset(self, rev=None, pre_load=None):
2557 warnings.warn("Use get_commit", DeprecationWarning)
2552 warnings.warn("Use get_commit", DeprecationWarning)
2558 commit_id = None
2553 commit_id = None
2559 commit_idx = None
2554 commit_idx = None
2560 if isinstance(rev, str):
2555 if isinstance(rev, str):
2561 commit_id = rev
2556 commit_id = rev
2562 else:
2557 else:
2563 commit_idx = rev
2558 commit_idx = rev
2564 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2559 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2565 pre_load=pre_load)
2560 pre_load=pre_load)
2566
2561
2567 def get_landing_commit(self):
2562 def get_landing_commit(self):
2568 """
2563 """
2569 Returns landing commit, or if that doesn't exist returns the tip
2564 Returns landing commit, or if that doesn't exist returns the tip
2570 """
2565 """
2571 _rev_type, _rev = self.landing_rev
2566 _rev_type, _rev = self.landing_rev
2572 commit = self.get_commit(_rev)
2567 commit = self.get_commit(_rev)
2573 if isinstance(commit, EmptyCommit):
2568 if isinstance(commit, EmptyCommit):
2574 return self.get_commit()
2569 return self.get_commit()
2575 return commit
2570 return commit
2576
2571
2577 def flush_commit_cache(self):
2572 def flush_commit_cache(self):
2578 self.update_commit_cache(cs_cache={'raw_id':'0'})
2573 self.update_commit_cache(cs_cache={'raw_id':'0'})
2579 self.update_commit_cache()
2574 self.update_commit_cache()
2580
2575
2581 def update_commit_cache(self, cs_cache=None, config=None):
2576 def update_commit_cache(self, cs_cache=None, config=None):
2582 """
2577 """
2583 Update cache of last commit for repository
2578 Update cache of last commit for repository
2584 cache_keys should be::
2579 cache_keys should be::
2585
2580
2586 source_repo_id
2581 source_repo_id
2587 short_id
2582 short_id
2588 raw_id
2583 raw_id
2589 revision
2584 revision
2590 parents
2585 parents
2591 message
2586 message
2592 date
2587 date
2593 author
2588 author
2594 updated_on
2589 updated_on
2595
2590
2596 """
2591 """
2597 from rhodecode.lib.vcs.backends.base import BaseCommit
2592 from rhodecode.lib.vcs.backends.base import BaseCommit
2598 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2593 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2599 empty_date = datetime.datetime.fromtimestamp(0)
2594 empty_date = datetime.datetime.fromtimestamp(0)
2600 repo_commit_count = 0
2595 repo_commit_count = 0
2601
2596
2602 if cs_cache is None:
2597 if cs_cache is None:
2603 # use no-cache version here
2598 # use no-cache version here
2604 try:
2599 try:
2605 scm_repo = self.scm_instance(cache=False, config=config)
2600 scm_repo = self.scm_instance(cache=False, config=config)
2606 except VCSError:
2601 except VCSError:
2607 scm_repo = None
2602 scm_repo = None
2608 empty = scm_repo is None or scm_repo.is_empty()
2603 empty = scm_repo is None or scm_repo.is_empty()
2609
2604
2610 if not empty:
2605 if not empty:
2611 cs_cache = scm_repo.get_commit(
2606 cs_cache = scm_repo.get_commit(
2612 pre_load=["author", "date", "message", "parents", "branch"])
2607 pre_load=["author", "date", "message", "parents", "branch"])
2613 repo_commit_count = scm_repo.count()
2608 repo_commit_count = scm_repo.count()
2614 else:
2609 else:
2615 cs_cache = EmptyCommit()
2610 cs_cache = EmptyCommit()
2616
2611
2617 if isinstance(cs_cache, BaseCommit):
2612 if isinstance(cs_cache, BaseCommit):
2618 cs_cache = cs_cache.__json__()
2613 cs_cache = cs_cache.__json__()
2619
2614
2620 def is_outdated(new_cs_cache):
2615 def is_outdated(new_cs_cache):
2621 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2616 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2622 new_cs_cache['revision'] != self.changeset_cache['revision']):
2617 new_cs_cache['revision'] != self.changeset_cache['revision']):
2623 return True
2618 return True
2624 return False
2619 return False
2625
2620
2626 # check if we have maybe already latest cached revision
2621 # check if we have maybe already latest cached revision
2627 if is_outdated(cs_cache) or not self.changeset_cache:
2622 if is_outdated(cs_cache) or not self.changeset_cache:
2628 _current_datetime = datetime.datetime.utcnow()
2623 _current_datetime = datetime.datetime.utcnow()
2629 last_change = cs_cache.get('date') or _current_datetime
2624 last_change = cs_cache.get('date') or _current_datetime
2630 # we check if last update is newer than the new value
2625 # we check if last update is newer than the new value
2631 # if yes, we use the current timestamp instead. Imagine you get
2626 # if yes, we use the current timestamp instead. Imagine you get
2632 # old commit pushed 1y ago, we'd set last update 1y to ago.
2627 # old commit pushed 1y ago, we'd set last update 1y to ago.
2633 last_change_timestamp = datetime_to_time(last_change)
2628 last_change_timestamp = datetime_to_time(last_change)
2634 current_timestamp = datetime_to_time(last_change)
2629 current_timestamp = datetime_to_time(last_change)
2635 if last_change_timestamp > current_timestamp and not empty:
2630 if last_change_timestamp > current_timestamp and not empty:
2636 cs_cache['date'] = _current_datetime
2631 cs_cache['date'] = _current_datetime
2637
2632
2638 # also store size of repo
2633 # also store size of repo
2639 cs_cache['repo_commit_count'] = repo_commit_count
2634 cs_cache['repo_commit_count'] = repo_commit_count
2640
2635
2641 _date_latest = parse_datetime(cs_cache.get('date') or empty_date)
2636 _date_latest = parse_datetime(cs_cache.get('date') or empty_date)
2642 cs_cache['updated_on'] = time.time()
2637 cs_cache['updated_on'] = time.time()
2643 self.changeset_cache = cs_cache
2638 self.changeset_cache = cs_cache
2644 self.updated_on = last_change
2639 self.updated_on = last_change
2645 Session().add(self)
2640 Session().add(self)
2646 Session().commit()
2641 Session().commit()
2647
2642
2648 else:
2643 else:
2649 if empty:
2644 if empty:
2650 cs_cache = EmptyCommit().__json__()
2645 cs_cache = EmptyCommit().__json__()
2651 else:
2646 else:
2652 cs_cache = self.changeset_cache
2647 cs_cache = self.changeset_cache
2653
2648
2654 _date_latest = parse_datetime(cs_cache.get('date') or empty_date)
2649 _date_latest = parse_datetime(cs_cache.get('date') or empty_date)
2655
2650
2656 cs_cache['updated_on'] = time.time()
2651 cs_cache['updated_on'] = time.time()
2657 self.changeset_cache = cs_cache
2652 self.changeset_cache = cs_cache
2658 self.updated_on = _date_latest
2653 self.updated_on = _date_latest
2659 Session().add(self)
2654 Session().add(self)
2660 Session().commit()
2655 Session().commit()
2661
2656
2662 log.debug('updated repo `%s` with new commit cache %s, and last update_date: %s',
2657 log.debug('updated repo `%s` with new commit cache %s, and last update_date: %s',
2663 self.repo_name, cs_cache, _date_latest)
2658 self.repo_name, cs_cache, _date_latest)
2664
2659
2665 @property
2660 @property
2666 def tip(self):
2661 def tip(self):
2667 return self.get_commit('tip')
2662 return self.get_commit('tip')
2668
2663
2669 @property
2664 @property
2670 def author(self):
2665 def author(self):
2671 return self.tip.author
2666 return self.tip.author
2672
2667
2673 @property
2668 @property
2674 def last_change(self):
2669 def last_change(self):
2675 return self.scm_instance().last_change
2670 return self.scm_instance().last_change
2676
2671
2677 def get_comments(self, revisions=None):
2672 def get_comments(self, revisions=None):
2678 """
2673 """
2679 Returns comments for this repository grouped by revisions
2674 Returns comments for this repository grouped by revisions
2680
2675
2681 :param revisions: filter query by revisions only
2676 :param revisions: filter query by revisions only
2682 """
2677 """
2683 cmts = ChangesetComment.query()\
2678 cmts = ChangesetComment.query()\
2684 .filter(ChangesetComment.repo == self)
2679 .filter(ChangesetComment.repo == self)
2685 if revisions:
2680 if revisions:
2686 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2681 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2687 grouped = collections.defaultdict(list)
2682 grouped = collections.defaultdict(list)
2688 for cmt in cmts.all():
2683 for cmt in cmts.all():
2689 grouped[cmt.revision].append(cmt)
2684 grouped[cmt.revision].append(cmt)
2690 return grouped
2685 return grouped
2691
2686
2692 def statuses(self, revisions=None):
2687 def statuses(self, revisions=None):
2693 """
2688 """
2694 Returns statuses for this repository
2689 Returns statuses for this repository
2695
2690
2696 :param revisions: list of revisions to get statuses for
2691 :param revisions: list of revisions to get statuses for
2697 """
2692 """
2698 statuses = ChangesetStatus.query()\
2693 statuses = ChangesetStatus.query()\
2699 .filter(ChangesetStatus.repo == self)\
2694 .filter(ChangesetStatus.repo == self)\
2700 .filter(ChangesetStatus.version == 0)
2695 .filter(ChangesetStatus.version == 0)
2701
2696
2702 if revisions:
2697 if revisions:
2703 # Try doing the filtering in chunks to avoid hitting limits
2698 # Try doing the filtering in chunks to avoid hitting limits
2704 size = 500
2699 size = 500
2705 status_results = []
2700 status_results = []
2706 for chunk in range(0, len(revisions), size):
2701 for chunk in range(0, len(revisions), size):
2707 status_results += statuses.filter(
2702 status_results += statuses.filter(
2708 ChangesetStatus.revision.in_(
2703 ChangesetStatus.revision.in_(
2709 revisions[chunk: chunk+size])
2704 revisions[chunk: chunk+size])
2710 ).all()
2705 ).all()
2711 else:
2706 else:
2712 status_results = statuses.all()
2707 status_results = statuses.all()
2713
2708
2714 grouped = {}
2709 grouped = {}
2715
2710
2716 # maybe we have open new pullrequest without a status?
2711 # maybe we have open new pullrequest without a status?
2717 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2712 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2718 status_lbl = ChangesetStatus.get_status_lbl(stat)
2713 status_lbl = ChangesetStatus.get_status_lbl(stat)
2719 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2714 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2720 for rev in pr.revisions:
2715 for rev in pr.revisions:
2721 pr_id = pr.pull_request_id
2716 pr_id = pr.pull_request_id
2722 pr_repo = pr.target_repo.repo_name
2717 pr_repo = pr.target_repo.repo_name
2723 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2718 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2724
2719
2725 for stat in status_results:
2720 for stat in status_results:
2726 pr_id = pr_repo = None
2721 pr_id = pr_repo = None
2727 if stat.pull_request:
2722 if stat.pull_request:
2728 pr_id = stat.pull_request.pull_request_id
2723 pr_id = stat.pull_request.pull_request_id
2729 pr_repo = stat.pull_request.target_repo.repo_name
2724 pr_repo = stat.pull_request.target_repo.repo_name
2730 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2725 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2731 pr_id, pr_repo]
2726 pr_id, pr_repo]
2732 return grouped
2727 return grouped
2733
2728
2734 # ==========================================================================
2729 # ==========================================================================
2735 # SCM CACHE INSTANCE
2730 # SCM CACHE INSTANCE
2736 # ==========================================================================
2731 # ==========================================================================
2737
2732
2738 def scm_instance(self, **kwargs):
2733 def scm_instance(self, **kwargs):
2739 import rhodecode
2734 import rhodecode
2740
2735
2741 # Passing a config will not hit the cache currently only used
2736 # Passing a config will not hit the cache currently only used
2742 # for repo2dbmapper
2737 # for repo2dbmapper
2743 config = kwargs.pop('config', None)
2738 config = kwargs.pop('config', None)
2744 cache = kwargs.pop('cache', None)
2739 cache = kwargs.pop('cache', None)
2745 vcs_full_cache = kwargs.pop('vcs_full_cache', None)
2740 vcs_full_cache = kwargs.pop('vcs_full_cache', None)
2746 if vcs_full_cache is not None:
2741 if vcs_full_cache is not None:
2747 # allows override global config
2742 # allows override global config
2748 full_cache = vcs_full_cache
2743 full_cache = vcs_full_cache
2749 else:
2744 else:
2750 full_cache = rhodecode.ConfigGet().get_bool('vcs_full_cache')
2745 full_cache = rhodecode.ConfigGet().get_bool('vcs_full_cache')
2751 # if cache is NOT defined use default global, else we have a full
2746 # if cache is NOT defined use default global, else we have a full
2752 # control over cache behaviour
2747 # control over cache behaviour
2753 if cache is None and full_cache and not config:
2748 if cache is None and full_cache and not config:
2754 log.debug('Initializing pure cached instance for %s', self.repo_path)
2749 log.debug('Initializing pure cached instance for %s', self.repo_path)
2755 return self._get_instance_cached()
2750 return self._get_instance_cached()
2756
2751
2757 # cache here is sent to the "vcs server"
2752 # cache here is sent to the "vcs server"
2758 return self._get_instance(cache=bool(cache), config=config)
2753 return self._get_instance(cache=bool(cache), config=config)
2759
2754
2760 def _get_instance_cached(self):
2755 def _get_instance_cached(self):
2761 from rhodecode.lib import rc_cache
2756 from rhodecode.lib import rc_cache
2762
2757
2763 cache_namespace_uid = f'repo_instance.{self.repo_id}'
2758 cache_namespace_uid = f'repo_instance.{self.repo_id}'
2764 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2759 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2765
2760
2766 # we must use thread scoped cache here,
2761 # we must use thread scoped cache here,
2767 # because each thread of gevent needs it's own not shared connection and cache
2762 # because each thread of gevent needs it's own not shared connection and cache
2768 # we also alter `args` so the cache key is individual for every green thread.
2763 # we also alter `args` so the cache key is individual for every green thread.
2769 repo_namespace_key = CacheKey.REPO_INVALIDATION_NAMESPACE.format(repo_id=self.repo_id)
2764 repo_namespace_key = CacheKey.REPO_INVALIDATION_NAMESPACE.format(repo_id=self.repo_id)
2770 inv_context_manager = rc_cache.InvalidationContext(key=repo_namespace_key, thread_scoped=True)
2765 inv_context_manager = rc_cache.InvalidationContext(key=repo_namespace_key, thread_scoped=True)
2771
2766
2772 # our wrapped caching function that takes state_uid to save the previous state in
2767 # our wrapped caching function that takes state_uid to save the previous state in
2773 def cache_generator(_state_uid):
2768 def cache_generator(_state_uid):
2774
2769
2775 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2770 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2776 def get_instance_cached(_repo_id, _process_context_id):
2771 def get_instance_cached(_repo_id, _process_context_id):
2777 # we save in cached func the generation state so we can detect a change and invalidate caches
2772 # we save in cached func the generation state so we can detect a change and invalidate caches
2778 return _state_uid, self._get_instance(repo_state_uid=_state_uid)
2773 return _state_uid, self._get_instance(repo_state_uid=_state_uid)
2779
2774
2780 return get_instance_cached
2775 return get_instance_cached
2781
2776
2782 with inv_context_manager as invalidation_context:
2777 with inv_context_manager as invalidation_context:
2783 cache_state_uid = invalidation_context.state_uid
2778 cache_state_uid = invalidation_context.state_uid
2784 cache_func = cache_generator(cache_state_uid)
2779 cache_func = cache_generator(cache_state_uid)
2785
2780
2786 args = self.repo_id, inv_context_manager.proc_key
2781 args = self.repo_id, inv_context_manager.proc_key
2787
2782
2788 previous_state_uid, instance = cache_func(*args)
2783 previous_state_uid, instance = cache_func(*args)
2789
2784
2790 # now compare keys, the "cache" state vs expected state.
2785 # now compare keys, the "cache" state vs expected state.
2791 if previous_state_uid != cache_state_uid:
2786 if previous_state_uid != cache_state_uid:
2792 log.warning('Cached state uid %s is different than current state uid %s',
2787 log.warning('Cached state uid %s is different than current state uid %s',
2793 previous_state_uid, cache_state_uid)
2788 previous_state_uid, cache_state_uid)
2794 _, instance = cache_func.refresh(*args)
2789 _, instance = cache_func.refresh(*args)
2795
2790
2796 log.debug('Repo instance fetched in %.4fs', inv_context_manager.compute_time)
2791 log.debug('Repo instance fetched in %.4fs', inv_context_manager.compute_time)
2797 return instance
2792 return instance
2798
2793
2799 def _get_instance(self, cache=True, config=None, repo_state_uid=None):
2794 def _get_instance(self, cache=True, config=None, repo_state_uid=None):
2800 log.debug('Initializing %s instance `%s` with cache flag set to: %s',
2795 log.debug('Initializing %s instance `%s` with cache flag set to: %s',
2801 self.repo_type, self.repo_path, cache)
2796 self.repo_type, self.repo_path, cache)
2802 config = config or self._config
2797 config = config or self._config
2803 custom_wire = {
2798 custom_wire = {
2804 'cache': cache, # controls the vcs.remote cache
2799 'cache': cache, # controls the vcs.remote cache
2805 'repo_state_uid': repo_state_uid
2800 'repo_state_uid': repo_state_uid
2806 }
2801 }
2807
2802
2808 repo = get_vcs_instance(
2803 repo = get_vcs_instance(
2809 repo_path=safe_str(self.repo_full_path),
2804 repo_path=safe_str(self.repo_full_path),
2810 config=config,
2805 config=config,
2811 with_wire=custom_wire,
2806 with_wire=custom_wire,
2812 create=False,
2807 create=False,
2813 _vcs_alias=self.repo_type)
2808 _vcs_alias=self.repo_type)
2814 if repo is not None:
2809 if repo is not None:
2815 repo.count() # cache rebuild
2810 repo.count() # cache rebuild
2816
2811
2817 return repo
2812 return repo
2818
2813
2819 def get_shadow_repository_path(self, workspace_id):
2814 def get_shadow_repository_path(self, workspace_id):
2820 from rhodecode.lib.vcs.backends.base import BaseRepository
2815 from rhodecode.lib.vcs.backends.base import BaseRepository
2821 shadow_repo_path = BaseRepository._get_shadow_repository_path(
2816 shadow_repo_path = BaseRepository._get_shadow_repository_path(
2822 self.repo_full_path, self.repo_id, workspace_id)
2817 self.repo_full_path, self.repo_id, workspace_id)
2823 return shadow_repo_path
2818 return shadow_repo_path
2824
2819
2825 def __json__(self):
2820 def __json__(self):
2826 return {'landing_rev': self.landing_rev}
2821 return {'landing_rev': self.landing_rev}
2827
2822
2828 def get_dict(self):
2823 def get_dict(self):
2829
2824
2830 # Since we transformed `repo_name` to a hybrid property, we need to
2825 # Since we transformed `repo_name` to a hybrid property, we need to
2831 # keep compatibility with the code which uses `repo_name` field.
2826 # keep compatibility with the code which uses `repo_name` field.
2832
2827
2833 result = super(Repository, self).get_dict()
2828 result = super(Repository, self).get_dict()
2834 result['repo_name'] = result.pop('_repo_name', None)
2829 result['repo_name'] = result.pop('_repo_name', None)
2835 result.pop('_changeset_cache', '')
2830 result.pop('_changeset_cache', '')
2836 return result
2831 return result
2837
2832
2838
2833
2839 class RepoGroup(Base, BaseModel):
2834 class RepoGroup(Base, BaseModel):
2840 __tablename__ = 'groups'
2835 __tablename__ = 'groups'
2841 __table_args__ = (
2836 __table_args__ = (
2842 UniqueConstraint('group_name', 'group_parent_id'),
2837 UniqueConstraint('group_name', 'group_parent_id'),
2843 base_table_args,
2838 base_table_args,
2844 )
2839 )
2845
2840
2846 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2841 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2847
2842
2848 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2843 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2849 _group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2844 _group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2850 group_name_hash = Column("repo_group_name_hash", String(1024), nullable=False, unique=False)
2845 group_name_hash = Column("repo_group_name_hash", String(1024), nullable=False, unique=False)
2851 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2846 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2852 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2847 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2853 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2848 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2854 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2849 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2855 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2850 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2856 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2851 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2857 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2852 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2858 _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) # JSON data
2853 _changeset_cache = Column("changeset_cache", LargeBinary(), nullable=True) # JSON data
2859
2854
2860 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id', back_populates='group')
2855 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id', back_populates='group')
2861 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all', back_populates='group')
2856 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all', back_populates='group')
2862 parent_group = relationship('RepoGroup', remote_side=group_id)
2857 parent_group = relationship('RepoGroup', remote_side=group_id)
2863 user = relationship('User', back_populates='repository_groups')
2858 user = relationship('User', back_populates='repository_groups')
2864 integrations = relationship('Integration', cascade="all, delete-orphan", back_populates='repo_group')
2859 integrations = relationship('Integration', cascade="all, delete-orphan", back_populates='repo_group')
2865
2860
2866 # no cascade, set NULL
2861 # no cascade, set NULL
2867 scope_artifacts = relationship('FileStore', primaryjoin='FileStore.scope_repo_group_id==RepoGroup.group_id', viewonly=True)
2862 scope_artifacts = relationship('FileStore', primaryjoin='FileStore.scope_repo_group_id==RepoGroup.group_id', viewonly=True)
2868
2863
2869 def __init__(self, group_name='', parent_group=None):
2864 def __init__(self, group_name='', parent_group=None):
2870 self.group_name = group_name
2865 self.group_name = group_name
2871 self.parent_group = parent_group
2866 self.parent_group = parent_group
2872
2867
2873 def __repr__(self):
2868 def __repr__(self):
2874 return f"<{self.cls_name}('id:{self.group_id}:{self.group_name}')>"
2869 return f"<{self.cls_name}('id:{self.group_id}:{self.group_name}')>"
2875
2870
2876 @hybrid_property
2871 @hybrid_property
2877 def group_name(self):
2872 def group_name(self):
2878 return self._group_name
2873 return self._group_name
2879
2874
2880 @group_name.setter
2875 @group_name.setter
2881 def group_name(self, value):
2876 def group_name(self, value):
2882 self._group_name = value
2877 self._group_name = value
2883 self.group_name_hash = self.hash_repo_group_name(value)
2878 self.group_name_hash = self.hash_repo_group_name(value)
2884
2879
2885 @classmethod
2880 @classmethod
2886 def _load_changeset_cache(cls, repo_id, changeset_cache_raw):
2881 def _load_changeset_cache(cls, repo_id, changeset_cache_raw):
2887 from rhodecode.lib.vcs.backends.base import EmptyCommit
2882 from rhodecode.lib.vcs.backends.base import EmptyCommit
2888 dummy = EmptyCommit().__json__()
2883 dummy = EmptyCommit().__json__()
2889 if not changeset_cache_raw:
2884 if not changeset_cache_raw:
2890 dummy['source_repo_id'] = repo_id
2885 dummy['source_repo_id'] = repo_id
2891 return json.loads(json.dumps(dummy))
2886 return json.loads(json.dumps(dummy))
2892
2887
2893 try:
2888 try:
2894 return json.loads(changeset_cache_raw)
2889 return json.loads(changeset_cache_raw)
2895 except TypeError:
2890 except TypeError:
2896 return dummy
2891 return dummy
2897 except Exception:
2892 except Exception:
2898 log.error(traceback.format_exc())
2893 log.error(traceback.format_exc())
2899 return dummy
2894 return dummy
2900
2895
2901 @hybrid_property
2896 @hybrid_property
2902 def changeset_cache(self):
2897 def changeset_cache(self):
2903 return self._load_changeset_cache('', self._changeset_cache)
2898 return self._load_changeset_cache('', self._changeset_cache)
2904
2899
2905 @changeset_cache.setter
2900 @changeset_cache.setter
2906 def changeset_cache(self, val):
2901 def changeset_cache(self, val):
2907 try:
2902 try:
2908 self._changeset_cache = json.dumps(val)
2903 self._changeset_cache = json.dumps(val)
2909 except Exception:
2904 except Exception:
2910 log.error(traceback.format_exc())
2905 log.error(traceback.format_exc())
2911
2906
2912 @validates('group_parent_id')
2907 @validates('group_parent_id')
2913 def validate_group_parent_id(self, key, val):
2908 def validate_group_parent_id(self, key, val):
2914 """
2909 """
2915 Check cycle references for a parent group to self
2910 Check cycle references for a parent group to self
2916 """
2911 """
2917 if self.group_id and val:
2912 if self.group_id and val:
2918 assert val != self.group_id
2913 assert val != self.group_id
2919
2914
2920 return val
2915 return val
2921
2916
2922 @hybrid_property
2917 @hybrid_property
2923 def description_safe(self):
2918 def description_safe(self):
2924 from rhodecode.lib import helpers as h
2919 from rhodecode.lib import helpers as h
2925 return h.escape(self.group_description)
2920 return h.escape(self.group_description)
2926
2921
2927 @classmethod
2922 @classmethod
2928 def hash_repo_group_name(cls, repo_group_name):
2923 def hash_repo_group_name(cls, repo_group_name):
2929 val = remove_formatting(repo_group_name)
2924 val = remove_formatting(repo_group_name)
2930 val = safe_str(val).lower()
2925 val = safe_str(val).lower()
2931 chars = []
2926 chars = []
2932 for c in val:
2927 for c in val:
2933 if c not in string.ascii_letters:
2928 if c not in string.ascii_letters:
2934 c = str(ord(c))
2929 c = str(ord(c))
2935 chars.append(c)
2930 chars.append(c)
2936
2931
2937 return ''.join(chars)
2932 return ''.join(chars)
2938
2933
2939 @classmethod
2934 @classmethod
2940 def _generate_choice(cls, repo_group):
2935 def _generate_choice(cls, repo_group):
2941 from webhelpers2.html import literal as _literal
2936 from webhelpers2.html import literal as _literal
2942
2937
2943 def _name(k):
2938 def _name(k):
2944 return _literal(cls.CHOICES_SEPARATOR.join(k))
2939 return _literal(cls.CHOICES_SEPARATOR.join(k))
2945
2940
2946 return repo_group.group_id, _name(repo_group.full_path_splitted)
2941 return repo_group.group_id, _name(repo_group.full_path_splitted)
2947
2942
2948 @classmethod
2943 @classmethod
2949 def groups_choices(cls, groups=None, show_empty_group=True):
2944 def groups_choices(cls, groups=None, show_empty_group=True):
2950 if not groups:
2945 if not groups:
2951 groups = cls.query().all()
2946 groups = cls.query().all()
2952
2947
2953 repo_groups = []
2948 repo_groups = []
2954 if show_empty_group:
2949 if show_empty_group:
2955 repo_groups = [(-1, '-- %s --' % _('No parent'))]
2950 repo_groups = [(-1, '-- %s --' % _('No parent'))]
2956
2951
2957 repo_groups.extend([cls._generate_choice(x) for x in groups])
2952 repo_groups.extend([cls._generate_choice(x) for x in groups])
2958
2953
2959 repo_groups = sorted(
2954 repo_groups = sorted(
2960 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2955 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2961 return repo_groups
2956 return repo_groups
2962
2957
2963 @classmethod
2958 @classmethod
2964 def url_sep(cls):
2959 def url_sep(cls):
2965 return URL_SEP
2960 return URL_SEP
2966
2961
2967 @classmethod
2962 @classmethod
2968 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2963 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2969 if case_insensitive:
2964 if case_insensitive:
2970 gr = cls.query().filter(func.lower(cls.group_name)
2965 gr = cls.query().filter(func.lower(cls.group_name)
2971 == func.lower(group_name))
2966 == func.lower(group_name))
2972 else:
2967 else:
2973 gr = cls.query().filter(cls.group_name == group_name)
2968 gr = cls.query().filter(cls.group_name == group_name)
2974 if cache:
2969 if cache:
2975 name_key = _hash_key(group_name)
2970 name_key = _hash_key(group_name)
2976 gr = gr.options(
2971 gr = gr.options(
2977 FromCache("sql_cache_short", f"get_group_{name_key}"))
2972 FromCache("sql_cache_short", f"get_group_{name_key}"))
2978 return gr.scalar()
2973 return gr.scalar()
2979
2974
2980 @classmethod
2975 @classmethod
2981 def get_user_personal_repo_group(cls, user_id):
2976 def get_user_personal_repo_group(cls, user_id):
2982 user = User.get(user_id)
2977 user = User.get(user_id)
2983 if user.username == User.DEFAULT_USER:
2978 if user.username == User.DEFAULT_USER:
2984 return None
2979 return None
2985
2980
2986 return cls.query()\
2981 return cls.query()\
2987 .filter(cls.personal == true()) \
2982 .filter(cls.personal == true()) \
2988 .filter(cls.user == user) \
2983 .filter(cls.user == user) \
2989 .order_by(cls.group_id.asc()) \
2984 .order_by(cls.group_id.asc()) \
2990 .first()
2985 .first()
2991
2986
2992 @classmethod
2987 @classmethod
2993 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2988 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2994 case_insensitive=True):
2989 case_insensitive=True):
2995 q = RepoGroup.query()
2990 q = RepoGroup.query()
2996
2991
2997 if not isinstance(user_id, Optional):
2992 if not isinstance(user_id, Optional):
2998 q = q.filter(RepoGroup.user_id == user_id)
2993 q = q.filter(RepoGroup.user_id == user_id)
2999
2994
3000 if not isinstance(group_id, Optional):
2995 if not isinstance(group_id, Optional):
3001 q = q.filter(RepoGroup.group_parent_id == group_id)
2996 q = q.filter(RepoGroup.group_parent_id == group_id)
3002
2997
3003 if case_insensitive:
2998 if case_insensitive:
3004 q = q.order_by(func.lower(RepoGroup.group_name))
2999 q = q.order_by(func.lower(RepoGroup.group_name))
3005 else:
3000 else:
3006 q = q.order_by(RepoGroup.group_name)
3001 q = q.order_by(RepoGroup.group_name)
3007 return q.all()
3002 return q.all()
3008
3003
3009 @property
3004 @property
3010 def parents(self, parents_recursion_limit=10):
3005 def parents(self, parents_recursion_limit=10):
3011 groups = []
3006 groups = []
3012 if self.parent_group is None:
3007 if self.parent_group is None:
3013 return groups
3008 return groups
3014 cur_gr = self.parent_group
3009 cur_gr = self.parent_group
3015 groups.insert(0, cur_gr)
3010 groups.insert(0, cur_gr)
3016 cnt = 0
3011 cnt = 0
3017 while 1:
3012 while 1:
3018 cnt += 1
3013 cnt += 1
3019 gr = getattr(cur_gr, 'parent_group', None)
3014 gr = getattr(cur_gr, 'parent_group', None)
3020 cur_gr = cur_gr.parent_group
3015 cur_gr = cur_gr.parent_group
3021 if gr is None:
3016 if gr is None:
3022 break
3017 break
3023 if cnt == parents_recursion_limit:
3018 if cnt == parents_recursion_limit:
3024 # this will prevent accidental infinit loops
3019 # this will prevent accidental infinit loops
3025 log.error('more than %s parents found for group %s, stopping '
3020 log.error('more than %s parents found for group %s, stopping '
3026 'recursive parent fetching', parents_recursion_limit, self)
3021 'recursive parent fetching', parents_recursion_limit, self)
3027 break
3022 break
3028
3023
3029 groups.insert(0, gr)
3024 groups.insert(0, gr)
3030 return groups
3025 return groups
3031
3026
3032 @property
3027 @property
3033 def last_commit_cache_update_diff(self):
3028 def last_commit_cache_update_diff(self):
3034 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
3029 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
3035
3030
3036 @classmethod
3031 @classmethod
3037 def _load_commit_change(cls, last_commit_cache):
3032 def _load_commit_change(cls, last_commit_cache):
3038 from rhodecode.lib.vcs.utils.helpers import parse_datetime
3033 from rhodecode.lib.vcs.utils.helpers import parse_datetime
3039 empty_date = datetime.datetime.fromtimestamp(0)
3034 empty_date = datetime.datetime.fromtimestamp(0)
3040 date_latest = last_commit_cache.get('date', empty_date)
3035 date_latest = last_commit_cache.get('date', empty_date)
3041 try:
3036 try:
3042 return parse_datetime(date_latest)
3037 return parse_datetime(date_latest)
3043 except Exception:
3038 except Exception:
3044 return empty_date
3039 return empty_date
3045
3040
3046 @property
3041 @property
3047 def last_commit_change(self):
3042 def last_commit_change(self):
3048 return self._load_commit_change(self.changeset_cache)
3043 return self._load_commit_change(self.changeset_cache)
3049
3044
3050 @property
3045 @property
3051 def last_db_change(self):
3046 def last_db_change(self):
3052 return self.updated_on
3047 return self.updated_on
3053
3048
3054 @property
3049 @property
3055 def children(self):
3050 def children(self):
3056 return RepoGroup.query().filter(RepoGroup.parent_group == self)
3051 return RepoGroup.query().filter(RepoGroup.parent_group == self)
3057
3052
3058 @property
3053 @property
3059 def name(self):
3054 def name(self):
3060 return self.group_name.split(RepoGroup.url_sep())[-1]
3055 return self.group_name.split(RepoGroup.url_sep())[-1]
3061
3056
3062 @property
3057 @property
3063 def full_path(self):
3058 def full_path(self):
3064 return self.group_name
3059 return self.group_name
3065
3060
3066 @property
3061 @property
3067 def full_path_splitted(self):
3062 def full_path_splitted(self):
3068 return self.group_name.split(RepoGroup.url_sep())
3063 return self.group_name.split(RepoGroup.url_sep())
3069
3064
3070 @property
3065 @property
3071 def repositories(self):
3066 def repositories(self):
3072 return Repository.query()\
3067 return Repository.query()\
3073 .filter(Repository.group == self)\
3068 .filter(Repository.group == self)\
3074 .order_by(Repository.repo_name)
3069 .order_by(Repository.repo_name)
3075
3070
3076 @property
3071 @property
3077 def repositories_recursive_count(self):
3072 def repositories_recursive_count(self):
3078 cnt = self.repositories.count()
3073 cnt = self.repositories.count()
3079
3074
3080 def children_count(group):
3075 def children_count(group):
3081 cnt = 0
3076 cnt = 0
3082 for child in group.children:
3077 for child in group.children:
3083 cnt += child.repositories.count()
3078 cnt += child.repositories.count()
3084 cnt += children_count(child)
3079 cnt += children_count(child)
3085 return cnt
3080 return cnt
3086
3081
3087 return cnt + children_count(self)
3082 return cnt + children_count(self)
3088
3083
3089 def _recursive_objects(self, include_repos=True, include_groups=True):
3084 def _recursive_objects(self, include_repos=True, include_groups=True):
3090 all_ = []
3085 all_ = []
3091
3086
3092 def _get_members(root_gr):
3087 def _get_members(root_gr):
3093 if include_repos:
3088 if include_repos:
3094 for r in root_gr.repositories:
3089 for r in root_gr.repositories:
3095 all_.append(r)
3090 all_.append(r)
3096 childs = root_gr.children.all()
3091 childs = root_gr.children.all()
3097 if childs:
3092 if childs:
3098 for gr in childs:
3093 for gr in childs:
3099 if include_groups:
3094 if include_groups:
3100 all_.append(gr)
3095 all_.append(gr)
3101 _get_members(gr)
3096 _get_members(gr)
3102
3097
3103 root_group = []
3098 root_group = []
3104 if include_groups:
3099 if include_groups:
3105 root_group = [self]
3100 root_group = [self]
3106
3101
3107 _get_members(self)
3102 _get_members(self)
3108 return root_group + all_
3103 return root_group + all_
3109
3104
3110 def recursive_groups_and_repos(self):
3105 def recursive_groups_and_repos(self):
3111 """
3106 """
3112 Recursive return all groups, with repositories in those groups
3107 Recursive return all groups, with repositories in those groups
3113 """
3108 """
3114 return self._recursive_objects()
3109 return self._recursive_objects()
3115
3110
3116 def recursive_groups(self):
3111 def recursive_groups(self):
3117 """
3112 """
3118 Returns all children groups for this group including children of children
3113 Returns all children groups for this group including children of children
3119 """
3114 """
3120 return self._recursive_objects(include_repos=False)
3115 return self._recursive_objects(include_repos=False)
3121
3116
3122 def recursive_repos(self):
3117 def recursive_repos(self):
3123 """
3118 """
3124 Returns all children repositories for this group
3119 Returns all children repositories for this group
3125 """
3120 """
3126 return self._recursive_objects(include_groups=False)
3121 return self._recursive_objects(include_groups=False)
3127
3122
3128 def get_new_name(self, group_name):
3123 def get_new_name(self, group_name):
3129 """
3124 """
3130 returns new full group name based on parent and new name
3125 returns new full group name based on parent and new name
3131
3126
3132 :param group_name:
3127 :param group_name:
3133 """
3128 """
3134 path_prefix = (self.parent_group.full_path_splitted if
3129 path_prefix = (self.parent_group.full_path_splitted if
3135 self.parent_group else [])
3130 self.parent_group else [])
3136 return RepoGroup.url_sep().join(path_prefix + [group_name])
3131 return RepoGroup.url_sep().join(path_prefix + [group_name])
3137
3132
3138 def update_commit_cache(self, config=None):
3133 def update_commit_cache(self, config=None):
3139 """
3134 """
3140 Update cache of last commit for newest repository inside this repository group.
3135 Update cache of last commit for newest repository inside this repository group.
3141 cache_keys should be::
3136 cache_keys should be::
3142
3137
3143 source_repo_id
3138 source_repo_id
3144 short_id
3139 short_id
3145 raw_id
3140 raw_id
3146 revision
3141 revision
3147 parents
3142 parents
3148 message
3143 message
3149 date
3144 date
3150 author
3145 author
3151
3146
3152 """
3147 """
3153 from rhodecode.lib.vcs.utils.helpers import parse_datetime
3148 from rhodecode.lib.vcs.utils.helpers import parse_datetime
3154 empty_date = datetime.datetime.fromtimestamp(0)
3149 empty_date = datetime.datetime.fromtimestamp(0)
3155
3150
3156 def repo_groups_and_repos(root_gr):
3151 def repo_groups_and_repos(root_gr):
3157 for _repo in root_gr.repositories:
3152 for _repo in root_gr.repositories:
3158 yield _repo
3153 yield _repo
3159 for child_group in root_gr.children.all():
3154 for child_group in root_gr.children.all():
3160 yield child_group
3155 yield child_group
3161
3156
3162 latest_repo_cs_cache = {}
3157 latest_repo_cs_cache = {}
3163 for obj in repo_groups_and_repos(self):
3158 for obj in repo_groups_and_repos(self):
3164 repo_cs_cache = obj.changeset_cache
3159 repo_cs_cache = obj.changeset_cache
3165 date_latest = latest_repo_cs_cache.get('date', empty_date)
3160 date_latest = latest_repo_cs_cache.get('date', empty_date)
3166 date_current = repo_cs_cache.get('date', empty_date)
3161 date_current = repo_cs_cache.get('date', empty_date)
3167 current_timestamp = datetime_to_time(parse_datetime(date_latest))
3162 current_timestamp = datetime_to_time(parse_datetime(date_latest))
3168 if current_timestamp < datetime_to_time(parse_datetime(date_current)):
3163 if current_timestamp < datetime_to_time(parse_datetime(date_current)):
3169 latest_repo_cs_cache = repo_cs_cache
3164 latest_repo_cs_cache = repo_cs_cache
3170 if hasattr(obj, 'repo_id'):
3165 if hasattr(obj, 'repo_id'):
3171 latest_repo_cs_cache['source_repo_id'] = obj.repo_id
3166 latest_repo_cs_cache['source_repo_id'] = obj.repo_id
3172 else:
3167 else:
3173 latest_repo_cs_cache['source_repo_id'] = repo_cs_cache.get('source_repo_id')
3168 latest_repo_cs_cache['source_repo_id'] = repo_cs_cache.get('source_repo_id')
3174
3169
3175 _date_latest = parse_datetime(latest_repo_cs_cache.get('date') or empty_date)
3170 _date_latest = parse_datetime(latest_repo_cs_cache.get('date') or empty_date)
3176
3171
3177 latest_repo_cs_cache['updated_on'] = time.time()
3172 latest_repo_cs_cache['updated_on'] = time.time()
3178 self.changeset_cache = latest_repo_cs_cache
3173 self.changeset_cache = latest_repo_cs_cache
3179 self.updated_on = _date_latest
3174 self.updated_on = _date_latest
3180 Session().add(self)
3175 Session().add(self)
3181 Session().commit()
3176 Session().commit()
3182
3177
3183 log.debug('updated repo group `%s` with new commit cache %s, and last update_date: %s',
3178 log.debug('updated repo group `%s` with new commit cache %s, and last update_date: %s',
3184 self.group_name, latest_repo_cs_cache, _date_latest)
3179 self.group_name, latest_repo_cs_cache, _date_latest)
3185
3180
3186 def permissions(self, with_admins=True, with_owner=True,
3181 def permissions(self, with_admins=True, with_owner=True,
3187 expand_from_user_groups=False):
3182 expand_from_user_groups=False):
3188 """
3183 """
3189 Permissions for repository groups
3184 Permissions for repository groups
3190 """
3185 """
3191 _admin_perm = 'group.admin'
3186 _admin_perm = 'group.admin'
3192
3187
3193 owner_row = []
3188 owner_row = []
3194 if with_owner:
3189 if with_owner:
3195 usr = AttributeDict(self.user.get_dict())
3190 usr = AttributeDict(self.user.get_dict())
3196 usr.owner_row = True
3191 usr.owner_row = True
3197 usr.permission = _admin_perm
3192 usr.permission = _admin_perm
3198 owner_row.append(usr)
3193 owner_row.append(usr)
3199
3194
3200 super_admin_ids = []
3195 super_admin_ids = []
3201 super_admin_rows = []
3196 super_admin_rows = []
3202 if with_admins:
3197 if with_admins:
3203 for usr in User.get_all_super_admins():
3198 for usr in User.get_all_super_admins():
3204 super_admin_ids.append(usr.user_id)
3199 super_admin_ids.append(usr.user_id)
3205 # if this admin is also owner, don't double the record
3200 # if this admin is also owner, don't double the record
3206 if usr.user_id == owner_row[0].user_id:
3201 if usr.user_id == owner_row[0].user_id:
3207 owner_row[0].admin_row = True
3202 owner_row[0].admin_row = True
3208 else:
3203 else:
3209 usr = AttributeDict(usr.get_dict())
3204 usr = AttributeDict(usr.get_dict())
3210 usr.admin_row = True
3205 usr.admin_row = True
3211 usr.permission = _admin_perm
3206 usr.permission = _admin_perm
3212 super_admin_rows.append(usr)
3207 super_admin_rows.append(usr)
3213
3208
3214 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
3209 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
3215 q = q.options(joinedload(UserRepoGroupToPerm.group),
3210 q = q.options(joinedload(UserRepoGroupToPerm.group),
3216 joinedload(UserRepoGroupToPerm.user),
3211 joinedload(UserRepoGroupToPerm.user),
3217 joinedload(UserRepoGroupToPerm.permission),)
3212 joinedload(UserRepoGroupToPerm.permission),)
3218
3213
3219 # get owners and admins and permissions. We do a trick of re-writing
3214 # get owners and admins and permissions. We do a trick of re-writing
3220 # objects from sqlalchemy to named-tuples due to sqlalchemy session
3215 # objects from sqlalchemy to named-tuples due to sqlalchemy session
3221 # has a global reference and changing one object propagates to all
3216 # has a global reference and changing one object propagates to all
3222 # others. This means if admin is also an owner admin_row that change
3217 # others. This means if admin is also an owner admin_row that change
3223 # would propagate to both objects
3218 # would propagate to both objects
3224 perm_rows = []
3219 perm_rows = []
3225 for _usr in q.all():
3220 for _usr in q.all():
3226 usr = AttributeDict(_usr.user.get_dict())
3221 usr = AttributeDict(_usr.user.get_dict())
3227 # if this user is also owner/admin, mark as duplicate record
3222 # if this user is also owner/admin, mark as duplicate record
3228 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
3223 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
3229 usr.duplicate_perm = True
3224 usr.duplicate_perm = True
3230 usr.permission = _usr.permission.permission_name
3225 usr.permission = _usr.permission.permission_name
3231 perm_rows.append(usr)
3226 perm_rows.append(usr)
3232
3227
3233 # filter the perm rows by 'default' first and then sort them by
3228 # filter the perm rows by 'default' first and then sort them by
3234 # admin,write,read,none permissions sorted again alphabetically in
3229 # admin,write,read,none permissions sorted again alphabetically in
3235 # each group
3230 # each group
3236 perm_rows = sorted(perm_rows, key=display_user_sort)
3231 perm_rows = sorted(perm_rows, key=display_user_sort)
3237
3232
3238 user_groups_rows = []
3233 user_groups_rows = []
3239 if expand_from_user_groups:
3234 if expand_from_user_groups:
3240 for ug in self.permission_user_groups(with_members=True):
3235 for ug in self.permission_user_groups(with_members=True):
3241 for user_data in ug.members:
3236 for user_data in ug.members:
3242 user_groups_rows.append(user_data)
3237 user_groups_rows.append(user_data)
3243
3238
3244 return super_admin_rows + owner_row + perm_rows + user_groups_rows
3239 return super_admin_rows + owner_row + perm_rows + user_groups_rows
3245
3240
3246 def permission_user_groups(self, with_members=False):
3241 def permission_user_groups(self, with_members=False):
3247 q = UserGroupRepoGroupToPerm.query()\
3242 q = UserGroupRepoGroupToPerm.query()\
3248 .filter(UserGroupRepoGroupToPerm.group == self)
3243 .filter(UserGroupRepoGroupToPerm.group == self)
3249 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
3244 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
3250 joinedload(UserGroupRepoGroupToPerm.users_group),
3245 joinedload(UserGroupRepoGroupToPerm.users_group),
3251 joinedload(UserGroupRepoGroupToPerm.permission),)
3246 joinedload(UserGroupRepoGroupToPerm.permission),)
3252
3247
3253 perm_rows = []
3248 perm_rows = []
3254 for _user_group in q.all():
3249 for _user_group in q.all():
3255 entry = AttributeDict(_user_group.users_group.get_dict())
3250 entry = AttributeDict(_user_group.users_group.get_dict())
3256 entry.permission = _user_group.permission.permission_name
3251 entry.permission = _user_group.permission.permission_name
3257 if with_members:
3252 if with_members:
3258 entry.members = [x.user.get_dict()
3253 entry.members = [x.user.get_dict()
3259 for x in _user_group.users_group.members]
3254 for x in _user_group.users_group.members]
3260 perm_rows.append(entry)
3255 perm_rows.append(entry)
3261
3256
3262 perm_rows = sorted(perm_rows, key=display_user_group_sort)
3257 perm_rows = sorted(perm_rows, key=display_user_group_sort)
3263 return perm_rows
3258 return perm_rows
3264
3259
3265 def get_api_data(self):
3260 def get_api_data(self):
3266 """
3261 """
3267 Common function for generating api data
3262 Common function for generating api data
3268
3263
3269 """
3264 """
3270 group = self
3265 group = self
3271 data = {
3266 data = {
3272 'group_id': group.group_id,
3267 'group_id': group.group_id,
3273 'group_name': group.group_name,
3268 'group_name': group.group_name,
3274 'group_description': group.description_safe,
3269 'group_description': group.description_safe,
3275 'parent_group': group.parent_group.group_name if group.parent_group else None,
3270 'parent_group': group.parent_group.group_name if group.parent_group else None,
3276 'repositories': [x.repo_name for x in group.repositories],
3271 'repositories': [x.repo_name for x in group.repositories],
3277 'owner': group.user.username,
3272 'owner': group.user.username,
3278 }
3273 }
3279 return data
3274 return data
3280
3275
3281 def get_dict(self):
3276 def get_dict(self):
3282 # Since we transformed `group_name` to a hybrid property, we need to
3277 # Since we transformed `group_name` to a hybrid property, we need to
3283 # keep compatibility with the code which uses `group_name` field.
3278 # keep compatibility with the code which uses `group_name` field.
3284 result = super(RepoGroup, self).get_dict()
3279 result = super(RepoGroup, self).get_dict()
3285 result['group_name'] = result.pop('_group_name', None)
3280 result['group_name'] = result.pop('_group_name', None)
3286 result.pop('_changeset_cache', '')
3281 result.pop('_changeset_cache', '')
3287 return result
3282 return result
3288
3283
3289
3284
3290 class Permission(Base, BaseModel):
3285 class Permission(Base, BaseModel):
3291 __tablename__ = 'permissions'
3286 __tablename__ = 'permissions'
3292 __table_args__ = (
3287 __table_args__ = (
3293 Index('p_perm_name_idx', 'permission_name'),
3288 Index('p_perm_name_idx', 'permission_name'),
3294 base_table_args,
3289 base_table_args,
3295 )
3290 )
3296
3291
3297 PERMS = [
3292 PERMS = [
3298 ('hg.admin', _('RhodeCode Super Administrator')),
3293 ('hg.admin', _('RhodeCode Super Administrator')),
3299
3294
3300 ('repository.none', _('Repository no access')),
3295 ('repository.none', _('Repository no access')),
3301 ('repository.read', _('Repository read access')),
3296 ('repository.read', _('Repository read access')),
3302 ('repository.write', _('Repository write access')),
3297 ('repository.write', _('Repository write access')),
3303 ('repository.admin', _('Repository admin access')),
3298 ('repository.admin', _('Repository admin access')),
3304
3299
3305 ('group.none', _('Repository group no access')),
3300 ('group.none', _('Repository group no access')),
3306 ('group.read', _('Repository group read access')),
3301 ('group.read', _('Repository group read access')),
3307 ('group.write', _('Repository group write access')),
3302 ('group.write', _('Repository group write access')),
3308 ('group.admin', _('Repository group admin access')),
3303 ('group.admin', _('Repository group admin access')),
3309
3304
3310 ('usergroup.none', _('User group no access')),
3305 ('usergroup.none', _('User group no access')),
3311 ('usergroup.read', _('User group read access')),
3306 ('usergroup.read', _('User group read access')),
3312 ('usergroup.write', _('User group write access')),
3307 ('usergroup.write', _('User group write access')),
3313 ('usergroup.admin', _('User group admin access')),
3308 ('usergroup.admin', _('User group admin access')),
3314
3309
3315 ('branch.none', _('Branch no permissions')),
3310 ('branch.none', _('Branch no permissions')),
3316 ('branch.merge', _('Branch access by web merge')),
3311 ('branch.merge', _('Branch access by web merge')),
3317 ('branch.push', _('Branch access by push')),
3312 ('branch.push', _('Branch access by push')),
3318 ('branch.push_force', _('Branch access by push with force')),
3313 ('branch.push_force', _('Branch access by push with force')),
3319
3314
3320 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
3315 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
3321 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
3316 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
3322
3317
3323 ('hg.usergroup.create.false', _('User Group creation disabled')),
3318 ('hg.usergroup.create.false', _('User Group creation disabled')),
3324 ('hg.usergroup.create.true', _('User Group creation enabled')),
3319 ('hg.usergroup.create.true', _('User Group creation enabled')),
3325
3320
3326 ('hg.create.none', _('Repository creation disabled')),
3321 ('hg.create.none', _('Repository creation disabled')),
3327 ('hg.create.repository', _('Repository creation enabled')),
3322 ('hg.create.repository', _('Repository creation enabled')),
3328 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
3323 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
3329 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
3324 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
3330
3325
3331 ('hg.fork.none', _('Repository forking disabled')),
3326 ('hg.fork.none', _('Repository forking disabled')),
3332 ('hg.fork.repository', _('Repository forking enabled')),
3327 ('hg.fork.repository', _('Repository forking enabled')),
3333
3328
3334 ('hg.register.none', _('Registration disabled')),
3329 ('hg.register.none', _('Registration disabled')),
3335 ('hg.register.manual_activate', _('User Registration with manual account activation')),
3330 ('hg.register.manual_activate', _('User Registration with manual account activation')),
3336 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
3331 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
3337
3332
3338 ('hg.password_reset.enabled', _('Password reset enabled')),
3333 ('hg.password_reset.enabled', _('Password reset enabled')),
3339 ('hg.password_reset.hidden', _('Password reset hidden')),
3334 ('hg.password_reset.hidden', _('Password reset hidden')),
3340 ('hg.password_reset.disabled', _('Password reset disabled')),
3335 ('hg.password_reset.disabled', _('Password reset disabled')),
3341
3336
3342 ('hg.extern_activate.manual', _('Manual activation of external account')),
3337 ('hg.extern_activate.manual', _('Manual activation of external account')),
3343 ('hg.extern_activate.auto', _('Automatic activation of external account')),
3338 ('hg.extern_activate.auto', _('Automatic activation of external account')),
3344
3339
3345 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
3340 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
3346 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
3341 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
3347 ]
3342 ]
3348
3343
3349 # definition of system default permissions for DEFAULT user, created on
3344 # definition of system default permissions for DEFAULT user, created on
3350 # system setup
3345 # system setup
3351 DEFAULT_USER_PERMISSIONS = [
3346 DEFAULT_USER_PERMISSIONS = [
3352 # object perms
3347 # object perms
3353 'repository.read',
3348 'repository.read',
3354 'group.read',
3349 'group.read',
3355 'usergroup.read',
3350 'usergroup.read',
3356 # branch, for backward compat we need same value as before so forced pushed
3351 # branch, for backward compat we need same value as before so forced pushed
3357 'branch.push_force',
3352 'branch.push_force',
3358 # global
3353 # global
3359 'hg.create.repository',
3354 'hg.create.repository',
3360 'hg.repogroup.create.false',
3355 'hg.repogroup.create.false',
3361 'hg.usergroup.create.false',
3356 'hg.usergroup.create.false',
3362 'hg.create.write_on_repogroup.true',
3357 'hg.create.write_on_repogroup.true',
3363 'hg.fork.repository',
3358 'hg.fork.repository',
3364 'hg.register.manual_activate',
3359 'hg.register.manual_activate',
3365 'hg.password_reset.enabled',
3360 'hg.password_reset.enabled',
3366 'hg.extern_activate.auto',
3361 'hg.extern_activate.auto',
3367 'hg.inherit_default_perms.true',
3362 'hg.inherit_default_perms.true',
3368 ]
3363 ]
3369
3364
3370 # defines which permissions are more important higher the more important
3365 # defines which permissions are more important higher the more important
3371 # Weight defines which permissions are more important.
3366 # Weight defines which permissions are more important.
3372 # The higher number the more important.
3367 # The higher number the more important.
3373 PERM_WEIGHTS = {
3368 PERM_WEIGHTS = {
3374 'repository.none': 0,
3369 'repository.none': 0,
3375 'repository.read': 1,
3370 'repository.read': 1,
3376 'repository.write': 3,
3371 'repository.write': 3,
3377 'repository.admin': 4,
3372 'repository.admin': 4,
3378
3373
3379 'group.none': 0,
3374 'group.none': 0,
3380 'group.read': 1,
3375 'group.read': 1,
3381 'group.write': 3,
3376 'group.write': 3,
3382 'group.admin': 4,
3377 'group.admin': 4,
3383
3378
3384 'usergroup.none': 0,
3379 'usergroup.none': 0,
3385 'usergroup.read': 1,
3380 'usergroup.read': 1,
3386 'usergroup.write': 3,
3381 'usergroup.write': 3,
3387 'usergroup.admin': 4,
3382 'usergroup.admin': 4,
3388
3383
3389 'branch.none': 0,
3384 'branch.none': 0,
3390 'branch.merge': 1,
3385 'branch.merge': 1,
3391 'branch.push': 3,
3386 'branch.push': 3,
3392 'branch.push_force': 4,
3387 'branch.push_force': 4,
3393
3388
3394 'hg.repogroup.create.false': 0,
3389 'hg.repogroup.create.false': 0,
3395 'hg.repogroup.create.true': 1,
3390 'hg.repogroup.create.true': 1,
3396
3391
3397 'hg.usergroup.create.false': 0,
3392 'hg.usergroup.create.false': 0,
3398 'hg.usergroup.create.true': 1,
3393 'hg.usergroup.create.true': 1,
3399
3394
3400 'hg.fork.none': 0,
3395 'hg.fork.none': 0,
3401 'hg.fork.repository': 1,
3396 'hg.fork.repository': 1,
3402 'hg.create.none': 0,
3397 'hg.create.none': 0,
3403 'hg.create.repository': 1
3398 'hg.create.repository': 1
3404 }
3399 }
3405
3400
3406 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3401 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3407 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
3402 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
3408 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
3403 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
3409
3404
3410 def __repr__(self):
3405 def __repr__(self):
3411 return "<%s('%s:%s')>" % (
3406 return "<%s('%s:%s')>" % (
3412 self.cls_name, self.permission_id, self.permission_name
3407 self.cls_name, self.permission_id, self.permission_name
3413 )
3408 )
3414
3409
3415 @classmethod
3410 @classmethod
3416 def get_by_key(cls, key):
3411 def get_by_key(cls, key):
3417 return cls.query().filter(cls.permission_name == key).scalar()
3412 return cls.query().filter(cls.permission_name == key).scalar()
3418
3413
3419 @classmethod
3414 @classmethod
3420 def get_default_repo_perms(cls, user_id, repo_id=None):
3415 def get_default_repo_perms(cls, user_id, repo_id=None):
3421 q = Session().query(UserRepoToPerm, Repository, Permission)\
3416 q = Session().query(UserRepoToPerm, Repository, Permission)\
3422 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
3417 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
3423 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
3418 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
3424 .filter(UserRepoToPerm.user_id == user_id)
3419 .filter(UserRepoToPerm.user_id == user_id)
3425 if repo_id:
3420 if repo_id:
3426 q = q.filter(UserRepoToPerm.repository_id == repo_id)
3421 q = q.filter(UserRepoToPerm.repository_id == repo_id)
3427 return q.all()
3422 return q.all()
3428
3423
3429 @classmethod
3424 @classmethod
3430 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
3425 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
3431 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
3426 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
3432 .join(
3427 .join(
3433 Permission,
3428 Permission,
3434 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
3429 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
3435 .join(
3430 .join(
3436 UserRepoToPerm,
3431 UserRepoToPerm,
3437 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
3432 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
3438 .filter(UserRepoToPerm.user_id == user_id)
3433 .filter(UserRepoToPerm.user_id == user_id)
3439
3434
3440 if repo_id:
3435 if repo_id:
3441 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
3436 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
3442 return q.order_by(UserToRepoBranchPermission.rule_order).all()
3437 return q.order_by(UserToRepoBranchPermission.rule_order).all()
3443
3438
3444 @classmethod
3439 @classmethod
3445 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
3440 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
3446 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
3441 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
3447 .join(
3442 .join(
3448 Permission,
3443 Permission,
3449 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
3444 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
3450 .join(
3445 .join(
3451 Repository,
3446 Repository,
3452 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
3447 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
3453 .join(
3448 .join(
3454 UserGroup,
3449 UserGroup,
3455 UserGroupRepoToPerm.users_group_id ==
3450 UserGroupRepoToPerm.users_group_id ==
3456 UserGroup.users_group_id)\
3451 UserGroup.users_group_id)\
3457 .join(
3452 .join(
3458 UserGroupMember,
3453 UserGroupMember,
3459 UserGroupRepoToPerm.users_group_id ==
3454 UserGroupRepoToPerm.users_group_id ==
3460 UserGroupMember.users_group_id)\
3455 UserGroupMember.users_group_id)\
3461 .filter(
3456 .filter(
3462 UserGroupMember.user_id == user_id,
3457 UserGroupMember.user_id == user_id,
3463 UserGroup.users_group_active == true())
3458 UserGroup.users_group_active == true())
3464 if repo_id:
3459 if repo_id:
3465 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
3460 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
3466 return q.all()
3461 return q.all()
3467
3462
3468 @classmethod
3463 @classmethod
3469 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
3464 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
3470 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
3465 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
3471 .join(
3466 .join(
3472 Permission,
3467 Permission,
3473 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
3468 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
3474 .join(
3469 .join(
3475 UserGroupRepoToPerm,
3470 UserGroupRepoToPerm,
3476 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
3471 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
3477 .join(
3472 .join(
3478 UserGroup,
3473 UserGroup,
3479 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
3474 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
3480 .join(
3475 .join(
3481 UserGroupMember,
3476 UserGroupMember,
3482 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
3477 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
3483 .filter(
3478 .filter(
3484 UserGroupMember.user_id == user_id,
3479 UserGroupMember.user_id == user_id,
3485 UserGroup.users_group_active == true())
3480 UserGroup.users_group_active == true())
3486
3481
3487 if repo_id:
3482 if repo_id:
3488 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
3483 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
3489 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
3484 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
3490
3485
3491 @classmethod
3486 @classmethod
3492 def get_default_group_perms(cls, user_id, repo_group_id=None):
3487 def get_default_group_perms(cls, user_id, repo_group_id=None):
3493 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
3488 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
3494 .join(
3489 .join(
3495 Permission,
3490 Permission,
3496 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
3491 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
3497 .join(
3492 .join(
3498 RepoGroup,
3493 RepoGroup,
3499 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
3494 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
3500 .filter(UserRepoGroupToPerm.user_id == user_id)
3495 .filter(UserRepoGroupToPerm.user_id == user_id)
3501 if repo_group_id:
3496 if repo_group_id:
3502 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
3497 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
3503 return q.all()
3498 return q.all()
3504
3499
3505 @classmethod
3500 @classmethod
3506 def get_default_group_perms_from_user_group(
3501 def get_default_group_perms_from_user_group(
3507 cls, user_id, repo_group_id=None):
3502 cls, user_id, repo_group_id=None):
3508 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
3503 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
3509 .join(
3504 .join(
3510 Permission,
3505 Permission,
3511 UserGroupRepoGroupToPerm.permission_id ==
3506 UserGroupRepoGroupToPerm.permission_id ==
3512 Permission.permission_id)\
3507 Permission.permission_id)\
3513 .join(
3508 .join(
3514 RepoGroup,
3509 RepoGroup,
3515 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
3510 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
3516 .join(
3511 .join(
3517 UserGroup,
3512 UserGroup,
3518 UserGroupRepoGroupToPerm.users_group_id ==
3513 UserGroupRepoGroupToPerm.users_group_id ==
3519 UserGroup.users_group_id)\
3514 UserGroup.users_group_id)\
3520 .join(
3515 .join(
3521 UserGroupMember,
3516 UserGroupMember,
3522 UserGroupRepoGroupToPerm.users_group_id ==
3517 UserGroupRepoGroupToPerm.users_group_id ==
3523 UserGroupMember.users_group_id)\
3518 UserGroupMember.users_group_id)\
3524 .filter(
3519 .filter(
3525 UserGroupMember.user_id == user_id,
3520 UserGroupMember.user_id == user_id,
3526 UserGroup.users_group_active == true())
3521 UserGroup.users_group_active == true())
3527 if repo_group_id:
3522 if repo_group_id:
3528 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
3523 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
3529 return q.all()
3524 return q.all()
3530
3525
3531 @classmethod
3526 @classmethod
3532 def get_default_user_group_perms(cls, user_id, user_group_id=None):
3527 def get_default_user_group_perms(cls, user_id, user_group_id=None):
3533 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
3528 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
3534 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
3529 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
3535 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
3530 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
3536 .filter(UserUserGroupToPerm.user_id == user_id)
3531 .filter(UserUserGroupToPerm.user_id == user_id)
3537 if user_group_id:
3532 if user_group_id:
3538 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
3533 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
3539 return q.all()
3534 return q.all()
3540
3535
3541 @classmethod
3536 @classmethod
3542 def get_default_user_group_perms_from_user_group(
3537 def get_default_user_group_perms_from_user_group(
3543 cls, user_id, user_group_id=None):
3538 cls, user_id, user_group_id=None):
3544 TargetUserGroup = aliased(UserGroup, name='target_user_group')
3539 TargetUserGroup = aliased(UserGroup, name='target_user_group')
3545 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
3540 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
3546 .join(
3541 .join(
3547 Permission,
3542 Permission,
3548 UserGroupUserGroupToPerm.permission_id ==
3543 UserGroupUserGroupToPerm.permission_id ==
3549 Permission.permission_id)\
3544 Permission.permission_id)\
3550 .join(
3545 .join(
3551 TargetUserGroup,
3546 TargetUserGroup,
3552 UserGroupUserGroupToPerm.target_user_group_id ==
3547 UserGroupUserGroupToPerm.target_user_group_id ==
3553 TargetUserGroup.users_group_id)\
3548 TargetUserGroup.users_group_id)\
3554 .join(
3549 .join(
3555 UserGroup,
3550 UserGroup,
3556 UserGroupUserGroupToPerm.user_group_id ==
3551 UserGroupUserGroupToPerm.user_group_id ==
3557 UserGroup.users_group_id)\
3552 UserGroup.users_group_id)\
3558 .join(
3553 .join(
3559 UserGroupMember,
3554 UserGroupMember,
3560 UserGroupUserGroupToPerm.user_group_id ==
3555 UserGroupUserGroupToPerm.user_group_id ==
3561 UserGroupMember.users_group_id)\
3556 UserGroupMember.users_group_id)\
3562 .filter(
3557 .filter(
3563 UserGroupMember.user_id == user_id,
3558 UserGroupMember.user_id == user_id,
3564 UserGroup.users_group_active == true())
3559 UserGroup.users_group_active == true())
3565 if user_group_id:
3560 if user_group_id:
3566 q = q.filter(
3561 q = q.filter(
3567 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3562 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3568
3563
3569 return q.all()
3564 return q.all()
3570
3565
3571
3566
3572 class UserRepoToPerm(Base, BaseModel):
3567 class UserRepoToPerm(Base, BaseModel):
3573 __tablename__ = 'repo_to_perm'
3568 __tablename__ = 'repo_to_perm'
3574 __table_args__ = (
3569 __table_args__ = (
3575 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3570 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3576 base_table_args
3571 base_table_args
3577 )
3572 )
3578
3573
3579 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3574 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3580 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3575 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3581 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3576 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3582 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3577 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3583
3578
3584 user = relationship('User', back_populates="repo_to_perm")
3579 user = relationship('User', back_populates="repo_to_perm")
3585 repository = relationship('Repository', back_populates="repo_to_perm")
3580 repository = relationship('Repository', back_populates="repo_to_perm")
3586 permission = relationship('Permission')
3581 permission = relationship('Permission')
3587
3582
3588 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete-orphan", lazy='joined', back_populates='user_repo_to_perm')
3583 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete-orphan", lazy='joined', back_populates='user_repo_to_perm')
3589
3584
3590 @classmethod
3585 @classmethod
3591 def create(cls, user, repository, permission):
3586 def create(cls, user, repository, permission):
3592 n = cls()
3587 n = cls()
3593 n.user = user
3588 n.user = user
3594 n.repository = repository
3589 n.repository = repository
3595 n.permission = permission
3590 n.permission = permission
3596 Session().add(n)
3591 Session().add(n)
3597 return n
3592 return n
3598
3593
3599 def __repr__(self):
3594 def __repr__(self):
3600 return f'<{self.user} => {self.repository} >'
3595 return f'<{self.user} => {self.repository} >'
3601
3596
3602
3597
3603 class UserUserGroupToPerm(Base, BaseModel):
3598 class UserUserGroupToPerm(Base, BaseModel):
3604 __tablename__ = 'user_user_group_to_perm'
3599 __tablename__ = 'user_user_group_to_perm'
3605 __table_args__ = (
3600 __table_args__ = (
3606 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3601 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3607 base_table_args
3602 base_table_args
3608 )
3603 )
3609
3604
3610 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3605 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3611 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3606 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3612 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3607 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3613 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3608 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3614
3609
3615 user = relationship('User', back_populates='user_group_to_perm')
3610 user = relationship('User', back_populates='user_group_to_perm')
3616 user_group = relationship('UserGroup', back_populates='user_user_group_to_perm')
3611 user_group = relationship('UserGroup', back_populates='user_user_group_to_perm')
3617 permission = relationship('Permission')
3612 permission = relationship('Permission')
3618
3613
3619 @classmethod
3614 @classmethod
3620 def create(cls, user, user_group, permission):
3615 def create(cls, user, user_group, permission):
3621 n = cls()
3616 n = cls()
3622 n.user = user
3617 n.user = user
3623 n.user_group = user_group
3618 n.user_group = user_group
3624 n.permission = permission
3619 n.permission = permission
3625 Session().add(n)
3620 Session().add(n)
3626 return n
3621 return n
3627
3622
3628 def __repr__(self):
3623 def __repr__(self):
3629 return f'<{self.user} => {self.user_group} >'
3624 return f'<{self.user} => {self.user_group} >'
3630
3625
3631
3626
3632 class UserToPerm(Base, BaseModel):
3627 class UserToPerm(Base, BaseModel):
3633 __tablename__ = 'user_to_perm'
3628 __tablename__ = 'user_to_perm'
3634 __table_args__ = (
3629 __table_args__ = (
3635 UniqueConstraint('user_id', 'permission_id'),
3630 UniqueConstraint('user_id', 'permission_id'),
3636 base_table_args
3631 base_table_args
3637 )
3632 )
3638
3633
3639 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3634 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3640 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3635 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3641 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3636 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3642
3637
3643 user = relationship('User', back_populates='user_perms')
3638 user = relationship('User', back_populates='user_perms')
3644 permission = relationship('Permission', lazy='joined')
3639 permission = relationship('Permission', lazy='joined')
3645
3640
3646 def __repr__(self):
3641 def __repr__(self):
3647 return f'<{self.user} => {self.permission} >'
3642 return f'<{self.user} => {self.permission} >'
3648
3643
3649
3644
3650 class UserGroupRepoToPerm(Base, BaseModel):
3645 class UserGroupRepoToPerm(Base, BaseModel):
3651 __tablename__ = 'users_group_repo_to_perm'
3646 __tablename__ = 'users_group_repo_to_perm'
3652 __table_args__ = (
3647 __table_args__ = (
3653 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3648 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3654 base_table_args
3649 base_table_args
3655 )
3650 )
3656
3651
3657 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3652 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3658 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3653 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3659 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3654 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3660 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3655 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3661
3656
3662 users_group = relationship('UserGroup', back_populates='users_group_repo_to_perm')
3657 users_group = relationship('UserGroup', back_populates='users_group_repo_to_perm')
3663 permission = relationship('Permission')
3658 permission = relationship('Permission')
3664 repository = relationship('Repository', back_populates='users_group_to_perm')
3659 repository = relationship('Repository', back_populates='users_group_to_perm')
3665 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all', back_populates='user_group_repo_to_perm')
3660 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all', back_populates='user_group_repo_to_perm')
3666
3661
3667 @classmethod
3662 @classmethod
3668 def create(cls, users_group, repository, permission):
3663 def create(cls, users_group, repository, permission):
3669 n = cls()
3664 n = cls()
3670 n.users_group = users_group
3665 n.users_group = users_group
3671 n.repository = repository
3666 n.repository = repository
3672 n.permission = permission
3667 n.permission = permission
3673 Session().add(n)
3668 Session().add(n)
3674 return n
3669 return n
3675
3670
3676 def __repr__(self):
3671 def __repr__(self):
3677 return f'<UserGroupRepoToPerm:{self.users_group} => {self.repository} >'
3672 return f'<UserGroupRepoToPerm:{self.users_group} => {self.repository} >'
3678
3673
3679
3674
3680 class UserGroupUserGroupToPerm(Base, BaseModel):
3675 class UserGroupUserGroupToPerm(Base, BaseModel):
3681 __tablename__ = 'user_group_user_group_to_perm'
3676 __tablename__ = 'user_group_user_group_to_perm'
3682 __table_args__ = (
3677 __table_args__ = (
3683 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3678 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3684 CheckConstraint('target_user_group_id != user_group_id'),
3679 CheckConstraint('target_user_group_id != user_group_id'),
3685 base_table_args
3680 base_table_args
3686 )
3681 )
3687
3682
3688 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)
3683 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)
3689 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3684 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3690 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3685 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3691 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3686 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3692
3687
3693 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id', back_populates='user_group_user_group_to_perm')
3688 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id', back_populates='user_group_user_group_to_perm')
3694 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3689 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3695 permission = relationship('Permission')
3690 permission = relationship('Permission')
3696
3691
3697 @classmethod
3692 @classmethod
3698 def create(cls, target_user_group, user_group, permission):
3693 def create(cls, target_user_group, user_group, permission):
3699 n = cls()
3694 n = cls()
3700 n.target_user_group = target_user_group
3695 n.target_user_group = target_user_group
3701 n.user_group = user_group
3696 n.user_group = user_group
3702 n.permission = permission
3697 n.permission = permission
3703 Session().add(n)
3698 Session().add(n)
3704 return n
3699 return n
3705
3700
3706 def __repr__(self):
3701 def __repr__(self):
3707 return f'<UserGroupUserGroup:{self.target_user_group} => {self.user_group} >'
3702 return f'<UserGroupUserGroup:{self.target_user_group} => {self.user_group} >'
3708
3703
3709
3704
3710 class UserGroupToPerm(Base, BaseModel):
3705 class UserGroupToPerm(Base, BaseModel):
3711 __tablename__ = 'users_group_to_perm'
3706 __tablename__ = 'users_group_to_perm'
3712 __table_args__ = (
3707 __table_args__ = (
3713 UniqueConstraint('users_group_id', 'permission_id',),
3708 UniqueConstraint('users_group_id', 'permission_id',),
3714 base_table_args
3709 base_table_args
3715 )
3710 )
3716
3711
3717 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3712 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3718 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3713 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3719 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3714 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3720
3715
3721 users_group = relationship('UserGroup', back_populates='users_group_to_perm')
3716 users_group = relationship('UserGroup', back_populates='users_group_to_perm')
3722 permission = relationship('Permission')
3717 permission = relationship('Permission')
3723
3718
3724
3719
3725 class UserRepoGroupToPerm(Base, BaseModel):
3720 class UserRepoGroupToPerm(Base, BaseModel):
3726 __tablename__ = 'user_repo_group_to_perm'
3721 __tablename__ = 'user_repo_group_to_perm'
3727 __table_args__ = (
3722 __table_args__ = (
3728 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3723 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3729 base_table_args
3724 base_table_args
3730 )
3725 )
3731
3726
3732 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3727 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3733 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3728 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3734 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3729 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3735 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3730 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3736
3731
3737 user = relationship('User', back_populates='repo_group_to_perm')
3732 user = relationship('User', back_populates='repo_group_to_perm')
3738 group = relationship('RepoGroup', back_populates='repo_group_to_perm')
3733 group = relationship('RepoGroup', back_populates='repo_group_to_perm')
3739 permission = relationship('Permission')
3734 permission = relationship('Permission')
3740
3735
3741 @classmethod
3736 @classmethod
3742 def create(cls, user, repository_group, permission):
3737 def create(cls, user, repository_group, permission):
3743 n = cls()
3738 n = cls()
3744 n.user = user
3739 n.user = user
3745 n.group = repository_group
3740 n.group = repository_group
3746 n.permission = permission
3741 n.permission = permission
3747 Session().add(n)
3742 Session().add(n)
3748 return n
3743 return n
3749
3744
3750
3745
3751 class UserGroupRepoGroupToPerm(Base, BaseModel):
3746 class UserGroupRepoGroupToPerm(Base, BaseModel):
3752 __tablename__ = 'users_group_repo_group_to_perm'
3747 __tablename__ = 'users_group_repo_group_to_perm'
3753 __table_args__ = (
3748 __table_args__ = (
3754 UniqueConstraint('users_group_id', 'group_id'),
3749 UniqueConstraint('users_group_id', 'group_id'),
3755 base_table_args
3750 base_table_args
3756 )
3751 )
3757
3752
3758 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)
3753 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)
3759 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3754 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3760 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3755 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3761 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3756 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3762
3757
3763 users_group = relationship('UserGroup', back_populates='users_group_repo_group_to_perm')
3758 users_group = relationship('UserGroup', back_populates='users_group_repo_group_to_perm')
3764 permission = relationship('Permission')
3759 permission = relationship('Permission')
3765 group = relationship('RepoGroup', back_populates='users_group_to_perm')
3760 group = relationship('RepoGroup', back_populates='users_group_to_perm')
3766
3761
3767 @classmethod
3762 @classmethod
3768 def create(cls, user_group, repository_group, permission):
3763 def create(cls, user_group, repository_group, permission):
3769 n = cls()
3764 n = cls()
3770 n.users_group = user_group
3765 n.users_group = user_group
3771 n.group = repository_group
3766 n.group = repository_group
3772 n.permission = permission
3767 n.permission = permission
3773 Session().add(n)
3768 Session().add(n)
3774 return n
3769 return n
3775
3770
3776 def __repr__(self):
3771 def __repr__(self):
3777 return '<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3772 return '<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3778
3773
3779
3774
3780 class Statistics(Base, BaseModel):
3775 class Statistics(Base, BaseModel):
3781 __tablename__ = 'statistics'
3776 __tablename__ = 'statistics'
3782 __table_args__ = (
3777 __table_args__ = (
3783 base_table_args
3778 base_table_args
3784 )
3779 )
3785
3780
3786 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3781 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3787 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3782 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3788 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3783 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3789 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False) #JSON data
3784 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False) #JSON data
3790 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False) #JSON data
3785 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False) #JSON data
3791 languages = Column("languages", LargeBinary(1000000), nullable=False) #JSON data
3786 languages = Column("languages", LargeBinary(1000000), nullable=False) #JSON data
3792
3787
3793 repository = relationship('Repository', single_parent=True, viewonly=True)
3788 repository = relationship('Repository', single_parent=True, viewonly=True)
3794
3789
3795
3790
3796 class UserFollowing(Base, BaseModel):
3791 class UserFollowing(Base, BaseModel):
3797 __tablename__ = 'user_followings'
3792 __tablename__ = 'user_followings'
3798 __table_args__ = (
3793 __table_args__ = (
3799 UniqueConstraint('user_id', 'follows_repository_id'),
3794 UniqueConstraint('user_id', 'follows_repository_id'),
3800 UniqueConstraint('user_id', 'follows_user_id'),
3795 UniqueConstraint('user_id', 'follows_user_id'),
3801 base_table_args
3796 base_table_args
3802 )
3797 )
3803
3798
3804 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3799 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3805 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3800 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3806 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3801 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3807 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3802 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3808 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3803 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3809
3804
3810 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id', back_populates='followings')
3805 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id', back_populates='followings')
3811
3806
3812 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3807 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3813 follows_repository = relationship('Repository', order_by='Repository.repo_name', back_populates='followers')
3808 follows_repository = relationship('Repository', order_by='Repository.repo_name', back_populates='followers')
3814
3809
3815 @classmethod
3810 @classmethod
3816 def get_repo_followers(cls, repo_id):
3811 def get_repo_followers(cls, repo_id):
3817 return cls.query().filter(cls.follows_repo_id == repo_id)
3812 return cls.query().filter(cls.follows_repo_id == repo_id)
3818
3813
3819
3814
3820 class CacheKey(Base, BaseModel):
3815 class CacheKey(Base, BaseModel):
3821 __tablename__ = 'cache_invalidation'
3816 __tablename__ = 'cache_invalidation'
3822 __table_args__ = (
3817 __table_args__ = (
3823 UniqueConstraint('cache_key'),
3818 UniqueConstraint('cache_key'),
3824 Index('key_idx', 'cache_key'),
3819 Index('key_idx', 'cache_key'),
3825 Index('cache_args_idx', 'cache_args'),
3820 Index('cache_args_idx', 'cache_args'),
3826 base_table_args,
3821 base_table_args,
3827 )
3822 )
3828
3823
3829 CACHE_TYPE_FEED = 'FEED'
3824 CACHE_TYPE_FEED = 'FEED'
3830
3825
3831 # namespaces used to register process/thread aware caches
3826 # namespaces used to register process/thread aware caches
3832 REPO_INVALIDATION_NAMESPACE = 'repo_cache.v1:{repo_id}'
3827 REPO_INVALIDATION_NAMESPACE = 'repo_cache.v1:{repo_id}'
3833
3828
3834 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3829 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3835 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3830 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3836 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3831 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3837 cache_state_uid = Column("cache_state_uid", String(255), nullable=True, unique=None, default=None)
3832 cache_state_uid = Column("cache_state_uid", String(255), nullable=True, unique=None, default=None)
3838 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3833 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3839
3834
3840 def __init__(self, cache_key, cache_args='', cache_state_uid=None, cache_active=False):
3835 def __init__(self, cache_key, cache_args='', cache_state_uid=None, cache_active=False):
3841 self.cache_key = cache_key
3836 self.cache_key = cache_key
3842 self.cache_args = cache_args
3837 self.cache_args = cache_args
3843 self.cache_active = cache_active
3838 self.cache_active = cache_active
3844 # first key should be same for all entries, since all workers should share it
3839 # first key should be same for all entries, since all workers should share it
3845 self.cache_state_uid = cache_state_uid or self.generate_new_state_uid()
3840 self.cache_state_uid = cache_state_uid or self.generate_new_state_uid()
3846
3841
3847 def __repr__(self):
3842 def __repr__(self):
3848 return "<%s('%s:%s[%s]')>" % (
3843 return "<%s('%s:%s[%s]')>" % (
3849 self.cls_name,
3844 self.cls_name,
3850 self.cache_id, self.cache_key, self.cache_active)
3845 self.cache_id, self.cache_key, self.cache_active)
3851
3846
3852 def _cache_key_partition(self):
3847 def _cache_key_partition(self):
3853 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3848 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3854 return prefix, repo_name, suffix
3849 return prefix, repo_name, suffix
3855
3850
3856 def get_prefix(self):
3851 def get_prefix(self):
3857 """
3852 """
3858 Try to extract prefix from existing cache key. The key could consist
3853 Try to extract prefix from existing cache key. The key could consist
3859 of prefix, repo_name, suffix
3854 of prefix, repo_name, suffix
3860 """
3855 """
3861 # this returns prefix, repo_name, suffix
3856 # this returns prefix, repo_name, suffix
3862 return self._cache_key_partition()[0]
3857 return self._cache_key_partition()[0]
3863
3858
3864 def get_suffix(self):
3859 def get_suffix(self):
3865 """
3860 """
3866 get suffix that might have been used in _get_cache_key to
3861 get suffix that might have been used in _get_cache_key to
3867 generate self.cache_key. Only used for informational purposes
3862 generate self.cache_key. Only used for informational purposes
3868 in repo_edit.mako.
3863 in repo_edit.mako.
3869 """
3864 """
3870 # prefix, repo_name, suffix
3865 # prefix, repo_name, suffix
3871 return self._cache_key_partition()[2]
3866 return self._cache_key_partition()[2]
3872
3867
3873 @classmethod
3868 @classmethod
3874 def generate_new_state_uid(cls, based_on=None):
3869 def generate_new_state_uid(cls, based_on=None):
3875 if based_on:
3870 if based_on:
3876 return str(uuid.uuid5(uuid.NAMESPACE_URL, safe_str(based_on)))
3871 return str(uuid.uuid5(uuid.NAMESPACE_URL, safe_str(based_on)))
3877 else:
3872 else:
3878 return str(uuid.uuid4())
3873 return str(uuid.uuid4())
3879
3874
3880 @classmethod
3875 @classmethod
3881 def delete_all_cache(cls):
3876 def delete_all_cache(cls):
3882 """
3877 """
3883 Delete all cache keys from database.
3878 Delete all cache keys from database.
3884 Should only be run when all instances are down and all entries
3879 Should only be run when all instances are down and all entries
3885 thus stale.
3880 thus stale.
3886 """
3881 """
3887 cls.query().delete()
3882 cls.query().delete()
3888 Session().commit()
3883 Session().commit()
3889
3884
3890 @classmethod
3885 @classmethod
3891 def set_invalidate(cls, cache_uid, delete=False):
3886 def set_invalidate(cls, cache_uid, delete=False):
3892 """
3887 """
3893 Mark all caches of a repo as invalid in the database.
3888 Mark all caches of a repo as invalid in the database.
3894 """
3889 """
3895 try:
3890 try:
3896 qry = Session().query(cls).filter(cls.cache_key == cache_uid)
3891 qry = Session().query(cls).filter(cls.cache_key == cache_uid)
3897 if delete:
3892 if delete:
3898 qry.delete()
3893 qry.delete()
3899 log.debug('cache objects deleted for cache args %s',
3894 log.debug('cache objects deleted for cache args %s',
3900 safe_str(cache_uid))
3895 safe_str(cache_uid))
3901 else:
3896 else:
3902 new_uid = cls.generate_new_state_uid()
3897 new_uid = cls.generate_new_state_uid()
3903 qry.update({"cache_state_uid": new_uid,
3898 qry.update({"cache_state_uid": new_uid,
3904 "cache_args": f"repo_state:{time.time()}"})
3899 "cache_args": f"repo_state:{time.time()}"})
3905 log.debug('cache object %s set new UID %s',
3900 log.debug('cache object %s set new UID %s',
3906 safe_str(cache_uid), new_uid)
3901 safe_str(cache_uid), new_uid)
3907
3902
3908 Session().commit()
3903 Session().commit()
3909 except Exception:
3904 except Exception:
3910 log.exception(
3905 log.exception(
3911 'Cache key invalidation failed for cache args %s',
3906 'Cache key invalidation failed for cache args %s',
3912 safe_str(cache_uid))
3907 safe_str(cache_uid))
3913 Session().rollback()
3908 Session().rollback()
3914
3909
3915 @classmethod
3910 @classmethod
3916 def get_active_cache(cls, cache_key):
3911 def get_active_cache(cls, cache_key):
3917 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3912 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3918 if inv_obj:
3913 if inv_obj:
3919 return inv_obj
3914 return inv_obj
3920 return None
3915 return None
3921
3916
3922 @classmethod
3917 @classmethod
3923 def get_namespace_map(cls, namespace):
3918 def get_namespace_map(cls, namespace):
3924 return {
3919 return {
3925 x.cache_key: x
3920 x.cache_key: x
3926 for x in cls.query().filter(cls.cache_args == namespace)}
3921 for x in cls.query().filter(cls.cache_args == namespace)}
3927
3922
3928
3923
3929 class ChangesetComment(Base, BaseModel):
3924 class ChangesetComment(Base, BaseModel):
3930 __tablename__ = 'changeset_comments'
3925 __tablename__ = 'changeset_comments'
3931 __table_args__ = (
3926 __table_args__ = (
3932 Index('cc_revision_idx', 'revision'),
3927 Index('cc_revision_idx', 'revision'),
3933 base_table_args,
3928 base_table_args,
3934 )
3929 )
3935
3930
3936 COMMENT_OUTDATED = 'comment_outdated'
3931 COMMENT_OUTDATED = 'comment_outdated'
3937 COMMENT_TYPE_NOTE = 'note'
3932 COMMENT_TYPE_NOTE = 'note'
3938 COMMENT_TYPE_TODO = 'todo'
3933 COMMENT_TYPE_TODO = 'todo'
3939 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3934 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3940
3935
3941 OP_IMMUTABLE = 'immutable'
3936 OP_IMMUTABLE = 'immutable'
3942 OP_CHANGEABLE = 'changeable'
3937 OP_CHANGEABLE = 'changeable'
3943
3938
3944 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3939 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3945 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3940 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3946 revision = Column('revision', String(40), nullable=True)
3941 revision = Column('revision', String(40), nullable=True)
3947 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3942 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3948 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3943 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3949 line_no = Column('line_no', Unicode(10), nullable=True)
3944 line_no = Column('line_no', Unicode(10), nullable=True)
3950 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3945 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3951 f_path = Column('f_path', Unicode(1000), nullable=True)
3946 f_path = Column('f_path', Unicode(1000), nullable=True)
3952 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3947 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3953 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3948 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3954 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3949 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3955 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3950 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3956 renderer = Column('renderer', Unicode(64), nullable=True)
3951 renderer = Column('renderer', Unicode(64), nullable=True)
3957 display_state = Column('display_state', Unicode(128), nullable=True)
3952 display_state = Column('display_state', Unicode(128), nullable=True)
3958 immutable_state = Column('immutable_state', Unicode(128), nullable=True, default=OP_CHANGEABLE)
3953 immutable_state = Column('immutable_state', Unicode(128), nullable=True, default=OP_CHANGEABLE)
3959 draft = Column('draft', Boolean(), nullable=True, default=False)
3954 draft = Column('draft', Boolean(), nullable=True, default=False)
3960
3955
3961 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3956 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3962 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3957 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3963
3958
3964 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3959 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3965 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3960 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3966
3961
3967 author = relationship('User', lazy='select', back_populates='user_comments')
3962 author = relationship('User', lazy='select', back_populates='user_comments')
3968 repo = relationship('Repository', back_populates='comments')
3963 repo = relationship('Repository', back_populates='comments')
3969 status_change = relationship('ChangesetStatus', cascade="all, delete-orphan", lazy='select', back_populates='comment')
3964 status_change = relationship('ChangesetStatus', cascade="all, delete-orphan", lazy='select', back_populates='comment')
3970 pull_request = relationship('PullRequest', lazy='select', back_populates='comments')
3965 pull_request = relationship('PullRequest', lazy='select', back_populates='comments')
3971 pull_request_version = relationship('PullRequestVersion', lazy='select')
3966 pull_request_version = relationship('PullRequestVersion', lazy='select')
3972 history = relationship('ChangesetCommentHistory', cascade='all, delete-orphan', lazy='select', order_by='ChangesetCommentHistory.version', back_populates="comment")
3967 history = relationship('ChangesetCommentHistory', cascade='all, delete-orphan', lazy='select', order_by='ChangesetCommentHistory.version', back_populates="comment")
3973
3968
3974 @classmethod
3969 @classmethod
3975 def get_users(cls, revision=None, pull_request_id=None):
3970 def get_users(cls, revision=None, pull_request_id=None):
3976 """
3971 """
3977 Returns user associated with this ChangesetComment. ie those
3972 Returns user associated with this ChangesetComment. ie those
3978 who actually commented
3973 who actually commented
3979
3974
3980 :param cls:
3975 :param cls:
3981 :param revision:
3976 :param revision:
3982 """
3977 """
3983 q = Session().query(User).join(ChangesetComment.author)
3978 q = Session().query(User).join(ChangesetComment.author)
3984 if revision:
3979 if revision:
3985 q = q.filter(cls.revision == revision)
3980 q = q.filter(cls.revision == revision)
3986 elif pull_request_id:
3981 elif pull_request_id:
3987 q = q.filter(cls.pull_request_id == pull_request_id)
3982 q = q.filter(cls.pull_request_id == pull_request_id)
3988 return q.all()
3983 return q.all()
3989
3984
3990 @classmethod
3985 @classmethod
3991 def get_index_from_version(cls, pr_version, versions=None, num_versions=None) -> int:
3986 def get_index_from_version(cls, pr_version, versions=None, num_versions=None) -> int:
3992 if pr_version is None:
3987 if pr_version is None:
3993 return 0
3988 return 0
3994
3989
3995 if versions is not None:
3990 if versions is not None:
3996 num_versions = [x.pull_request_version_id for x in versions]
3991 num_versions = [x.pull_request_version_id for x in versions]
3997
3992
3998 num_versions = num_versions or []
3993 num_versions = num_versions or []
3999 try:
3994 try:
4000 return num_versions.index(pr_version) + 1
3995 return num_versions.index(pr_version) + 1
4001 except (IndexError, ValueError):
3996 except (IndexError, ValueError):
4002 return 0
3997 return 0
4003
3998
4004 @property
3999 @property
4005 def outdated(self):
4000 def outdated(self):
4006 return self.display_state == self.COMMENT_OUTDATED
4001 return self.display_state == self.COMMENT_OUTDATED
4007
4002
4008 @property
4003 @property
4009 def outdated_js(self):
4004 def outdated_js(self):
4010 return str_json(self.display_state == self.COMMENT_OUTDATED)
4005 return str_json(self.display_state == self.COMMENT_OUTDATED)
4011
4006
4012 @property
4007 @property
4013 def immutable(self):
4008 def immutable(self):
4014 return self.immutable_state == self.OP_IMMUTABLE
4009 return self.immutable_state == self.OP_IMMUTABLE
4015
4010
4016 def outdated_at_version(self, version: int) -> bool:
4011 def outdated_at_version(self, version: int) -> bool:
4017 """
4012 """
4018 Checks if comment is outdated for given pull request version
4013 Checks if comment is outdated for given pull request version
4019 """
4014 """
4020
4015
4021 def version_check():
4016 def version_check():
4022 return self.pull_request_version_id and self.pull_request_version_id != version
4017 return self.pull_request_version_id and self.pull_request_version_id != version
4023
4018
4024 if self.is_inline:
4019 if self.is_inline:
4025 return self.outdated and version_check()
4020 return self.outdated and version_check()
4026 else:
4021 else:
4027 # general comments don't have .outdated set, also latest don't have a version
4022 # general comments don't have .outdated set, also latest don't have a version
4028 return version_check()
4023 return version_check()
4029
4024
4030 def outdated_at_version_js(self, version):
4025 def outdated_at_version_js(self, version):
4031 """
4026 """
4032 Checks if comment is outdated for given pull request version
4027 Checks if comment is outdated for given pull request version
4033 """
4028 """
4034 return str_json(self.outdated_at_version(version))
4029 return str_json(self.outdated_at_version(version))
4035
4030
4036 def older_than_version(self, version: int) -> bool:
4031 def older_than_version(self, version: int) -> bool:
4037 """
4032 """
4038 Checks if comment is made from a previous version than given.
4033 Checks if comment is made from a previous version than given.
4039 Assumes self.pull_request_version.pull_request_version_id is an integer if not None.
4034 Assumes self.pull_request_version.pull_request_version_id is an integer if not None.
4040 """
4035 """
4041
4036
4042 # If version is None, return False as the current version cannot be less than None
4037 # If version is None, return False as the current version cannot be less than None
4043 if version is None:
4038 if version is None:
4044 return False
4039 return False
4045
4040
4046 # Ensure that the version is an integer to prevent TypeError on comparison
4041 # Ensure that the version is an integer to prevent TypeError on comparison
4047 if not isinstance(version, int):
4042 if not isinstance(version, int):
4048 raise ValueError("The provided version must be an integer.")
4043 raise ValueError("The provided version must be an integer.")
4049
4044
4050 # Initialize current version to 0 or pull_request_version_id if it's available
4045 # Initialize current version to 0 or pull_request_version_id if it's available
4051 cur_ver = 0
4046 cur_ver = 0
4052 if self.pull_request_version and self.pull_request_version.pull_request_version_id is not None:
4047 if self.pull_request_version and self.pull_request_version.pull_request_version_id is not None:
4053 cur_ver = self.pull_request_version.pull_request_version_id
4048 cur_ver = self.pull_request_version.pull_request_version_id
4054
4049
4055 # Return True if the current version is less than the given version
4050 # Return True if the current version is less than the given version
4056 return cur_ver < version
4051 return cur_ver < version
4057
4052
4058 def older_than_version_js(self, version):
4053 def older_than_version_js(self, version):
4059 """
4054 """
4060 Checks if comment is made from previous version than given
4055 Checks if comment is made from previous version than given
4061 """
4056 """
4062 return str_json(self.older_than_version(version))
4057 return str_json(self.older_than_version(version))
4063
4058
4064 @property
4059 @property
4065 def commit_id(self):
4060 def commit_id(self):
4066 """New style naming to stop using .revision"""
4061 """New style naming to stop using .revision"""
4067 return self.revision
4062 return self.revision
4068
4063
4069 @property
4064 @property
4070 def resolved(self):
4065 def resolved(self):
4071 return self.resolved_by[0] if self.resolved_by else None
4066 return self.resolved_by[0] if self.resolved_by else None
4072
4067
4073 @property
4068 @property
4074 def is_todo(self):
4069 def is_todo(self):
4075 return self.comment_type == self.COMMENT_TYPE_TODO
4070 return self.comment_type == self.COMMENT_TYPE_TODO
4076
4071
4077 @property
4072 @property
4078 def is_inline(self):
4073 def is_inline(self):
4079 if self.line_no and self.f_path:
4074 if self.line_no and self.f_path:
4080 return True
4075 return True
4081 return False
4076 return False
4082
4077
4083 @property
4078 @property
4084 def last_version(self):
4079 def last_version(self):
4085 version = 0
4080 version = 0
4086 if self.history:
4081 if self.history:
4087 version = self.history[-1].version
4082 version = self.history[-1].version
4088 return version
4083 return version
4089
4084
4090 def get_index_version(self, versions):
4085 def get_index_version(self, versions):
4091 return self.get_index_from_version(
4086 return self.get_index_from_version(
4092 self.pull_request_version_id, versions)
4087 self.pull_request_version_id, versions)
4093
4088
4094 @property
4089 @property
4095 def review_status(self):
4090 def review_status(self):
4096 if self.status_change:
4091 if self.status_change:
4097 return self.status_change[0].status
4092 return self.status_change[0].status
4098
4093
4099 @property
4094 @property
4100 def review_status_lbl(self):
4095 def review_status_lbl(self):
4101 if self.status_change:
4096 if self.status_change:
4102 return self.status_change[0].status_lbl
4097 return self.status_change[0].status_lbl
4103
4098
4104 def __repr__(self):
4099 def __repr__(self):
4105 if self.comment_id:
4100 if self.comment_id:
4106 return f'<DB:Comment #{self.comment_id}>'
4101 return f'<DB:Comment #{self.comment_id}>'
4107 else:
4102 else:
4108 return f'<DB:Comment at {id(self)!r}>'
4103 return f'<DB:Comment at {id(self)!r}>'
4109
4104
4110 def get_api_data(self):
4105 def get_api_data(self):
4111 comment = self
4106 comment = self
4112
4107
4113 data = {
4108 data = {
4114 'comment_id': comment.comment_id,
4109 'comment_id': comment.comment_id,
4115 'comment_type': comment.comment_type,
4110 'comment_type': comment.comment_type,
4116 'comment_text': comment.text,
4111 'comment_text': comment.text,
4117 'comment_status': comment.status_change,
4112 'comment_status': comment.status_change,
4118 'comment_f_path': comment.f_path,
4113 'comment_f_path': comment.f_path,
4119 'comment_lineno': comment.line_no,
4114 'comment_lineno': comment.line_no,
4120 'comment_author': comment.author,
4115 'comment_author': comment.author,
4121 'comment_created_on': comment.created_on,
4116 'comment_created_on': comment.created_on,
4122 'comment_resolved_by': self.resolved,
4117 'comment_resolved_by': self.resolved,
4123 'comment_commit_id': comment.revision,
4118 'comment_commit_id': comment.revision,
4124 'comment_pull_request_id': comment.pull_request_id,
4119 'comment_pull_request_id': comment.pull_request_id,
4125 'comment_last_version': self.last_version
4120 'comment_last_version': self.last_version
4126 }
4121 }
4127 return data
4122 return data
4128
4123
4129 def __json__(self):
4124 def __json__(self):
4130 data = dict()
4125 data = dict()
4131 data.update(self.get_api_data())
4126 data.update(self.get_api_data())
4132 return data
4127 return data
4133
4128
4134
4129
4135 class ChangesetCommentHistory(Base, BaseModel):
4130 class ChangesetCommentHistory(Base, BaseModel):
4136 __tablename__ = 'changeset_comments_history'
4131 __tablename__ = 'changeset_comments_history'
4137 __table_args__ = (
4132 __table_args__ = (
4138 Index('cch_comment_id_idx', 'comment_id'),
4133 Index('cch_comment_id_idx', 'comment_id'),
4139 base_table_args,
4134 base_table_args,
4140 )
4135 )
4141
4136
4142 comment_history_id = Column('comment_history_id', Integer(), nullable=False, primary_key=True)
4137 comment_history_id = Column('comment_history_id', Integer(), nullable=False, primary_key=True)
4143 comment_id = Column('comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=False)
4138 comment_id = Column('comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=False)
4144 version = Column("version", Integer(), nullable=False, default=0)
4139 version = Column("version", Integer(), nullable=False, default=0)
4145 created_by_user_id = Column('created_by_user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
4140 created_by_user_id = Column('created_by_user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
4146 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
4141 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
4147 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4142 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4148 deleted = Column('deleted', Boolean(), default=False)
4143 deleted = Column('deleted', Boolean(), default=False)
4149
4144
4150 author = relationship('User', lazy='joined')
4145 author = relationship('User', lazy='joined')
4151 comment = relationship('ChangesetComment', cascade="all, delete", back_populates="history")
4146 comment = relationship('ChangesetComment', cascade="all, delete", back_populates="history")
4152
4147
4153 @classmethod
4148 @classmethod
4154 def get_version(cls, comment_id):
4149 def get_version(cls, comment_id):
4155 q = Session().query(ChangesetCommentHistory).filter(
4150 q = Session().query(ChangesetCommentHistory).filter(
4156 ChangesetCommentHistory.comment_id == comment_id).order_by(ChangesetCommentHistory.version.desc())
4151 ChangesetCommentHistory.comment_id == comment_id).order_by(ChangesetCommentHistory.version.desc())
4157 if q.count() == 0:
4152 if q.count() == 0:
4158 return 1
4153 return 1
4159 elif q.count() >= q[0].version:
4154 elif q.count() >= q[0].version:
4160 return q.count() + 1
4155 return q.count() + 1
4161 else:
4156 else:
4162 return q[0].version + 1
4157 return q[0].version + 1
4163
4158
4164
4159
4165 class ChangesetStatus(Base, BaseModel):
4160 class ChangesetStatus(Base, BaseModel):
4166 __tablename__ = 'changeset_statuses'
4161 __tablename__ = 'changeset_statuses'
4167 __table_args__ = (
4162 __table_args__ = (
4168 Index('cs_revision_idx', 'revision'),
4163 Index('cs_revision_idx', 'revision'),
4169 Index('cs_version_idx', 'version'),
4164 Index('cs_version_idx', 'version'),
4170 UniqueConstraint('repo_id', 'revision', 'version'),
4165 UniqueConstraint('repo_id', 'revision', 'version'),
4171 base_table_args
4166 base_table_args
4172 )
4167 )
4173
4168
4174 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
4169 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
4175 STATUS_APPROVED = 'approved'
4170 STATUS_APPROVED = 'approved'
4176 STATUS_REJECTED = 'rejected'
4171 STATUS_REJECTED = 'rejected'
4177 STATUS_UNDER_REVIEW = 'under_review'
4172 STATUS_UNDER_REVIEW = 'under_review'
4178
4173
4179 STATUSES = [
4174 STATUSES = [
4180 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
4175 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
4181 (STATUS_APPROVED, _("Approved")),
4176 (STATUS_APPROVED, _("Approved")),
4182 (STATUS_REJECTED, _("Rejected")),
4177 (STATUS_REJECTED, _("Rejected")),
4183 (STATUS_UNDER_REVIEW, _("Under Review")),
4178 (STATUS_UNDER_REVIEW, _("Under Review")),
4184 ]
4179 ]
4185
4180
4186 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
4181 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
4187 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
4182 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
4188 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
4183 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
4189 revision = Column('revision', String(40), nullable=False)
4184 revision = Column('revision', String(40), nullable=False)
4190 status = Column('status', String(128), nullable=False, default=DEFAULT)
4185 status = Column('status', String(128), nullable=False, default=DEFAULT)
4191 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
4186 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
4192 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
4187 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
4193 version = Column('version', Integer(), nullable=False, default=0)
4188 version = Column('version', Integer(), nullable=False, default=0)
4194 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
4189 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
4195
4190
4196 author = relationship('User', lazy='select')
4191 author = relationship('User', lazy='select')
4197 repo = relationship('Repository', lazy='select')
4192 repo = relationship('Repository', lazy='select')
4198 comment = relationship('ChangesetComment', lazy='select', back_populates='status_change')
4193 comment = relationship('ChangesetComment', lazy='select', back_populates='status_change')
4199 pull_request = relationship('PullRequest', lazy='select', back_populates='statuses')
4194 pull_request = relationship('PullRequest', lazy='select', back_populates='statuses')
4200
4195
4201 def __repr__(self):
4196 def __repr__(self):
4202 return f"<{self.cls_name}('{self.status}[v{self.version}]:{self.author}')>"
4197 return f"<{self.cls_name}('{self.status}[v{self.version}]:{self.author}')>"
4203
4198
4204 @classmethod
4199 @classmethod
4205 def get_status_lbl(cls, value):
4200 def get_status_lbl(cls, value):
4206 return dict(cls.STATUSES).get(value)
4201 return dict(cls.STATUSES).get(value)
4207
4202
4208 @property
4203 @property
4209 def status_lbl(self):
4204 def status_lbl(self):
4210 return ChangesetStatus.get_status_lbl(self.status)
4205 return ChangesetStatus.get_status_lbl(self.status)
4211
4206
4212 def get_api_data(self):
4207 def get_api_data(self):
4213 status = self
4208 status = self
4214 data = {
4209 data = {
4215 'status_id': status.changeset_status_id,
4210 'status_id': status.changeset_status_id,
4216 'status': status.status,
4211 'status': status.status,
4217 }
4212 }
4218 return data
4213 return data
4219
4214
4220 def __json__(self):
4215 def __json__(self):
4221 data = dict()
4216 data = dict()
4222 data.update(self.get_api_data())
4217 data.update(self.get_api_data())
4223 return data
4218 return data
4224
4219
4225
4220
4226 class _SetState(object):
4221 class _SetState(object):
4227 """
4222 """
4228 Context processor allowing changing state for sensitive operation such as
4223 Context processor allowing changing state for sensitive operation such as
4229 pull request update or merge
4224 pull request update or merge
4230 """
4225 """
4231
4226
4232 def __init__(self, pull_request, pr_state, back_state=None):
4227 def __init__(self, pull_request, pr_state, back_state=None):
4233 self._pr = pull_request
4228 self._pr = pull_request
4234 self._org_state = back_state or pull_request.pull_request_state
4229 self._org_state = back_state or pull_request.pull_request_state
4235 self._pr_state = pr_state
4230 self._pr_state = pr_state
4236 self._current_state = None
4231 self._current_state = None
4237
4232
4238 def __enter__(self):
4233 def __enter__(self):
4239 log.debug('StateLock: entering set state context of pr %s, setting state to: `%s`',
4234 log.debug('StateLock: entering set state context of pr %s, setting state to: `%s`',
4240 self._pr, self._pr_state)
4235 self._pr, self._pr_state)
4241 self.set_pr_state(self._pr_state)
4236 self.set_pr_state(self._pr_state)
4242 return self
4237 return self
4243
4238
4244 def __exit__(self, exc_type, exc_val, exc_tb):
4239 def __exit__(self, exc_type, exc_val, exc_tb):
4245 if exc_val is not None or exc_type is not None:
4240 if exc_val is not None or exc_type is not None:
4246 log.error(traceback.format_tb(exc_tb))
4241 log.error(traceback.format_tb(exc_tb))
4247 return None
4242 return None
4248
4243
4249 self.set_pr_state(self._org_state)
4244 self.set_pr_state(self._org_state)
4250 log.debug('StateLock: exiting set state context of pr %s, setting state to: `%s`',
4245 log.debug('StateLock: exiting set state context of pr %s, setting state to: `%s`',
4251 self._pr, self._org_state)
4246 self._pr, self._org_state)
4252
4247
4253 @property
4248 @property
4254 def state(self):
4249 def state(self):
4255 return self._current_state
4250 return self._current_state
4256
4251
4257 def set_pr_state(self, pr_state):
4252 def set_pr_state(self, pr_state):
4258 try:
4253 try:
4259 self._pr.pull_request_state = pr_state
4254 self._pr.pull_request_state = pr_state
4260 Session().add(self._pr)
4255 Session().add(self._pr)
4261 Session().commit()
4256 Session().commit()
4262 self._current_state = pr_state
4257 self._current_state = pr_state
4263 except Exception:
4258 except Exception:
4264 log.exception('Failed to set PullRequest %s state to %s', self._pr, pr_state)
4259 log.exception('Failed to set PullRequest %s state to %s', self._pr, pr_state)
4265 raise
4260 raise
4266
4261
4267
4262
4268 class _PullRequestBase(BaseModel):
4263 class _PullRequestBase(BaseModel):
4269 """
4264 """
4270 Common attributes of pull request and version entries.
4265 Common attributes of pull request and version entries.
4271 """
4266 """
4272
4267
4273 # .status values
4268 # .status values
4274 STATUS_NEW = 'new'
4269 STATUS_NEW = 'new'
4275 STATUS_OPEN = 'open'
4270 STATUS_OPEN = 'open'
4276 STATUS_CLOSED = 'closed'
4271 STATUS_CLOSED = 'closed'
4277
4272
4278 # available states
4273 # available states
4279 STATE_CREATING = 'creating'
4274 STATE_CREATING = 'creating'
4280 STATE_UPDATING = 'updating'
4275 STATE_UPDATING = 'updating'
4281 STATE_MERGING = 'merging'
4276 STATE_MERGING = 'merging'
4282 STATE_CREATED = 'created'
4277 STATE_CREATED = 'created'
4283
4278
4284 title = Column('title', Unicode(255), nullable=True)
4279 title = Column('title', Unicode(255), nullable=True)
4285 description = Column(
4280 description = Column(
4286 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
4281 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
4287 nullable=True)
4282 nullable=True)
4288 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
4283 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
4289
4284
4290 # new/open/closed status of pull request (not approve/reject/etc)
4285 # new/open/closed status of pull request (not approve/reject/etc)
4291 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
4286 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
4292 created_on = Column(
4287 created_on = Column(
4293 'created_on', DateTime(timezone=False), nullable=False,
4288 'created_on', DateTime(timezone=False), nullable=False,
4294 default=datetime.datetime.now)
4289 default=datetime.datetime.now)
4295 updated_on = Column(
4290 updated_on = Column(
4296 'updated_on', DateTime(timezone=False), nullable=False,
4291 'updated_on', DateTime(timezone=False), nullable=False,
4297 default=datetime.datetime.now)
4292 default=datetime.datetime.now)
4298
4293
4299 pull_request_state = Column("pull_request_state", String(255), nullable=True)
4294 pull_request_state = Column("pull_request_state", String(255), nullable=True)
4300
4295
4301 @declared_attr
4296 @declared_attr
4302 def user_id(cls):
4297 def user_id(cls):
4303 return Column(
4298 return Column(
4304 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
4299 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
4305 unique=None)
4300 unique=None)
4306
4301
4307 # 500 revisions max
4302 # 500 revisions max
4308 _revisions = Column(
4303 _revisions = Column(
4309 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
4304 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
4310
4305
4311 common_ancestor_id = Column('common_ancestor_id', Unicode(255), nullable=True)
4306 common_ancestor_id = Column('common_ancestor_id', Unicode(255), nullable=True)
4312
4307
4313 @declared_attr
4308 @declared_attr
4314 def source_repo_id(cls):
4309 def source_repo_id(cls):
4315 # TODO: dan: rename column to source_repo_id
4310 # TODO: dan: rename column to source_repo_id
4316 return Column(
4311 return Column(
4317 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
4312 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
4318 nullable=False)
4313 nullable=False)
4319
4314
4320 @declared_attr
4315 @declared_attr
4321 def pr_source(cls):
4316 def pr_source(cls):
4322 return relationship(
4317 return relationship(
4323 'Repository',
4318 'Repository',
4324 primaryjoin=f'{cls.__name__}.source_repo_id==Repository.repo_id',
4319 primaryjoin=f'{cls.__name__}.source_repo_id==Repository.repo_id',
4325 overlaps="pull_requests_source"
4320 overlaps="pull_requests_source"
4326 )
4321 )
4327
4322
4328 _source_ref = Column('org_ref', Unicode(255), nullable=False)
4323 _source_ref = Column('org_ref', Unicode(255), nullable=False)
4329
4324
4330 @hybrid_property
4325 @hybrid_property
4331 def source_ref(self):
4326 def source_ref(self):
4332 return self._source_ref
4327 return self._source_ref
4333
4328
4334 @source_ref.setter
4329 @source_ref.setter
4335 def source_ref(self, val):
4330 def source_ref(self, val):
4336 parts = (val or '').split(':')
4331 parts = (val or '').split(':')
4337 if len(parts) != 3:
4332 if len(parts) != 3:
4338 raise ValueError(
4333 raise ValueError(
4339 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
4334 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
4340 self._source_ref = safe_str(val)
4335 self._source_ref = safe_str(val)
4341
4336
4342 _target_ref = Column('other_ref', Unicode(255), nullable=False)
4337 _target_ref = Column('other_ref', Unicode(255), nullable=False)
4343
4338
4344 @hybrid_property
4339 @hybrid_property
4345 def target_ref(self):
4340 def target_ref(self):
4346 return self._target_ref
4341 return self._target_ref
4347
4342
4348 @target_ref.setter
4343 @target_ref.setter
4349 def target_ref(self, val):
4344 def target_ref(self, val):
4350 parts = (val or '').split(':')
4345 parts = (val or '').split(':')
4351 if len(parts) != 3:
4346 if len(parts) != 3:
4352 raise ValueError(
4347 raise ValueError(
4353 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
4348 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
4354 self._target_ref = safe_str(val)
4349 self._target_ref = safe_str(val)
4355
4350
4356 @declared_attr
4351 @declared_attr
4357 def target_repo_id(cls):
4352 def target_repo_id(cls):
4358 # TODO: dan: rename column to target_repo_id
4353 # TODO: dan: rename column to target_repo_id
4359 return Column(
4354 return Column(
4360 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
4355 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
4361 nullable=False)
4356 nullable=False)
4362
4357
4363 @declared_attr
4358 @declared_attr
4364 def pr_target(cls):
4359 def pr_target(cls):
4365 return relationship(
4360 return relationship(
4366 'Repository',
4361 'Repository',
4367 primaryjoin=f'{cls.__name__}.target_repo_id==Repository.repo_id',
4362 primaryjoin=f'{cls.__name__}.target_repo_id==Repository.repo_id',
4368 overlaps="pull_requests_target"
4363 overlaps="pull_requests_target"
4369 )
4364 )
4370
4365
4371 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
4366 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
4372
4367
4373 # TODO: dan: rename column to last_merge_source_rev
4368 # TODO: dan: rename column to last_merge_source_rev
4374 _last_merge_source_rev = Column(
4369 _last_merge_source_rev = Column(
4375 'last_merge_org_rev', String(40), nullable=True)
4370 'last_merge_org_rev', String(40), nullable=True)
4376 # TODO: dan: rename column to last_merge_target_rev
4371 # TODO: dan: rename column to last_merge_target_rev
4377 _last_merge_target_rev = Column(
4372 _last_merge_target_rev = Column(
4378 'last_merge_other_rev', String(40), nullable=True)
4373 'last_merge_other_rev', String(40), nullable=True)
4379 _last_merge_status = Column('merge_status', Integer(), nullable=True)
4374 _last_merge_status = Column('merge_status', Integer(), nullable=True)
4380 last_merge_metadata = Column(
4375 last_merge_metadata = Column(
4381 'last_merge_metadata', MutationObj.as_mutable(
4376 'last_merge_metadata', MutationObj.as_mutable(
4382 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4377 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4383
4378
4384 merge_rev = Column('merge_rev', String(40), nullable=True)
4379 merge_rev = Column('merge_rev', String(40), nullable=True)
4385
4380
4386 reviewer_data = Column(
4381 reviewer_data = Column(
4387 'reviewer_data_json', MutationObj.as_mutable(
4382 'reviewer_data_json', MutationObj.as_mutable(
4388 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4383 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4389
4384
4390 @property
4385 @property
4391 def reviewer_data_json(self):
4386 def reviewer_data_json(self):
4392 return str_json(self.reviewer_data)
4387 return str_json(self.reviewer_data)
4393
4388
4394 @property
4389 @property
4395 def last_merge_metadata_parsed(self):
4390 def last_merge_metadata_parsed(self):
4396 metadata = {}
4391 metadata = {}
4397 if not self.last_merge_metadata:
4392 if not self.last_merge_metadata:
4398 return metadata
4393 return metadata
4399
4394
4400 if hasattr(self.last_merge_metadata, 'de_coerce'):
4395 if hasattr(self.last_merge_metadata, 'de_coerce'):
4401 for k, v in self.last_merge_metadata.de_coerce().items():
4396 for k, v in self.last_merge_metadata.de_coerce().items():
4402 if k in ['target_ref', 'source_ref']:
4397 if k in ['target_ref', 'source_ref']:
4403 metadata[k] = Reference(v['type'], v['name'], v['commit_id'])
4398 metadata[k] = Reference(v['type'], v['name'], v['commit_id'])
4404 else:
4399 else:
4405 if hasattr(v, 'de_coerce'):
4400 if hasattr(v, 'de_coerce'):
4406 metadata[k] = v.de_coerce()
4401 metadata[k] = v.de_coerce()
4407 else:
4402 else:
4408 metadata[k] = v
4403 metadata[k] = v
4409 return metadata
4404 return metadata
4410
4405
4411 @property
4406 @property
4412 def work_in_progress(self):
4407 def work_in_progress(self):
4413 """checks if pull request is work in progress by checking the title"""
4408 """checks if pull request is work in progress by checking the title"""
4414 title = self.title.upper()
4409 title = self.title.upper()
4415 if re.match(r'^(\[WIP\]\s*|WIP:\s*|WIP\s+)', title):
4410 if re.match(r'^(\[WIP\]\s*|WIP:\s*|WIP\s+)', title):
4416 return True
4411 return True
4417 return False
4412 return False
4418
4413
4419 @property
4414 @property
4420 def title_safe(self):
4415 def title_safe(self):
4421 return self.title\
4416 return self.title\
4422 .replace('{', '{{')\
4417 .replace('{', '{{')\
4423 .replace('}', '}}')
4418 .replace('}', '}}')
4424
4419
4425 @hybrid_property
4420 @hybrid_property
4426 def description_safe(self):
4421 def description_safe(self):
4427 from rhodecode.lib import helpers as h
4422 from rhodecode.lib import helpers as h
4428 return h.escape(self.description)
4423 return h.escape(self.description)
4429
4424
4430 @hybrid_property
4425 @hybrid_property
4431 def revisions(self):
4426 def revisions(self):
4432 return self._revisions.split(':') if self._revisions else []
4427 return self._revisions.split(':') if self._revisions else []
4433
4428
4434 @revisions.setter
4429 @revisions.setter
4435 def revisions(self, val):
4430 def revisions(self, val):
4436 self._revisions = ':'.join(val)
4431 self._revisions = ':'.join(val)
4437
4432
4438 @hybrid_property
4433 @hybrid_property
4439 def last_merge_status(self):
4434 def last_merge_status(self):
4440 return safe_int(self._last_merge_status)
4435 return safe_int(self._last_merge_status)
4441
4436
4442 @last_merge_status.setter
4437 @last_merge_status.setter
4443 def last_merge_status(self, val):
4438 def last_merge_status(self, val):
4444 self._last_merge_status = val
4439 self._last_merge_status = val
4445
4440
4446 @declared_attr
4441 @declared_attr
4447 def author(cls):
4442 def author(cls):
4448 return relationship(
4443 return relationship(
4449 'User', lazy='joined',
4444 'User', lazy='joined',
4450 #TODO, problem that is somehow :?
4445 #TODO, problem that is somehow :?
4451 #back_populates='user_pull_requests'
4446 #back_populates='user_pull_requests'
4452 )
4447 )
4453
4448
4454 @declared_attr
4449 @declared_attr
4455 def source_repo(cls):
4450 def source_repo(cls):
4456 return relationship(
4451 return relationship(
4457 'Repository',
4452 'Repository',
4458 primaryjoin=f'{cls.__name__}.source_repo_id==Repository.repo_id',
4453 primaryjoin=f'{cls.__name__}.source_repo_id==Repository.repo_id',
4459 overlaps="pr_source"
4454 overlaps="pr_source"
4460 )
4455 )
4461
4456
4462 @property
4457 @property
4463 def source_ref_parts(self):
4458 def source_ref_parts(self):
4464 return self.unicode_to_reference(self.source_ref)
4459 return self.unicode_to_reference(self.source_ref)
4465
4460
4466 @declared_attr
4461 @declared_attr
4467 def target_repo(cls):
4462 def target_repo(cls):
4468 return relationship(
4463 return relationship(
4469 'Repository',
4464 'Repository',
4470 primaryjoin=f'{cls.__name__}.target_repo_id==Repository.repo_id',
4465 primaryjoin=f'{cls.__name__}.target_repo_id==Repository.repo_id',
4471 overlaps="pr_target"
4466 overlaps="pr_target"
4472 )
4467 )
4473
4468
4474 @property
4469 @property
4475 def target_ref_parts(self):
4470 def target_ref_parts(self):
4476 return self.unicode_to_reference(self.target_ref)
4471 return self.unicode_to_reference(self.target_ref)
4477
4472
4478 @property
4473 @property
4479 def shadow_merge_ref(self):
4474 def shadow_merge_ref(self):
4480 return self.unicode_to_reference(self._shadow_merge_ref)
4475 return self.unicode_to_reference(self._shadow_merge_ref)
4481
4476
4482 @shadow_merge_ref.setter
4477 @shadow_merge_ref.setter
4483 def shadow_merge_ref(self, ref):
4478 def shadow_merge_ref(self, ref):
4484 self._shadow_merge_ref = self.reference_to_unicode(ref)
4479 self._shadow_merge_ref = self.reference_to_unicode(ref)
4485
4480
4486 @staticmethod
4481 @staticmethod
4487 def unicode_to_reference(raw):
4482 def unicode_to_reference(raw):
4488 return unicode_to_reference(raw)
4483 return unicode_to_reference(raw)
4489
4484
4490 @staticmethod
4485 @staticmethod
4491 def reference_to_unicode(ref):
4486 def reference_to_unicode(ref):
4492 return reference_to_unicode(ref)
4487 return reference_to_unicode(ref)
4493
4488
4494 def get_api_data(self, with_merge_state=True):
4489 def get_api_data(self, with_merge_state=True):
4495 from rhodecode.model.pull_request import PullRequestModel
4490 from rhodecode.model.pull_request import PullRequestModel
4496
4491
4497 pull_request = self
4492 pull_request = self
4498 if with_merge_state:
4493 if with_merge_state:
4499 merge_response, merge_status, msg = \
4494 merge_response, merge_status, msg = \
4500 PullRequestModel().merge_status(pull_request)
4495 PullRequestModel().merge_status(pull_request)
4501 merge_state = {
4496 merge_state = {
4502 'status': merge_status,
4497 'status': merge_status,
4503 'message': safe_str(msg),
4498 'message': safe_str(msg),
4504 }
4499 }
4505 else:
4500 else:
4506 merge_state = {'status': 'not_available',
4501 merge_state = {'status': 'not_available',
4507 'message': 'not_available'}
4502 'message': 'not_available'}
4508
4503
4509 merge_data = {
4504 merge_data = {
4510 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
4505 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
4511 'reference': (
4506 'reference': (
4512 pull_request.shadow_merge_ref.asdict()
4507 pull_request.shadow_merge_ref.asdict()
4513 if pull_request.shadow_merge_ref else None),
4508 if pull_request.shadow_merge_ref else None),
4514 }
4509 }
4515
4510
4516 data = {
4511 data = {
4517 'pull_request_id': pull_request.pull_request_id,
4512 'pull_request_id': pull_request.pull_request_id,
4518 'url': PullRequestModel().get_url(pull_request),
4513 'url': PullRequestModel().get_url(pull_request),
4519 'title': pull_request.title,
4514 'title': pull_request.title,
4520 'description': pull_request.description,
4515 'description': pull_request.description,
4521 'status': pull_request.status,
4516 'status': pull_request.status,
4522 'state': pull_request.pull_request_state,
4517 'state': pull_request.pull_request_state,
4523 'created_on': pull_request.created_on,
4518 'created_on': pull_request.created_on,
4524 'updated_on': pull_request.updated_on,
4519 'updated_on': pull_request.updated_on,
4525 'commit_ids': pull_request.revisions,
4520 'commit_ids': pull_request.revisions,
4526 'review_status': pull_request.calculated_review_status(),
4521 'review_status': pull_request.calculated_review_status(),
4527 'mergeable': merge_state,
4522 'mergeable': merge_state,
4528 'source': {
4523 'source': {
4529 'clone_url': pull_request.source_repo.clone_url(),
4524 'clone_url': pull_request.source_repo.clone_url(),
4530 'repository': pull_request.source_repo.repo_name,
4525 'repository': pull_request.source_repo.repo_name,
4531 'reference': {
4526 'reference': {
4532 'name': pull_request.source_ref_parts.name,
4527 'name': pull_request.source_ref_parts.name,
4533 'type': pull_request.source_ref_parts.type,
4528 'type': pull_request.source_ref_parts.type,
4534 'commit_id': pull_request.source_ref_parts.commit_id,
4529 'commit_id': pull_request.source_ref_parts.commit_id,
4535 },
4530 },
4536 },
4531 },
4537 'target': {
4532 'target': {
4538 'clone_url': pull_request.target_repo.clone_url(),
4533 'clone_url': pull_request.target_repo.clone_url(),
4539 'repository': pull_request.target_repo.repo_name,
4534 'repository': pull_request.target_repo.repo_name,
4540 'reference': {
4535 'reference': {
4541 'name': pull_request.target_ref_parts.name,
4536 'name': pull_request.target_ref_parts.name,
4542 'type': pull_request.target_ref_parts.type,
4537 'type': pull_request.target_ref_parts.type,
4543 'commit_id': pull_request.target_ref_parts.commit_id,
4538 'commit_id': pull_request.target_ref_parts.commit_id,
4544 },
4539 },
4545 },
4540 },
4546 'merge': merge_data,
4541 'merge': merge_data,
4547 'author': pull_request.author.get_api_data(include_secrets=False,
4542 'author': pull_request.author.get_api_data(include_secrets=False,
4548 details='basic'),
4543 details='basic'),
4549 'reviewers': [
4544 'reviewers': [
4550 {
4545 {
4551 'user': reviewer.get_api_data(include_secrets=False,
4546 'user': reviewer.get_api_data(include_secrets=False,
4552 details='basic'),
4547 details='basic'),
4553 'reasons': reasons,
4548 'reasons': reasons,
4554 'review_status': st[0][1].status if st else 'not_reviewed',
4549 'review_status': st[0][1].status if st else 'not_reviewed',
4555 }
4550 }
4556 for obj, reviewer, reasons, mandatory, st in
4551 for obj, reviewer, reasons, mandatory, st in
4557 pull_request.reviewers_statuses()
4552 pull_request.reviewers_statuses()
4558 ]
4553 ]
4559 }
4554 }
4560
4555
4561 return data
4556 return data
4562
4557
4563 def set_state(self, pull_request_state, final_state=None):
4558 def set_state(self, pull_request_state, final_state=None):
4564 """
4559 """
4565 # goes from initial state to updating to initial state.
4560 # goes from initial state to updating to initial state.
4566 # initial state can be changed by specifying back_state=
4561 # initial state can be changed by specifying back_state=
4567 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
4562 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
4568 pull_request.merge()
4563 pull_request.merge()
4569
4564
4570 :param pull_request_state:
4565 :param pull_request_state:
4571 :param final_state:
4566 :param final_state:
4572
4567
4573 """
4568 """
4574
4569
4575 return _SetState(self, pull_request_state, back_state=final_state)
4570 return _SetState(self, pull_request_state, back_state=final_state)
4576
4571
4577
4572
4578 class PullRequest(Base, _PullRequestBase):
4573 class PullRequest(Base, _PullRequestBase):
4579 __tablename__ = 'pull_requests'
4574 __tablename__ = 'pull_requests'
4580 __table_args__ = (
4575 __table_args__ = (
4581 base_table_args,
4576 base_table_args,
4582 )
4577 )
4583 LATEST_VER = 'latest'
4578 LATEST_VER = 'latest'
4584
4579
4585 pull_request_id = Column(
4580 pull_request_id = Column(
4586 'pull_request_id', Integer(), nullable=False, primary_key=True)
4581 'pull_request_id', Integer(), nullable=False, primary_key=True)
4587
4582
4588 def __repr__(self):
4583 def __repr__(self):
4589 if self.pull_request_id:
4584 if self.pull_request_id:
4590 return f'<DB:PullRequest #{self.pull_request_id}>'
4585 return f'<DB:PullRequest #{self.pull_request_id}>'
4591 else:
4586 else:
4592 return f'<DB:PullRequest at {id(self)!r}>'
4587 return f'<DB:PullRequest at {id(self)!r}>'
4593
4588
4594 reviewers = relationship('PullRequestReviewers', cascade="all, delete-orphan", back_populates='pull_request')
4589 reviewers = relationship('PullRequestReviewers', cascade="all, delete-orphan", back_populates='pull_request')
4595 statuses = relationship('ChangesetStatus', cascade="all, delete-orphan", back_populates='pull_request')
4590 statuses = relationship('ChangesetStatus', cascade="all, delete-orphan", back_populates='pull_request')
4596 comments = relationship('ChangesetComment', cascade="all, delete-orphan", back_populates='pull_request')
4591 comments = relationship('ChangesetComment', cascade="all, delete-orphan", back_populates='pull_request')
4597 versions = relationship('PullRequestVersion', cascade="all, delete-orphan", lazy='dynamic', back_populates='pull_request')
4592 versions = relationship('PullRequestVersion', cascade="all, delete-orphan", lazy='dynamic', back_populates='pull_request')
4598
4593
4599 @classmethod
4594 @classmethod
4600 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
4595 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
4601 internal_methods=None):
4596 internal_methods=None):
4602
4597
4603 class PullRequestDisplay(object):
4598 class PullRequestDisplay(object):
4604 """
4599 """
4605 Special object wrapper for showing PullRequest data via Versions
4600 Special object wrapper for showing PullRequest data via Versions
4606 It mimics PR object as close as possible. This is read only object
4601 It mimics PR object as close as possible. This is read only object
4607 just for display
4602 just for display
4608 """
4603 """
4609
4604
4610 def __init__(self, attrs, internal=None):
4605 def __init__(self, attrs, internal=None):
4611 self.attrs = attrs
4606 self.attrs = attrs
4612 # internal have priority over the given ones via attrs
4607 # internal have priority over the given ones via attrs
4613 self.internal = internal or ['versions']
4608 self.internal = internal or ['versions']
4614
4609
4615 def __getattr__(self, item):
4610 def __getattr__(self, item):
4616 if item in self.internal:
4611 if item in self.internal:
4617 return getattr(self, item)
4612 return getattr(self, item)
4618 try:
4613 try:
4619 return self.attrs[item]
4614 return self.attrs[item]
4620 except KeyError:
4615 except KeyError:
4621 raise AttributeError(
4616 raise AttributeError(
4622 '%s object has no attribute %s' % (self, item))
4617 '%s object has no attribute %s' % (self, item))
4623
4618
4624 def __repr__(self):
4619 def __repr__(self):
4625 pr_id = self.attrs.get('pull_request_id')
4620 pr_id = self.attrs.get('pull_request_id')
4626 return f'<DB:PullRequestDisplay #{pr_id}>'
4621 return f'<DB:PullRequestDisplay #{pr_id}>'
4627
4622
4628 def versions(self):
4623 def versions(self):
4629 return pull_request_obj.versions.order_by(
4624 return pull_request_obj.versions.order_by(
4630 PullRequestVersion.pull_request_version_id).all()
4625 PullRequestVersion.pull_request_version_id).all()
4631
4626
4632 def is_closed(self):
4627 def is_closed(self):
4633 return pull_request_obj.is_closed()
4628 return pull_request_obj.is_closed()
4634
4629
4635 def is_state_changing(self):
4630 def is_state_changing(self):
4636 return pull_request_obj.is_state_changing()
4631 return pull_request_obj.is_state_changing()
4637
4632
4638 @property
4633 @property
4639 def pull_request_version_id(self):
4634 def pull_request_version_id(self):
4640 return getattr(pull_request_obj, 'pull_request_version_id', None)
4635 return getattr(pull_request_obj, 'pull_request_version_id', None)
4641
4636
4642 @property
4637 @property
4643 def pull_request_last_version(self):
4638 def pull_request_last_version(self):
4644 return pull_request_obj.pull_request_last_version
4639 return pull_request_obj.pull_request_last_version
4645
4640
4646 attrs = StrictAttributeDict(pull_request_obj.get_api_data(with_merge_state=False))
4641 attrs = StrictAttributeDict(pull_request_obj.get_api_data(with_merge_state=False))
4647
4642
4648 attrs.author = StrictAttributeDict(
4643 attrs.author = StrictAttributeDict(
4649 pull_request_obj.author.get_api_data())
4644 pull_request_obj.author.get_api_data())
4650 if pull_request_obj.target_repo:
4645 if pull_request_obj.target_repo:
4651 attrs.target_repo = StrictAttributeDict(
4646 attrs.target_repo = StrictAttributeDict(
4652 pull_request_obj.target_repo.get_api_data())
4647 pull_request_obj.target_repo.get_api_data())
4653 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
4648 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
4654
4649
4655 if pull_request_obj.source_repo:
4650 if pull_request_obj.source_repo:
4656 attrs.source_repo = StrictAttributeDict(
4651 attrs.source_repo = StrictAttributeDict(
4657 pull_request_obj.source_repo.get_api_data())
4652 pull_request_obj.source_repo.get_api_data())
4658 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
4653 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
4659
4654
4660 attrs.source_ref_parts = pull_request_obj.source_ref_parts
4655 attrs.source_ref_parts = pull_request_obj.source_ref_parts
4661 attrs.target_ref_parts = pull_request_obj.target_ref_parts
4656 attrs.target_ref_parts = pull_request_obj.target_ref_parts
4662 attrs.revisions = pull_request_obj.revisions
4657 attrs.revisions = pull_request_obj.revisions
4663 attrs.common_ancestor_id = pull_request_obj.common_ancestor_id
4658 attrs.common_ancestor_id = pull_request_obj.common_ancestor_id
4664 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
4659 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
4665 attrs.reviewer_data = org_pull_request_obj.reviewer_data
4660 attrs.reviewer_data = org_pull_request_obj.reviewer_data
4666 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
4661 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
4667
4662
4668 return PullRequestDisplay(attrs, internal=internal_methods)
4663 return PullRequestDisplay(attrs, internal=internal_methods)
4669
4664
4670 def is_closed(self):
4665 def is_closed(self):
4671 return self.status == self.STATUS_CLOSED
4666 return self.status == self.STATUS_CLOSED
4672
4667
4673 def is_state_changing(self):
4668 def is_state_changing(self):
4674 return self.pull_request_state != PullRequest.STATE_CREATED
4669 return self.pull_request_state != PullRequest.STATE_CREATED
4675
4670
4676 def __json__(self):
4671 def __json__(self):
4677 return {
4672 return {
4678 'revisions': self.revisions,
4673 'revisions': self.revisions,
4679 'versions': self.versions_count
4674 'versions': self.versions_count
4680 }
4675 }
4681
4676
4682 def calculated_review_status(self):
4677 def calculated_review_status(self):
4683 from rhodecode.model.changeset_status import ChangesetStatusModel
4678 from rhodecode.model.changeset_status import ChangesetStatusModel
4684 return ChangesetStatusModel().calculated_review_status(self)
4679 return ChangesetStatusModel().calculated_review_status(self)
4685
4680
4686 def reviewers_statuses(self, user=None):
4681 def reviewers_statuses(self, user=None):
4687 from rhodecode.model.changeset_status import ChangesetStatusModel
4682 from rhodecode.model.changeset_status import ChangesetStatusModel
4688 return ChangesetStatusModel().reviewers_statuses(self, user=user)
4683 return ChangesetStatusModel().reviewers_statuses(self, user=user)
4689
4684
4690 def get_pull_request_reviewers(self, role=None):
4685 def get_pull_request_reviewers(self, role=None):
4691 qry = PullRequestReviewers.query()\
4686 qry = PullRequestReviewers.query()\
4692 .filter(PullRequestReviewers.pull_request_id == self.pull_request_id)
4687 .filter(PullRequestReviewers.pull_request_id == self.pull_request_id)
4693 if role:
4688 if role:
4694 qry = qry.filter(PullRequestReviewers.role == role)
4689 qry = qry.filter(PullRequestReviewers.role == role)
4695
4690
4696 return qry.all()
4691 return qry.all()
4697
4692
4698 @property
4693 @property
4699 def reviewers_count(self):
4694 def reviewers_count(self):
4700 qry = PullRequestReviewers.query()\
4695 qry = PullRequestReviewers.query()\
4701 .filter(PullRequestReviewers.pull_request_id == self.pull_request_id)\
4696 .filter(PullRequestReviewers.pull_request_id == self.pull_request_id)\
4702 .filter(PullRequestReviewers.role == PullRequestReviewers.ROLE_REVIEWER)
4697 .filter(PullRequestReviewers.role == PullRequestReviewers.ROLE_REVIEWER)
4703 return qry.count()
4698 return qry.count()
4704
4699
4705 @property
4700 @property
4706 def observers_count(self):
4701 def observers_count(self):
4707 qry = PullRequestReviewers.query()\
4702 qry = PullRequestReviewers.query()\
4708 .filter(PullRequestReviewers.pull_request_id == self.pull_request_id)\
4703 .filter(PullRequestReviewers.pull_request_id == self.pull_request_id)\
4709 .filter(PullRequestReviewers.role == PullRequestReviewers.ROLE_OBSERVER)
4704 .filter(PullRequestReviewers.role == PullRequestReviewers.ROLE_OBSERVER)
4710 return qry.count()
4705 return qry.count()
4711
4706
4712 def observers(self):
4707 def observers(self):
4713 qry = PullRequestReviewers.query()\
4708 qry = PullRequestReviewers.query()\
4714 .filter(PullRequestReviewers.pull_request_id == self.pull_request_id)\
4709 .filter(PullRequestReviewers.pull_request_id == self.pull_request_id)\
4715 .filter(PullRequestReviewers.role == PullRequestReviewers.ROLE_OBSERVER)\
4710 .filter(PullRequestReviewers.role == PullRequestReviewers.ROLE_OBSERVER)\
4716 .all()
4711 .all()
4717
4712
4718 for entry in qry:
4713 for entry in qry:
4719 yield entry, entry.user
4714 yield entry, entry.user
4720
4715
4721 @property
4716 @property
4722 def workspace_id(self):
4717 def workspace_id(self):
4723 from rhodecode.model.pull_request import PullRequestModel
4718 from rhodecode.model.pull_request import PullRequestModel
4724 return PullRequestModel()._workspace_id(self)
4719 return PullRequestModel()._workspace_id(self)
4725
4720
4726 def get_shadow_repo(self):
4721 def get_shadow_repo(self):
4727 workspace_id = self.workspace_id
4722 workspace_id = self.workspace_id
4728 shadow_repository_path = self.target_repo.get_shadow_repository_path(workspace_id)
4723 shadow_repository_path = self.target_repo.get_shadow_repository_path(workspace_id)
4729 if os.path.isdir(shadow_repository_path):
4724 if os.path.isdir(shadow_repository_path):
4730 vcs_obj = self.target_repo.scm_instance()
4725 vcs_obj = self.target_repo.scm_instance()
4731 return vcs_obj.get_shadow_instance(shadow_repository_path)
4726 return vcs_obj.get_shadow_instance(shadow_repository_path)
4732
4727
4733 @property
4728 @property
4734 def versions_count(self):
4729 def versions_count(self):
4735 """
4730 """
4736 return number of versions this PR have, e.g a PR that once been
4731 return number of versions this PR have, e.g a PR that once been
4737 updated will have 2 versions
4732 updated will have 2 versions
4738 """
4733 """
4739 return self.versions.count() + 1
4734 return self.versions.count() + 1
4740
4735
4741 @property
4736 @property
4742 def pull_request_last_version(self):
4737 def pull_request_last_version(self):
4743 return self.versions_count
4738 return self.versions_count
4744
4739
4745
4740
4746 class PullRequestVersion(Base, _PullRequestBase):
4741 class PullRequestVersion(Base, _PullRequestBase):
4747 __tablename__ = 'pull_request_versions'
4742 __tablename__ = 'pull_request_versions'
4748 __table_args__ = (
4743 __table_args__ = (
4749 base_table_args,
4744 base_table_args,
4750 )
4745 )
4751
4746
4752 pull_request_version_id = Column('pull_request_version_id', Integer(), nullable=False, primary_key=True)
4747 pull_request_version_id = Column('pull_request_version_id', Integer(), nullable=False, primary_key=True)
4753 pull_request_id = Column('pull_request_id', Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=False)
4748 pull_request_id = Column('pull_request_id', Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=False)
4754 pull_request = relationship('PullRequest', back_populates='versions')
4749 pull_request = relationship('PullRequest', back_populates='versions')
4755
4750
4756 def __repr__(self):
4751 def __repr__(self):
4757 if self.pull_request_version_id:
4752 if self.pull_request_version_id:
4758 return f'<DB:PullRequestVersion #{self.pull_request_version_id}>'
4753 return f'<DB:PullRequestVersion #{self.pull_request_version_id}>'
4759 else:
4754 else:
4760 return f'<DB:PullRequestVersion at {id(self)!r}>'
4755 return f'<DB:PullRequestVersion at {id(self)!r}>'
4761
4756
4762 @property
4757 @property
4763 def reviewers(self):
4758 def reviewers(self):
4764 return self.pull_request.reviewers
4759 return self.pull_request.reviewers
4765
4760
4766 @property
4761 @property
4767 def versions(self):
4762 def versions(self):
4768 return self.pull_request.versions
4763 return self.pull_request.versions
4769
4764
4770 def is_closed(self):
4765 def is_closed(self):
4771 # calculate from original
4766 # calculate from original
4772 return self.pull_request.status == self.STATUS_CLOSED
4767 return self.pull_request.status == self.STATUS_CLOSED
4773
4768
4774 def is_state_changing(self):
4769 def is_state_changing(self):
4775 return self.pull_request.pull_request_state != PullRequest.STATE_CREATED
4770 return self.pull_request.pull_request_state != PullRequest.STATE_CREATED
4776
4771
4777 def calculated_review_status(self):
4772 def calculated_review_status(self):
4778 return self.pull_request.calculated_review_status()
4773 return self.pull_request.calculated_review_status()
4779
4774
4780 def reviewers_statuses(self):
4775 def reviewers_statuses(self):
4781 return self.pull_request.reviewers_statuses()
4776 return self.pull_request.reviewers_statuses()
4782
4777
4783 def observers(self):
4778 def observers(self):
4784 return self.pull_request.observers()
4779 return self.pull_request.observers()
4785
4780
4786
4781
4787 class PullRequestReviewers(Base, BaseModel):
4782 class PullRequestReviewers(Base, BaseModel):
4788 __tablename__ = 'pull_request_reviewers'
4783 __tablename__ = 'pull_request_reviewers'
4789 __table_args__ = (
4784 __table_args__ = (
4790 base_table_args,
4785 base_table_args,
4791 )
4786 )
4792 ROLE_REVIEWER = 'reviewer'
4787 ROLE_REVIEWER = 'reviewer'
4793 ROLE_OBSERVER = 'observer'
4788 ROLE_OBSERVER = 'observer'
4794 ROLES = [ROLE_REVIEWER, ROLE_OBSERVER]
4789 ROLES = [ROLE_REVIEWER, ROLE_OBSERVER]
4795
4790
4796 @hybrid_property
4791 @hybrid_property
4797 def reasons(self):
4792 def reasons(self):
4798 if not self._reasons:
4793 if not self._reasons:
4799 return []
4794 return []
4800 return self._reasons
4795 return self._reasons
4801
4796
4802 @reasons.setter
4797 @reasons.setter
4803 def reasons(self, val):
4798 def reasons(self, val):
4804 val = val or []
4799 val = val or []
4805 if any(not isinstance(x, str) for x in val):
4800 if any(not isinstance(x, str) for x in val):
4806 raise Exception('invalid reasons type, must be list of strings')
4801 raise Exception('invalid reasons type, must be list of strings')
4807 self._reasons = val
4802 self._reasons = val
4808
4803
4809 pull_requests_reviewers_id = Column(
4804 pull_requests_reviewers_id = Column(
4810 'pull_requests_reviewers_id', Integer(), nullable=False,
4805 'pull_requests_reviewers_id', Integer(), nullable=False,
4811 primary_key=True)
4806 primary_key=True)
4812 pull_request_id = Column(
4807 pull_request_id = Column(
4813 "pull_request_id", Integer(),
4808 "pull_request_id", Integer(),
4814 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4809 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4815 user_id = Column(
4810 user_id = Column(
4816 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4811 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4817 _reasons = Column(
4812 _reasons = Column(
4818 'reason', MutationList.as_mutable(
4813 'reason', MutationList.as_mutable(
4819 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4814 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4820
4815
4821 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4816 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4822 role = Column('role', Unicode(255), nullable=True, default=ROLE_REVIEWER)
4817 role = Column('role', Unicode(255), nullable=True, default=ROLE_REVIEWER)
4823
4818
4824 user = relationship('User')
4819 user = relationship('User')
4825 pull_request = relationship('PullRequest', back_populates='reviewers')
4820 pull_request = relationship('PullRequest', back_populates='reviewers')
4826
4821
4827 rule_data = Column(
4822 rule_data = Column(
4828 'rule_data_json',
4823 'rule_data_json',
4829 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4824 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4830
4825
4831 def rule_user_group_data(self):
4826 def rule_user_group_data(self):
4832 """
4827 """
4833 Returns the voting user group rule data for this reviewer
4828 Returns the voting user group rule data for this reviewer
4834 """
4829 """
4835
4830
4836 if self.rule_data and 'vote_rule' in self.rule_data:
4831 if self.rule_data and 'vote_rule' in self.rule_data:
4837 user_group_data = {}
4832 user_group_data = {}
4838 if 'rule_user_group_entry_id' in self.rule_data:
4833 if 'rule_user_group_entry_id' in self.rule_data:
4839 # means a group with voting rules !
4834 # means a group with voting rules !
4840 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4835 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4841 user_group_data['name'] = self.rule_data['rule_name']
4836 user_group_data['name'] = self.rule_data['rule_name']
4842 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4837 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4843
4838
4844 return user_group_data
4839 return user_group_data
4845
4840
4846 @classmethod
4841 @classmethod
4847 def get_pull_request_reviewers(cls, pull_request_id, role=None):
4842 def get_pull_request_reviewers(cls, pull_request_id, role=None):
4848 qry = PullRequestReviewers.query()\
4843 qry = PullRequestReviewers.query()\
4849 .filter(PullRequestReviewers.pull_request_id == pull_request_id)
4844 .filter(PullRequestReviewers.pull_request_id == pull_request_id)
4850 if role:
4845 if role:
4851 qry = qry.filter(PullRequestReviewers.role == role)
4846 qry = qry.filter(PullRequestReviewers.role == role)
4852
4847
4853 return qry.all()
4848 return qry.all()
4854
4849
4855 def __repr__(self):
4850 def __repr__(self):
4856 return f"<{self.cls_name}('id:{self.pull_requests_reviewers_id}')>"
4851 return f"<{self.cls_name}('id:{self.pull_requests_reviewers_id}')>"
4857
4852
4858
4853
4859 class Notification(Base, BaseModel):
4854 class Notification(Base, BaseModel):
4860 __tablename__ = 'notifications'
4855 __tablename__ = 'notifications'
4861 __table_args__ = (
4856 __table_args__ = (
4862 Index('notification_type_idx', 'type'),
4857 Index('notification_type_idx', 'type'),
4863 base_table_args,
4858 base_table_args,
4864 )
4859 )
4865
4860
4866 TYPE_CHANGESET_COMMENT = 'cs_comment'
4861 TYPE_CHANGESET_COMMENT = 'cs_comment'
4867 TYPE_MESSAGE = 'message'
4862 TYPE_MESSAGE = 'message'
4868 TYPE_MENTION = 'mention'
4863 TYPE_MENTION = 'mention'
4869 TYPE_REGISTRATION = 'registration'
4864 TYPE_REGISTRATION = 'registration'
4870 TYPE_PULL_REQUEST = 'pull_request'
4865 TYPE_PULL_REQUEST = 'pull_request'
4871 TYPE_PULL_REQUEST_COMMENT = 'pull_request_comment'
4866 TYPE_PULL_REQUEST_COMMENT = 'pull_request_comment'
4872 TYPE_PULL_REQUEST_UPDATE = 'pull_request_update'
4867 TYPE_PULL_REQUEST_UPDATE = 'pull_request_update'
4873
4868
4874 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4869 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4875 subject = Column('subject', Unicode(512), nullable=True)
4870 subject = Column('subject', Unicode(512), nullable=True)
4876 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4871 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4877 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4872 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4878 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4873 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4879 type_ = Column('type', Unicode(255))
4874 type_ = Column('type', Unicode(255))
4880
4875
4881 created_by_user = relationship('User', back_populates='user_created_notifications')
4876 created_by_user = relationship('User', back_populates='user_created_notifications')
4882 notifications_to_users = relationship('UserNotification', lazy='joined', cascade="all, delete-orphan", back_populates='notification')
4877 notifications_to_users = relationship('UserNotification', lazy='joined', cascade="all, delete-orphan", back_populates='notification')
4883
4878
4884 @property
4879 @property
4885 def recipients(self):
4880 def recipients(self):
4886 return [x.user for x in UserNotification.query()\
4881 return [x.user for x in UserNotification.query()\
4887 .filter(UserNotification.notification == self)\
4882 .filter(UserNotification.notification == self)\
4888 .order_by(UserNotification.user_id.asc()).all()]
4883 .order_by(UserNotification.user_id.asc()).all()]
4889
4884
4890 @classmethod
4885 @classmethod
4891 def create(cls, created_by, subject, body, recipients, type_=None):
4886 def create(cls, created_by, subject, body, recipients, type_=None):
4892 if type_ is None:
4887 if type_ is None:
4893 type_ = Notification.TYPE_MESSAGE
4888 type_ = Notification.TYPE_MESSAGE
4894
4889
4895 notification = cls()
4890 notification = cls()
4896 notification.created_by_user = created_by
4891 notification.created_by_user = created_by
4897 notification.subject = subject
4892 notification.subject = subject
4898 notification.body = body
4893 notification.body = body
4899 notification.type_ = type_
4894 notification.type_ = type_
4900 notification.created_on = datetime.datetime.now()
4895 notification.created_on = datetime.datetime.now()
4901
4896
4902 # For each recipient link the created notification to his account
4897 # For each recipient link the created notification to his account
4903 for u in recipients:
4898 for u in recipients:
4904 assoc = UserNotification()
4899 assoc = UserNotification()
4905 assoc.user_id = u.user_id
4900 assoc.user_id = u.user_id
4906 assoc.notification = notification
4901 assoc.notification = notification
4907
4902
4908 # if created_by is inside recipients mark his notification
4903 # if created_by is inside recipients mark his notification
4909 # as read
4904 # as read
4910 if u.user_id == created_by.user_id:
4905 if u.user_id == created_by.user_id:
4911 assoc.read = True
4906 assoc.read = True
4912 Session().add(assoc)
4907 Session().add(assoc)
4913
4908
4914 Session().add(notification)
4909 Session().add(notification)
4915
4910
4916 return notification
4911 return notification
4917
4912
4918
4913
4919 class UserNotification(Base, BaseModel):
4914 class UserNotification(Base, BaseModel):
4920 __tablename__ = 'user_to_notification'
4915 __tablename__ = 'user_to_notification'
4921 __table_args__ = (
4916 __table_args__ = (
4922 UniqueConstraint('user_id', 'notification_id'),
4917 UniqueConstraint('user_id', 'notification_id'),
4923 base_table_args
4918 base_table_args
4924 )
4919 )
4925
4920
4926 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4921 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4927 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4922 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4928 read = Column('read', Boolean, default=False)
4923 read = Column('read', Boolean, default=False)
4929 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4924 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4930
4925
4931 user = relationship('User', lazy="joined", back_populates='notifications')
4926 user = relationship('User', lazy="joined", back_populates='notifications')
4932 notification = relationship('Notification', lazy="joined", order_by=lambda: Notification.created_on.desc(), back_populates='notifications_to_users')
4927 notification = relationship('Notification', lazy="joined", order_by=lambda: Notification.created_on.desc(), back_populates='notifications_to_users')
4933
4928
4934 def mark_as_read(self):
4929 def mark_as_read(self):
4935 self.read = True
4930 self.read = True
4936 Session().add(self)
4931 Session().add(self)
4937
4932
4938
4933
4939 class UserNotice(Base, BaseModel):
4934 class UserNotice(Base, BaseModel):
4940 __tablename__ = 'user_notices'
4935 __tablename__ = 'user_notices'
4941 __table_args__ = (
4936 __table_args__ = (
4942 base_table_args
4937 base_table_args
4943 )
4938 )
4944
4939
4945 NOTIFICATION_TYPE_MESSAGE = 'message'
4940 NOTIFICATION_TYPE_MESSAGE = 'message'
4946 NOTIFICATION_TYPE_NOTICE = 'notice'
4941 NOTIFICATION_TYPE_NOTICE = 'notice'
4947
4942
4948 NOTIFICATION_LEVEL_INFO = 'info'
4943 NOTIFICATION_LEVEL_INFO = 'info'
4949 NOTIFICATION_LEVEL_WARNING = 'warning'
4944 NOTIFICATION_LEVEL_WARNING = 'warning'
4950 NOTIFICATION_LEVEL_ERROR = 'error'
4945 NOTIFICATION_LEVEL_ERROR = 'error'
4951
4946
4952 user_notice_id = Column('gist_id', Integer(), primary_key=True)
4947 user_notice_id = Column('gist_id', Integer(), primary_key=True)
4953
4948
4954 notice_subject = Column('notice_subject', Unicode(512), nullable=True)
4949 notice_subject = Column('notice_subject', Unicode(512), nullable=True)
4955 notice_body = Column('notice_body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4950 notice_body = Column('notice_body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4956
4951
4957 notice_read = Column('notice_read', Boolean, default=False)
4952 notice_read = Column('notice_read', Boolean, default=False)
4958
4953
4959 notification_level = Column('notification_level', String(1024), default=NOTIFICATION_LEVEL_INFO)
4954 notification_level = Column('notification_level', String(1024), default=NOTIFICATION_LEVEL_INFO)
4960 notification_type = Column('notification_type', String(1024), default=NOTIFICATION_TYPE_NOTICE)
4955 notification_type = Column('notification_type', String(1024), default=NOTIFICATION_TYPE_NOTICE)
4961
4956
4962 notice_created_by = Column('notice_created_by', Integer(), ForeignKey('users.user_id'), nullable=True)
4957 notice_created_by = Column('notice_created_by', Integer(), ForeignKey('users.user_id'), nullable=True)
4963 notice_created_on = Column('notice_created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4958 notice_created_on = Column('notice_created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4964
4959
4965 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'))
4960 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'))
4966 user = relationship('User', lazy="joined", primaryjoin='User.user_id==UserNotice.user_id')
4961 user = relationship('User', lazy="joined", primaryjoin='User.user_id==UserNotice.user_id')
4967
4962
4968 @classmethod
4963 @classmethod
4969 def create_for_user(cls, user, subject, body, notice_level=NOTIFICATION_LEVEL_INFO, allow_duplicate=False):
4964 def create_for_user(cls, user, subject, body, notice_level=NOTIFICATION_LEVEL_INFO, allow_duplicate=False):
4970
4965
4971 if notice_level not in [cls.NOTIFICATION_LEVEL_ERROR,
4966 if notice_level not in [cls.NOTIFICATION_LEVEL_ERROR,
4972 cls.NOTIFICATION_LEVEL_WARNING,
4967 cls.NOTIFICATION_LEVEL_WARNING,
4973 cls.NOTIFICATION_LEVEL_INFO]:
4968 cls.NOTIFICATION_LEVEL_INFO]:
4974 return
4969 return
4975
4970
4976 from rhodecode.model.user import UserModel
4971 from rhodecode.model.user import UserModel
4977 user = UserModel().get_user(user)
4972 user = UserModel().get_user(user)
4978
4973
4979 new_notice = UserNotice()
4974 new_notice = UserNotice()
4980 if not allow_duplicate:
4975 if not allow_duplicate:
4981 existing_msg = UserNotice().query() \
4976 existing_msg = UserNotice().query() \
4982 .filter(UserNotice.user == user) \
4977 .filter(UserNotice.user == user) \
4983 .filter(UserNotice.notice_body == body) \
4978 .filter(UserNotice.notice_body == body) \
4984 .filter(UserNotice.notice_read == false()) \
4979 .filter(UserNotice.notice_read == false()) \
4985 .scalar()
4980 .scalar()
4986 if existing_msg:
4981 if existing_msg:
4987 log.warning('Ignoring duplicate notice for user %s', user)
4982 log.warning('Ignoring duplicate notice for user %s', user)
4988 return
4983 return
4989
4984
4990 new_notice.user = user
4985 new_notice.user = user
4991 new_notice.notice_subject = subject
4986 new_notice.notice_subject = subject
4992 new_notice.notice_body = body
4987 new_notice.notice_body = body
4993 new_notice.notification_level = notice_level
4988 new_notice.notification_level = notice_level
4994 Session().add(new_notice)
4989 Session().add(new_notice)
4995 Session().commit()
4990 Session().commit()
4996
4991
4997
4992
4998 class Gist(Base, BaseModel):
4993 class Gist(Base, BaseModel):
4999 __tablename__ = 'gists'
4994 __tablename__ = 'gists'
5000 __table_args__ = (
4995 __table_args__ = (
5001 Index('g_gist_access_id_idx', 'gist_access_id'),
4996 Index('g_gist_access_id_idx', 'gist_access_id'),
5002 Index('g_created_on_idx', 'created_on'),
4997 Index('g_created_on_idx', 'created_on'),
5003 base_table_args
4998 base_table_args
5004 )
4999 )
5005
5000
5006 GIST_PUBLIC = 'public'
5001 GIST_PUBLIC = 'public'
5007 GIST_PRIVATE = 'private'
5002 GIST_PRIVATE = 'private'
5008 DEFAULT_FILENAME = 'gistfile1.txt'
5003 DEFAULT_FILENAME = 'gistfile1.txt'
5009
5004
5010 ACL_LEVEL_PUBLIC = 'acl_public'
5005 ACL_LEVEL_PUBLIC = 'acl_public'
5011 ACL_LEVEL_PRIVATE = 'acl_private'
5006 ACL_LEVEL_PRIVATE = 'acl_private'
5012
5007
5013 gist_id = Column('gist_id', Integer(), primary_key=True)
5008 gist_id = Column('gist_id', Integer(), primary_key=True)
5014 gist_access_id = Column('gist_access_id', Unicode(250))
5009 gist_access_id = Column('gist_access_id', Unicode(250))
5015 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
5010 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
5016 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
5011 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
5017 gist_expires = Column('gist_expires', Float(53), nullable=False)
5012 gist_expires = Column('gist_expires', Float(53), nullable=False)
5018 gist_type = Column('gist_type', Unicode(128), nullable=False)
5013 gist_type = Column('gist_type', Unicode(128), nullable=False)
5019 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5014 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5020 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5015 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5021 acl_level = Column('acl_level', Unicode(128), nullable=True)
5016 acl_level = Column('acl_level', Unicode(128), nullable=True)
5022
5017
5023 owner = relationship('User', back_populates='user_gists')
5018 owner = relationship('User', back_populates='user_gists')
5024
5019
5025 def __repr__(self):
5020 def __repr__(self):
5026 return f'<Gist:[{self.gist_type}]{self.gist_access_id}>'
5021 return f'<Gist:[{self.gist_type}]{self.gist_access_id}>'
5027
5022
5028 @hybrid_property
5023 @hybrid_property
5029 def description_safe(self):
5024 def description_safe(self):
5030 from rhodecode.lib import helpers as h
5025 from rhodecode.lib import helpers as h
5031 return h.escape(self.gist_description)
5026 return h.escape(self.gist_description)
5032
5027
5033 @classmethod
5028 @classmethod
5034 def get_or_404(cls, id_):
5029 def get_or_404(cls, id_):
5035 from pyramid.httpexceptions import HTTPNotFound
5030 from pyramid.httpexceptions import HTTPNotFound
5036
5031
5037 res = cls.query().filter(cls.gist_access_id == id_).scalar()
5032 res = cls.query().filter(cls.gist_access_id == id_).scalar()
5038 if not res:
5033 if not res:
5039 log.debug('WARN: No DB entry with id %s', id_)
5034 log.debug('WARN: No DB entry with id %s', id_)
5040 raise HTTPNotFound()
5035 raise HTTPNotFound()
5041 return res
5036 return res
5042
5037
5043 @classmethod
5038 @classmethod
5044 def get_by_access_id(cls, gist_access_id):
5039 def get_by_access_id(cls, gist_access_id):
5045 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
5040 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
5046
5041
5047 def gist_url(self):
5042 def gist_url(self):
5048 from rhodecode.model.gist import GistModel
5043 from rhodecode.model.gist import GistModel
5049 return GistModel().get_url(self)
5044 return GistModel().get_url(self)
5050
5045
5051 @classmethod
5046 @classmethod
5052 def base_path(cls):
5047 def base_path(cls):
5053 """
5048 """
5054 Returns base path when all gists are stored
5049 Returns base path when all gists are stored
5055
5050
5056 :param cls:
5051 :param cls:
5057 """
5052 """
5058 from rhodecode.model.gist import GIST_STORE_LOC
5053 from rhodecode.model.gist import GIST_STORE_LOC
5059 from rhodecode.lib.utils import get_rhodecode_repo_store_path
5054 from rhodecode.lib.utils import get_rhodecode_repo_store_path
5060 repo_store_path = get_rhodecode_repo_store_path()
5055 repo_store_path = get_rhodecode_repo_store_path()
5061 return os.path.join(repo_store_path, GIST_STORE_LOC)
5056 return os.path.join(repo_store_path, GIST_STORE_LOC)
5062
5057
5063 def get_api_data(self):
5058 def get_api_data(self):
5064 """
5059 """
5065 Common function for generating gist related data for API
5060 Common function for generating gist related data for API
5066 """
5061 """
5067 gist = self
5062 gist = self
5068 data = {
5063 data = {
5069 'gist_id': gist.gist_id,
5064 'gist_id': gist.gist_id,
5070 'type': gist.gist_type,
5065 'type': gist.gist_type,
5071 'access_id': gist.gist_access_id,
5066 'access_id': gist.gist_access_id,
5072 'description': gist.gist_description,
5067 'description': gist.gist_description,
5073 'url': gist.gist_url(),
5068 'url': gist.gist_url(),
5074 'expires': gist.gist_expires,
5069 'expires': gist.gist_expires,
5075 'created_on': gist.created_on,
5070 'created_on': gist.created_on,
5076 'modified_at': gist.modified_at,
5071 'modified_at': gist.modified_at,
5077 'content': None,
5072 'content': None,
5078 'acl_level': gist.acl_level,
5073 'acl_level': gist.acl_level,
5079 }
5074 }
5080 return data
5075 return data
5081
5076
5082 def __json__(self):
5077 def __json__(self):
5083 data = dict()
5078 data = dict()
5084 data.update(self.get_api_data())
5079 data.update(self.get_api_data())
5085 return data
5080 return data
5086 # SCM functions
5081 # SCM functions
5087
5082
5088 def scm_instance(self, **kwargs):
5083 def scm_instance(self, **kwargs):
5089 """
5084 """
5090 Get an instance of VCS Repository
5085 Get an instance of VCS Repository
5091
5086
5092 :param kwargs:
5087 :param kwargs:
5093 """
5088 """
5094 from rhodecode.model.gist import GistModel
5089 from rhodecode.model.gist import GistModel
5095 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
5090 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
5096 return get_vcs_instance(
5091 return get_vcs_instance(
5097 repo_path=safe_str(full_repo_path), create=False,
5092 repo_path=safe_str(full_repo_path), create=False,
5098 _vcs_alias=GistModel.vcs_backend)
5093 _vcs_alias=GistModel.vcs_backend)
5099
5094
5100
5095
5101 class ExternalIdentity(Base, BaseModel):
5096 class ExternalIdentity(Base, BaseModel):
5102 __tablename__ = 'external_identities'
5097 __tablename__ = 'external_identities'
5103 __table_args__ = (
5098 __table_args__ = (
5104 Index('local_user_id_idx', 'local_user_id'),
5099 Index('local_user_id_idx', 'local_user_id'),
5105 Index('external_id_idx', 'external_id'),
5100 Index('external_id_idx', 'external_id'),
5106 base_table_args
5101 base_table_args
5107 )
5102 )
5108
5103
5109 external_id = Column('external_id', Unicode(255), default='', primary_key=True)
5104 external_id = Column('external_id', Unicode(255), default='', primary_key=True)
5110 external_username = Column('external_username', Unicode(1024), default='')
5105 external_username = Column('external_username', Unicode(1024), default='')
5111 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
5106 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
5112 provider_name = Column('provider_name', Unicode(255), default='', primary_key=True)
5107 provider_name = Column('provider_name', Unicode(255), default='', primary_key=True)
5113 access_token = Column('access_token', String(1024), default='')
5108 access_token = Column('access_token', String(1024), default='')
5114 alt_token = Column('alt_token', String(1024), default='')
5109 alt_token = Column('alt_token', String(1024), default='')
5115 token_secret = Column('token_secret', String(1024), default='')
5110 token_secret = Column('token_secret', String(1024), default='')
5116
5111
5117 @classmethod
5112 @classmethod
5118 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
5113 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
5119 """
5114 """
5120 Returns ExternalIdentity instance based on search params
5115 Returns ExternalIdentity instance based on search params
5121
5116
5122 :param external_id:
5117 :param external_id:
5123 :param provider_name:
5118 :param provider_name:
5124 :return: ExternalIdentity
5119 :return: ExternalIdentity
5125 """
5120 """
5126 query = cls.query()
5121 query = cls.query()
5127 query = query.filter(cls.external_id == external_id)
5122 query = query.filter(cls.external_id == external_id)
5128 query = query.filter(cls.provider_name == provider_name)
5123 query = query.filter(cls.provider_name == provider_name)
5129 if local_user_id:
5124 if local_user_id:
5130 query = query.filter(cls.local_user_id == local_user_id)
5125 query = query.filter(cls.local_user_id == local_user_id)
5131 return query.first()
5126 return query.first()
5132
5127
5133 @classmethod
5128 @classmethod
5134 def user_by_external_id_and_provider(cls, external_id, provider_name):
5129 def user_by_external_id_and_provider(cls, external_id, provider_name):
5135 """
5130 """
5136 Returns User instance based on search params
5131 Returns User instance based on search params
5137
5132
5138 :param external_id:
5133 :param external_id:
5139 :param provider_name:
5134 :param provider_name:
5140 :return: User
5135 :return: User
5141 """
5136 """
5142 query = User.query()
5137 query = User.query()
5143 query = query.filter(cls.external_id == external_id)
5138 query = query.filter(cls.external_id == external_id)
5144 query = query.filter(cls.provider_name == provider_name)
5139 query = query.filter(cls.provider_name == provider_name)
5145 query = query.filter(User.user_id == cls.local_user_id)
5140 query = query.filter(User.user_id == cls.local_user_id)
5146 return query.first()
5141 return query.first()
5147
5142
5148 @classmethod
5143 @classmethod
5149 def by_local_user_id(cls, local_user_id):
5144 def by_local_user_id(cls, local_user_id):
5150 """
5145 """
5151 Returns all tokens for user
5146 Returns all tokens for user
5152
5147
5153 :param local_user_id:
5148 :param local_user_id:
5154 :return: ExternalIdentity
5149 :return: ExternalIdentity
5155 """
5150 """
5156 query = cls.query()
5151 query = cls.query()
5157 query = query.filter(cls.local_user_id == local_user_id)
5152 query = query.filter(cls.local_user_id == local_user_id)
5158 return query
5153 return query
5159
5154
5160 @classmethod
5155 @classmethod
5161 def load_provider_plugin(cls, plugin_id):
5156 def load_provider_plugin(cls, plugin_id):
5162 from rhodecode.authentication.base import loadplugin
5157 from rhodecode.authentication.base import loadplugin
5163 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
5158 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
5164 auth_plugin = loadplugin(_plugin_id)
5159 auth_plugin = loadplugin(_plugin_id)
5165 return auth_plugin
5160 return auth_plugin
5166
5161
5167
5162
5168 class Integration(Base, BaseModel):
5163 class Integration(Base, BaseModel):
5169 __tablename__ = 'integrations'
5164 __tablename__ = 'integrations'
5170 __table_args__ = (
5165 __table_args__ = (
5171 base_table_args
5166 base_table_args
5172 )
5167 )
5173
5168
5174 integration_id = Column('integration_id', Integer(), primary_key=True)
5169 integration_id = Column('integration_id', Integer(), primary_key=True)
5175 integration_type = Column('integration_type', String(255))
5170 integration_type = Column('integration_type', String(255))
5176 enabled = Column('enabled', Boolean(), nullable=False)
5171 enabled = Column('enabled', Boolean(), nullable=False)
5177 name = Column('name', String(255), nullable=False)
5172 name = Column('name', String(255), nullable=False)
5178 child_repos_only = Column('child_repos_only', Boolean(), nullable=False, default=False)
5173 child_repos_only = Column('child_repos_only', Boolean(), nullable=False, default=False)
5179
5174
5180 settings = Column(
5175 settings = Column(
5181 'settings_json', MutationObj.as_mutable(
5176 'settings_json', MutationObj.as_mutable(
5182 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
5177 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
5183 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
5178 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
5184 repo = relationship('Repository', lazy='joined', back_populates='integrations')
5179 repo = relationship('Repository', lazy='joined', back_populates='integrations')
5185
5180
5186 repo_group_id = Column('repo_group_id', Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
5181 repo_group_id = Column('repo_group_id', Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
5187 repo_group = relationship('RepoGroup', lazy='joined', back_populates='integrations')
5182 repo_group = relationship('RepoGroup', lazy='joined', back_populates='integrations')
5188
5183
5189 @property
5184 @property
5190 def scope(self):
5185 def scope(self):
5191 if self.repo:
5186 if self.repo:
5192 return repr(self.repo)
5187 return repr(self.repo)
5193 if self.repo_group:
5188 if self.repo_group:
5194 if self.child_repos_only:
5189 if self.child_repos_only:
5195 return repr(self.repo_group) + ' (child repos only)'
5190 return repr(self.repo_group) + ' (child repos only)'
5196 else:
5191 else:
5197 return repr(self.repo_group) + ' (recursive)'
5192 return repr(self.repo_group) + ' (recursive)'
5198 if self.child_repos_only:
5193 if self.child_repos_only:
5199 return 'root_repos'
5194 return 'root_repos'
5200 return 'global'
5195 return 'global'
5201
5196
5202 def __repr__(self):
5197 def __repr__(self):
5203 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
5198 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
5204
5199
5205
5200
5206 class RepoReviewRuleUser(Base, BaseModel):
5201 class RepoReviewRuleUser(Base, BaseModel):
5207 __tablename__ = 'repo_review_rules_users'
5202 __tablename__ = 'repo_review_rules_users'
5208 __table_args__ = (
5203 __table_args__ = (
5209 base_table_args
5204 base_table_args
5210 )
5205 )
5211 ROLE_REVIEWER = 'reviewer'
5206 ROLE_REVIEWER = 'reviewer'
5212 ROLE_OBSERVER = 'observer'
5207 ROLE_OBSERVER = 'observer'
5213 ROLES = [ROLE_REVIEWER, ROLE_OBSERVER]
5208 ROLES = [ROLE_REVIEWER, ROLE_OBSERVER]
5214
5209
5215 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
5210 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
5216 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
5211 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
5217 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
5212 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
5218 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
5213 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
5219 role = Column('role', Unicode(255), nullable=True, default=ROLE_REVIEWER)
5214 role = Column('role', Unicode(255), nullable=True, default=ROLE_REVIEWER)
5220 user = relationship('User', back_populates='user_review_rules')
5215 user = relationship('User', back_populates='user_review_rules')
5221
5216
5222 def rule_data(self):
5217 def rule_data(self):
5223 return {
5218 return {
5224 'mandatory': self.mandatory,
5219 'mandatory': self.mandatory,
5225 'role': self.role,
5220 'role': self.role,
5226 }
5221 }
5227
5222
5228
5223
5229 class RepoReviewRuleUserGroup(Base, BaseModel):
5224 class RepoReviewRuleUserGroup(Base, BaseModel):
5230 __tablename__ = 'repo_review_rules_users_groups'
5225 __tablename__ = 'repo_review_rules_users_groups'
5231 __table_args__ = (
5226 __table_args__ = (
5232 base_table_args
5227 base_table_args
5233 )
5228 )
5234
5229
5235 VOTE_RULE_ALL = -1
5230 VOTE_RULE_ALL = -1
5236 ROLE_REVIEWER = 'reviewer'
5231 ROLE_REVIEWER = 'reviewer'
5237 ROLE_OBSERVER = 'observer'
5232 ROLE_OBSERVER = 'observer'
5238 ROLES = [ROLE_REVIEWER, ROLE_OBSERVER]
5233 ROLES = [ROLE_REVIEWER, ROLE_OBSERVER]
5239
5234
5240 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
5235 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
5241 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
5236 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
5242 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False)
5237 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False)
5243 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
5238 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
5244 role = Column('role', Unicode(255), nullable=True, default=ROLE_REVIEWER)
5239 role = Column('role', Unicode(255), nullable=True, default=ROLE_REVIEWER)
5245 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
5240 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
5246 users_group = relationship('UserGroup')
5241 users_group = relationship('UserGroup')
5247
5242
5248 def rule_data(self):
5243 def rule_data(self):
5249 return {
5244 return {
5250 'mandatory': self.mandatory,
5245 'mandatory': self.mandatory,
5251 'role': self.role,
5246 'role': self.role,
5252 'vote_rule': self.vote_rule
5247 'vote_rule': self.vote_rule
5253 }
5248 }
5254
5249
5255 @property
5250 @property
5256 def vote_rule_label(self):
5251 def vote_rule_label(self):
5257 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
5252 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
5258 return 'all must vote'
5253 return 'all must vote'
5259 else:
5254 else:
5260 return 'min. vote {}'.format(self.vote_rule)
5255 return 'min. vote {}'.format(self.vote_rule)
5261
5256
5262
5257
5263 class RepoReviewRule(Base, BaseModel):
5258 class RepoReviewRule(Base, BaseModel):
5264 __tablename__ = 'repo_review_rules'
5259 __tablename__ = 'repo_review_rules'
5265 __table_args__ = (
5260 __table_args__ = (
5266 base_table_args
5261 base_table_args
5267 )
5262 )
5268
5263
5269 repo_review_rule_id = Column(
5264 repo_review_rule_id = Column(
5270 'repo_review_rule_id', Integer(), primary_key=True)
5265 'repo_review_rule_id', Integer(), primary_key=True)
5271 repo_id = Column(
5266 repo_id = Column(
5272 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
5267 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
5273 repo = relationship('Repository', back_populates='review_rules')
5268 repo = relationship('Repository', back_populates='review_rules')
5274
5269
5275 review_rule_name = Column('review_rule_name', String(255))
5270 review_rule_name = Column('review_rule_name', String(255))
5276 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default='*') # glob
5271 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default='*') # glob
5277 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default='*') # glob
5272 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default='*') # glob
5278 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default='*') # glob
5273 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default='*') # glob
5279
5274
5280 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
5275 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
5281
5276
5282 # Legacy fields, just for backward compat
5277 # Legacy fields, just for backward compat
5283 _forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
5278 _forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
5284 _forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
5279 _forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
5285
5280
5286 pr_author = Column("pr_author", UnicodeText().with_variant(UnicodeText(255), 'mysql'), nullable=True)
5281 pr_author = Column("pr_author", UnicodeText().with_variant(UnicodeText(255), 'mysql'), nullable=True)
5287 commit_author = Column("commit_author", UnicodeText().with_variant(UnicodeText(255), 'mysql'), nullable=True)
5282 commit_author = Column("commit_author", UnicodeText().with_variant(UnicodeText(255), 'mysql'), nullable=True)
5288
5283
5289 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
5284 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
5290
5285
5291 rule_users = relationship('RepoReviewRuleUser')
5286 rule_users = relationship('RepoReviewRuleUser')
5292 rule_user_groups = relationship('RepoReviewRuleUserGroup')
5287 rule_user_groups = relationship('RepoReviewRuleUserGroup')
5293
5288
5294 def _validate_pattern(self, value):
5289 def _validate_pattern(self, value):
5295 re.compile('^' + glob2re(value) + '$')
5290 re.compile('^' + glob2re(value) + '$')
5296
5291
5297 @hybrid_property
5292 @hybrid_property
5298 def source_branch_pattern(self):
5293 def source_branch_pattern(self):
5299 return self._branch_pattern or '*'
5294 return self._branch_pattern or '*'
5300
5295
5301 @source_branch_pattern.setter
5296 @source_branch_pattern.setter
5302 def source_branch_pattern(self, value):
5297 def source_branch_pattern(self, value):
5303 self._validate_pattern(value)
5298 self._validate_pattern(value)
5304 self._branch_pattern = value or '*'
5299 self._branch_pattern = value or '*'
5305
5300
5306 @hybrid_property
5301 @hybrid_property
5307 def target_branch_pattern(self):
5302 def target_branch_pattern(self):
5308 return self._target_branch_pattern or '*'
5303 return self._target_branch_pattern or '*'
5309
5304
5310 @target_branch_pattern.setter
5305 @target_branch_pattern.setter
5311 def target_branch_pattern(self, value):
5306 def target_branch_pattern(self, value):
5312 self._validate_pattern(value)
5307 self._validate_pattern(value)
5313 self._target_branch_pattern = value or '*'
5308 self._target_branch_pattern = value or '*'
5314
5309
5315 @hybrid_property
5310 @hybrid_property
5316 def file_pattern(self):
5311 def file_pattern(self):
5317 return self._file_pattern or '*'
5312 return self._file_pattern or '*'
5318
5313
5319 @file_pattern.setter
5314 @file_pattern.setter
5320 def file_pattern(self, value):
5315 def file_pattern(self, value):
5321 self._validate_pattern(value)
5316 self._validate_pattern(value)
5322 self._file_pattern = value or '*'
5317 self._file_pattern = value or '*'
5323
5318
5324 @hybrid_property
5319 @hybrid_property
5325 def forbid_pr_author_to_review(self):
5320 def forbid_pr_author_to_review(self):
5326 return self.pr_author == 'forbid_pr_author'
5321 return self.pr_author == 'forbid_pr_author'
5327
5322
5328 @hybrid_property
5323 @hybrid_property
5329 def include_pr_author_to_review(self):
5324 def include_pr_author_to_review(self):
5330 return self.pr_author == 'include_pr_author'
5325 return self.pr_author == 'include_pr_author'
5331
5326
5332 @hybrid_property
5327 @hybrid_property
5333 def forbid_commit_author_to_review(self):
5328 def forbid_commit_author_to_review(self):
5334 return self.commit_author == 'forbid_commit_author'
5329 return self.commit_author == 'forbid_commit_author'
5335
5330
5336 @hybrid_property
5331 @hybrid_property
5337 def include_commit_author_to_review(self):
5332 def include_commit_author_to_review(self):
5338 return self.commit_author == 'include_commit_author'
5333 return self.commit_author == 'include_commit_author'
5339
5334
5340 def matches(self, source_branch, target_branch, files_changed):
5335 def matches(self, source_branch, target_branch, files_changed):
5341 """
5336 """
5342 Check if this review rule matches a branch/files in a pull request
5337 Check if this review rule matches a branch/files in a pull request
5343
5338
5344 :param source_branch: source branch name for the commit
5339 :param source_branch: source branch name for the commit
5345 :param target_branch: target branch name for the commit
5340 :param target_branch: target branch name for the commit
5346 :param files_changed: list of file paths changed in the pull request
5341 :param files_changed: list of file paths changed in the pull request
5347 """
5342 """
5348
5343
5349 source_branch = source_branch or ''
5344 source_branch = source_branch or ''
5350 target_branch = target_branch or ''
5345 target_branch = target_branch or ''
5351 files_changed = files_changed or []
5346 files_changed = files_changed or []
5352
5347
5353 branch_matches = True
5348 branch_matches = True
5354 if source_branch or target_branch:
5349 if source_branch or target_branch:
5355 if self.source_branch_pattern == '*':
5350 if self.source_branch_pattern == '*':
5356 source_branch_match = True
5351 source_branch_match = True
5357 else:
5352 else:
5358 if self.source_branch_pattern.startswith('re:'):
5353 if self.source_branch_pattern.startswith('re:'):
5359 source_pattern = self.source_branch_pattern[3:]
5354 source_pattern = self.source_branch_pattern[3:]
5360 else:
5355 else:
5361 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
5356 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
5362 source_branch_regex = re.compile(source_pattern)
5357 source_branch_regex = re.compile(source_pattern)
5363 source_branch_match = bool(source_branch_regex.search(source_branch))
5358 source_branch_match = bool(source_branch_regex.search(source_branch))
5364 if self.target_branch_pattern == '*':
5359 if self.target_branch_pattern == '*':
5365 target_branch_match = True
5360 target_branch_match = True
5366 else:
5361 else:
5367 if self.target_branch_pattern.startswith('re:'):
5362 if self.target_branch_pattern.startswith('re:'):
5368 target_pattern = self.target_branch_pattern[3:]
5363 target_pattern = self.target_branch_pattern[3:]
5369 else:
5364 else:
5370 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
5365 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
5371 target_branch_regex = re.compile(target_pattern)
5366 target_branch_regex = re.compile(target_pattern)
5372 target_branch_match = bool(target_branch_regex.search(target_branch))
5367 target_branch_match = bool(target_branch_regex.search(target_branch))
5373
5368
5374 branch_matches = source_branch_match and target_branch_match
5369 branch_matches = source_branch_match and target_branch_match
5375
5370
5376 files_matches = True
5371 files_matches = True
5377 if self.file_pattern != '*':
5372 if self.file_pattern != '*':
5378 files_matches = False
5373 files_matches = False
5379 if self.file_pattern.startswith('re:'):
5374 if self.file_pattern.startswith('re:'):
5380 file_pattern = self.file_pattern[3:]
5375 file_pattern = self.file_pattern[3:]
5381 else:
5376 else:
5382 file_pattern = glob2re(self.file_pattern)
5377 file_pattern = glob2re(self.file_pattern)
5383 file_regex = re.compile(file_pattern)
5378 file_regex = re.compile(file_pattern)
5384 for file_data in files_changed:
5379 for file_data in files_changed:
5385 filename = file_data.get('filename')
5380 filename = file_data.get('filename')
5386
5381
5387 if file_regex.search(filename):
5382 if file_regex.search(filename):
5388 files_matches = True
5383 files_matches = True
5389 break
5384 break
5390
5385
5391 return branch_matches and files_matches
5386 return branch_matches and files_matches
5392
5387
5393 @property
5388 @property
5394 def review_users(self):
5389 def review_users(self):
5395 """ Returns the users which this rule applies to """
5390 """ Returns the users which this rule applies to """
5396
5391
5397 users = collections.OrderedDict()
5392 users = collections.OrderedDict()
5398
5393
5399 for rule_user in self.rule_users:
5394 for rule_user in self.rule_users:
5400 if rule_user.user.active:
5395 if rule_user.user.active:
5401 if rule_user.user not in users:
5396 if rule_user.user not in users:
5402 users[rule_user.user.username] = {
5397 users[rule_user.user.username] = {
5403 'user': rule_user.user,
5398 'user': rule_user.user,
5404 'source': 'user',
5399 'source': 'user',
5405 'source_data': {},
5400 'source_data': {},
5406 'data': rule_user.rule_data()
5401 'data': rule_user.rule_data()
5407 }
5402 }
5408
5403
5409 for rule_user_group in self.rule_user_groups:
5404 for rule_user_group in self.rule_user_groups:
5410 source_data = {
5405 source_data = {
5411 'user_group_id': rule_user_group.users_group.users_group_id,
5406 'user_group_id': rule_user_group.users_group.users_group_id,
5412 'name': rule_user_group.users_group.users_group_name,
5407 'name': rule_user_group.users_group.users_group_name,
5413 'members': len(rule_user_group.users_group.members)
5408 'members': len(rule_user_group.users_group.members)
5414 }
5409 }
5415 for member in rule_user_group.users_group.members:
5410 for member in rule_user_group.users_group.members:
5416 if member.user.active:
5411 if member.user.active:
5417 key = member.user.username
5412 key = member.user.username
5418 if key in users:
5413 if key in users:
5419 # skip this member as we have him already
5414 # skip this member as we have him already
5420 # this prevents from override the "first" matched
5415 # this prevents from override the "first" matched
5421 # users with duplicates in multiple groups
5416 # users with duplicates in multiple groups
5422 continue
5417 continue
5423
5418
5424 users[key] = {
5419 users[key] = {
5425 'user': member.user,
5420 'user': member.user,
5426 'source': 'user_group',
5421 'source': 'user_group',
5427 'source_data': source_data,
5422 'source_data': source_data,
5428 'data': rule_user_group.rule_data()
5423 'data': rule_user_group.rule_data()
5429 }
5424 }
5430
5425
5431 return users
5426 return users
5432
5427
5433 def user_group_vote_rule(self, user_id):
5428 def user_group_vote_rule(self, user_id):
5434
5429
5435 rules = []
5430 rules = []
5436 if not self.rule_user_groups:
5431 if not self.rule_user_groups:
5437 return rules
5432 return rules
5438
5433
5439 for user_group in self.rule_user_groups:
5434 for user_group in self.rule_user_groups:
5440 user_group_members = [x.user_id for x in user_group.users_group.members]
5435 user_group_members = [x.user_id for x in user_group.users_group.members]
5441 if user_id in user_group_members:
5436 if user_id in user_group_members:
5442 rules.append(user_group)
5437 rules.append(user_group)
5443 return rules
5438 return rules
5444
5439
5445 def __repr__(self):
5440 def __repr__(self):
5446 return f'<RepoReviewerRule(id={self.repo_review_rule_id}, repo={self.repo!r})>'
5441 return f'<RepoReviewerRule(id={self.repo_review_rule_id}, repo={self.repo!r})>'
5447
5442
5448
5443
5449 class ScheduleEntry(Base, BaseModel):
5444 class ScheduleEntry(Base, BaseModel):
5450 __tablename__ = 'schedule_entries'
5445 __tablename__ = 'schedule_entries'
5451 __table_args__ = (
5446 __table_args__ = (
5452 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
5447 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
5453 UniqueConstraint('task_uid', name='s_task_uid_idx'),
5448 UniqueConstraint('task_uid', name='s_task_uid_idx'),
5454 base_table_args,
5449 base_table_args,
5455 )
5450 )
5456 SCHEDULE_TYPE_INTEGER = "integer"
5451 SCHEDULE_TYPE_INTEGER = "integer"
5457 SCHEDULE_TYPE_CRONTAB = "crontab"
5452 SCHEDULE_TYPE_CRONTAB = "crontab"
5458
5453
5459 schedule_types = [SCHEDULE_TYPE_CRONTAB, SCHEDULE_TYPE_INTEGER]
5454 schedule_types = [SCHEDULE_TYPE_CRONTAB, SCHEDULE_TYPE_INTEGER]
5460 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
5455 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
5461
5456
5462 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
5457 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
5463 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
5458 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
5464 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
5459 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
5465
5460
5466 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
5461 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
5467 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
5462 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
5468
5463
5469 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
5464 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
5470 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
5465 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
5471
5466
5472 # task
5467 # task
5473 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
5468 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
5474 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
5469 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
5475 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
5470 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
5476 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
5471 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
5477
5472
5478 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5473 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5479 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
5474 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
5480
5475
5481 @hybrid_property
5476 @hybrid_property
5482 def schedule_type(self):
5477 def schedule_type(self):
5483 return self._schedule_type
5478 return self._schedule_type
5484
5479
5485 @schedule_type.setter
5480 @schedule_type.setter
5486 def schedule_type(self, val):
5481 def schedule_type(self, val):
5487 if val not in self.schedule_types:
5482 if val not in self.schedule_types:
5488 raise ValueError('Value must be on of `{}` and got `{}`'.format(
5483 raise ValueError('Value must be on of `{}` and got `{}`'.format(
5489 val, self.schedule_type))
5484 val, self.schedule_type))
5490
5485
5491 self._schedule_type = val
5486 self._schedule_type = val
5492
5487
5493 @classmethod
5488 @classmethod
5494 def get_uid(cls, obj):
5489 def get_uid(cls, obj):
5495 args = obj.task_args
5490 args = obj.task_args
5496 kwargs = obj.task_kwargs
5491 kwargs = obj.task_kwargs
5497 if isinstance(args, JsonRaw):
5492 if isinstance(args, JsonRaw):
5498 try:
5493 try:
5499 args = json.loads(args)
5494 args = json.loads(args)
5500 except ValueError:
5495 except ValueError:
5501 args = tuple()
5496 args = tuple()
5502
5497
5503 if isinstance(kwargs, JsonRaw):
5498 if isinstance(kwargs, JsonRaw):
5504 try:
5499 try:
5505 kwargs = json.loads(kwargs)
5500 kwargs = json.loads(kwargs)
5506 except ValueError:
5501 except ValueError:
5507 kwargs = dict()
5502 kwargs = dict()
5508
5503
5509 dot_notation = obj.task_dot_notation
5504 dot_notation = obj.task_dot_notation
5510 val = '.'.join(map(safe_str, [
5505 val = '.'.join(map(safe_str, [
5511 sorted(dot_notation), args, sorted(kwargs.items())]))
5506 sorted(dot_notation), args, sorted(kwargs.items())]))
5512 return sha1(safe_bytes(val))
5507 return sha1(safe_bytes(val))
5513
5508
5514 @classmethod
5509 @classmethod
5515 def get_by_schedule_name(cls, schedule_name):
5510 def get_by_schedule_name(cls, schedule_name):
5516 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
5511 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
5517
5512
5518 @classmethod
5513 @classmethod
5519 def get_by_schedule_id(cls, schedule_id):
5514 def get_by_schedule_id(cls, schedule_id):
5520 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
5515 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
5521
5516
5522 @property
5517 @property
5523 def task(self):
5518 def task(self):
5524 return self.task_dot_notation
5519 return self.task_dot_notation
5525
5520
5526 @property
5521 @property
5527 def schedule(self):
5522 def schedule(self):
5528 from rhodecode.lib.celerylib.utils import raw_2_schedule
5523 from rhodecode.lib.celerylib.utils import raw_2_schedule
5529 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
5524 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
5530 return schedule
5525 return schedule
5531
5526
5532 @property
5527 @property
5533 def args(self):
5528 def args(self):
5534 try:
5529 try:
5535 return list(self.task_args or [])
5530 return list(self.task_args or [])
5536 except ValueError:
5531 except ValueError:
5537 return list()
5532 return list()
5538
5533
5539 @property
5534 @property
5540 def kwargs(self):
5535 def kwargs(self):
5541 try:
5536 try:
5542 return dict(self.task_kwargs or {})
5537 return dict(self.task_kwargs or {})
5543 except ValueError:
5538 except ValueError:
5544 return dict()
5539 return dict()
5545
5540
5546 def _as_raw(self, val, indent=False):
5541 def _as_raw(self, val, indent=False):
5547 if hasattr(val, 'de_coerce'):
5542 if hasattr(val, 'de_coerce'):
5548 val = val.de_coerce()
5543 val = val.de_coerce()
5549 if val:
5544 if val:
5550 if indent:
5545 if indent:
5551 val = ext_json.formatted_str_json(val)
5546 val = ext_json.formatted_str_json(val)
5552 else:
5547 else:
5553 val = ext_json.str_json(val)
5548 val = ext_json.str_json(val)
5554
5549
5555 return val
5550 return val
5556
5551
5557 @property
5552 @property
5558 def schedule_definition_raw(self):
5553 def schedule_definition_raw(self):
5559 return self._as_raw(self.schedule_definition)
5554 return self._as_raw(self.schedule_definition)
5560
5555
5561 def args_raw(self, indent=False):
5556 def args_raw(self, indent=False):
5562 return self._as_raw(self.task_args, indent)
5557 return self._as_raw(self.task_args, indent)
5563
5558
5564 def kwargs_raw(self, indent=False):
5559 def kwargs_raw(self, indent=False):
5565 return self._as_raw(self.task_kwargs, indent)
5560 return self._as_raw(self.task_kwargs, indent)
5566
5561
5567 def __repr__(self):
5562 def __repr__(self):
5568 return f'<DB:ScheduleEntry({self.schedule_entry_id}:{self.schedule_name})>'
5563 return f'<DB:ScheduleEntry({self.schedule_entry_id}:{self.schedule_name})>'
5569
5564
5570
5565
5571 @event.listens_for(ScheduleEntry, 'before_update')
5566 @event.listens_for(ScheduleEntry, 'before_update')
5572 def update_task_uid(mapper, connection, target):
5567 def update_task_uid(mapper, connection, target):
5573 target.task_uid = ScheduleEntry.get_uid(target)
5568 target.task_uid = ScheduleEntry.get_uid(target)
5574
5569
5575
5570
5576 @event.listens_for(ScheduleEntry, 'before_insert')
5571 @event.listens_for(ScheduleEntry, 'before_insert')
5577 def set_task_uid(mapper, connection, target):
5572 def set_task_uid(mapper, connection, target):
5578 target.task_uid = ScheduleEntry.get_uid(target)
5573 target.task_uid = ScheduleEntry.get_uid(target)
5579
5574
5580
5575
5581 class _BaseBranchPerms(BaseModel):
5576 class _BaseBranchPerms(BaseModel):
5582 @classmethod
5577 @classmethod
5583 def compute_hash(cls, value):
5578 def compute_hash(cls, value):
5584 return sha1_safe(value)
5579 return sha1_safe(value)
5585
5580
5586 @hybrid_property
5581 @hybrid_property
5587 def branch_pattern(self):
5582 def branch_pattern(self):
5588 return self._branch_pattern or '*'
5583 return self._branch_pattern or '*'
5589
5584
5590 @hybrid_property
5585 @hybrid_property
5591 def branch_hash(self):
5586 def branch_hash(self):
5592 return self._branch_hash
5587 return self._branch_hash
5593
5588
5594 def _validate_glob(self, value):
5589 def _validate_glob(self, value):
5595 re.compile('^' + glob2re(value) + '$')
5590 re.compile('^' + glob2re(value) + '$')
5596
5591
5597 @branch_pattern.setter
5592 @branch_pattern.setter
5598 def branch_pattern(self, value):
5593 def branch_pattern(self, value):
5599 self._validate_glob(value)
5594 self._validate_glob(value)
5600 self._branch_pattern = value or '*'
5595 self._branch_pattern = value or '*'
5601 # set the Hash when setting the branch pattern
5596 # set the Hash when setting the branch pattern
5602 self._branch_hash = self.compute_hash(self._branch_pattern)
5597 self._branch_hash = self.compute_hash(self._branch_pattern)
5603
5598
5604 def matches(self, branch):
5599 def matches(self, branch):
5605 """
5600 """
5606 Check if this the branch matches entry
5601 Check if this the branch matches entry
5607
5602
5608 :param branch: branch name for the commit
5603 :param branch: branch name for the commit
5609 """
5604 """
5610
5605
5611 branch = branch or ''
5606 branch = branch or ''
5612
5607
5613 branch_matches = True
5608 branch_matches = True
5614 if branch:
5609 if branch:
5615 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
5610 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
5616 branch_matches = bool(branch_regex.search(branch))
5611 branch_matches = bool(branch_regex.search(branch))
5617
5612
5618 return branch_matches
5613 return branch_matches
5619
5614
5620
5615
5621 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
5616 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
5622 __tablename__ = 'user_to_repo_branch_permissions'
5617 __tablename__ = 'user_to_repo_branch_permissions'
5623 __table_args__ = (
5618 __table_args__ = (
5624 base_table_args
5619 base_table_args
5625 )
5620 )
5626
5621
5627 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5622 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5628
5623
5629 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5624 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5630 repo = relationship('Repository', back_populates='user_branch_perms')
5625 repo = relationship('Repository', back_populates='user_branch_perms')
5631
5626
5632 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5627 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5633 permission = relationship('Permission')
5628 permission = relationship('Permission')
5634
5629
5635 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
5630 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
5636 user_repo_to_perm = relationship('UserRepoToPerm', back_populates='branch_perm_entry')
5631 user_repo_to_perm = relationship('UserRepoToPerm', back_populates='branch_perm_entry')
5637
5632
5638 rule_order = Column('rule_order', Integer(), nullable=False)
5633 rule_order = Column('rule_order', Integer(), nullable=False)
5639 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default='*') # glob
5634 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default='*') # glob
5640 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5635 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5641
5636
5642 def __repr__(self):
5637 def __repr__(self):
5643 return f'<UserBranchPermission({self.user_repo_to_perm} => {self.branch_pattern!r})>'
5638 return f'<UserBranchPermission({self.user_repo_to_perm} => {self.branch_pattern!r})>'
5644
5639
5645
5640
5646 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
5641 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
5647 __tablename__ = 'user_group_to_repo_branch_permissions'
5642 __tablename__ = 'user_group_to_repo_branch_permissions'
5648 __table_args__ = (
5643 __table_args__ = (
5649 base_table_args
5644 base_table_args
5650 )
5645 )
5651
5646
5652 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5647 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5653
5648
5654 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5649 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5655 repo = relationship('Repository', back_populates='user_group_branch_perms')
5650 repo = relationship('Repository', back_populates='user_group_branch_perms')
5656
5651
5657 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5652 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5658 permission = relationship('Permission')
5653 permission = relationship('Permission')
5659
5654
5660 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)
5655 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)
5661 user_group_repo_to_perm = relationship('UserGroupRepoToPerm', back_populates='user_group_branch_perms')
5656 user_group_repo_to_perm = relationship('UserGroupRepoToPerm', back_populates='user_group_branch_perms')
5662
5657
5663 rule_order = Column('rule_order', Integer(), nullable=False)
5658 rule_order = Column('rule_order', Integer(), nullable=False)
5664 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default='*') # glob
5659 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default='*') # glob
5665 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5660 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5666
5661
5667 def __repr__(self):
5662 def __repr__(self):
5668 return f'<UserBranchPermission({self.user_group_repo_to_perm} => {self.branch_pattern!r})>'
5663 return f'<UserBranchPermission({self.user_group_repo_to_perm} => {self.branch_pattern!r})>'
5669
5664
5670
5665
5671 class UserBookmark(Base, BaseModel):
5666 class UserBookmark(Base, BaseModel):
5672 __tablename__ = 'user_bookmarks'
5667 __tablename__ = 'user_bookmarks'
5673 __table_args__ = (
5668 __table_args__ = (
5674 UniqueConstraint('user_id', 'bookmark_repo_id'),
5669 UniqueConstraint('user_id', 'bookmark_repo_id'),
5675 UniqueConstraint('user_id', 'bookmark_repo_group_id'),
5670 UniqueConstraint('user_id', 'bookmark_repo_group_id'),
5676 UniqueConstraint('user_id', 'bookmark_position'),
5671 UniqueConstraint('user_id', 'bookmark_position'),
5677 base_table_args
5672 base_table_args
5678 )
5673 )
5679
5674
5680 user_bookmark_id = Column("user_bookmark_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
5675 user_bookmark_id = Column("user_bookmark_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
5681 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
5676 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
5682 position = Column("bookmark_position", Integer(), nullable=False)
5677 position = Column("bookmark_position", Integer(), nullable=False)
5683 title = Column("bookmark_title", String(255), nullable=True, unique=None, default=None)
5678 title = Column("bookmark_title", String(255), nullable=True, unique=None, default=None)
5684 redirect_url = Column("bookmark_redirect_url", String(10240), nullable=True, unique=None, default=None)
5679 redirect_url = Column("bookmark_redirect_url", String(10240), nullable=True, unique=None, default=None)
5685 created_on = Column("created_on", DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5680 created_on = Column("created_on", DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5686
5681
5687 bookmark_repo_id = Column("bookmark_repo_id", Integer(), ForeignKey("repositories.repo_id"), nullable=True, unique=None, default=None)
5682 bookmark_repo_id = Column("bookmark_repo_id", Integer(), ForeignKey("repositories.repo_id"), nullable=True, unique=None, default=None)
5688 bookmark_repo_group_id = Column("bookmark_repo_group_id", Integer(), ForeignKey("groups.group_id"), nullable=True, unique=None, default=None)
5683 bookmark_repo_group_id = Column("bookmark_repo_group_id", Integer(), ForeignKey("groups.group_id"), nullable=True, unique=None, default=None)
5689
5684
5690 user = relationship("User")
5685 user = relationship("User")
5691
5686
5692 repository = relationship("Repository")
5687 repository = relationship("Repository")
5693 repository_group = relationship("RepoGroup")
5688 repository_group = relationship("RepoGroup")
5694
5689
5695 @classmethod
5690 @classmethod
5696 def get_by_position_for_user(cls, position, user_id):
5691 def get_by_position_for_user(cls, position, user_id):
5697 return cls.query() \
5692 return cls.query() \
5698 .filter(UserBookmark.user_id == user_id) \
5693 .filter(UserBookmark.user_id == user_id) \
5699 .filter(UserBookmark.position == position).scalar()
5694 .filter(UserBookmark.position == position).scalar()
5700
5695
5701 @classmethod
5696 @classmethod
5702 def get_bookmarks_for_user(cls, user_id, cache=True):
5697 def get_bookmarks_for_user(cls, user_id, cache=True):
5703 bookmarks = select(
5698 bookmarks = select(
5704 UserBookmark.title,
5699 UserBookmark.title,
5705 UserBookmark.position,
5700 UserBookmark.position,
5706 ) \
5701 ) \
5707 .add_columns(Repository.repo_id, Repository.repo_type, Repository.repo_name) \
5702 .add_columns(Repository.repo_id, Repository.repo_type, Repository.repo_name) \
5708 .add_columns(RepoGroup.group_id, RepoGroup.group_name) \
5703 .add_columns(RepoGroup.group_id, RepoGroup.group_name) \
5709 .where(UserBookmark.user_id == user_id) \
5704 .where(UserBookmark.user_id == user_id) \
5710 .outerjoin(Repository, Repository.repo_id == UserBookmark.bookmark_repo_id) \
5705 .outerjoin(Repository, Repository.repo_id == UserBookmark.bookmark_repo_id) \
5711 .outerjoin(RepoGroup, RepoGroup.group_id == UserBookmark.bookmark_repo_group_id) \
5706 .outerjoin(RepoGroup, RepoGroup.group_id == UserBookmark.bookmark_repo_group_id) \
5712 .order_by(UserBookmark.position.asc())
5707 .order_by(UserBookmark.position.asc())
5713
5708
5714 if cache:
5709 if cache:
5715 bookmarks = bookmarks.options(
5710 bookmarks = bookmarks.options(
5716 FromCache("sql_cache_short", f"get_user_{user_id}_bookmarks")
5711 FromCache("sql_cache_short", f"get_user_{user_id}_bookmarks")
5717 )
5712 )
5718
5713
5719 return Session().execute(bookmarks).all()
5714 return Session().execute(bookmarks).all()
5720
5715
5721 def __repr__(self):
5716 def __repr__(self):
5722 return f'<UserBookmark({self.position} @ {self.redirect_url!r})>'
5717 return f'<UserBookmark({self.position} @ {self.redirect_url!r})>'
5723
5718
5724
5719
5725 class FileStore(Base, BaseModel):
5720 class FileStore(Base, BaseModel):
5726 __tablename__ = 'file_store'
5721 __tablename__ = 'file_store'
5727 __table_args__ = (
5722 __table_args__ = (
5728 base_table_args
5723 base_table_args
5729 )
5724 )
5730
5725
5731 file_store_id = Column('file_store_id', Integer(), primary_key=True)
5726 file_store_id = Column('file_store_id', Integer(), primary_key=True)
5732 file_uid = Column('file_uid', String(1024), nullable=False)
5727 file_uid = Column('file_uid', String(1024), nullable=False)
5733 file_display_name = Column('file_display_name', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), nullable=True)
5728 file_display_name = Column('file_display_name', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), nullable=True)
5734 file_description = Column('file_description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=True)
5729 file_description = Column('file_description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=True)
5735 file_org_name = Column('file_org_name', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=False)
5730 file_org_name = Column('file_org_name', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=False)
5736
5731
5737 # sha256 hash
5732 # sha256 hash
5738 file_hash = Column('file_hash', String(512), nullable=False)
5733 file_hash = Column('file_hash', String(512), nullable=False)
5739 file_size = Column('file_size', BigInteger(), nullable=False)
5734 file_size = Column('file_size', BigInteger(), nullable=False)
5740
5735
5741 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5736 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5742 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True)
5737 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True)
5743 accessed_count = Column('accessed_count', Integer(), default=0)
5738 accessed_count = Column('accessed_count', Integer(), default=0)
5744
5739
5745 enabled = Column('enabled', Boolean(), nullable=False, default=True)
5740 enabled = Column('enabled', Boolean(), nullable=False, default=True)
5746
5741
5747 # if repo/repo_group reference is set, check for permissions
5742 # if repo/repo_group reference is set, check for permissions
5748 check_acl = Column('check_acl', Boolean(), nullable=False, default=True)
5743 check_acl = Column('check_acl', Boolean(), nullable=False, default=True)
5749
5744
5750 # hidden defines an attachment that should be hidden from showing in artifact listing
5745 # hidden defines an attachment that should be hidden from showing in artifact listing
5751 hidden = Column('hidden', Boolean(), nullable=False, default=False)
5746 hidden = Column('hidden', Boolean(), nullable=False, default=False)
5752
5747
5753 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
5748 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
5754 upload_user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.user_id', back_populates='artifacts')
5749 upload_user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.user_id', back_populates='artifacts')
5755
5750
5756 file_metadata = relationship('FileStoreMetadata', lazy='joined')
5751 file_metadata = relationship('FileStoreMetadata', lazy='joined')
5757
5752
5758 # scope limited to user, which requester have access to
5753 # scope limited to user, which requester have access to
5759 scope_user_id = Column(
5754 scope_user_id = Column(
5760 'scope_user_id', Integer(), ForeignKey('users.user_id'),
5755 'scope_user_id', Integer(), ForeignKey('users.user_id'),
5761 nullable=True, unique=None, default=None)
5756 nullable=True, unique=None, default=None)
5762 user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.scope_user_id', back_populates='scope_artifacts')
5757 user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.scope_user_id', back_populates='scope_artifacts')
5763
5758
5764 # scope limited to user group, which requester have access to
5759 # scope limited to user group, which requester have access to
5765 scope_user_group_id = Column(
5760 scope_user_group_id = Column(
5766 'scope_user_group_id', Integer(), ForeignKey('users_groups.users_group_id'),
5761 'scope_user_group_id', Integer(), ForeignKey('users_groups.users_group_id'),
5767 nullable=True, unique=None, default=None)
5762 nullable=True, unique=None, default=None)
5768 user_group = relationship('UserGroup', lazy='joined')
5763 user_group = relationship('UserGroup', lazy='joined')
5769
5764
5770 # scope limited to repo, which requester have access to
5765 # scope limited to repo, which requester have access to
5771 scope_repo_id = Column(
5766 scope_repo_id = Column(
5772 'scope_repo_id', Integer(), ForeignKey('repositories.repo_id'),
5767 'scope_repo_id', Integer(), ForeignKey('repositories.repo_id'),
5773 nullable=True, unique=None, default=None)
5768 nullable=True, unique=None, default=None)
5774 repo = relationship('Repository', lazy='joined')
5769 repo = relationship('Repository', lazy='joined')
5775
5770
5776 # scope limited to repo group, which requester have access to
5771 # scope limited to repo group, which requester have access to
5777 scope_repo_group_id = Column(
5772 scope_repo_group_id = Column(
5778 'scope_repo_group_id', Integer(), ForeignKey('groups.group_id'),
5773 'scope_repo_group_id', Integer(), ForeignKey('groups.group_id'),
5779 nullable=True, unique=None, default=None)
5774 nullable=True, unique=None, default=None)
5780 repo_group = relationship('RepoGroup', lazy='joined')
5775 repo_group = relationship('RepoGroup', lazy='joined')
5781
5776
5782 @classmethod
5777 @classmethod
5783 def get_scope(cls, scope_type, scope_id):
5778 def get_scope(cls, scope_type, scope_id):
5784 if scope_type == 'repo':
5779 if scope_type == 'repo':
5785 return f'repo:{scope_id}'
5780 return f'repo:{scope_id}'
5786 elif scope_type == 'repo-group':
5781 elif scope_type == 'repo-group':
5787 return f'repo-group:{scope_id}'
5782 return f'repo-group:{scope_id}'
5788 elif scope_type == 'user':
5783 elif scope_type == 'user':
5789 return f'user:{scope_id}'
5784 return f'user:{scope_id}'
5790 elif scope_type == 'user-group':
5785 elif scope_type == 'user-group':
5791 return f'user-group:{scope_id}'
5786 return f'user-group:{scope_id}'
5792 else:
5787 else:
5793 return scope_type
5788 return scope_type
5794
5789
5795 @classmethod
5790 @classmethod
5796 def get_by_store_uid(cls, file_store_uid, safe=False):
5791 def get_by_store_uid(cls, file_store_uid, safe=False):
5797 if safe:
5792 if safe:
5798 return FileStore.query().filter(FileStore.file_uid == file_store_uid).first()
5793 return FileStore.query().filter(FileStore.file_uid == file_store_uid).first()
5799 else:
5794 else:
5800 return FileStore.query().filter(FileStore.file_uid == file_store_uid).scalar()
5795 return FileStore.query().filter(FileStore.file_uid == file_store_uid).scalar()
5801
5796
5802 @classmethod
5797 @classmethod
5803 def create(cls, file_uid, filename, file_hash, file_size, file_display_name='',
5798 def create(cls, file_uid, filename, file_hash, file_size, file_display_name='',
5804 file_description='', enabled=True, hidden=False, check_acl=True,
5799 file_description='', enabled=True, hidden=False, check_acl=True,
5805 user_id=None, scope_user_id=None, scope_repo_id=None, scope_repo_group_id=None):
5800 user_id=None, scope_user_id=None, scope_repo_id=None, scope_repo_group_id=None):
5806
5801
5807 store_entry = FileStore()
5802 store_entry = FileStore()
5808 store_entry.file_uid = file_uid
5803 store_entry.file_uid = file_uid
5809 store_entry.file_display_name = file_display_name
5804 store_entry.file_display_name = file_display_name
5810 store_entry.file_org_name = filename
5805 store_entry.file_org_name = filename
5811 store_entry.file_size = file_size
5806 store_entry.file_size = file_size
5812 store_entry.file_hash = file_hash
5807 store_entry.file_hash = file_hash
5813 store_entry.file_description = file_description
5808 store_entry.file_description = file_description
5814
5809
5815 store_entry.check_acl = check_acl
5810 store_entry.check_acl = check_acl
5816 store_entry.enabled = enabled
5811 store_entry.enabled = enabled
5817 store_entry.hidden = hidden
5812 store_entry.hidden = hidden
5818
5813
5819 store_entry.user_id = user_id
5814 store_entry.user_id = user_id
5820 store_entry.scope_user_id = scope_user_id
5815 store_entry.scope_user_id = scope_user_id
5821 store_entry.scope_repo_id = scope_repo_id
5816 store_entry.scope_repo_id = scope_repo_id
5822 store_entry.scope_repo_group_id = scope_repo_group_id
5817 store_entry.scope_repo_group_id = scope_repo_group_id
5823
5818
5824 return store_entry
5819 return store_entry
5825
5820
5826 @classmethod
5821 @classmethod
5827 def store_metadata(cls, file_store_id, args, commit=True):
5822 def store_metadata(cls, file_store_id, args, commit=True):
5828 file_store = FileStore.get(file_store_id)
5823 file_store = FileStore.get(file_store_id)
5829 if file_store is None:
5824 if file_store is None:
5830 return
5825 return
5831
5826
5832 for section, key, value, value_type in args:
5827 for section, key, value, value_type in args:
5833 has_key = FileStoreMetadata().query() \
5828 has_key = FileStoreMetadata().query() \
5834 .filter(FileStoreMetadata.file_store_id == file_store.file_store_id) \
5829 .filter(FileStoreMetadata.file_store_id == file_store.file_store_id) \
5835 .filter(FileStoreMetadata.file_store_meta_section == section) \
5830 .filter(FileStoreMetadata.file_store_meta_section == section) \
5836 .filter(FileStoreMetadata.file_store_meta_key == key) \
5831 .filter(FileStoreMetadata.file_store_meta_key == key) \
5837 .scalar()
5832 .scalar()
5838 if has_key:
5833 if has_key:
5839 msg = 'key `{}` already defined under section `{}` for this file.'\
5834 msg = 'key `{}` already defined under section `{}` for this file.'\
5840 .format(key, section)
5835 .format(key, section)
5841 raise ArtifactMetadataDuplicate(msg, err_section=section, err_key=key)
5836 raise ArtifactMetadataDuplicate(msg, err_section=section, err_key=key)
5842
5837
5843 # NOTE(marcink): raises ArtifactMetadataBadValueType
5838 # NOTE(marcink): raises ArtifactMetadataBadValueType
5844 FileStoreMetadata.valid_value_type(value_type)
5839 FileStoreMetadata.valid_value_type(value_type)
5845
5840
5846 meta_entry = FileStoreMetadata()
5841 meta_entry = FileStoreMetadata()
5847 meta_entry.file_store = file_store
5842 meta_entry.file_store = file_store
5848 meta_entry.file_store_meta_section = section
5843 meta_entry.file_store_meta_section = section
5849 meta_entry.file_store_meta_key = key
5844 meta_entry.file_store_meta_key = key
5850 meta_entry.file_store_meta_value_type = value_type
5845 meta_entry.file_store_meta_value_type = value_type
5851 meta_entry.file_store_meta_value = value
5846 meta_entry.file_store_meta_value = value
5852
5847
5853 Session().add(meta_entry)
5848 Session().add(meta_entry)
5854
5849
5855 try:
5850 try:
5856 if commit:
5851 if commit:
5857 Session().commit()
5852 Session().commit()
5858 except IntegrityError:
5853 except IntegrityError:
5859 Session().rollback()
5854 Session().rollback()
5860 raise ArtifactMetadataDuplicate('Duplicate section/key found for this file.')
5855 raise ArtifactMetadataDuplicate('Duplicate section/key found for this file.')
5861
5856
5862 @classmethod
5857 @classmethod
5863 def bump_access_counter(cls, file_uid, commit=True):
5858 def bump_access_counter(cls, file_uid, commit=True):
5864 FileStore().query()\
5859 FileStore().query()\
5865 .filter(FileStore.file_uid == file_uid)\
5860 .filter(FileStore.file_uid == file_uid)\
5866 .update({FileStore.accessed_count: (FileStore.accessed_count + 1),
5861 .update({FileStore.accessed_count: (FileStore.accessed_count + 1),
5867 FileStore.accessed_on: datetime.datetime.now()})
5862 FileStore.accessed_on: datetime.datetime.now()})
5868 if commit:
5863 if commit:
5869 Session().commit()
5864 Session().commit()
5870
5865
5871 def __json__(self):
5866 def __json__(self):
5872 data = {
5867 data = {
5873 'filename': self.file_display_name,
5868 'filename': self.file_display_name,
5874 'filename_org': self.file_org_name,
5869 'filename_org': self.file_org_name,
5875 'file_uid': self.file_uid,
5870 'file_uid': self.file_uid,
5876 'description': self.file_description,
5871 'description': self.file_description,
5877 'hidden': self.hidden,
5872 'hidden': self.hidden,
5878 'size': self.file_size,
5873 'size': self.file_size,
5879 'created_on': self.created_on,
5874 'created_on': self.created_on,
5880 'uploaded_by': self.upload_user.get_api_data(details='basic'),
5875 'uploaded_by': self.upload_user.get_api_data(details='basic'),
5881 'downloaded_times': self.accessed_count,
5876 'downloaded_times': self.accessed_count,
5882 'sha256': self.file_hash,
5877 'sha256': self.file_hash,
5883 'metadata': self.file_metadata,
5878 'metadata': self.file_metadata,
5884 }
5879 }
5885
5880
5886 return data
5881 return data
5887
5882
5888 def __repr__(self):
5883 def __repr__(self):
5889 return f'<FileStore({self.file_store_id})>'
5884 return f'<FileStore({self.file_store_id})>'
5890
5885
5891
5886
5892 class FileStoreMetadata(Base, BaseModel):
5887 class FileStoreMetadata(Base, BaseModel):
5893 __tablename__ = 'file_store_metadata'
5888 __tablename__ = 'file_store_metadata'
5894 __table_args__ = (
5889 __table_args__ = (
5895 UniqueConstraint('file_store_id', 'file_store_meta_section_hash', 'file_store_meta_key_hash'),
5890 UniqueConstraint('file_store_id', 'file_store_meta_section_hash', 'file_store_meta_key_hash'),
5896 Index('file_store_meta_section_idx', 'file_store_meta_section', mysql_length=255),
5891 Index('file_store_meta_section_idx', 'file_store_meta_section', mysql_length=255),
5897 Index('file_store_meta_key_idx', 'file_store_meta_key', mysql_length=255),
5892 Index('file_store_meta_key_idx', 'file_store_meta_key', mysql_length=255),
5898 base_table_args
5893 base_table_args
5899 )
5894 )
5900 SETTINGS_TYPES = {
5895 SETTINGS_TYPES = {
5901 'str': safe_str,
5896 'str': safe_str,
5902 'int': safe_int,
5897 'int': safe_int,
5903 'unicode': safe_str,
5898 'unicode': safe_str,
5904 'bool': str2bool,
5899 'bool': str2bool,
5905 'list': functools.partial(aslist, sep=',')
5900 'list': functools.partial(aslist, sep=',')
5906 }
5901 }
5907
5902
5908 file_store_meta_id = Column(
5903 file_store_meta_id = Column(
5909 "file_store_meta_id", Integer(), nullable=False, unique=True, default=None,
5904 "file_store_meta_id", Integer(), nullable=False, unique=True, default=None,
5910 primary_key=True)
5905 primary_key=True)
5911 _file_store_meta_section = Column(
5906 _file_store_meta_section = Column(
5912 "file_store_meta_section", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5907 "file_store_meta_section", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5913 nullable=True, unique=None, default=None)
5908 nullable=True, unique=None, default=None)
5914 _file_store_meta_section_hash = Column(
5909 _file_store_meta_section_hash = Column(
5915 "file_store_meta_section_hash", String(255),
5910 "file_store_meta_section_hash", String(255),
5916 nullable=True, unique=None, default=None)
5911 nullable=True, unique=None, default=None)
5917 _file_store_meta_key = Column(
5912 _file_store_meta_key = Column(
5918 "file_store_meta_key", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5913 "file_store_meta_key", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5919 nullable=True, unique=None, default=None)
5914 nullable=True, unique=None, default=None)
5920 _file_store_meta_key_hash = Column(
5915 _file_store_meta_key_hash = Column(
5921 "file_store_meta_key_hash", String(255), nullable=True, unique=None, default=None)
5916 "file_store_meta_key_hash", String(255), nullable=True, unique=None, default=None)
5922 _file_store_meta_value = Column(
5917 _file_store_meta_value = Column(
5923 "file_store_meta_value", UnicodeText().with_variant(UnicodeText(20480), 'mysql'),
5918 "file_store_meta_value", UnicodeText().with_variant(UnicodeText(20480), 'mysql'),
5924 nullable=True, unique=None, default=None)
5919 nullable=True, unique=None, default=None)
5925 _file_store_meta_value_type = Column(
5920 _file_store_meta_value_type = Column(
5926 "file_store_meta_value_type", String(255), nullable=True, unique=None,
5921 "file_store_meta_value_type", String(255), nullable=True, unique=None,
5927 default='unicode')
5922 default='unicode')
5928
5923
5929 file_store_id = Column(
5924 file_store_id = Column(
5930 'file_store_id', Integer(), ForeignKey('file_store.file_store_id'),
5925 'file_store_id', Integer(), ForeignKey('file_store.file_store_id'),
5931 nullable=True, unique=None, default=None)
5926 nullable=True, unique=None, default=None)
5932
5927
5933 file_store = relationship('FileStore', lazy='joined', viewonly=True)
5928 file_store = relationship('FileStore', lazy='joined', viewonly=True)
5934
5929
5935 @classmethod
5930 @classmethod
5936 def valid_value_type(cls, value):
5931 def valid_value_type(cls, value):
5937 if value.split('.')[0] not in cls.SETTINGS_TYPES:
5932 if value.split('.')[0] not in cls.SETTINGS_TYPES:
5938 raise ArtifactMetadataBadValueType(
5933 raise ArtifactMetadataBadValueType(
5939 'value_type must be one of %s got %s' % (cls.SETTINGS_TYPES.keys(), value))
5934 'value_type must be one of %s got %s' % (cls.SETTINGS_TYPES.keys(), value))
5940
5935
5941 @hybrid_property
5936 @hybrid_property
5942 def file_store_meta_section(self):
5937 def file_store_meta_section(self):
5943 return self._file_store_meta_section
5938 return self._file_store_meta_section
5944
5939
5945 @file_store_meta_section.setter
5940 @file_store_meta_section.setter
5946 def file_store_meta_section(self, value):
5941 def file_store_meta_section(self, value):
5947 self._file_store_meta_section = value
5942 self._file_store_meta_section = value
5948 self._file_store_meta_section_hash = _hash_key(value)
5943 self._file_store_meta_section_hash = _hash_key(value)
5949
5944
5950 @hybrid_property
5945 @hybrid_property
5951 def file_store_meta_key(self):
5946 def file_store_meta_key(self):
5952 return self._file_store_meta_key
5947 return self._file_store_meta_key
5953
5948
5954 @file_store_meta_key.setter
5949 @file_store_meta_key.setter
5955 def file_store_meta_key(self, value):
5950 def file_store_meta_key(self, value):
5956 self._file_store_meta_key = value
5951 self._file_store_meta_key = value
5957 self._file_store_meta_key_hash = _hash_key(value)
5952 self._file_store_meta_key_hash = _hash_key(value)
5958
5953
5959 @hybrid_property
5954 @hybrid_property
5960 def file_store_meta_value(self):
5955 def file_store_meta_value(self):
5961 val = self._file_store_meta_value
5956 val = self._file_store_meta_value
5962
5957
5963 if self._file_store_meta_value_type:
5958 if self._file_store_meta_value_type:
5964 # e.g unicode.encrypted == unicode
5959 # e.g unicode.encrypted == unicode
5965 _type = self._file_store_meta_value_type.split('.')[0]
5960 _type = self._file_store_meta_value_type.split('.')[0]
5966 # decode the encrypted value if it's encrypted field type
5961 # decode the encrypted value if it's encrypted field type
5967 if '.encrypted' in self._file_store_meta_value_type:
5962 if '.encrypted' in self._file_store_meta_value_type:
5968 cipher = EncryptedTextValue()
5963 cipher = EncryptedTextValue()
5969 val = safe_str(cipher.process_result_value(val, None))
5964 val = safe_str(cipher.process_result_value(val, None))
5970 # do final type conversion
5965 # do final type conversion
5971 converter = self.SETTINGS_TYPES.get(_type) or self.SETTINGS_TYPES['unicode']
5966 converter = self.SETTINGS_TYPES.get(_type) or self.SETTINGS_TYPES['unicode']
5972 val = converter(val)
5967 val = converter(val)
5973
5968
5974 return val
5969 return val
5975
5970
5976 @file_store_meta_value.setter
5971 @file_store_meta_value.setter
5977 def file_store_meta_value(self, val):
5972 def file_store_meta_value(self, val):
5978 val = safe_str(val)
5973 val = safe_str(val)
5979 # encode the encrypted value
5974 # encode the encrypted value
5980 if '.encrypted' in self.file_store_meta_value_type:
5975 if '.encrypted' in self.file_store_meta_value_type:
5981 cipher = EncryptedTextValue()
5976 cipher = EncryptedTextValue()
5982 val = safe_str(cipher.process_bind_param(val, None))
5977 val = safe_str(cipher.process_bind_param(val, None))
5983 self._file_store_meta_value = val
5978 self._file_store_meta_value = val
5984
5979
5985 @hybrid_property
5980 @hybrid_property
5986 def file_store_meta_value_type(self):
5981 def file_store_meta_value_type(self):
5987 return self._file_store_meta_value_type
5982 return self._file_store_meta_value_type
5988
5983
5989 @file_store_meta_value_type.setter
5984 @file_store_meta_value_type.setter
5990 def file_store_meta_value_type(self, val):
5985 def file_store_meta_value_type(self, val):
5991 # e.g unicode.encrypted
5986 # e.g unicode.encrypted
5992 self.valid_value_type(val)
5987 self.valid_value_type(val)
5993 self._file_store_meta_value_type = val
5988 self._file_store_meta_value_type = val
5994
5989
5995 def __json__(self):
5990 def __json__(self):
5996 data = {
5991 data = {
5997 'artifact': self.file_store.file_uid,
5992 'artifact': self.file_store.file_uid,
5998 'section': self.file_store_meta_section,
5993 'section': self.file_store_meta_section,
5999 'key': self.file_store_meta_key,
5994 'key': self.file_store_meta_key,
6000 'value': self.file_store_meta_value,
5995 'value': self.file_store_meta_value,
6001 }
5996 }
6002
5997
6003 return data
5998 return data
6004
5999
6005 def __repr__(self):
6000 def __repr__(self):
6006 return '<%s[%s]%s=>%s]>' % (self.cls_name, self.file_store_meta_section,
6001 return '<%s[%s]%s=>%s]>' % (self.cls_name, self.file_store_meta_section,
6007 self.file_store_meta_key, self.file_store_meta_value)
6002 self.file_store_meta_key, self.file_store_meta_value)
6008
6003
6009
6004
6010 class DbMigrateVersion(Base, BaseModel):
6005 class DbMigrateVersion(Base, BaseModel):
6011 __tablename__ = 'db_migrate_version'
6006 __tablename__ = 'db_migrate_version'
6012 __table_args__ = (
6007 __table_args__ = (
6013 base_table_args,
6008 base_table_args,
6014 )
6009 )
6015
6010
6016 repository_id = Column('repository_id', String(250), primary_key=True)
6011 repository_id = Column('repository_id', String(250), primary_key=True)
6017 repository_path = Column('repository_path', Text)
6012 repository_path = Column('repository_path', Text)
6018 version = Column('version', Integer)
6013 version = Column('version', Integer)
6019
6014
6020 @classmethod
6015 @classmethod
6021 def set_version(cls, version):
6016 def set_version(cls, version):
6022 """
6017 """
6023 Helper for forcing a different version, usually for debugging purposes via ishell.
6018 Helper for forcing a different version, usually for debugging purposes via ishell.
6024 """
6019 """
6025 ver = DbMigrateVersion.query().first()
6020 ver = DbMigrateVersion.query().first()
6026 ver.version = version
6021 ver.version = version
6027 Session().commit()
6022 Session().commit()
6028
6023
6029
6024
6030 class DbSession(Base, BaseModel):
6025 class DbSession(Base, BaseModel):
6031 __tablename__ = 'db_session'
6026 __tablename__ = 'db_session'
6032 __table_args__ = (
6027 __table_args__ = (
6033 base_table_args,
6028 base_table_args,
6034 )
6029 )
6035
6030
6036 def __repr__(self):
6031 def __repr__(self):
6037 return f'<DB:DbSession({self.id})>'
6032 return f'<DB:DbSession({self.id})>'
6038
6033
6039 id = Column('id', Integer())
6034 id = Column('id', Integer())
6040 namespace = Column('namespace', String(255), primary_key=True)
6035 namespace = Column('namespace', String(255), primary_key=True)
6041 accessed = Column('accessed', DateTime, nullable=False)
6036 accessed = Column('accessed', DateTime, nullable=False)
6042 created = Column('created', DateTime, nullable=False)
6037 created = Column('created', DateTime, nullable=False)
6043 data = Column('data', PickleType, nullable=False)
6038 data = Column('data', PickleType, nullable=False)
General Comments 0
You need to be logged in to leave comments. Login now