##// END OF EJS Templates
permissions: fixed wrong permissions display for user groups
marcink -
r3592:3bac8145 stable
parent child Browse files
Show More
@@ -1,4972 +1,4972 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2019 RhodeCode GmbH
3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 Database Models for RhodeCode Enterprise
22 Database Models for RhodeCode Enterprise
23 """
23 """
24
24
25 import re
25 import re
26 import os
26 import os
27 import time
27 import time
28 import hashlib
28 import hashlib
29 import logging
29 import logging
30 import datetime
30 import datetime
31 import warnings
31 import warnings
32 import ipaddress
32 import ipaddress
33 import functools
33 import functools
34 import traceback
34 import traceback
35 import collections
35 import collections
36
36
37 from sqlalchemy import (
37 from sqlalchemy import (
38 or_, and_, not_, func, TypeDecorator, event,
38 or_, and_, not_, func, TypeDecorator, event,
39 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
39 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
40 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
40 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
41 Text, Float, PickleType)
41 Text, Float, PickleType)
42 from sqlalchemy.sql.expression import true, false
42 from sqlalchemy.sql.expression import true, false
43 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
43 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
44 from sqlalchemy.orm import (
44 from sqlalchemy.orm import (
45 relationship, joinedload, class_mapper, validates, aliased)
45 relationship, joinedload, class_mapper, validates, aliased)
46 from sqlalchemy.ext.declarative import declared_attr
46 from sqlalchemy.ext.declarative import declared_attr
47 from sqlalchemy.ext.hybrid import hybrid_property
47 from sqlalchemy.ext.hybrid import hybrid_property
48 from sqlalchemy.exc import IntegrityError # pragma: no cover
48 from sqlalchemy.exc import IntegrityError # pragma: no cover
49 from sqlalchemy.dialects.mysql import LONGTEXT
49 from sqlalchemy.dialects.mysql import LONGTEXT
50 from zope.cachedescriptors.property import Lazy as LazyProperty
50 from zope.cachedescriptors.property import Lazy as LazyProperty
51 from pyramid import compat
51 from pyramid import compat
52 from pyramid.threadlocal import get_current_request
52 from pyramid.threadlocal import get_current_request
53
53
54 from rhodecode.translation import _
54 from rhodecode.translation import _
55 from rhodecode.lib.vcs import get_vcs_instance
55 from rhodecode.lib.vcs import get_vcs_instance
56 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
56 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
57 from rhodecode.lib.utils2 import (
57 from rhodecode.lib.utils2 import (
58 str2bool, safe_str, get_commit_safe, safe_unicode, sha1_safe,
58 str2bool, safe_str, get_commit_safe, safe_unicode, sha1_safe,
59 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
59 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
60 glob2re, StrictAttributeDict, cleaned_uri)
60 glob2re, StrictAttributeDict, cleaned_uri)
61 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
61 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
62 JsonRaw
62 JsonRaw
63 from rhodecode.lib.ext_json import json
63 from rhodecode.lib.ext_json import json
64 from rhodecode.lib.caching_query import FromCache
64 from rhodecode.lib.caching_query import FromCache
65 from rhodecode.lib.encrypt import AESCipher
65 from rhodecode.lib.encrypt import AESCipher
66
66
67 from rhodecode.model.meta import Base, Session
67 from rhodecode.model.meta import Base, Session
68
68
69 URL_SEP = '/'
69 URL_SEP = '/'
70 log = logging.getLogger(__name__)
70 log = logging.getLogger(__name__)
71
71
72 # =============================================================================
72 # =============================================================================
73 # BASE CLASSES
73 # BASE CLASSES
74 # =============================================================================
74 # =============================================================================
75
75
76 # this is propagated from .ini file rhodecode.encrypted_values.secret or
76 # this is propagated from .ini file rhodecode.encrypted_values.secret or
77 # beaker.session.secret if first is not set.
77 # beaker.session.secret if first is not set.
78 # and initialized at environment.py
78 # and initialized at environment.py
79 ENCRYPTION_KEY = None
79 ENCRYPTION_KEY = None
80
80
81 # used to sort permissions by types, '#' used here is not allowed to be in
81 # used to sort permissions by types, '#' used here is not allowed to be in
82 # usernames, and it's very early in sorted string.printable table.
82 # usernames, and it's very early in sorted string.printable table.
83 PERMISSION_TYPE_SORT = {
83 PERMISSION_TYPE_SORT = {
84 'admin': '####',
84 'admin': '####',
85 'write': '###',
85 'write': '###',
86 'read': '##',
86 'read': '##',
87 'none': '#',
87 'none': '#',
88 }
88 }
89
89
90
90
91 def display_user_sort(obj):
91 def display_user_sort(obj):
92 """
92 """
93 Sort function used to sort permissions in .permissions() function of
93 Sort function used to sort permissions in .permissions() function of
94 Repository, RepoGroup, UserGroup. Also it put the default user in front
94 Repository, RepoGroup, UserGroup. Also it put the default user in front
95 of all other resources
95 of all other resources
96 """
96 """
97
97
98 if obj.username == User.DEFAULT_USER:
98 if obj.username == User.DEFAULT_USER:
99 return '#####'
99 return '#####'
100 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
100 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
101 return prefix + obj.username
101 return prefix + obj.username
102
102
103
103
104 def display_user_group_sort(obj):
104 def display_user_group_sort(obj):
105 """
105 """
106 Sort function used to sort permissions in .permissions() function of
106 Sort function used to sort permissions in .permissions() function of
107 Repository, RepoGroup, UserGroup. Also it put the default user in front
107 Repository, RepoGroup, UserGroup. Also it put the default user in front
108 of all other resources
108 of all other resources
109 """
109 """
110
110
111 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
111 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
112 return prefix + obj.users_group_name
112 return prefix + obj.users_group_name
113
113
114
114
115 def _hash_key(k):
115 def _hash_key(k):
116 return sha1_safe(k)
116 return sha1_safe(k)
117
117
118
118
119 def in_filter_generator(qry, items, limit=500):
119 def in_filter_generator(qry, items, limit=500):
120 """
120 """
121 Splits IN() into multiple with OR
121 Splits IN() into multiple with OR
122 e.g.::
122 e.g.::
123 cnt = Repository.query().filter(
123 cnt = Repository.query().filter(
124 or_(
124 or_(
125 *in_filter_generator(Repository.repo_id, range(100000))
125 *in_filter_generator(Repository.repo_id, range(100000))
126 )).count()
126 )).count()
127 """
127 """
128 if not items:
128 if not items:
129 # empty list will cause empty query which might cause security issues
129 # empty list will cause empty query which might cause security issues
130 # this can lead to hidden unpleasant results
130 # this can lead to hidden unpleasant results
131 items = [-1]
131 items = [-1]
132
132
133 parts = []
133 parts = []
134 for chunk in xrange(0, len(items), limit):
134 for chunk in xrange(0, len(items), limit):
135 parts.append(
135 parts.append(
136 qry.in_(items[chunk: chunk + limit])
136 qry.in_(items[chunk: chunk + limit])
137 )
137 )
138
138
139 return parts
139 return parts
140
140
141
141
142 base_table_args = {
142 base_table_args = {
143 'extend_existing': True,
143 'extend_existing': True,
144 'mysql_engine': 'InnoDB',
144 'mysql_engine': 'InnoDB',
145 'mysql_charset': 'utf8',
145 'mysql_charset': 'utf8',
146 'sqlite_autoincrement': True
146 'sqlite_autoincrement': True
147 }
147 }
148
148
149
149
150 class EncryptedTextValue(TypeDecorator):
150 class EncryptedTextValue(TypeDecorator):
151 """
151 """
152 Special column for encrypted long text data, use like::
152 Special column for encrypted long text data, use like::
153
153
154 value = Column("encrypted_value", EncryptedValue(), nullable=False)
154 value = Column("encrypted_value", EncryptedValue(), nullable=False)
155
155
156 This column is intelligent so if value is in unencrypted form it return
156 This column is intelligent so if value is in unencrypted form it return
157 unencrypted form, but on save it always encrypts
157 unencrypted form, but on save it always encrypts
158 """
158 """
159 impl = Text
159 impl = Text
160
160
161 def process_bind_param(self, value, dialect):
161 def process_bind_param(self, value, dialect):
162 if not value:
162 if not value:
163 return value
163 return value
164 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
164 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
165 # protect against double encrypting if someone manually starts
165 # protect against double encrypting if someone manually starts
166 # doing
166 # doing
167 raise ValueError('value needs to be in unencrypted format, ie. '
167 raise ValueError('value needs to be in unencrypted format, ie. '
168 'not starting with enc$aes')
168 'not starting with enc$aes')
169 return 'enc$aes_hmac$%s' % AESCipher(
169 return 'enc$aes_hmac$%s' % AESCipher(
170 ENCRYPTION_KEY, hmac=True).encrypt(value)
170 ENCRYPTION_KEY, hmac=True).encrypt(value)
171
171
172 def process_result_value(self, value, dialect):
172 def process_result_value(self, value, dialect):
173 import rhodecode
173 import rhodecode
174
174
175 if not value:
175 if not value:
176 return value
176 return value
177
177
178 parts = value.split('$', 3)
178 parts = value.split('$', 3)
179 if not len(parts) == 3:
179 if not len(parts) == 3:
180 # probably not encrypted values
180 # probably not encrypted values
181 return value
181 return value
182 else:
182 else:
183 if parts[0] != 'enc':
183 if parts[0] != 'enc':
184 # parts ok but without our header ?
184 # parts ok but without our header ?
185 return value
185 return value
186 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
186 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
187 'rhodecode.encrypted_values.strict') or True)
187 'rhodecode.encrypted_values.strict') or True)
188 # at that stage we know it's our encryption
188 # at that stage we know it's our encryption
189 if parts[1] == 'aes':
189 if parts[1] == 'aes':
190 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
190 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
191 elif parts[1] == 'aes_hmac':
191 elif parts[1] == 'aes_hmac':
192 decrypted_data = AESCipher(
192 decrypted_data = AESCipher(
193 ENCRYPTION_KEY, hmac=True,
193 ENCRYPTION_KEY, hmac=True,
194 strict_verification=enc_strict_mode).decrypt(parts[2])
194 strict_verification=enc_strict_mode).decrypt(parts[2])
195 else:
195 else:
196 raise ValueError(
196 raise ValueError(
197 'Encryption type part is wrong, must be `aes` '
197 'Encryption type part is wrong, must be `aes` '
198 'or `aes_hmac`, got `%s` instead' % (parts[1]))
198 'or `aes_hmac`, got `%s` instead' % (parts[1]))
199 return decrypted_data
199 return decrypted_data
200
200
201
201
202 class BaseModel(object):
202 class BaseModel(object):
203 """
203 """
204 Base Model for all classes
204 Base Model for all classes
205 """
205 """
206
206
207 @classmethod
207 @classmethod
208 def _get_keys(cls):
208 def _get_keys(cls):
209 """return column names for this model """
209 """return column names for this model """
210 return class_mapper(cls).c.keys()
210 return class_mapper(cls).c.keys()
211
211
212 def get_dict(self):
212 def get_dict(self):
213 """
213 """
214 return dict with keys and values corresponding
214 return dict with keys and values corresponding
215 to this model data """
215 to this model data """
216
216
217 d = {}
217 d = {}
218 for k in self._get_keys():
218 for k in self._get_keys():
219 d[k] = getattr(self, k)
219 d[k] = getattr(self, k)
220
220
221 # also use __json__() if present to get additional fields
221 # also use __json__() if present to get additional fields
222 _json_attr = getattr(self, '__json__', None)
222 _json_attr = getattr(self, '__json__', None)
223 if _json_attr:
223 if _json_attr:
224 # update with attributes from __json__
224 # update with attributes from __json__
225 if callable(_json_attr):
225 if callable(_json_attr):
226 _json_attr = _json_attr()
226 _json_attr = _json_attr()
227 for k, val in _json_attr.iteritems():
227 for k, val in _json_attr.iteritems():
228 d[k] = val
228 d[k] = val
229 return d
229 return d
230
230
231 def get_appstruct(self):
231 def get_appstruct(self):
232 """return list with keys and values tuples corresponding
232 """return list with keys and values tuples corresponding
233 to this model data """
233 to this model data """
234
234
235 lst = []
235 lst = []
236 for k in self._get_keys():
236 for k in self._get_keys():
237 lst.append((k, getattr(self, k),))
237 lst.append((k, getattr(self, k),))
238 return lst
238 return lst
239
239
240 def populate_obj(self, populate_dict):
240 def populate_obj(self, populate_dict):
241 """populate model with data from given populate_dict"""
241 """populate model with data from given populate_dict"""
242
242
243 for k in self._get_keys():
243 for k in self._get_keys():
244 if k in populate_dict:
244 if k in populate_dict:
245 setattr(self, k, populate_dict[k])
245 setattr(self, k, populate_dict[k])
246
246
247 @classmethod
247 @classmethod
248 def query(cls):
248 def query(cls):
249 return Session().query(cls)
249 return Session().query(cls)
250
250
251 @classmethod
251 @classmethod
252 def get(cls, id_):
252 def get(cls, id_):
253 if id_:
253 if id_:
254 return cls.query().get(id_)
254 return cls.query().get(id_)
255
255
256 @classmethod
256 @classmethod
257 def get_or_404(cls, id_):
257 def get_or_404(cls, id_):
258 from pyramid.httpexceptions import HTTPNotFound
258 from pyramid.httpexceptions import HTTPNotFound
259
259
260 try:
260 try:
261 id_ = int(id_)
261 id_ = int(id_)
262 except (TypeError, ValueError):
262 except (TypeError, ValueError):
263 raise HTTPNotFound()
263 raise HTTPNotFound()
264
264
265 res = cls.query().get(id_)
265 res = cls.query().get(id_)
266 if not res:
266 if not res:
267 raise HTTPNotFound()
267 raise HTTPNotFound()
268 return res
268 return res
269
269
270 @classmethod
270 @classmethod
271 def getAll(cls):
271 def getAll(cls):
272 # deprecated and left for backward compatibility
272 # deprecated and left for backward compatibility
273 return cls.get_all()
273 return cls.get_all()
274
274
275 @classmethod
275 @classmethod
276 def get_all(cls):
276 def get_all(cls):
277 return cls.query().all()
277 return cls.query().all()
278
278
279 @classmethod
279 @classmethod
280 def delete(cls, id_):
280 def delete(cls, id_):
281 obj = cls.query().get(id_)
281 obj = cls.query().get(id_)
282 Session().delete(obj)
282 Session().delete(obj)
283
283
284 @classmethod
284 @classmethod
285 def identity_cache(cls, session, attr_name, value):
285 def identity_cache(cls, session, attr_name, value):
286 exist_in_session = []
286 exist_in_session = []
287 for (item_cls, pkey), instance in session.identity_map.items():
287 for (item_cls, pkey), instance in session.identity_map.items():
288 if cls == item_cls and getattr(instance, attr_name) == value:
288 if cls == item_cls and getattr(instance, attr_name) == value:
289 exist_in_session.append(instance)
289 exist_in_session.append(instance)
290 if exist_in_session:
290 if exist_in_session:
291 if len(exist_in_session) == 1:
291 if len(exist_in_session) == 1:
292 return exist_in_session[0]
292 return exist_in_session[0]
293 log.exception(
293 log.exception(
294 'multiple objects with attr %s and '
294 'multiple objects with attr %s and '
295 'value %s found with same name: %r',
295 'value %s found with same name: %r',
296 attr_name, value, exist_in_session)
296 attr_name, value, exist_in_session)
297
297
298 def __repr__(self):
298 def __repr__(self):
299 if hasattr(self, '__unicode__'):
299 if hasattr(self, '__unicode__'):
300 # python repr needs to return str
300 # python repr needs to return str
301 try:
301 try:
302 return safe_str(self.__unicode__())
302 return safe_str(self.__unicode__())
303 except UnicodeDecodeError:
303 except UnicodeDecodeError:
304 pass
304 pass
305 return '<DB:%s>' % (self.__class__.__name__)
305 return '<DB:%s>' % (self.__class__.__name__)
306
306
307
307
308 class RhodeCodeSetting(Base, BaseModel):
308 class RhodeCodeSetting(Base, BaseModel):
309 __tablename__ = 'rhodecode_settings'
309 __tablename__ = 'rhodecode_settings'
310 __table_args__ = (
310 __table_args__ = (
311 UniqueConstraint('app_settings_name'),
311 UniqueConstraint('app_settings_name'),
312 base_table_args
312 base_table_args
313 )
313 )
314
314
315 SETTINGS_TYPES = {
315 SETTINGS_TYPES = {
316 'str': safe_str,
316 'str': safe_str,
317 'int': safe_int,
317 'int': safe_int,
318 'unicode': safe_unicode,
318 'unicode': safe_unicode,
319 'bool': str2bool,
319 'bool': str2bool,
320 'list': functools.partial(aslist, sep=',')
320 'list': functools.partial(aslist, sep=',')
321 }
321 }
322 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
322 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
323 GLOBAL_CONF_KEY = 'app_settings'
323 GLOBAL_CONF_KEY = 'app_settings'
324
324
325 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
325 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
326 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
326 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
327 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
327 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
328 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
328 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
329
329
330 def __init__(self, key='', val='', type='unicode'):
330 def __init__(self, key='', val='', type='unicode'):
331 self.app_settings_name = key
331 self.app_settings_name = key
332 self.app_settings_type = type
332 self.app_settings_type = type
333 self.app_settings_value = val
333 self.app_settings_value = val
334
334
335 @validates('_app_settings_value')
335 @validates('_app_settings_value')
336 def validate_settings_value(self, key, val):
336 def validate_settings_value(self, key, val):
337 assert type(val) == unicode
337 assert type(val) == unicode
338 return val
338 return val
339
339
340 @hybrid_property
340 @hybrid_property
341 def app_settings_value(self):
341 def app_settings_value(self):
342 v = self._app_settings_value
342 v = self._app_settings_value
343 _type = self.app_settings_type
343 _type = self.app_settings_type
344 if _type:
344 if _type:
345 _type = self.app_settings_type.split('.')[0]
345 _type = self.app_settings_type.split('.')[0]
346 # decode the encrypted value
346 # decode the encrypted value
347 if 'encrypted' in self.app_settings_type:
347 if 'encrypted' in self.app_settings_type:
348 cipher = EncryptedTextValue()
348 cipher = EncryptedTextValue()
349 v = safe_unicode(cipher.process_result_value(v, None))
349 v = safe_unicode(cipher.process_result_value(v, None))
350
350
351 converter = self.SETTINGS_TYPES.get(_type) or \
351 converter = self.SETTINGS_TYPES.get(_type) or \
352 self.SETTINGS_TYPES['unicode']
352 self.SETTINGS_TYPES['unicode']
353 return converter(v)
353 return converter(v)
354
354
355 @app_settings_value.setter
355 @app_settings_value.setter
356 def app_settings_value(self, val):
356 def app_settings_value(self, val):
357 """
357 """
358 Setter that will always make sure we use unicode in app_settings_value
358 Setter that will always make sure we use unicode in app_settings_value
359
359
360 :param val:
360 :param val:
361 """
361 """
362 val = safe_unicode(val)
362 val = safe_unicode(val)
363 # encode the encrypted value
363 # encode the encrypted value
364 if 'encrypted' in self.app_settings_type:
364 if 'encrypted' in self.app_settings_type:
365 cipher = EncryptedTextValue()
365 cipher = EncryptedTextValue()
366 val = safe_unicode(cipher.process_bind_param(val, None))
366 val = safe_unicode(cipher.process_bind_param(val, None))
367 self._app_settings_value = val
367 self._app_settings_value = val
368
368
369 @hybrid_property
369 @hybrid_property
370 def app_settings_type(self):
370 def app_settings_type(self):
371 return self._app_settings_type
371 return self._app_settings_type
372
372
373 @app_settings_type.setter
373 @app_settings_type.setter
374 def app_settings_type(self, val):
374 def app_settings_type(self, val):
375 if val.split('.')[0] not in self.SETTINGS_TYPES:
375 if val.split('.')[0] not in self.SETTINGS_TYPES:
376 raise Exception('type must be one of %s got %s'
376 raise Exception('type must be one of %s got %s'
377 % (self.SETTINGS_TYPES.keys(), val))
377 % (self.SETTINGS_TYPES.keys(), val))
378 self._app_settings_type = val
378 self._app_settings_type = val
379
379
380 @classmethod
380 @classmethod
381 def get_by_prefix(cls, prefix):
381 def get_by_prefix(cls, prefix):
382 return RhodeCodeSetting.query()\
382 return RhodeCodeSetting.query()\
383 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
383 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
384 .all()
384 .all()
385
385
386 def __unicode__(self):
386 def __unicode__(self):
387 return u"<%s('%s:%s[%s]')>" % (
387 return u"<%s('%s:%s[%s]')>" % (
388 self.__class__.__name__,
388 self.__class__.__name__,
389 self.app_settings_name, self.app_settings_value,
389 self.app_settings_name, self.app_settings_value,
390 self.app_settings_type
390 self.app_settings_type
391 )
391 )
392
392
393
393
394 class RhodeCodeUi(Base, BaseModel):
394 class RhodeCodeUi(Base, BaseModel):
395 __tablename__ = 'rhodecode_ui'
395 __tablename__ = 'rhodecode_ui'
396 __table_args__ = (
396 __table_args__ = (
397 UniqueConstraint('ui_key'),
397 UniqueConstraint('ui_key'),
398 base_table_args
398 base_table_args
399 )
399 )
400
400
401 HOOK_REPO_SIZE = 'changegroup.repo_size'
401 HOOK_REPO_SIZE = 'changegroup.repo_size'
402 # HG
402 # HG
403 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
403 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
404 HOOK_PULL = 'outgoing.pull_logger'
404 HOOK_PULL = 'outgoing.pull_logger'
405 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
405 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
406 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
406 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
407 HOOK_PUSH = 'changegroup.push_logger'
407 HOOK_PUSH = 'changegroup.push_logger'
408 HOOK_PUSH_KEY = 'pushkey.key_push'
408 HOOK_PUSH_KEY = 'pushkey.key_push'
409
409
410 # TODO: johbo: Unify way how hooks are configured for git and hg,
410 # TODO: johbo: Unify way how hooks are configured for git and hg,
411 # git part is currently hardcoded.
411 # git part is currently hardcoded.
412
412
413 # SVN PATTERNS
413 # SVN PATTERNS
414 SVN_BRANCH_ID = 'vcs_svn_branch'
414 SVN_BRANCH_ID = 'vcs_svn_branch'
415 SVN_TAG_ID = 'vcs_svn_tag'
415 SVN_TAG_ID = 'vcs_svn_tag'
416
416
417 ui_id = Column(
417 ui_id = Column(
418 "ui_id", Integer(), nullable=False, unique=True, default=None,
418 "ui_id", Integer(), nullable=False, unique=True, default=None,
419 primary_key=True)
419 primary_key=True)
420 ui_section = Column(
420 ui_section = Column(
421 "ui_section", String(255), nullable=True, unique=None, default=None)
421 "ui_section", String(255), nullable=True, unique=None, default=None)
422 ui_key = Column(
422 ui_key = Column(
423 "ui_key", String(255), nullable=True, unique=None, default=None)
423 "ui_key", String(255), nullable=True, unique=None, default=None)
424 ui_value = Column(
424 ui_value = Column(
425 "ui_value", String(255), nullable=True, unique=None, default=None)
425 "ui_value", String(255), nullable=True, unique=None, default=None)
426 ui_active = Column(
426 ui_active = Column(
427 "ui_active", Boolean(), nullable=True, unique=None, default=True)
427 "ui_active", Boolean(), nullable=True, unique=None, default=True)
428
428
429 def __repr__(self):
429 def __repr__(self):
430 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
430 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
431 self.ui_key, self.ui_value)
431 self.ui_key, self.ui_value)
432
432
433
433
434 class RepoRhodeCodeSetting(Base, BaseModel):
434 class RepoRhodeCodeSetting(Base, BaseModel):
435 __tablename__ = 'repo_rhodecode_settings'
435 __tablename__ = 'repo_rhodecode_settings'
436 __table_args__ = (
436 __table_args__ = (
437 UniqueConstraint(
437 UniqueConstraint(
438 'app_settings_name', 'repository_id',
438 'app_settings_name', 'repository_id',
439 name='uq_repo_rhodecode_setting_name_repo_id'),
439 name='uq_repo_rhodecode_setting_name_repo_id'),
440 base_table_args
440 base_table_args
441 )
441 )
442
442
443 repository_id = Column(
443 repository_id = Column(
444 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
444 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
445 nullable=False)
445 nullable=False)
446 app_settings_id = Column(
446 app_settings_id = Column(
447 "app_settings_id", Integer(), nullable=False, unique=True,
447 "app_settings_id", Integer(), nullable=False, unique=True,
448 default=None, primary_key=True)
448 default=None, primary_key=True)
449 app_settings_name = Column(
449 app_settings_name = Column(
450 "app_settings_name", String(255), nullable=True, unique=None,
450 "app_settings_name", String(255), nullable=True, unique=None,
451 default=None)
451 default=None)
452 _app_settings_value = Column(
452 _app_settings_value = Column(
453 "app_settings_value", String(4096), nullable=True, unique=None,
453 "app_settings_value", String(4096), nullable=True, unique=None,
454 default=None)
454 default=None)
455 _app_settings_type = Column(
455 _app_settings_type = Column(
456 "app_settings_type", String(255), nullable=True, unique=None,
456 "app_settings_type", String(255), nullable=True, unique=None,
457 default=None)
457 default=None)
458
458
459 repository = relationship('Repository')
459 repository = relationship('Repository')
460
460
461 def __init__(self, repository_id, key='', val='', type='unicode'):
461 def __init__(self, repository_id, key='', val='', type='unicode'):
462 self.repository_id = repository_id
462 self.repository_id = repository_id
463 self.app_settings_name = key
463 self.app_settings_name = key
464 self.app_settings_type = type
464 self.app_settings_type = type
465 self.app_settings_value = val
465 self.app_settings_value = val
466
466
467 @validates('_app_settings_value')
467 @validates('_app_settings_value')
468 def validate_settings_value(self, key, val):
468 def validate_settings_value(self, key, val):
469 assert type(val) == unicode
469 assert type(val) == unicode
470 return val
470 return val
471
471
472 @hybrid_property
472 @hybrid_property
473 def app_settings_value(self):
473 def app_settings_value(self):
474 v = self._app_settings_value
474 v = self._app_settings_value
475 type_ = self.app_settings_type
475 type_ = self.app_settings_type
476 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
476 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
477 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
477 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
478 return converter(v)
478 return converter(v)
479
479
480 @app_settings_value.setter
480 @app_settings_value.setter
481 def app_settings_value(self, val):
481 def app_settings_value(self, val):
482 """
482 """
483 Setter that will always make sure we use unicode in app_settings_value
483 Setter that will always make sure we use unicode in app_settings_value
484
484
485 :param val:
485 :param val:
486 """
486 """
487 self._app_settings_value = safe_unicode(val)
487 self._app_settings_value = safe_unicode(val)
488
488
489 @hybrid_property
489 @hybrid_property
490 def app_settings_type(self):
490 def app_settings_type(self):
491 return self._app_settings_type
491 return self._app_settings_type
492
492
493 @app_settings_type.setter
493 @app_settings_type.setter
494 def app_settings_type(self, val):
494 def app_settings_type(self, val):
495 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
495 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
496 if val not in SETTINGS_TYPES:
496 if val not in SETTINGS_TYPES:
497 raise Exception('type must be one of %s got %s'
497 raise Exception('type must be one of %s got %s'
498 % (SETTINGS_TYPES.keys(), val))
498 % (SETTINGS_TYPES.keys(), val))
499 self._app_settings_type = val
499 self._app_settings_type = val
500
500
501 def __unicode__(self):
501 def __unicode__(self):
502 return u"<%s('%s:%s:%s[%s]')>" % (
502 return u"<%s('%s:%s:%s[%s]')>" % (
503 self.__class__.__name__, self.repository.repo_name,
503 self.__class__.__name__, self.repository.repo_name,
504 self.app_settings_name, self.app_settings_value,
504 self.app_settings_name, self.app_settings_value,
505 self.app_settings_type
505 self.app_settings_type
506 )
506 )
507
507
508
508
509 class RepoRhodeCodeUi(Base, BaseModel):
509 class RepoRhodeCodeUi(Base, BaseModel):
510 __tablename__ = 'repo_rhodecode_ui'
510 __tablename__ = 'repo_rhodecode_ui'
511 __table_args__ = (
511 __table_args__ = (
512 UniqueConstraint(
512 UniqueConstraint(
513 'repository_id', 'ui_section', 'ui_key',
513 'repository_id', 'ui_section', 'ui_key',
514 name='uq_repo_rhodecode_ui_repository_id_section_key'),
514 name='uq_repo_rhodecode_ui_repository_id_section_key'),
515 base_table_args
515 base_table_args
516 )
516 )
517
517
518 repository_id = Column(
518 repository_id = Column(
519 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
519 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
520 nullable=False)
520 nullable=False)
521 ui_id = Column(
521 ui_id = Column(
522 "ui_id", Integer(), nullable=False, unique=True, default=None,
522 "ui_id", Integer(), nullable=False, unique=True, default=None,
523 primary_key=True)
523 primary_key=True)
524 ui_section = Column(
524 ui_section = Column(
525 "ui_section", String(255), nullable=True, unique=None, default=None)
525 "ui_section", String(255), nullable=True, unique=None, default=None)
526 ui_key = Column(
526 ui_key = Column(
527 "ui_key", String(255), nullable=True, unique=None, default=None)
527 "ui_key", String(255), nullable=True, unique=None, default=None)
528 ui_value = Column(
528 ui_value = Column(
529 "ui_value", String(255), nullable=True, unique=None, default=None)
529 "ui_value", String(255), nullable=True, unique=None, default=None)
530 ui_active = Column(
530 ui_active = Column(
531 "ui_active", Boolean(), nullable=True, unique=None, default=True)
531 "ui_active", Boolean(), nullable=True, unique=None, default=True)
532
532
533 repository = relationship('Repository')
533 repository = relationship('Repository')
534
534
535 def __repr__(self):
535 def __repr__(self):
536 return '<%s[%s:%s]%s=>%s]>' % (
536 return '<%s[%s:%s]%s=>%s]>' % (
537 self.__class__.__name__, self.repository.repo_name,
537 self.__class__.__name__, self.repository.repo_name,
538 self.ui_section, self.ui_key, self.ui_value)
538 self.ui_section, self.ui_key, self.ui_value)
539
539
540
540
541 class User(Base, BaseModel):
541 class User(Base, BaseModel):
542 __tablename__ = 'users'
542 __tablename__ = 'users'
543 __table_args__ = (
543 __table_args__ = (
544 UniqueConstraint('username'), UniqueConstraint('email'),
544 UniqueConstraint('username'), UniqueConstraint('email'),
545 Index('u_username_idx', 'username'),
545 Index('u_username_idx', 'username'),
546 Index('u_email_idx', 'email'),
546 Index('u_email_idx', 'email'),
547 base_table_args
547 base_table_args
548 )
548 )
549
549
550 DEFAULT_USER = 'default'
550 DEFAULT_USER = 'default'
551 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
551 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
552 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
552 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
553
553
554 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
554 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
555 username = Column("username", String(255), nullable=True, unique=None, default=None)
555 username = Column("username", String(255), nullable=True, unique=None, default=None)
556 password = Column("password", String(255), nullable=True, unique=None, default=None)
556 password = Column("password", String(255), nullable=True, unique=None, default=None)
557 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
557 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
558 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
558 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
559 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
559 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
560 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
560 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
561 _email = Column("email", String(255), nullable=True, unique=None, default=None)
561 _email = Column("email", String(255), nullable=True, unique=None, default=None)
562 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
562 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
563 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
563 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
564
564
565 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
565 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
566 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
566 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
567 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
567 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
568 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
568 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
569 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
569 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
570 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
570 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
571
571
572 user_log = relationship('UserLog')
572 user_log = relationship('UserLog')
573 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
573 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
574
574
575 repositories = relationship('Repository')
575 repositories = relationship('Repository')
576 repository_groups = relationship('RepoGroup')
576 repository_groups = relationship('RepoGroup')
577 user_groups = relationship('UserGroup')
577 user_groups = relationship('UserGroup')
578
578
579 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
579 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
580 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
580 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
581
581
582 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
582 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
583 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
583 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
584 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
584 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
585
585
586 group_member = relationship('UserGroupMember', cascade='all')
586 group_member = relationship('UserGroupMember', cascade='all')
587
587
588 notifications = relationship('UserNotification', cascade='all')
588 notifications = relationship('UserNotification', cascade='all')
589 # notifications assigned to this user
589 # notifications assigned to this user
590 user_created_notifications = relationship('Notification', cascade='all')
590 user_created_notifications = relationship('Notification', cascade='all')
591 # comments created by this user
591 # comments created by this user
592 user_comments = relationship('ChangesetComment', cascade='all')
592 user_comments = relationship('ChangesetComment', cascade='all')
593 # user profile extra info
593 # user profile extra info
594 user_emails = relationship('UserEmailMap', cascade='all')
594 user_emails = relationship('UserEmailMap', cascade='all')
595 user_ip_map = relationship('UserIpMap', cascade='all')
595 user_ip_map = relationship('UserIpMap', cascade='all')
596 user_auth_tokens = relationship('UserApiKeys', cascade='all')
596 user_auth_tokens = relationship('UserApiKeys', cascade='all')
597 user_ssh_keys = relationship('UserSshKeys', cascade='all')
597 user_ssh_keys = relationship('UserSshKeys', cascade='all')
598
598
599 # gists
599 # gists
600 user_gists = relationship('Gist', cascade='all')
600 user_gists = relationship('Gist', cascade='all')
601 # user pull requests
601 # user pull requests
602 user_pull_requests = relationship('PullRequest', cascade='all')
602 user_pull_requests = relationship('PullRequest', cascade='all')
603 # external identities
603 # external identities
604 extenal_identities = relationship(
604 extenal_identities = relationship(
605 'ExternalIdentity',
605 'ExternalIdentity',
606 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
606 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
607 cascade='all')
607 cascade='all')
608 # review rules
608 # review rules
609 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
609 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
610
610
611 def __unicode__(self):
611 def __unicode__(self):
612 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
612 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
613 self.user_id, self.username)
613 self.user_id, self.username)
614
614
615 @hybrid_property
615 @hybrid_property
616 def email(self):
616 def email(self):
617 return self._email
617 return self._email
618
618
619 @email.setter
619 @email.setter
620 def email(self, val):
620 def email(self, val):
621 self._email = val.lower() if val else None
621 self._email = val.lower() if val else None
622
622
623 @hybrid_property
623 @hybrid_property
624 def first_name(self):
624 def first_name(self):
625 from rhodecode.lib import helpers as h
625 from rhodecode.lib import helpers as h
626 if self.name:
626 if self.name:
627 return h.escape(self.name)
627 return h.escape(self.name)
628 return self.name
628 return self.name
629
629
630 @hybrid_property
630 @hybrid_property
631 def last_name(self):
631 def last_name(self):
632 from rhodecode.lib import helpers as h
632 from rhodecode.lib import helpers as h
633 if self.lastname:
633 if self.lastname:
634 return h.escape(self.lastname)
634 return h.escape(self.lastname)
635 return self.lastname
635 return self.lastname
636
636
637 @hybrid_property
637 @hybrid_property
638 def api_key(self):
638 def api_key(self):
639 """
639 """
640 Fetch if exist an auth-token with role ALL connected to this user
640 Fetch if exist an auth-token with role ALL connected to this user
641 """
641 """
642 user_auth_token = UserApiKeys.query()\
642 user_auth_token = UserApiKeys.query()\
643 .filter(UserApiKeys.user_id == self.user_id)\
643 .filter(UserApiKeys.user_id == self.user_id)\
644 .filter(or_(UserApiKeys.expires == -1,
644 .filter(or_(UserApiKeys.expires == -1,
645 UserApiKeys.expires >= time.time()))\
645 UserApiKeys.expires >= time.time()))\
646 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
646 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
647 if user_auth_token:
647 if user_auth_token:
648 user_auth_token = user_auth_token.api_key
648 user_auth_token = user_auth_token.api_key
649
649
650 return user_auth_token
650 return user_auth_token
651
651
652 @api_key.setter
652 @api_key.setter
653 def api_key(self, val):
653 def api_key(self, val):
654 # don't allow to set API key this is deprecated for now
654 # don't allow to set API key this is deprecated for now
655 self._api_key = None
655 self._api_key = None
656
656
657 @property
657 @property
658 def reviewer_pull_requests(self):
658 def reviewer_pull_requests(self):
659 return PullRequestReviewers.query() \
659 return PullRequestReviewers.query() \
660 .options(joinedload(PullRequestReviewers.pull_request)) \
660 .options(joinedload(PullRequestReviewers.pull_request)) \
661 .filter(PullRequestReviewers.user_id == self.user_id) \
661 .filter(PullRequestReviewers.user_id == self.user_id) \
662 .all()
662 .all()
663
663
664 @property
664 @property
665 def firstname(self):
665 def firstname(self):
666 # alias for future
666 # alias for future
667 return self.name
667 return self.name
668
668
669 @property
669 @property
670 def emails(self):
670 def emails(self):
671 other = UserEmailMap.query()\
671 other = UserEmailMap.query()\
672 .filter(UserEmailMap.user == self) \
672 .filter(UserEmailMap.user == self) \
673 .order_by(UserEmailMap.email_id.asc()) \
673 .order_by(UserEmailMap.email_id.asc()) \
674 .all()
674 .all()
675 return [self.email] + [x.email for x in other]
675 return [self.email] + [x.email for x in other]
676
676
677 @property
677 @property
678 def auth_tokens(self):
678 def auth_tokens(self):
679 auth_tokens = self.get_auth_tokens()
679 auth_tokens = self.get_auth_tokens()
680 return [x.api_key for x in auth_tokens]
680 return [x.api_key for x in auth_tokens]
681
681
682 def get_auth_tokens(self):
682 def get_auth_tokens(self):
683 return UserApiKeys.query()\
683 return UserApiKeys.query()\
684 .filter(UserApiKeys.user == self)\
684 .filter(UserApiKeys.user == self)\
685 .order_by(UserApiKeys.user_api_key_id.asc())\
685 .order_by(UserApiKeys.user_api_key_id.asc())\
686 .all()
686 .all()
687
687
688 @LazyProperty
688 @LazyProperty
689 def feed_token(self):
689 def feed_token(self):
690 return self.get_feed_token()
690 return self.get_feed_token()
691
691
692 def get_feed_token(self, cache=True):
692 def get_feed_token(self, cache=True):
693 feed_tokens = UserApiKeys.query()\
693 feed_tokens = UserApiKeys.query()\
694 .filter(UserApiKeys.user == self)\
694 .filter(UserApiKeys.user == self)\
695 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
695 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
696 if cache:
696 if cache:
697 feed_tokens = feed_tokens.options(
697 feed_tokens = feed_tokens.options(
698 FromCache("sql_cache_short", "get_user_feed_token_%s" % self.user_id))
698 FromCache("sql_cache_short", "get_user_feed_token_%s" % self.user_id))
699
699
700 feed_tokens = feed_tokens.all()
700 feed_tokens = feed_tokens.all()
701 if feed_tokens:
701 if feed_tokens:
702 return feed_tokens[0].api_key
702 return feed_tokens[0].api_key
703 return 'NO_FEED_TOKEN_AVAILABLE'
703 return 'NO_FEED_TOKEN_AVAILABLE'
704
704
705 @classmethod
705 @classmethod
706 def get(cls, user_id, cache=False):
706 def get(cls, user_id, cache=False):
707 if not user_id:
707 if not user_id:
708 return
708 return
709
709
710 user = cls.query()
710 user = cls.query()
711 if cache:
711 if cache:
712 user = user.options(
712 user = user.options(
713 FromCache("sql_cache_short", "get_users_%s" % user_id))
713 FromCache("sql_cache_short", "get_users_%s" % user_id))
714 return user.get(user_id)
714 return user.get(user_id)
715
715
716 @classmethod
716 @classmethod
717 def extra_valid_auth_tokens(cls, user, role=None):
717 def extra_valid_auth_tokens(cls, user, role=None):
718 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
718 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
719 .filter(or_(UserApiKeys.expires == -1,
719 .filter(or_(UserApiKeys.expires == -1,
720 UserApiKeys.expires >= time.time()))
720 UserApiKeys.expires >= time.time()))
721 if role:
721 if role:
722 tokens = tokens.filter(or_(UserApiKeys.role == role,
722 tokens = tokens.filter(or_(UserApiKeys.role == role,
723 UserApiKeys.role == UserApiKeys.ROLE_ALL))
723 UserApiKeys.role == UserApiKeys.ROLE_ALL))
724 return tokens.all()
724 return tokens.all()
725
725
726 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
726 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
727 from rhodecode.lib import auth
727 from rhodecode.lib import auth
728
728
729 log.debug('Trying to authenticate user: %s via auth-token, '
729 log.debug('Trying to authenticate user: %s via auth-token, '
730 'and roles: %s', self, roles)
730 'and roles: %s', self, roles)
731
731
732 if not auth_token:
732 if not auth_token:
733 return False
733 return False
734
734
735 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
735 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
736 tokens_q = UserApiKeys.query()\
736 tokens_q = UserApiKeys.query()\
737 .filter(UserApiKeys.user_id == self.user_id)\
737 .filter(UserApiKeys.user_id == self.user_id)\
738 .filter(or_(UserApiKeys.expires == -1,
738 .filter(or_(UserApiKeys.expires == -1,
739 UserApiKeys.expires >= time.time()))
739 UserApiKeys.expires >= time.time()))
740
740
741 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
741 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
742
742
743 crypto_backend = auth.crypto_backend()
743 crypto_backend = auth.crypto_backend()
744 enc_token_map = {}
744 enc_token_map = {}
745 plain_token_map = {}
745 plain_token_map = {}
746 for token in tokens_q:
746 for token in tokens_q:
747 if token.api_key.startswith(crypto_backend.ENC_PREF):
747 if token.api_key.startswith(crypto_backend.ENC_PREF):
748 enc_token_map[token.api_key] = token
748 enc_token_map[token.api_key] = token
749 else:
749 else:
750 plain_token_map[token.api_key] = token
750 plain_token_map[token.api_key] = token
751 log.debug(
751 log.debug(
752 'Found %s plain and %s encrypted user tokens to check for authentication',
752 'Found %s plain and %s encrypted user tokens to check for authentication',
753 len(plain_token_map), len(enc_token_map))
753 len(plain_token_map), len(enc_token_map))
754
754
755 # plain token match comes first
755 # plain token match comes first
756 match = plain_token_map.get(auth_token)
756 match = plain_token_map.get(auth_token)
757
757
758 # check encrypted tokens now
758 # check encrypted tokens now
759 if not match:
759 if not match:
760 for token_hash, token in enc_token_map.items():
760 for token_hash, token in enc_token_map.items():
761 # NOTE(marcink): this is expensive to calculate, but most secure
761 # NOTE(marcink): this is expensive to calculate, but most secure
762 if crypto_backend.hash_check(auth_token, token_hash):
762 if crypto_backend.hash_check(auth_token, token_hash):
763 match = token
763 match = token
764 break
764 break
765
765
766 if match:
766 if match:
767 log.debug('Found matching token %s', match)
767 log.debug('Found matching token %s', match)
768 if match.repo_id:
768 if match.repo_id:
769 log.debug('Found scope, checking for scope match of token %s', match)
769 log.debug('Found scope, checking for scope match of token %s', match)
770 if match.repo_id == scope_repo_id:
770 if match.repo_id == scope_repo_id:
771 return True
771 return True
772 else:
772 else:
773 log.debug(
773 log.debug(
774 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
774 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
775 'and calling scope is:%s, skipping further checks',
775 'and calling scope is:%s, skipping further checks',
776 match.repo, scope_repo_id)
776 match.repo, scope_repo_id)
777 return False
777 return False
778 else:
778 else:
779 return True
779 return True
780
780
781 return False
781 return False
782
782
783 @property
783 @property
784 def ip_addresses(self):
784 def ip_addresses(self):
785 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
785 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
786 return [x.ip_addr for x in ret]
786 return [x.ip_addr for x in ret]
787
787
788 @property
788 @property
789 def username_and_name(self):
789 def username_and_name(self):
790 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
790 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
791
791
792 @property
792 @property
793 def username_or_name_or_email(self):
793 def username_or_name_or_email(self):
794 full_name = self.full_name if self.full_name is not ' ' else None
794 full_name = self.full_name if self.full_name is not ' ' else None
795 return self.username or full_name or self.email
795 return self.username or full_name or self.email
796
796
797 @property
797 @property
798 def full_name(self):
798 def full_name(self):
799 return '%s %s' % (self.first_name, self.last_name)
799 return '%s %s' % (self.first_name, self.last_name)
800
800
801 @property
801 @property
802 def full_name_or_username(self):
802 def full_name_or_username(self):
803 return ('%s %s' % (self.first_name, self.last_name)
803 return ('%s %s' % (self.first_name, self.last_name)
804 if (self.first_name and self.last_name) else self.username)
804 if (self.first_name and self.last_name) else self.username)
805
805
806 @property
806 @property
807 def full_contact(self):
807 def full_contact(self):
808 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
808 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
809
809
810 @property
810 @property
811 def short_contact(self):
811 def short_contact(self):
812 return '%s %s' % (self.first_name, self.last_name)
812 return '%s %s' % (self.first_name, self.last_name)
813
813
814 @property
814 @property
815 def is_admin(self):
815 def is_admin(self):
816 return self.admin
816 return self.admin
817
817
818 def AuthUser(self, **kwargs):
818 def AuthUser(self, **kwargs):
819 """
819 """
820 Returns instance of AuthUser for this user
820 Returns instance of AuthUser for this user
821 """
821 """
822 from rhodecode.lib.auth import AuthUser
822 from rhodecode.lib.auth import AuthUser
823 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
823 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
824
824
825 @hybrid_property
825 @hybrid_property
826 def user_data(self):
826 def user_data(self):
827 if not self._user_data:
827 if not self._user_data:
828 return {}
828 return {}
829
829
830 try:
830 try:
831 return json.loads(self._user_data)
831 return json.loads(self._user_data)
832 except TypeError:
832 except TypeError:
833 return {}
833 return {}
834
834
835 @user_data.setter
835 @user_data.setter
836 def user_data(self, val):
836 def user_data(self, val):
837 if not isinstance(val, dict):
837 if not isinstance(val, dict):
838 raise Exception('user_data must be dict, got %s' % type(val))
838 raise Exception('user_data must be dict, got %s' % type(val))
839 try:
839 try:
840 self._user_data = json.dumps(val)
840 self._user_data = json.dumps(val)
841 except Exception:
841 except Exception:
842 log.error(traceback.format_exc())
842 log.error(traceback.format_exc())
843
843
844 @classmethod
844 @classmethod
845 def get_by_username(cls, username, case_insensitive=False,
845 def get_by_username(cls, username, case_insensitive=False,
846 cache=False, identity_cache=False):
846 cache=False, identity_cache=False):
847 session = Session()
847 session = Session()
848
848
849 if case_insensitive:
849 if case_insensitive:
850 q = cls.query().filter(
850 q = cls.query().filter(
851 func.lower(cls.username) == func.lower(username))
851 func.lower(cls.username) == func.lower(username))
852 else:
852 else:
853 q = cls.query().filter(cls.username == username)
853 q = cls.query().filter(cls.username == username)
854
854
855 if cache:
855 if cache:
856 if identity_cache:
856 if identity_cache:
857 val = cls.identity_cache(session, 'username', username)
857 val = cls.identity_cache(session, 'username', username)
858 if val:
858 if val:
859 return val
859 return val
860 else:
860 else:
861 cache_key = "get_user_by_name_%s" % _hash_key(username)
861 cache_key = "get_user_by_name_%s" % _hash_key(username)
862 q = q.options(
862 q = q.options(
863 FromCache("sql_cache_short", cache_key))
863 FromCache("sql_cache_short", cache_key))
864
864
865 return q.scalar()
865 return q.scalar()
866
866
867 @classmethod
867 @classmethod
868 def get_by_auth_token(cls, auth_token, cache=False):
868 def get_by_auth_token(cls, auth_token, cache=False):
869 q = UserApiKeys.query()\
869 q = UserApiKeys.query()\
870 .filter(UserApiKeys.api_key == auth_token)\
870 .filter(UserApiKeys.api_key == auth_token)\
871 .filter(or_(UserApiKeys.expires == -1,
871 .filter(or_(UserApiKeys.expires == -1,
872 UserApiKeys.expires >= time.time()))
872 UserApiKeys.expires >= time.time()))
873 if cache:
873 if cache:
874 q = q.options(
874 q = q.options(
875 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
875 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
876
876
877 match = q.first()
877 match = q.first()
878 if match:
878 if match:
879 return match.user
879 return match.user
880
880
881 @classmethod
881 @classmethod
882 def get_by_email(cls, email, case_insensitive=False, cache=False):
882 def get_by_email(cls, email, case_insensitive=False, cache=False):
883
883
884 if case_insensitive:
884 if case_insensitive:
885 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
885 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
886
886
887 else:
887 else:
888 q = cls.query().filter(cls.email == email)
888 q = cls.query().filter(cls.email == email)
889
889
890 email_key = _hash_key(email)
890 email_key = _hash_key(email)
891 if cache:
891 if cache:
892 q = q.options(
892 q = q.options(
893 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
893 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
894
894
895 ret = q.scalar()
895 ret = q.scalar()
896 if ret is None:
896 if ret is None:
897 q = UserEmailMap.query()
897 q = UserEmailMap.query()
898 # try fetching in alternate email map
898 # try fetching in alternate email map
899 if case_insensitive:
899 if case_insensitive:
900 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
900 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
901 else:
901 else:
902 q = q.filter(UserEmailMap.email == email)
902 q = q.filter(UserEmailMap.email == email)
903 q = q.options(joinedload(UserEmailMap.user))
903 q = q.options(joinedload(UserEmailMap.user))
904 if cache:
904 if cache:
905 q = q.options(
905 q = q.options(
906 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
906 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
907 ret = getattr(q.scalar(), 'user', None)
907 ret = getattr(q.scalar(), 'user', None)
908
908
909 return ret
909 return ret
910
910
911 @classmethod
911 @classmethod
912 def get_from_cs_author(cls, author):
912 def get_from_cs_author(cls, author):
913 """
913 """
914 Tries to get User objects out of commit author string
914 Tries to get User objects out of commit author string
915
915
916 :param author:
916 :param author:
917 """
917 """
918 from rhodecode.lib.helpers import email, author_name
918 from rhodecode.lib.helpers import email, author_name
919 # Valid email in the attribute passed, see if they're in the system
919 # Valid email in the attribute passed, see if they're in the system
920 _email = email(author)
920 _email = email(author)
921 if _email:
921 if _email:
922 user = cls.get_by_email(_email, case_insensitive=True)
922 user = cls.get_by_email(_email, case_insensitive=True)
923 if user:
923 if user:
924 return user
924 return user
925 # Maybe we can match by username?
925 # Maybe we can match by username?
926 _author = author_name(author)
926 _author = author_name(author)
927 user = cls.get_by_username(_author, case_insensitive=True)
927 user = cls.get_by_username(_author, case_insensitive=True)
928 if user:
928 if user:
929 return user
929 return user
930
930
931 def update_userdata(self, **kwargs):
931 def update_userdata(self, **kwargs):
932 usr = self
932 usr = self
933 old = usr.user_data
933 old = usr.user_data
934 old.update(**kwargs)
934 old.update(**kwargs)
935 usr.user_data = old
935 usr.user_data = old
936 Session().add(usr)
936 Session().add(usr)
937 log.debug('updated userdata with ', kwargs)
937 log.debug('updated userdata with ', kwargs)
938
938
939 def update_lastlogin(self):
939 def update_lastlogin(self):
940 """Update user lastlogin"""
940 """Update user lastlogin"""
941 self.last_login = datetime.datetime.now()
941 self.last_login = datetime.datetime.now()
942 Session().add(self)
942 Session().add(self)
943 log.debug('updated user %s lastlogin', self.username)
943 log.debug('updated user %s lastlogin', self.username)
944
944
945 def update_password(self, new_password):
945 def update_password(self, new_password):
946 from rhodecode.lib.auth import get_crypt_password
946 from rhodecode.lib.auth import get_crypt_password
947
947
948 self.password = get_crypt_password(new_password)
948 self.password = get_crypt_password(new_password)
949 Session().add(self)
949 Session().add(self)
950
950
951 @classmethod
951 @classmethod
952 def get_first_super_admin(cls):
952 def get_first_super_admin(cls):
953 user = User.query()\
953 user = User.query()\
954 .filter(User.admin == true()) \
954 .filter(User.admin == true()) \
955 .order_by(User.user_id.asc()) \
955 .order_by(User.user_id.asc()) \
956 .first()
956 .first()
957
957
958 if user is None:
958 if user is None:
959 raise Exception('FATAL: Missing administrative account!')
959 raise Exception('FATAL: Missing administrative account!')
960 return user
960 return user
961
961
962 @classmethod
962 @classmethod
963 def get_all_super_admins(cls, only_active=False):
963 def get_all_super_admins(cls, only_active=False):
964 """
964 """
965 Returns all admin accounts sorted by username
965 Returns all admin accounts sorted by username
966 """
966 """
967 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
967 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
968 if only_active:
968 if only_active:
969 qry = qry.filter(User.active == true())
969 qry = qry.filter(User.active == true())
970 return qry.all()
970 return qry.all()
971
971
972 @classmethod
972 @classmethod
973 def get_default_user(cls, cache=False, refresh=False):
973 def get_default_user(cls, cache=False, refresh=False):
974 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
974 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
975 if user is None:
975 if user is None:
976 raise Exception('FATAL: Missing default account!')
976 raise Exception('FATAL: Missing default account!')
977 if refresh:
977 if refresh:
978 # The default user might be based on outdated state which
978 # The default user might be based on outdated state which
979 # has been loaded from the cache.
979 # has been loaded from the cache.
980 # A call to refresh() ensures that the
980 # A call to refresh() ensures that the
981 # latest state from the database is used.
981 # latest state from the database is used.
982 Session().refresh(user)
982 Session().refresh(user)
983 return user
983 return user
984
984
985 def _get_default_perms(self, user, suffix=''):
985 def _get_default_perms(self, user, suffix=''):
986 from rhodecode.model.permission import PermissionModel
986 from rhodecode.model.permission import PermissionModel
987 return PermissionModel().get_default_perms(user.user_perms, suffix)
987 return PermissionModel().get_default_perms(user.user_perms, suffix)
988
988
989 def get_default_perms(self, suffix=''):
989 def get_default_perms(self, suffix=''):
990 return self._get_default_perms(self, suffix)
990 return self._get_default_perms(self, suffix)
991
991
992 def get_api_data(self, include_secrets=False, details='full'):
992 def get_api_data(self, include_secrets=False, details='full'):
993 """
993 """
994 Common function for generating user related data for API
994 Common function for generating user related data for API
995
995
996 :param include_secrets: By default secrets in the API data will be replaced
996 :param include_secrets: By default secrets in the API data will be replaced
997 by a placeholder value to prevent exposing this data by accident. In case
997 by a placeholder value to prevent exposing this data by accident. In case
998 this data shall be exposed, set this flag to ``True``.
998 this data shall be exposed, set this flag to ``True``.
999
999
1000 :param details: details can be 'basic|full' basic gives only a subset of
1000 :param details: details can be 'basic|full' basic gives only a subset of
1001 the available user information that includes user_id, name and emails.
1001 the available user information that includes user_id, name and emails.
1002 """
1002 """
1003 user = self
1003 user = self
1004 user_data = self.user_data
1004 user_data = self.user_data
1005 data = {
1005 data = {
1006 'user_id': user.user_id,
1006 'user_id': user.user_id,
1007 'username': user.username,
1007 'username': user.username,
1008 'firstname': user.name,
1008 'firstname': user.name,
1009 'lastname': user.lastname,
1009 'lastname': user.lastname,
1010 'email': user.email,
1010 'email': user.email,
1011 'emails': user.emails,
1011 'emails': user.emails,
1012 }
1012 }
1013 if details == 'basic':
1013 if details == 'basic':
1014 return data
1014 return data
1015
1015
1016 auth_token_length = 40
1016 auth_token_length = 40
1017 auth_token_replacement = '*' * auth_token_length
1017 auth_token_replacement = '*' * auth_token_length
1018
1018
1019 extras = {
1019 extras = {
1020 'auth_tokens': [auth_token_replacement],
1020 'auth_tokens': [auth_token_replacement],
1021 'active': user.active,
1021 'active': user.active,
1022 'admin': user.admin,
1022 'admin': user.admin,
1023 'extern_type': user.extern_type,
1023 'extern_type': user.extern_type,
1024 'extern_name': user.extern_name,
1024 'extern_name': user.extern_name,
1025 'last_login': user.last_login,
1025 'last_login': user.last_login,
1026 'last_activity': user.last_activity,
1026 'last_activity': user.last_activity,
1027 'ip_addresses': user.ip_addresses,
1027 'ip_addresses': user.ip_addresses,
1028 'language': user_data.get('language')
1028 'language': user_data.get('language')
1029 }
1029 }
1030 data.update(extras)
1030 data.update(extras)
1031
1031
1032 if include_secrets:
1032 if include_secrets:
1033 data['auth_tokens'] = user.auth_tokens
1033 data['auth_tokens'] = user.auth_tokens
1034 return data
1034 return data
1035
1035
1036 def __json__(self):
1036 def __json__(self):
1037 data = {
1037 data = {
1038 'full_name': self.full_name,
1038 'full_name': self.full_name,
1039 'full_name_or_username': self.full_name_or_username,
1039 'full_name_or_username': self.full_name_or_username,
1040 'short_contact': self.short_contact,
1040 'short_contact': self.short_contact,
1041 'full_contact': self.full_contact,
1041 'full_contact': self.full_contact,
1042 }
1042 }
1043 data.update(self.get_api_data())
1043 data.update(self.get_api_data())
1044 return data
1044 return data
1045
1045
1046
1046
1047 class UserApiKeys(Base, BaseModel):
1047 class UserApiKeys(Base, BaseModel):
1048 __tablename__ = 'user_api_keys'
1048 __tablename__ = 'user_api_keys'
1049 __table_args__ = (
1049 __table_args__ = (
1050 Index('uak_api_key_idx', 'api_key', unique=True),
1050 Index('uak_api_key_idx', 'api_key', unique=True),
1051 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1051 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1052 base_table_args
1052 base_table_args
1053 )
1053 )
1054 __mapper_args__ = {}
1054 __mapper_args__ = {}
1055
1055
1056 # ApiKey role
1056 # ApiKey role
1057 ROLE_ALL = 'token_role_all'
1057 ROLE_ALL = 'token_role_all'
1058 ROLE_HTTP = 'token_role_http'
1058 ROLE_HTTP = 'token_role_http'
1059 ROLE_VCS = 'token_role_vcs'
1059 ROLE_VCS = 'token_role_vcs'
1060 ROLE_API = 'token_role_api'
1060 ROLE_API = 'token_role_api'
1061 ROLE_FEED = 'token_role_feed'
1061 ROLE_FEED = 'token_role_feed'
1062 ROLE_PASSWORD_RESET = 'token_password_reset'
1062 ROLE_PASSWORD_RESET = 'token_password_reset'
1063
1063
1064 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
1064 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
1065
1065
1066 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1066 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1067 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1067 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1068 api_key = Column("api_key", String(255), nullable=False, unique=True)
1068 api_key = Column("api_key", String(255), nullable=False, unique=True)
1069 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1069 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1070 expires = Column('expires', Float(53), nullable=False)
1070 expires = Column('expires', Float(53), nullable=False)
1071 role = Column('role', String(255), nullable=True)
1071 role = Column('role', String(255), nullable=True)
1072 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1072 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1073
1073
1074 # scope columns
1074 # scope columns
1075 repo_id = Column(
1075 repo_id = Column(
1076 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1076 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1077 nullable=True, unique=None, default=None)
1077 nullable=True, unique=None, default=None)
1078 repo = relationship('Repository', lazy='joined')
1078 repo = relationship('Repository', lazy='joined')
1079
1079
1080 repo_group_id = Column(
1080 repo_group_id = Column(
1081 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1081 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1082 nullable=True, unique=None, default=None)
1082 nullable=True, unique=None, default=None)
1083 repo_group = relationship('RepoGroup', lazy='joined')
1083 repo_group = relationship('RepoGroup', lazy='joined')
1084
1084
1085 user = relationship('User', lazy='joined')
1085 user = relationship('User', lazy='joined')
1086
1086
1087 def __unicode__(self):
1087 def __unicode__(self):
1088 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1088 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1089
1089
1090 def __json__(self):
1090 def __json__(self):
1091 data = {
1091 data = {
1092 'auth_token': self.api_key,
1092 'auth_token': self.api_key,
1093 'role': self.role,
1093 'role': self.role,
1094 'scope': self.scope_humanized,
1094 'scope': self.scope_humanized,
1095 'expired': self.expired
1095 'expired': self.expired
1096 }
1096 }
1097 return data
1097 return data
1098
1098
1099 def get_api_data(self, include_secrets=False):
1099 def get_api_data(self, include_secrets=False):
1100 data = self.__json__()
1100 data = self.__json__()
1101 if include_secrets:
1101 if include_secrets:
1102 return data
1102 return data
1103 else:
1103 else:
1104 data['auth_token'] = self.token_obfuscated
1104 data['auth_token'] = self.token_obfuscated
1105 return data
1105 return data
1106
1106
1107 @hybrid_property
1107 @hybrid_property
1108 def description_safe(self):
1108 def description_safe(self):
1109 from rhodecode.lib import helpers as h
1109 from rhodecode.lib import helpers as h
1110 return h.escape(self.description)
1110 return h.escape(self.description)
1111
1111
1112 @property
1112 @property
1113 def expired(self):
1113 def expired(self):
1114 if self.expires == -1:
1114 if self.expires == -1:
1115 return False
1115 return False
1116 return time.time() > self.expires
1116 return time.time() > self.expires
1117
1117
1118 @classmethod
1118 @classmethod
1119 def _get_role_name(cls, role):
1119 def _get_role_name(cls, role):
1120 return {
1120 return {
1121 cls.ROLE_ALL: _('all'),
1121 cls.ROLE_ALL: _('all'),
1122 cls.ROLE_HTTP: _('http/web interface'),
1122 cls.ROLE_HTTP: _('http/web interface'),
1123 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1123 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1124 cls.ROLE_API: _('api calls'),
1124 cls.ROLE_API: _('api calls'),
1125 cls.ROLE_FEED: _('feed access'),
1125 cls.ROLE_FEED: _('feed access'),
1126 }.get(role, role)
1126 }.get(role, role)
1127
1127
1128 @property
1128 @property
1129 def role_humanized(self):
1129 def role_humanized(self):
1130 return self._get_role_name(self.role)
1130 return self._get_role_name(self.role)
1131
1131
1132 def _get_scope(self):
1132 def _get_scope(self):
1133 if self.repo:
1133 if self.repo:
1134 return 'Repository: {}'.format(self.repo.repo_name)
1134 return 'Repository: {}'.format(self.repo.repo_name)
1135 if self.repo_group:
1135 if self.repo_group:
1136 return 'RepositoryGroup: {} (recursive)'.format(self.repo_group.group_name)
1136 return 'RepositoryGroup: {} (recursive)'.format(self.repo_group.group_name)
1137 return 'Global'
1137 return 'Global'
1138
1138
1139 @property
1139 @property
1140 def scope_humanized(self):
1140 def scope_humanized(self):
1141 return self._get_scope()
1141 return self._get_scope()
1142
1142
1143 @property
1143 @property
1144 def token_obfuscated(self):
1144 def token_obfuscated(self):
1145 if self.api_key:
1145 if self.api_key:
1146 return self.api_key[:4] + "****"
1146 return self.api_key[:4] + "****"
1147
1147
1148
1148
1149 class UserEmailMap(Base, BaseModel):
1149 class UserEmailMap(Base, BaseModel):
1150 __tablename__ = 'user_email_map'
1150 __tablename__ = 'user_email_map'
1151 __table_args__ = (
1151 __table_args__ = (
1152 Index('uem_email_idx', 'email'),
1152 Index('uem_email_idx', 'email'),
1153 UniqueConstraint('email'),
1153 UniqueConstraint('email'),
1154 base_table_args
1154 base_table_args
1155 )
1155 )
1156 __mapper_args__ = {}
1156 __mapper_args__ = {}
1157
1157
1158 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1158 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1159 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1159 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1160 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1160 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1161 user = relationship('User', lazy='joined')
1161 user = relationship('User', lazy='joined')
1162
1162
1163 @validates('_email')
1163 @validates('_email')
1164 def validate_email(self, key, email):
1164 def validate_email(self, key, email):
1165 # check if this email is not main one
1165 # check if this email is not main one
1166 main_email = Session().query(User).filter(User.email == email).scalar()
1166 main_email = Session().query(User).filter(User.email == email).scalar()
1167 if main_email is not None:
1167 if main_email is not None:
1168 raise AttributeError('email %s is present is user table' % email)
1168 raise AttributeError('email %s is present is user table' % email)
1169 return email
1169 return email
1170
1170
1171 @hybrid_property
1171 @hybrid_property
1172 def email(self):
1172 def email(self):
1173 return self._email
1173 return self._email
1174
1174
1175 @email.setter
1175 @email.setter
1176 def email(self, val):
1176 def email(self, val):
1177 self._email = val.lower() if val else None
1177 self._email = val.lower() if val else None
1178
1178
1179
1179
1180 class UserIpMap(Base, BaseModel):
1180 class UserIpMap(Base, BaseModel):
1181 __tablename__ = 'user_ip_map'
1181 __tablename__ = 'user_ip_map'
1182 __table_args__ = (
1182 __table_args__ = (
1183 UniqueConstraint('user_id', 'ip_addr'),
1183 UniqueConstraint('user_id', 'ip_addr'),
1184 base_table_args
1184 base_table_args
1185 )
1185 )
1186 __mapper_args__ = {}
1186 __mapper_args__ = {}
1187
1187
1188 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1188 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1189 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1189 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1190 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1190 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1191 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1191 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1192 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1192 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1193 user = relationship('User', lazy='joined')
1193 user = relationship('User', lazy='joined')
1194
1194
1195 @hybrid_property
1195 @hybrid_property
1196 def description_safe(self):
1196 def description_safe(self):
1197 from rhodecode.lib import helpers as h
1197 from rhodecode.lib import helpers as h
1198 return h.escape(self.description)
1198 return h.escape(self.description)
1199
1199
1200 @classmethod
1200 @classmethod
1201 def _get_ip_range(cls, ip_addr):
1201 def _get_ip_range(cls, ip_addr):
1202 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1202 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1203 return [str(net.network_address), str(net.broadcast_address)]
1203 return [str(net.network_address), str(net.broadcast_address)]
1204
1204
1205 def __json__(self):
1205 def __json__(self):
1206 return {
1206 return {
1207 'ip_addr': self.ip_addr,
1207 'ip_addr': self.ip_addr,
1208 'ip_range': self._get_ip_range(self.ip_addr),
1208 'ip_range': self._get_ip_range(self.ip_addr),
1209 }
1209 }
1210
1210
1211 def __unicode__(self):
1211 def __unicode__(self):
1212 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1212 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1213 self.user_id, self.ip_addr)
1213 self.user_id, self.ip_addr)
1214
1214
1215
1215
1216 class UserSshKeys(Base, BaseModel):
1216 class UserSshKeys(Base, BaseModel):
1217 __tablename__ = 'user_ssh_keys'
1217 __tablename__ = 'user_ssh_keys'
1218 __table_args__ = (
1218 __table_args__ = (
1219 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1219 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1220
1220
1221 UniqueConstraint('ssh_key_fingerprint'),
1221 UniqueConstraint('ssh_key_fingerprint'),
1222
1222
1223 base_table_args
1223 base_table_args
1224 )
1224 )
1225 __mapper_args__ = {}
1225 __mapper_args__ = {}
1226
1226
1227 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1227 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1228 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1228 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1229 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1229 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1230
1230
1231 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1231 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1232
1232
1233 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1233 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1234 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1234 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1235 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1235 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1236
1236
1237 user = relationship('User', lazy='joined')
1237 user = relationship('User', lazy='joined')
1238
1238
1239 def __json__(self):
1239 def __json__(self):
1240 data = {
1240 data = {
1241 'ssh_fingerprint': self.ssh_key_fingerprint,
1241 'ssh_fingerprint': self.ssh_key_fingerprint,
1242 'description': self.description,
1242 'description': self.description,
1243 'created_on': self.created_on
1243 'created_on': self.created_on
1244 }
1244 }
1245 return data
1245 return data
1246
1246
1247 def get_api_data(self):
1247 def get_api_data(self):
1248 data = self.__json__()
1248 data = self.__json__()
1249 return data
1249 return data
1250
1250
1251
1251
1252 class UserLog(Base, BaseModel):
1252 class UserLog(Base, BaseModel):
1253 __tablename__ = 'user_logs'
1253 __tablename__ = 'user_logs'
1254 __table_args__ = (
1254 __table_args__ = (
1255 base_table_args,
1255 base_table_args,
1256 )
1256 )
1257
1257
1258 VERSION_1 = 'v1'
1258 VERSION_1 = 'v1'
1259 VERSION_2 = 'v2'
1259 VERSION_2 = 'v2'
1260 VERSIONS = [VERSION_1, VERSION_2]
1260 VERSIONS = [VERSION_1, VERSION_2]
1261
1261
1262 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1262 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1263 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1263 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1264 username = Column("username", String(255), nullable=True, unique=None, default=None)
1264 username = Column("username", String(255), nullable=True, unique=None, default=None)
1265 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1265 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1266 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1266 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1267 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1267 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1268 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1268 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1269 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1269 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1270
1270
1271 version = Column("version", String(255), nullable=True, default=VERSION_1)
1271 version = Column("version", String(255), nullable=True, default=VERSION_1)
1272 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1272 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1273 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1273 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1274
1274
1275 def __unicode__(self):
1275 def __unicode__(self):
1276 return u"<%s('id:%s:%s')>" % (
1276 return u"<%s('id:%s:%s')>" % (
1277 self.__class__.__name__, self.repository_name, self.action)
1277 self.__class__.__name__, self.repository_name, self.action)
1278
1278
1279 def __json__(self):
1279 def __json__(self):
1280 return {
1280 return {
1281 'user_id': self.user_id,
1281 'user_id': self.user_id,
1282 'username': self.username,
1282 'username': self.username,
1283 'repository_id': self.repository_id,
1283 'repository_id': self.repository_id,
1284 'repository_name': self.repository_name,
1284 'repository_name': self.repository_name,
1285 'user_ip': self.user_ip,
1285 'user_ip': self.user_ip,
1286 'action_date': self.action_date,
1286 'action_date': self.action_date,
1287 'action': self.action,
1287 'action': self.action,
1288 }
1288 }
1289
1289
1290 @hybrid_property
1290 @hybrid_property
1291 def entry_id(self):
1291 def entry_id(self):
1292 return self.user_log_id
1292 return self.user_log_id
1293
1293
1294 @property
1294 @property
1295 def action_as_day(self):
1295 def action_as_day(self):
1296 return datetime.date(*self.action_date.timetuple()[:3])
1296 return datetime.date(*self.action_date.timetuple()[:3])
1297
1297
1298 user = relationship('User')
1298 user = relationship('User')
1299 repository = relationship('Repository', cascade='')
1299 repository = relationship('Repository', cascade='')
1300
1300
1301
1301
1302 class UserGroup(Base, BaseModel):
1302 class UserGroup(Base, BaseModel):
1303 __tablename__ = 'users_groups'
1303 __tablename__ = 'users_groups'
1304 __table_args__ = (
1304 __table_args__ = (
1305 base_table_args,
1305 base_table_args,
1306 )
1306 )
1307
1307
1308 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1308 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1309 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1309 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1310 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1310 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1311 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1311 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1312 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1312 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1313 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1313 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1314 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1314 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1315 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1315 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1316
1316
1317 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1317 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1318 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1318 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1319 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1319 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1320 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1320 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1321 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1321 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1322 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1322 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1323
1323
1324 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1324 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1325 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1325 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1326
1326
1327 @classmethod
1327 @classmethod
1328 def _load_group_data(cls, column):
1328 def _load_group_data(cls, column):
1329 if not column:
1329 if not column:
1330 return {}
1330 return {}
1331
1331
1332 try:
1332 try:
1333 return json.loads(column) or {}
1333 return json.loads(column) or {}
1334 except TypeError:
1334 except TypeError:
1335 return {}
1335 return {}
1336
1336
1337 @hybrid_property
1337 @hybrid_property
1338 def description_safe(self):
1338 def description_safe(self):
1339 from rhodecode.lib import helpers as h
1339 from rhodecode.lib import helpers as h
1340 return h.escape(self.user_group_description)
1340 return h.escape(self.user_group_description)
1341
1341
1342 @hybrid_property
1342 @hybrid_property
1343 def group_data(self):
1343 def group_data(self):
1344 return self._load_group_data(self._group_data)
1344 return self._load_group_data(self._group_data)
1345
1345
1346 @group_data.expression
1346 @group_data.expression
1347 def group_data(self, **kwargs):
1347 def group_data(self, **kwargs):
1348 return self._group_data
1348 return self._group_data
1349
1349
1350 @group_data.setter
1350 @group_data.setter
1351 def group_data(self, val):
1351 def group_data(self, val):
1352 try:
1352 try:
1353 self._group_data = json.dumps(val)
1353 self._group_data = json.dumps(val)
1354 except Exception:
1354 except Exception:
1355 log.error(traceback.format_exc())
1355 log.error(traceback.format_exc())
1356
1356
1357 @classmethod
1357 @classmethod
1358 def _load_sync(cls, group_data):
1358 def _load_sync(cls, group_data):
1359 if group_data:
1359 if group_data:
1360 return group_data.get('extern_type')
1360 return group_data.get('extern_type')
1361
1361
1362 @property
1362 @property
1363 def sync(self):
1363 def sync(self):
1364 return self._load_sync(self.group_data)
1364 return self._load_sync(self.group_data)
1365
1365
1366 def __unicode__(self):
1366 def __unicode__(self):
1367 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1367 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1368 self.users_group_id,
1368 self.users_group_id,
1369 self.users_group_name)
1369 self.users_group_name)
1370
1370
1371 @classmethod
1371 @classmethod
1372 def get_by_group_name(cls, group_name, cache=False,
1372 def get_by_group_name(cls, group_name, cache=False,
1373 case_insensitive=False):
1373 case_insensitive=False):
1374 if case_insensitive:
1374 if case_insensitive:
1375 q = cls.query().filter(func.lower(cls.users_group_name) ==
1375 q = cls.query().filter(func.lower(cls.users_group_name) ==
1376 func.lower(group_name))
1376 func.lower(group_name))
1377
1377
1378 else:
1378 else:
1379 q = cls.query().filter(cls.users_group_name == group_name)
1379 q = cls.query().filter(cls.users_group_name == group_name)
1380 if cache:
1380 if cache:
1381 q = q.options(
1381 q = q.options(
1382 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1382 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1383 return q.scalar()
1383 return q.scalar()
1384
1384
1385 @classmethod
1385 @classmethod
1386 def get(cls, user_group_id, cache=False):
1386 def get(cls, user_group_id, cache=False):
1387 if not user_group_id:
1387 if not user_group_id:
1388 return
1388 return
1389
1389
1390 user_group = cls.query()
1390 user_group = cls.query()
1391 if cache:
1391 if cache:
1392 user_group = user_group.options(
1392 user_group = user_group.options(
1393 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1393 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1394 return user_group.get(user_group_id)
1394 return user_group.get(user_group_id)
1395
1395
1396 def permissions(self, with_admins=True, with_owner=True,
1396 def permissions(self, with_admins=True, with_owner=True,
1397 expand_from_user_groups=False):
1397 expand_from_user_groups=False):
1398 """
1398 """
1399 Permissions for user groups
1399 Permissions for user groups
1400 """
1400 """
1401 _admin_perm = 'usergroup.admin'
1401 _admin_perm = 'usergroup.admin'
1402
1402
1403 owner_row = []
1403 owner_row = []
1404 if with_owner:
1404 if with_owner:
1405 usr = AttributeDict(self.user.get_dict())
1405 usr = AttributeDict(self.user.get_dict())
1406 usr.owner_row = True
1406 usr.owner_row = True
1407 usr.permission = _admin_perm
1407 usr.permission = _admin_perm
1408 owner_row.append(usr)
1408 owner_row.append(usr)
1409
1409
1410 super_admin_ids = []
1410 super_admin_ids = []
1411 super_admin_rows = []
1411 super_admin_rows = []
1412 if with_admins:
1412 if with_admins:
1413 for usr in User.get_all_super_admins():
1413 for usr in User.get_all_super_admins():
1414 super_admin_ids.append(usr.user_id)
1414 super_admin_ids.append(usr.user_id)
1415 # if this admin is also owner, don't double the record
1415 # if this admin is also owner, don't double the record
1416 if usr.user_id == owner_row[0].user_id:
1416 if usr.user_id == owner_row[0].user_id:
1417 owner_row[0].admin_row = True
1417 owner_row[0].admin_row = True
1418 else:
1418 else:
1419 usr = AttributeDict(usr.get_dict())
1419 usr = AttributeDict(usr.get_dict())
1420 usr.admin_row = True
1420 usr.admin_row = True
1421 usr.permission = _admin_perm
1421 usr.permission = _admin_perm
1422 super_admin_rows.append(usr)
1422 super_admin_rows.append(usr)
1423
1423
1424 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1424 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1425 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1425 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1426 joinedload(UserUserGroupToPerm.user),
1426 joinedload(UserUserGroupToPerm.user),
1427 joinedload(UserUserGroupToPerm.permission),)
1427 joinedload(UserUserGroupToPerm.permission),)
1428
1428
1429 # get owners and admins and permissions. We do a trick of re-writing
1429 # get owners and admins and permissions. We do a trick of re-writing
1430 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1430 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1431 # has a global reference and changing one object propagates to all
1431 # has a global reference and changing one object propagates to all
1432 # others. This means if admin is also an owner admin_row that change
1432 # others. This means if admin is also an owner admin_row that change
1433 # would propagate to both objects
1433 # would propagate to both objects
1434 perm_rows = []
1434 perm_rows = []
1435 for _usr in q.all():
1435 for _usr in q.all():
1436 usr = AttributeDict(_usr.user.get_dict())
1436 usr = AttributeDict(_usr.user.get_dict())
1437 # if this user is also owner/admin, mark as duplicate record
1437 # if this user is also owner/admin, mark as duplicate record
1438 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1438 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1439 usr.duplicate_perm = True
1439 usr.duplicate_perm = True
1440 usr.permission = _usr.permission.permission_name
1440 usr.permission = _usr.permission.permission_name
1441 perm_rows.append(usr)
1441 perm_rows.append(usr)
1442
1442
1443 # filter the perm rows by 'default' first and then sort them by
1443 # filter the perm rows by 'default' first and then sort them by
1444 # admin,write,read,none permissions sorted again alphabetically in
1444 # admin,write,read,none permissions sorted again alphabetically in
1445 # each group
1445 # each group
1446 perm_rows = sorted(perm_rows, key=display_user_sort)
1446 perm_rows = sorted(perm_rows, key=display_user_sort)
1447
1447
1448 user_groups_rows = []
1448 user_groups_rows = []
1449 if expand_from_user_groups:
1449 if expand_from_user_groups:
1450 for ug in self.permission_user_groups(with_members=True):
1450 for ug in self.permission_user_groups(with_members=True):
1451 for user_data in ug.members:
1451 for user_data in ug.members:
1452 user_groups_rows.append(user_data)
1452 user_groups_rows.append(user_data)
1453
1453
1454 return super_admin_rows + owner_row + perm_rows + user_groups_rows
1454 return super_admin_rows + owner_row + perm_rows + user_groups_rows
1455
1455
1456 def permission_user_groups(self, with_members=False):
1456 def permission_user_groups(self, with_members=False):
1457 q = UserGroupUserGroupToPerm.query()\
1457 q = UserGroupUserGroupToPerm.query()\
1458 .filter(UserGroupUserGroupToPerm.target_user_group == self)
1458 .filter(UserGroupUserGroupToPerm.target_user_group == self)
1459 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1459 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1460 joinedload(UserGroupUserGroupToPerm.target_user_group),
1460 joinedload(UserGroupUserGroupToPerm.target_user_group),
1461 joinedload(UserGroupUserGroupToPerm.permission),)
1461 joinedload(UserGroupUserGroupToPerm.permission),)
1462
1462
1463 perm_rows = []
1463 perm_rows = []
1464 for _user_group in q.all():
1464 for _user_group in q.all():
1465 entry = AttributeDict(_user_group.user_group.get_dict())
1465 entry = AttributeDict(_user_group.user_group.get_dict())
1466 entry.permission = _user_group.permission.permission_name
1466 entry.permission = _user_group.permission.permission_name
1467 if with_members:
1467 if with_members:
1468 entry.members = [x.user.get_dict()
1468 entry.members = [x.user.get_dict()
1469 for x in _user_group.users_group.members]
1469 for x in _user_group.user_group.members]
1470 perm_rows.append(entry)
1470 perm_rows.append(entry)
1471
1471
1472 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1472 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1473 return perm_rows
1473 return perm_rows
1474
1474
1475 def _get_default_perms(self, user_group, suffix=''):
1475 def _get_default_perms(self, user_group, suffix=''):
1476 from rhodecode.model.permission import PermissionModel
1476 from rhodecode.model.permission import PermissionModel
1477 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1477 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1478
1478
1479 def get_default_perms(self, suffix=''):
1479 def get_default_perms(self, suffix=''):
1480 return self._get_default_perms(self, suffix)
1480 return self._get_default_perms(self, suffix)
1481
1481
1482 def get_api_data(self, with_group_members=True, include_secrets=False):
1482 def get_api_data(self, with_group_members=True, include_secrets=False):
1483 """
1483 """
1484 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1484 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1485 basically forwarded.
1485 basically forwarded.
1486
1486
1487 """
1487 """
1488 user_group = self
1488 user_group = self
1489 data = {
1489 data = {
1490 'users_group_id': user_group.users_group_id,
1490 'users_group_id': user_group.users_group_id,
1491 'group_name': user_group.users_group_name,
1491 'group_name': user_group.users_group_name,
1492 'group_description': user_group.user_group_description,
1492 'group_description': user_group.user_group_description,
1493 'active': user_group.users_group_active,
1493 'active': user_group.users_group_active,
1494 'owner': user_group.user.username,
1494 'owner': user_group.user.username,
1495 'sync': user_group.sync,
1495 'sync': user_group.sync,
1496 'owner_email': user_group.user.email,
1496 'owner_email': user_group.user.email,
1497 }
1497 }
1498
1498
1499 if with_group_members:
1499 if with_group_members:
1500 users = []
1500 users = []
1501 for user in user_group.members:
1501 for user in user_group.members:
1502 user = user.user
1502 user = user.user
1503 users.append(user.get_api_data(include_secrets=include_secrets))
1503 users.append(user.get_api_data(include_secrets=include_secrets))
1504 data['users'] = users
1504 data['users'] = users
1505
1505
1506 return data
1506 return data
1507
1507
1508
1508
1509 class UserGroupMember(Base, BaseModel):
1509 class UserGroupMember(Base, BaseModel):
1510 __tablename__ = 'users_groups_members'
1510 __tablename__ = 'users_groups_members'
1511 __table_args__ = (
1511 __table_args__ = (
1512 base_table_args,
1512 base_table_args,
1513 )
1513 )
1514
1514
1515 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1515 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1516 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1516 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1517 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1517 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1518
1518
1519 user = relationship('User', lazy='joined')
1519 user = relationship('User', lazy='joined')
1520 users_group = relationship('UserGroup')
1520 users_group = relationship('UserGroup')
1521
1521
1522 def __init__(self, gr_id='', u_id=''):
1522 def __init__(self, gr_id='', u_id=''):
1523 self.users_group_id = gr_id
1523 self.users_group_id = gr_id
1524 self.user_id = u_id
1524 self.user_id = u_id
1525
1525
1526
1526
1527 class RepositoryField(Base, BaseModel):
1527 class RepositoryField(Base, BaseModel):
1528 __tablename__ = 'repositories_fields'
1528 __tablename__ = 'repositories_fields'
1529 __table_args__ = (
1529 __table_args__ = (
1530 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1530 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1531 base_table_args,
1531 base_table_args,
1532 )
1532 )
1533
1533
1534 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1534 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1535
1535
1536 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1536 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1537 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1537 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1538 field_key = Column("field_key", String(250))
1538 field_key = Column("field_key", String(250))
1539 field_label = Column("field_label", String(1024), nullable=False)
1539 field_label = Column("field_label", String(1024), nullable=False)
1540 field_value = Column("field_value", String(10000), nullable=False)
1540 field_value = Column("field_value", String(10000), nullable=False)
1541 field_desc = Column("field_desc", String(1024), nullable=False)
1541 field_desc = Column("field_desc", String(1024), nullable=False)
1542 field_type = Column("field_type", String(255), nullable=False, unique=None)
1542 field_type = Column("field_type", String(255), nullable=False, unique=None)
1543 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1543 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1544
1544
1545 repository = relationship('Repository')
1545 repository = relationship('Repository')
1546
1546
1547 @property
1547 @property
1548 def field_key_prefixed(self):
1548 def field_key_prefixed(self):
1549 return 'ex_%s' % self.field_key
1549 return 'ex_%s' % self.field_key
1550
1550
1551 @classmethod
1551 @classmethod
1552 def un_prefix_key(cls, key):
1552 def un_prefix_key(cls, key):
1553 if key.startswith(cls.PREFIX):
1553 if key.startswith(cls.PREFIX):
1554 return key[len(cls.PREFIX):]
1554 return key[len(cls.PREFIX):]
1555 return key
1555 return key
1556
1556
1557 @classmethod
1557 @classmethod
1558 def get_by_key_name(cls, key, repo):
1558 def get_by_key_name(cls, key, repo):
1559 row = cls.query()\
1559 row = cls.query()\
1560 .filter(cls.repository == repo)\
1560 .filter(cls.repository == repo)\
1561 .filter(cls.field_key == key).scalar()
1561 .filter(cls.field_key == key).scalar()
1562 return row
1562 return row
1563
1563
1564
1564
1565 class Repository(Base, BaseModel):
1565 class Repository(Base, BaseModel):
1566 __tablename__ = 'repositories'
1566 __tablename__ = 'repositories'
1567 __table_args__ = (
1567 __table_args__ = (
1568 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1568 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1569 base_table_args,
1569 base_table_args,
1570 )
1570 )
1571 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1571 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1572 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1572 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1573 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1573 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1574
1574
1575 STATE_CREATED = 'repo_state_created'
1575 STATE_CREATED = 'repo_state_created'
1576 STATE_PENDING = 'repo_state_pending'
1576 STATE_PENDING = 'repo_state_pending'
1577 STATE_ERROR = 'repo_state_error'
1577 STATE_ERROR = 'repo_state_error'
1578
1578
1579 LOCK_AUTOMATIC = 'lock_auto'
1579 LOCK_AUTOMATIC = 'lock_auto'
1580 LOCK_API = 'lock_api'
1580 LOCK_API = 'lock_api'
1581 LOCK_WEB = 'lock_web'
1581 LOCK_WEB = 'lock_web'
1582 LOCK_PULL = 'lock_pull'
1582 LOCK_PULL = 'lock_pull'
1583
1583
1584 NAME_SEP = URL_SEP
1584 NAME_SEP = URL_SEP
1585
1585
1586 repo_id = Column(
1586 repo_id = Column(
1587 "repo_id", Integer(), nullable=False, unique=True, default=None,
1587 "repo_id", Integer(), nullable=False, unique=True, default=None,
1588 primary_key=True)
1588 primary_key=True)
1589 _repo_name = Column(
1589 _repo_name = Column(
1590 "repo_name", Text(), nullable=False, default=None)
1590 "repo_name", Text(), nullable=False, default=None)
1591 _repo_name_hash = Column(
1591 _repo_name_hash = Column(
1592 "repo_name_hash", String(255), nullable=False, unique=True)
1592 "repo_name_hash", String(255), nullable=False, unique=True)
1593 repo_state = Column("repo_state", String(255), nullable=True)
1593 repo_state = Column("repo_state", String(255), nullable=True)
1594
1594
1595 clone_uri = Column(
1595 clone_uri = Column(
1596 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1596 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1597 default=None)
1597 default=None)
1598 push_uri = Column(
1598 push_uri = Column(
1599 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1599 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1600 default=None)
1600 default=None)
1601 repo_type = Column(
1601 repo_type = Column(
1602 "repo_type", String(255), nullable=False, unique=False, default=None)
1602 "repo_type", String(255), nullable=False, unique=False, default=None)
1603 user_id = Column(
1603 user_id = Column(
1604 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1604 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1605 unique=False, default=None)
1605 unique=False, default=None)
1606 private = Column(
1606 private = Column(
1607 "private", Boolean(), nullable=True, unique=None, default=None)
1607 "private", Boolean(), nullable=True, unique=None, default=None)
1608 archived = Column(
1608 archived = Column(
1609 "archived", Boolean(), nullable=True, unique=None, default=None)
1609 "archived", Boolean(), nullable=True, unique=None, default=None)
1610 enable_statistics = Column(
1610 enable_statistics = Column(
1611 "statistics", Boolean(), nullable=True, unique=None, default=True)
1611 "statistics", Boolean(), nullable=True, unique=None, default=True)
1612 enable_downloads = Column(
1612 enable_downloads = Column(
1613 "downloads", Boolean(), nullable=True, unique=None, default=True)
1613 "downloads", Boolean(), nullable=True, unique=None, default=True)
1614 description = Column(
1614 description = Column(
1615 "description", String(10000), nullable=True, unique=None, default=None)
1615 "description", String(10000), nullable=True, unique=None, default=None)
1616 created_on = Column(
1616 created_on = Column(
1617 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1617 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1618 default=datetime.datetime.now)
1618 default=datetime.datetime.now)
1619 updated_on = Column(
1619 updated_on = Column(
1620 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1620 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1621 default=datetime.datetime.now)
1621 default=datetime.datetime.now)
1622 _landing_revision = Column(
1622 _landing_revision = Column(
1623 "landing_revision", String(255), nullable=False, unique=False,
1623 "landing_revision", String(255), nullable=False, unique=False,
1624 default=None)
1624 default=None)
1625 enable_locking = Column(
1625 enable_locking = Column(
1626 "enable_locking", Boolean(), nullable=False, unique=None,
1626 "enable_locking", Boolean(), nullable=False, unique=None,
1627 default=False)
1627 default=False)
1628 _locked = Column(
1628 _locked = Column(
1629 "locked", String(255), nullable=True, unique=False, default=None)
1629 "locked", String(255), nullable=True, unique=False, default=None)
1630 _changeset_cache = Column(
1630 _changeset_cache = Column(
1631 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1631 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1632
1632
1633 fork_id = Column(
1633 fork_id = Column(
1634 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1634 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1635 nullable=True, unique=False, default=None)
1635 nullable=True, unique=False, default=None)
1636 group_id = Column(
1636 group_id = Column(
1637 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1637 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1638 unique=False, default=None)
1638 unique=False, default=None)
1639
1639
1640 user = relationship('User', lazy='joined')
1640 user = relationship('User', lazy='joined')
1641 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1641 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1642 group = relationship('RepoGroup', lazy='joined')
1642 group = relationship('RepoGroup', lazy='joined')
1643 repo_to_perm = relationship(
1643 repo_to_perm = relationship(
1644 'UserRepoToPerm', cascade='all',
1644 'UserRepoToPerm', cascade='all',
1645 order_by='UserRepoToPerm.repo_to_perm_id')
1645 order_by='UserRepoToPerm.repo_to_perm_id')
1646 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1646 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1647 stats = relationship('Statistics', cascade='all', uselist=False)
1647 stats = relationship('Statistics', cascade='all', uselist=False)
1648
1648
1649 followers = relationship(
1649 followers = relationship(
1650 'UserFollowing',
1650 'UserFollowing',
1651 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1651 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1652 cascade='all')
1652 cascade='all')
1653 extra_fields = relationship(
1653 extra_fields = relationship(
1654 'RepositoryField', cascade="all, delete, delete-orphan")
1654 'RepositoryField', cascade="all, delete, delete-orphan")
1655 logs = relationship('UserLog')
1655 logs = relationship('UserLog')
1656 comments = relationship(
1656 comments = relationship(
1657 'ChangesetComment', cascade="all, delete, delete-orphan")
1657 'ChangesetComment', cascade="all, delete, delete-orphan")
1658 pull_requests_source = relationship(
1658 pull_requests_source = relationship(
1659 'PullRequest',
1659 'PullRequest',
1660 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1660 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1661 cascade="all, delete, delete-orphan")
1661 cascade="all, delete, delete-orphan")
1662 pull_requests_target = relationship(
1662 pull_requests_target = relationship(
1663 'PullRequest',
1663 'PullRequest',
1664 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1664 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1665 cascade="all, delete, delete-orphan")
1665 cascade="all, delete, delete-orphan")
1666 ui = relationship('RepoRhodeCodeUi', cascade="all")
1666 ui = relationship('RepoRhodeCodeUi', cascade="all")
1667 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1667 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1668 integrations = relationship('Integration',
1668 integrations = relationship('Integration',
1669 cascade="all, delete, delete-orphan")
1669 cascade="all, delete, delete-orphan")
1670
1670
1671 scoped_tokens = relationship('UserApiKeys', cascade="all")
1671 scoped_tokens = relationship('UserApiKeys', cascade="all")
1672
1672
1673 def __unicode__(self):
1673 def __unicode__(self):
1674 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1674 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1675 safe_unicode(self.repo_name))
1675 safe_unicode(self.repo_name))
1676
1676
1677 @hybrid_property
1677 @hybrid_property
1678 def description_safe(self):
1678 def description_safe(self):
1679 from rhodecode.lib import helpers as h
1679 from rhodecode.lib import helpers as h
1680 return h.escape(self.description)
1680 return h.escape(self.description)
1681
1681
1682 @hybrid_property
1682 @hybrid_property
1683 def landing_rev(self):
1683 def landing_rev(self):
1684 # always should return [rev_type, rev]
1684 # always should return [rev_type, rev]
1685 if self._landing_revision:
1685 if self._landing_revision:
1686 _rev_info = self._landing_revision.split(':')
1686 _rev_info = self._landing_revision.split(':')
1687 if len(_rev_info) < 2:
1687 if len(_rev_info) < 2:
1688 _rev_info.insert(0, 'rev')
1688 _rev_info.insert(0, 'rev')
1689 return [_rev_info[0], _rev_info[1]]
1689 return [_rev_info[0], _rev_info[1]]
1690 return [None, None]
1690 return [None, None]
1691
1691
1692 @landing_rev.setter
1692 @landing_rev.setter
1693 def landing_rev(self, val):
1693 def landing_rev(self, val):
1694 if ':' not in val:
1694 if ':' not in val:
1695 raise ValueError('value must be delimited with `:` and consist '
1695 raise ValueError('value must be delimited with `:` and consist '
1696 'of <rev_type>:<rev>, got %s instead' % val)
1696 'of <rev_type>:<rev>, got %s instead' % val)
1697 self._landing_revision = val
1697 self._landing_revision = val
1698
1698
1699 @hybrid_property
1699 @hybrid_property
1700 def locked(self):
1700 def locked(self):
1701 if self._locked:
1701 if self._locked:
1702 user_id, timelocked, reason = self._locked.split(':')
1702 user_id, timelocked, reason = self._locked.split(':')
1703 lock_values = int(user_id), timelocked, reason
1703 lock_values = int(user_id), timelocked, reason
1704 else:
1704 else:
1705 lock_values = [None, None, None]
1705 lock_values = [None, None, None]
1706 return lock_values
1706 return lock_values
1707
1707
1708 @locked.setter
1708 @locked.setter
1709 def locked(self, val):
1709 def locked(self, val):
1710 if val and isinstance(val, (list, tuple)):
1710 if val and isinstance(val, (list, tuple)):
1711 self._locked = ':'.join(map(str, val))
1711 self._locked = ':'.join(map(str, val))
1712 else:
1712 else:
1713 self._locked = None
1713 self._locked = None
1714
1714
1715 @hybrid_property
1715 @hybrid_property
1716 def changeset_cache(self):
1716 def changeset_cache(self):
1717 from rhodecode.lib.vcs.backends.base import EmptyCommit
1717 from rhodecode.lib.vcs.backends.base import EmptyCommit
1718 dummy = EmptyCommit().__json__()
1718 dummy = EmptyCommit().__json__()
1719 if not self._changeset_cache:
1719 if not self._changeset_cache:
1720 return dummy
1720 return dummy
1721 try:
1721 try:
1722 return json.loads(self._changeset_cache)
1722 return json.loads(self._changeset_cache)
1723 except TypeError:
1723 except TypeError:
1724 return dummy
1724 return dummy
1725 except Exception:
1725 except Exception:
1726 log.error(traceback.format_exc())
1726 log.error(traceback.format_exc())
1727 return dummy
1727 return dummy
1728
1728
1729 @changeset_cache.setter
1729 @changeset_cache.setter
1730 def changeset_cache(self, val):
1730 def changeset_cache(self, val):
1731 try:
1731 try:
1732 self._changeset_cache = json.dumps(val)
1732 self._changeset_cache = json.dumps(val)
1733 except Exception:
1733 except Exception:
1734 log.error(traceback.format_exc())
1734 log.error(traceback.format_exc())
1735
1735
1736 @hybrid_property
1736 @hybrid_property
1737 def repo_name(self):
1737 def repo_name(self):
1738 return self._repo_name
1738 return self._repo_name
1739
1739
1740 @repo_name.setter
1740 @repo_name.setter
1741 def repo_name(self, value):
1741 def repo_name(self, value):
1742 self._repo_name = value
1742 self._repo_name = value
1743 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1743 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1744
1744
1745 @classmethod
1745 @classmethod
1746 def normalize_repo_name(cls, repo_name):
1746 def normalize_repo_name(cls, repo_name):
1747 """
1747 """
1748 Normalizes os specific repo_name to the format internally stored inside
1748 Normalizes os specific repo_name to the format internally stored inside
1749 database using URL_SEP
1749 database using URL_SEP
1750
1750
1751 :param cls:
1751 :param cls:
1752 :param repo_name:
1752 :param repo_name:
1753 """
1753 """
1754 return cls.NAME_SEP.join(repo_name.split(os.sep))
1754 return cls.NAME_SEP.join(repo_name.split(os.sep))
1755
1755
1756 @classmethod
1756 @classmethod
1757 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1757 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1758 session = Session()
1758 session = Session()
1759 q = session.query(cls).filter(cls.repo_name == repo_name)
1759 q = session.query(cls).filter(cls.repo_name == repo_name)
1760
1760
1761 if cache:
1761 if cache:
1762 if identity_cache:
1762 if identity_cache:
1763 val = cls.identity_cache(session, 'repo_name', repo_name)
1763 val = cls.identity_cache(session, 'repo_name', repo_name)
1764 if val:
1764 if val:
1765 return val
1765 return val
1766 else:
1766 else:
1767 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1767 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1768 q = q.options(
1768 q = q.options(
1769 FromCache("sql_cache_short", cache_key))
1769 FromCache("sql_cache_short", cache_key))
1770
1770
1771 return q.scalar()
1771 return q.scalar()
1772
1772
1773 @classmethod
1773 @classmethod
1774 def get_by_id_or_repo_name(cls, repoid):
1774 def get_by_id_or_repo_name(cls, repoid):
1775 if isinstance(repoid, (int, long)):
1775 if isinstance(repoid, (int, long)):
1776 try:
1776 try:
1777 repo = cls.get(repoid)
1777 repo = cls.get(repoid)
1778 except ValueError:
1778 except ValueError:
1779 repo = None
1779 repo = None
1780 else:
1780 else:
1781 repo = cls.get_by_repo_name(repoid)
1781 repo = cls.get_by_repo_name(repoid)
1782 return repo
1782 return repo
1783
1783
1784 @classmethod
1784 @classmethod
1785 def get_by_full_path(cls, repo_full_path):
1785 def get_by_full_path(cls, repo_full_path):
1786 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1786 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1787 repo_name = cls.normalize_repo_name(repo_name)
1787 repo_name = cls.normalize_repo_name(repo_name)
1788 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1788 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1789
1789
1790 @classmethod
1790 @classmethod
1791 def get_repo_forks(cls, repo_id):
1791 def get_repo_forks(cls, repo_id):
1792 return cls.query().filter(Repository.fork_id == repo_id)
1792 return cls.query().filter(Repository.fork_id == repo_id)
1793
1793
1794 @classmethod
1794 @classmethod
1795 def base_path(cls):
1795 def base_path(cls):
1796 """
1796 """
1797 Returns base path when all repos are stored
1797 Returns base path when all repos are stored
1798
1798
1799 :param cls:
1799 :param cls:
1800 """
1800 """
1801 q = Session().query(RhodeCodeUi)\
1801 q = Session().query(RhodeCodeUi)\
1802 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1802 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1803 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1803 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1804 return q.one().ui_value
1804 return q.one().ui_value
1805
1805
1806 @classmethod
1806 @classmethod
1807 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1807 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1808 case_insensitive=True, archived=False):
1808 case_insensitive=True, archived=False):
1809 q = Repository.query()
1809 q = Repository.query()
1810
1810
1811 if not archived:
1811 if not archived:
1812 q = q.filter(Repository.archived.isnot(true()))
1812 q = q.filter(Repository.archived.isnot(true()))
1813
1813
1814 if not isinstance(user_id, Optional):
1814 if not isinstance(user_id, Optional):
1815 q = q.filter(Repository.user_id == user_id)
1815 q = q.filter(Repository.user_id == user_id)
1816
1816
1817 if not isinstance(group_id, Optional):
1817 if not isinstance(group_id, Optional):
1818 q = q.filter(Repository.group_id == group_id)
1818 q = q.filter(Repository.group_id == group_id)
1819
1819
1820 if case_insensitive:
1820 if case_insensitive:
1821 q = q.order_by(func.lower(Repository.repo_name))
1821 q = q.order_by(func.lower(Repository.repo_name))
1822 else:
1822 else:
1823 q = q.order_by(Repository.repo_name)
1823 q = q.order_by(Repository.repo_name)
1824
1824
1825 return q.all()
1825 return q.all()
1826
1826
1827 @property
1827 @property
1828 def forks(self):
1828 def forks(self):
1829 """
1829 """
1830 Return forks of this repo
1830 Return forks of this repo
1831 """
1831 """
1832 return Repository.get_repo_forks(self.repo_id)
1832 return Repository.get_repo_forks(self.repo_id)
1833
1833
1834 @property
1834 @property
1835 def parent(self):
1835 def parent(self):
1836 """
1836 """
1837 Returns fork parent
1837 Returns fork parent
1838 """
1838 """
1839 return self.fork
1839 return self.fork
1840
1840
1841 @property
1841 @property
1842 def just_name(self):
1842 def just_name(self):
1843 return self.repo_name.split(self.NAME_SEP)[-1]
1843 return self.repo_name.split(self.NAME_SEP)[-1]
1844
1844
1845 @property
1845 @property
1846 def groups_with_parents(self):
1846 def groups_with_parents(self):
1847 groups = []
1847 groups = []
1848 if self.group is None:
1848 if self.group is None:
1849 return groups
1849 return groups
1850
1850
1851 cur_gr = self.group
1851 cur_gr = self.group
1852 groups.insert(0, cur_gr)
1852 groups.insert(0, cur_gr)
1853 while 1:
1853 while 1:
1854 gr = getattr(cur_gr, 'parent_group', None)
1854 gr = getattr(cur_gr, 'parent_group', None)
1855 cur_gr = cur_gr.parent_group
1855 cur_gr = cur_gr.parent_group
1856 if gr is None:
1856 if gr is None:
1857 break
1857 break
1858 groups.insert(0, gr)
1858 groups.insert(0, gr)
1859
1859
1860 return groups
1860 return groups
1861
1861
1862 @property
1862 @property
1863 def groups_and_repo(self):
1863 def groups_and_repo(self):
1864 return self.groups_with_parents, self
1864 return self.groups_with_parents, self
1865
1865
1866 @LazyProperty
1866 @LazyProperty
1867 def repo_path(self):
1867 def repo_path(self):
1868 """
1868 """
1869 Returns base full path for that repository means where it actually
1869 Returns base full path for that repository means where it actually
1870 exists on a filesystem
1870 exists on a filesystem
1871 """
1871 """
1872 q = Session().query(RhodeCodeUi).filter(
1872 q = Session().query(RhodeCodeUi).filter(
1873 RhodeCodeUi.ui_key == self.NAME_SEP)
1873 RhodeCodeUi.ui_key == self.NAME_SEP)
1874 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1874 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1875 return q.one().ui_value
1875 return q.one().ui_value
1876
1876
1877 @property
1877 @property
1878 def repo_full_path(self):
1878 def repo_full_path(self):
1879 p = [self.repo_path]
1879 p = [self.repo_path]
1880 # we need to split the name by / since this is how we store the
1880 # we need to split the name by / since this is how we store the
1881 # names in the database, but that eventually needs to be converted
1881 # names in the database, but that eventually needs to be converted
1882 # into a valid system path
1882 # into a valid system path
1883 p += self.repo_name.split(self.NAME_SEP)
1883 p += self.repo_name.split(self.NAME_SEP)
1884 return os.path.join(*map(safe_unicode, p))
1884 return os.path.join(*map(safe_unicode, p))
1885
1885
1886 @property
1886 @property
1887 def cache_keys(self):
1887 def cache_keys(self):
1888 """
1888 """
1889 Returns associated cache keys for that repo
1889 Returns associated cache keys for that repo
1890 """
1890 """
1891 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
1891 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
1892 repo_id=self.repo_id)
1892 repo_id=self.repo_id)
1893 return CacheKey.query()\
1893 return CacheKey.query()\
1894 .filter(CacheKey.cache_args == invalidation_namespace)\
1894 .filter(CacheKey.cache_args == invalidation_namespace)\
1895 .order_by(CacheKey.cache_key)\
1895 .order_by(CacheKey.cache_key)\
1896 .all()
1896 .all()
1897
1897
1898 @property
1898 @property
1899 def cached_diffs_relative_dir(self):
1899 def cached_diffs_relative_dir(self):
1900 """
1900 """
1901 Return a relative to the repository store path of cached diffs
1901 Return a relative to the repository store path of cached diffs
1902 used for safe display for users, who shouldn't know the absolute store
1902 used for safe display for users, who shouldn't know the absolute store
1903 path
1903 path
1904 """
1904 """
1905 return os.path.join(
1905 return os.path.join(
1906 os.path.dirname(self.repo_name),
1906 os.path.dirname(self.repo_name),
1907 self.cached_diffs_dir.split(os.path.sep)[-1])
1907 self.cached_diffs_dir.split(os.path.sep)[-1])
1908
1908
1909 @property
1909 @property
1910 def cached_diffs_dir(self):
1910 def cached_diffs_dir(self):
1911 path = self.repo_full_path
1911 path = self.repo_full_path
1912 return os.path.join(
1912 return os.path.join(
1913 os.path.dirname(path),
1913 os.path.dirname(path),
1914 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
1914 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
1915
1915
1916 def cached_diffs(self):
1916 def cached_diffs(self):
1917 diff_cache_dir = self.cached_diffs_dir
1917 diff_cache_dir = self.cached_diffs_dir
1918 if os.path.isdir(diff_cache_dir):
1918 if os.path.isdir(diff_cache_dir):
1919 return os.listdir(diff_cache_dir)
1919 return os.listdir(diff_cache_dir)
1920 return []
1920 return []
1921
1921
1922 def shadow_repos(self):
1922 def shadow_repos(self):
1923 shadow_repos_pattern = '.__shadow_repo_{}'.format(self.repo_id)
1923 shadow_repos_pattern = '.__shadow_repo_{}'.format(self.repo_id)
1924 return [
1924 return [
1925 x for x in os.listdir(os.path.dirname(self.repo_full_path))
1925 x for x in os.listdir(os.path.dirname(self.repo_full_path))
1926 if x.startswith(shadow_repos_pattern)]
1926 if x.startswith(shadow_repos_pattern)]
1927
1927
1928 def get_new_name(self, repo_name):
1928 def get_new_name(self, repo_name):
1929 """
1929 """
1930 returns new full repository name based on assigned group and new new
1930 returns new full repository name based on assigned group and new new
1931
1931
1932 :param group_name:
1932 :param group_name:
1933 """
1933 """
1934 path_prefix = self.group.full_path_splitted if self.group else []
1934 path_prefix = self.group.full_path_splitted if self.group else []
1935 return self.NAME_SEP.join(path_prefix + [repo_name])
1935 return self.NAME_SEP.join(path_prefix + [repo_name])
1936
1936
1937 @property
1937 @property
1938 def _config(self):
1938 def _config(self):
1939 """
1939 """
1940 Returns db based config object.
1940 Returns db based config object.
1941 """
1941 """
1942 from rhodecode.lib.utils import make_db_config
1942 from rhodecode.lib.utils import make_db_config
1943 return make_db_config(clear_session=False, repo=self)
1943 return make_db_config(clear_session=False, repo=self)
1944
1944
1945 def permissions(self, with_admins=True, with_owner=True,
1945 def permissions(self, with_admins=True, with_owner=True,
1946 expand_from_user_groups=False):
1946 expand_from_user_groups=False):
1947 """
1947 """
1948 Permissions for repositories
1948 Permissions for repositories
1949 """
1949 """
1950 _admin_perm = 'repository.admin'
1950 _admin_perm = 'repository.admin'
1951
1951
1952 owner_row = []
1952 owner_row = []
1953 if with_owner:
1953 if with_owner:
1954 usr = AttributeDict(self.user.get_dict())
1954 usr = AttributeDict(self.user.get_dict())
1955 usr.owner_row = True
1955 usr.owner_row = True
1956 usr.permission = _admin_perm
1956 usr.permission = _admin_perm
1957 usr.permission_id = None
1957 usr.permission_id = None
1958 owner_row.append(usr)
1958 owner_row.append(usr)
1959
1959
1960 super_admin_ids = []
1960 super_admin_ids = []
1961 super_admin_rows = []
1961 super_admin_rows = []
1962 if with_admins:
1962 if with_admins:
1963 for usr in User.get_all_super_admins():
1963 for usr in User.get_all_super_admins():
1964 super_admin_ids.append(usr.user_id)
1964 super_admin_ids.append(usr.user_id)
1965 # if this admin is also owner, don't double the record
1965 # if this admin is also owner, don't double the record
1966 if usr.user_id == owner_row[0].user_id:
1966 if usr.user_id == owner_row[0].user_id:
1967 owner_row[0].admin_row = True
1967 owner_row[0].admin_row = True
1968 else:
1968 else:
1969 usr = AttributeDict(usr.get_dict())
1969 usr = AttributeDict(usr.get_dict())
1970 usr.admin_row = True
1970 usr.admin_row = True
1971 usr.permission = _admin_perm
1971 usr.permission = _admin_perm
1972 usr.permission_id = None
1972 usr.permission_id = None
1973 super_admin_rows.append(usr)
1973 super_admin_rows.append(usr)
1974
1974
1975 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1975 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1976 q = q.options(joinedload(UserRepoToPerm.repository),
1976 q = q.options(joinedload(UserRepoToPerm.repository),
1977 joinedload(UserRepoToPerm.user),
1977 joinedload(UserRepoToPerm.user),
1978 joinedload(UserRepoToPerm.permission),)
1978 joinedload(UserRepoToPerm.permission),)
1979
1979
1980 # get owners and admins and permissions. We do a trick of re-writing
1980 # get owners and admins and permissions. We do a trick of re-writing
1981 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1981 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1982 # has a global reference and changing one object propagates to all
1982 # has a global reference and changing one object propagates to all
1983 # others. This means if admin is also an owner admin_row that change
1983 # others. This means if admin is also an owner admin_row that change
1984 # would propagate to both objects
1984 # would propagate to both objects
1985 perm_rows = []
1985 perm_rows = []
1986 for _usr in q.all():
1986 for _usr in q.all():
1987 usr = AttributeDict(_usr.user.get_dict())
1987 usr = AttributeDict(_usr.user.get_dict())
1988 # if this user is also owner/admin, mark as duplicate record
1988 # if this user is also owner/admin, mark as duplicate record
1989 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1989 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1990 usr.duplicate_perm = True
1990 usr.duplicate_perm = True
1991 # also check if this permission is maybe used by branch_permissions
1991 # also check if this permission is maybe used by branch_permissions
1992 if _usr.branch_perm_entry:
1992 if _usr.branch_perm_entry:
1993 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
1993 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
1994
1994
1995 usr.permission = _usr.permission.permission_name
1995 usr.permission = _usr.permission.permission_name
1996 usr.permission_id = _usr.repo_to_perm_id
1996 usr.permission_id = _usr.repo_to_perm_id
1997 perm_rows.append(usr)
1997 perm_rows.append(usr)
1998
1998
1999 # filter the perm rows by 'default' first and then sort them by
1999 # filter the perm rows by 'default' first and then sort them by
2000 # admin,write,read,none permissions sorted again alphabetically in
2000 # admin,write,read,none permissions sorted again alphabetically in
2001 # each group
2001 # each group
2002 perm_rows = sorted(perm_rows, key=display_user_sort)
2002 perm_rows = sorted(perm_rows, key=display_user_sort)
2003
2003
2004 user_groups_rows = []
2004 user_groups_rows = []
2005 if expand_from_user_groups:
2005 if expand_from_user_groups:
2006 for ug in self.permission_user_groups(with_members=True):
2006 for ug in self.permission_user_groups(with_members=True):
2007 for user_data in ug.members:
2007 for user_data in ug.members:
2008 user_groups_rows.append(user_data)
2008 user_groups_rows.append(user_data)
2009
2009
2010 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2010 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2011
2011
2012 def permission_user_groups(self, with_members=True):
2012 def permission_user_groups(self, with_members=True):
2013 q = UserGroupRepoToPerm.query()\
2013 q = UserGroupRepoToPerm.query()\
2014 .filter(UserGroupRepoToPerm.repository == self)
2014 .filter(UserGroupRepoToPerm.repository == self)
2015 q = q.options(joinedload(UserGroupRepoToPerm.repository),
2015 q = q.options(joinedload(UserGroupRepoToPerm.repository),
2016 joinedload(UserGroupRepoToPerm.users_group),
2016 joinedload(UserGroupRepoToPerm.users_group),
2017 joinedload(UserGroupRepoToPerm.permission),)
2017 joinedload(UserGroupRepoToPerm.permission),)
2018
2018
2019 perm_rows = []
2019 perm_rows = []
2020 for _user_group in q.all():
2020 for _user_group in q.all():
2021 entry = AttributeDict(_user_group.users_group.get_dict())
2021 entry = AttributeDict(_user_group.users_group.get_dict())
2022 entry.permission = _user_group.permission.permission_name
2022 entry.permission = _user_group.permission.permission_name
2023 if with_members:
2023 if with_members:
2024 entry.members = [x.user.get_dict()
2024 entry.members = [x.user.get_dict()
2025 for x in _user_group.users_group.members]
2025 for x in _user_group.users_group.members]
2026 perm_rows.append(entry)
2026 perm_rows.append(entry)
2027
2027
2028 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2028 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2029 return perm_rows
2029 return perm_rows
2030
2030
2031 def get_api_data(self, include_secrets=False):
2031 def get_api_data(self, include_secrets=False):
2032 """
2032 """
2033 Common function for generating repo api data
2033 Common function for generating repo api data
2034
2034
2035 :param include_secrets: See :meth:`User.get_api_data`.
2035 :param include_secrets: See :meth:`User.get_api_data`.
2036
2036
2037 """
2037 """
2038 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2038 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2039 # move this methods on models level.
2039 # move this methods on models level.
2040 from rhodecode.model.settings import SettingsModel
2040 from rhodecode.model.settings import SettingsModel
2041 from rhodecode.model.repo import RepoModel
2041 from rhodecode.model.repo import RepoModel
2042
2042
2043 repo = self
2043 repo = self
2044 _user_id, _time, _reason = self.locked
2044 _user_id, _time, _reason = self.locked
2045
2045
2046 data = {
2046 data = {
2047 'repo_id': repo.repo_id,
2047 'repo_id': repo.repo_id,
2048 'repo_name': repo.repo_name,
2048 'repo_name': repo.repo_name,
2049 'repo_type': repo.repo_type,
2049 'repo_type': repo.repo_type,
2050 'clone_uri': repo.clone_uri or '',
2050 'clone_uri': repo.clone_uri or '',
2051 'push_uri': repo.push_uri or '',
2051 'push_uri': repo.push_uri or '',
2052 'url': RepoModel().get_url(self),
2052 'url': RepoModel().get_url(self),
2053 'private': repo.private,
2053 'private': repo.private,
2054 'created_on': repo.created_on,
2054 'created_on': repo.created_on,
2055 'description': repo.description_safe,
2055 'description': repo.description_safe,
2056 'landing_rev': repo.landing_rev,
2056 'landing_rev': repo.landing_rev,
2057 'owner': repo.user.username,
2057 'owner': repo.user.username,
2058 'fork_of': repo.fork.repo_name if repo.fork else None,
2058 'fork_of': repo.fork.repo_name if repo.fork else None,
2059 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2059 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2060 'enable_statistics': repo.enable_statistics,
2060 'enable_statistics': repo.enable_statistics,
2061 'enable_locking': repo.enable_locking,
2061 'enable_locking': repo.enable_locking,
2062 'enable_downloads': repo.enable_downloads,
2062 'enable_downloads': repo.enable_downloads,
2063 'last_changeset': repo.changeset_cache,
2063 'last_changeset': repo.changeset_cache,
2064 'locked_by': User.get(_user_id).get_api_data(
2064 'locked_by': User.get(_user_id).get_api_data(
2065 include_secrets=include_secrets) if _user_id else None,
2065 include_secrets=include_secrets) if _user_id else None,
2066 'locked_date': time_to_datetime(_time) if _time else None,
2066 'locked_date': time_to_datetime(_time) if _time else None,
2067 'lock_reason': _reason if _reason else None,
2067 'lock_reason': _reason if _reason else None,
2068 }
2068 }
2069
2069
2070 # TODO: mikhail: should be per-repo settings here
2070 # TODO: mikhail: should be per-repo settings here
2071 rc_config = SettingsModel().get_all_settings()
2071 rc_config = SettingsModel().get_all_settings()
2072 repository_fields = str2bool(
2072 repository_fields = str2bool(
2073 rc_config.get('rhodecode_repository_fields'))
2073 rc_config.get('rhodecode_repository_fields'))
2074 if repository_fields:
2074 if repository_fields:
2075 for f in self.extra_fields:
2075 for f in self.extra_fields:
2076 data[f.field_key_prefixed] = f.field_value
2076 data[f.field_key_prefixed] = f.field_value
2077
2077
2078 return data
2078 return data
2079
2079
2080 @classmethod
2080 @classmethod
2081 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2081 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2082 if not lock_time:
2082 if not lock_time:
2083 lock_time = time.time()
2083 lock_time = time.time()
2084 if not lock_reason:
2084 if not lock_reason:
2085 lock_reason = cls.LOCK_AUTOMATIC
2085 lock_reason = cls.LOCK_AUTOMATIC
2086 repo.locked = [user_id, lock_time, lock_reason]
2086 repo.locked = [user_id, lock_time, lock_reason]
2087 Session().add(repo)
2087 Session().add(repo)
2088 Session().commit()
2088 Session().commit()
2089
2089
2090 @classmethod
2090 @classmethod
2091 def unlock(cls, repo):
2091 def unlock(cls, repo):
2092 repo.locked = None
2092 repo.locked = None
2093 Session().add(repo)
2093 Session().add(repo)
2094 Session().commit()
2094 Session().commit()
2095
2095
2096 @classmethod
2096 @classmethod
2097 def getlock(cls, repo):
2097 def getlock(cls, repo):
2098 return repo.locked
2098 return repo.locked
2099
2099
2100 def is_user_lock(self, user_id):
2100 def is_user_lock(self, user_id):
2101 if self.lock[0]:
2101 if self.lock[0]:
2102 lock_user_id = safe_int(self.lock[0])
2102 lock_user_id = safe_int(self.lock[0])
2103 user_id = safe_int(user_id)
2103 user_id = safe_int(user_id)
2104 # both are ints, and they are equal
2104 # both are ints, and they are equal
2105 return all([lock_user_id, user_id]) and lock_user_id == user_id
2105 return all([lock_user_id, user_id]) and lock_user_id == user_id
2106
2106
2107 return False
2107 return False
2108
2108
2109 def get_locking_state(self, action, user_id, only_when_enabled=True):
2109 def get_locking_state(self, action, user_id, only_when_enabled=True):
2110 """
2110 """
2111 Checks locking on this repository, if locking is enabled and lock is
2111 Checks locking on this repository, if locking is enabled and lock is
2112 present returns a tuple of make_lock, locked, locked_by.
2112 present returns a tuple of make_lock, locked, locked_by.
2113 make_lock can have 3 states None (do nothing) True, make lock
2113 make_lock can have 3 states None (do nothing) True, make lock
2114 False release lock, This value is later propagated to hooks, which
2114 False release lock, This value is later propagated to hooks, which
2115 do the locking. Think about this as signals passed to hooks what to do.
2115 do the locking. Think about this as signals passed to hooks what to do.
2116
2116
2117 """
2117 """
2118 # TODO: johbo: This is part of the business logic and should be moved
2118 # TODO: johbo: This is part of the business logic and should be moved
2119 # into the RepositoryModel.
2119 # into the RepositoryModel.
2120
2120
2121 if action not in ('push', 'pull'):
2121 if action not in ('push', 'pull'):
2122 raise ValueError("Invalid action value: %s" % repr(action))
2122 raise ValueError("Invalid action value: %s" % repr(action))
2123
2123
2124 # defines if locked error should be thrown to user
2124 # defines if locked error should be thrown to user
2125 currently_locked = False
2125 currently_locked = False
2126 # defines if new lock should be made, tri-state
2126 # defines if new lock should be made, tri-state
2127 make_lock = None
2127 make_lock = None
2128 repo = self
2128 repo = self
2129 user = User.get(user_id)
2129 user = User.get(user_id)
2130
2130
2131 lock_info = repo.locked
2131 lock_info = repo.locked
2132
2132
2133 if repo and (repo.enable_locking or not only_when_enabled):
2133 if repo and (repo.enable_locking or not only_when_enabled):
2134 if action == 'push':
2134 if action == 'push':
2135 # check if it's already locked !, if it is compare users
2135 # check if it's already locked !, if it is compare users
2136 locked_by_user_id = lock_info[0]
2136 locked_by_user_id = lock_info[0]
2137 if user.user_id == locked_by_user_id:
2137 if user.user_id == locked_by_user_id:
2138 log.debug(
2138 log.debug(
2139 'Got `push` action from user %s, now unlocking', user)
2139 'Got `push` action from user %s, now unlocking', user)
2140 # unlock if we have push from user who locked
2140 # unlock if we have push from user who locked
2141 make_lock = False
2141 make_lock = False
2142 else:
2142 else:
2143 # we're not the same user who locked, ban with
2143 # we're not the same user who locked, ban with
2144 # code defined in settings (default is 423 HTTP Locked) !
2144 # code defined in settings (default is 423 HTTP Locked) !
2145 log.debug('Repo %s is currently locked by %s', repo, user)
2145 log.debug('Repo %s is currently locked by %s', repo, user)
2146 currently_locked = True
2146 currently_locked = True
2147 elif action == 'pull':
2147 elif action == 'pull':
2148 # [0] user [1] date
2148 # [0] user [1] date
2149 if lock_info[0] and lock_info[1]:
2149 if lock_info[0] and lock_info[1]:
2150 log.debug('Repo %s is currently locked by %s', repo, user)
2150 log.debug('Repo %s is currently locked by %s', repo, user)
2151 currently_locked = True
2151 currently_locked = True
2152 else:
2152 else:
2153 log.debug('Setting lock on repo %s by %s', repo, user)
2153 log.debug('Setting lock on repo %s by %s', repo, user)
2154 make_lock = True
2154 make_lock = True
2155
2155
2156 else:
2156 else:
2157 log.debug('Repository %s do not have locking enabled', repo)
2157 log.debug('Repository %s do not have locking enabled', repo)
2158
2158
2159 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2159 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2160 make_lock, currently_locked, lock_info)
2160 make_lock, currently_locked, lock_info)
2161
2161
2162 from rhodecode.lib.auth import HasRepoPermissionAny
2162 from rhodecode.lib.auth import HasRepoPermissionAny
2163 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2163 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2164 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2164 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2165 # if we don't have at least write permission we cannot make a lock
2165 # if we don't have at least write permission we cannot make a lock
2166 log.debug('lock state reset back to FALSE due to lack '
2166 log.debug('lock state reset back to FALSE due to lack '
2167 'of at least read permission')
2167 'of at least read permission')
2168 make_lock = False
2168 make_lock = False
2169
2169
2170 return make_lock, currently_locked, lock_info
2170 return make_lock, currently_locked, lock_info
2171
2171
2172 @property
2172 @property
2173 def last_db_change(self):
2173 def last_db_change(self):
2174 return self.updated_on
2174 return self.updated_on
2175
2175
2176 @property
2176 @property
2177 def clone_uri_hidden(self):
2177 def clone_uri_hidden(self):
2178 clone_uri = self.clone_uri
2178 clone_uri = self.clone_uri
2179 if clone_uri:
2179 if clone_uri:
2180 import urlobject
2180 import urlobject
2181 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2181 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2182 if url_obj.password:
2182 if url_obj.password:
2183 clone_uri = url_obj.with_password('*****')
2183 clone_uri = url_obj.with_password('*****')
2184 return clone_uri
2184 return clone_uri
2185
2185
2186 @property
2186 @property
2187 def push_uri_hidden(self):
2187 def push_uri_hidden(self):
2188 push_uri = self.push_uri
2188 push_uri = self.push_uri
2189 if push_uri:
2189 if push_uri:
2190 import urlobject
2190 import urlobject
2191 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2191 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2192 if url_obj.password:
2192 if url_obj.password:
2193 push_uri = url_obj.with_password('*****')
2193 push_uri = url_obj.with_password('*****')
2194 return push_uri
2194 return push_uri
2195
2195
2196 def clone_url(self, **override):
2196 def clone_url(self, **override):
2197 from rhodecode.model.settings import SettingsModel
2197 from rhodecode.model.settings import SettingsModel
2198
2198
2199 uri_tmpl = None
2199 uri_tmpl = None
2200 if 'with_id' in override:
2200 if 'with_id' in override:
2201 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2201 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2202 del override['with_id']
2202 del override['with_id']
2203
2203
2204 if 'uri_tmpl' in override:
2204 if 'uri_tmpl' in override:
2205 uri_tmpl = override['uri_tmpl']
2205 uri_tmpl = override['uri_tmpl']
2206 del override['uri_tmpl']
2206 del override['uri_tmpl']
2207
2207
2208 ssh = False
2208 ssh = False
2209 if 'ssh' in override:
2209 if 'ssh' in override:
2210 ssh = True
2210 ssh = True
2211 del override['ssh']
2211 del override['ssh']
2212
2212
2213 # we didn't override our tmpl from **overrides
2213 # we didn't override our tmpl from **overrides
2214 if not uri_tmpl:
2214 if not uri_tmpl:
2215 rc_config = SettingsModel().get_all_settings(cache=True)
2215 rc_config = SettingsModel().get_all_settings(cache=True)
2216 if ssh:
2216 if ssh:
2217 uri_tmpl = rc_config.get(
2217 uri_tmpl = rc_config.get(
2218 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2218 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2219 else:
2219 else:
2220 uri_tmpl = rc_config.get(
2220 uri_tmpl = rc_config.get(
2221 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2221 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2222
2222
2223 request = get_current_request()
2223 request = get_current_request()
2224 return get_clone_url(request=request,
2224 return get_clone_url(request=request,
2225 uri_tmpl=uri_tmpl,
2225 uri_tmpl=uri_tmpl,
2226 repo_name=self.repo_name,
2226 repo_name=self.repo_name,
2227 repo_id=self.repo_id, **override)
2227 repo_id=self.repo_id, **override)
2228
2228
2229 def set_state(self, state):
2229 def set_state(self, state):
2230 self.repo_state = state
2230 self.repo_state = state
2231 Session().add(self)
2231 Session().add(self)
2232 #==========================================================================
2232 #==========================================================================
2233 # SCM PROPERTIES
2233 # SCM PROPERTIES
2234 #==========================================================================
2234 #==========================================================================
2235
2235
2236 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2236 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2237 return get_commit_safe(
2237 return get_commit_safe(
2238 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2238 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2239
2239
2240 def get_changeset(self, rev=None, pre_load=None):
2240 def get_changeset(self, rev=None, pre_load=None):
2241 warnings.warn("Use get_commit", DeprecationWarning)
2241 warnings.warn("Use get_commit", DeprecationWarning)
2242 commit_id = None
2242 commit_id = None
2243 commit_idx = None
2243 commit_idx = None
2244 if isinstance(rev, compat.string_types):
2244 if isinstance(rev, compat.string_types):
2245 commit_id = rev
2245 commit_id = rev
2246 else:
2246 else:
2247 commit_idx = rev
2247 commit_idx = rev
2248 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2248 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2249 pre_load=pre_load)
2249 pre_load=pre_load)
2250
2250
2251 def get_landing_commit(self):
2251 def get_landing_commit(self):
2252 """
2252 """
2253 Returns landing commit, or if that doesn't exist returns the tip
2253 Returns landing commit, or if that doesn't exist returns the tip
2254 """
2254 """
2255 _rev_type, _rev = self.landing_rev
2255 _rev_type, _rev = self.landing_rev
2256 commit = self.get_commit(_rev)
2256 commit = self.get_commit(_rev)
2257 if isinstance(commit, EmptyCommit):
2257 if isinstance(commit, EmptyCommit):
2258 return self.get_commit()
2258 return self.get_commit()
2259 return commit
2259 return commit
2260
2260
2261 def update_commit_cache(self, cs_cache=None, config=None):
2261 def update_commit_cache(self, cs_cache=None, config=None):
2262 """
2262 """
2263 Update cache of last changeset for repository, keys should be::
2263 Update cache of last changeset for repository, keys should be::
2264
2264
2265 short_id
2265 short_id
2266 raw_id
2266 raw_id
2267 revision
2267 revision
2268 parents
2268 parents
2269 message
2269 message
2270 date
2270 date
2271 author
2271 author
2272
2272
2273 :param cs_cache:
2273 :param cs_cache:
2274 """
2274 """
2275 from rhodecode.lib.vcs.backends.base import BaseChangeset
2275 from rhodecode.lib.vcs.backends.base import BaseChangeset
2276 if cs_cache is None:
2276 if cs_cache is None:
2277 # use no-cache version here
2277 # use no-cache version here
2278 scm_repo = self.scm_instance(cache=False, config=config)
2278 scm_repo = self.scm_instance(cache=False, config=config)
2279
2279
2280 empty = not scm_repo or scm_repo.is_empty()
2280 empty = not scm_repo or scm_repo.is_empty()
2281 if not empty:
2281 if not empty:
2282 cs_cache = scm_repo.get_commit(
2282 cs_cache = scm_repo.get_commit(
2283 pre_load=["author", "date", "message", "parents"])
2283 pre_load=["author", "date", "message", "parents"])
2284 else:
2284 else:
2285 cs_cache = EmptyCommit()
2285 cs_cache = EmptyCommit()
2286
2286
2287 if isinstance(cs_cache, BaseChangeset):
2287 if isinstance(cs_cache, BaseChangeset):
2288 cs_cache = cs_cache.__json__()
2288 cs_cache = cs_cache.__json__()
2289
2289
2290 def is_outdated(new_cs_cache):
2290 def is_outdated(new_cs_cache):
2291 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2291 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2292 new_cs_cache['revision'] != self.changeset_cache['revision']):
2292 new_cs_cache['revision'] != self.changeset_cache['revision']):
2293 return True
2293 return True
2294 return False
2294 return False
2295
2295
2296 # check if we have maybe already latest cached revision
2296 # check if we have maybe already latest cached revision
2297 if is_outdated(cs_cache) or not self.changeset_cache:
2297 if is_outdated(cs_cache) or not self.changeset_cache:
2298 _default = datetime.datetime.utcnow()
2298 _default = datetime.datetime.utcnow()
2299 last_change = cs_cache.get('date') or _default
2299 last_change = cs_cache.get('date') or _default
2300 if self.updated_on and self.updated_on > last_change:
2300 if self.updated_on and self.updated_on > last_change:
2301 # we check if last update is newer than the new value
2301 # we check if last update is newer than the new value
2302 # if yes, we use the current timestamp instead. Imagine you get
2302 # if yes, we use the current timestamp instead. Imagine you get
2303 # old commit pushed 1y ago, we'd set last update 1y to ago.
2303 # old commit pushed 1y ago, we'd set last update 1y to ago.
2304 last_change = _default
2304 last_change = _default
2305 log.debug('updated repo %s with new cs cache %s',
2305 log.debug('updated repo %s with new cs cache %s',
2306 self.repo_name, cs_cache)
2306 self.repo_name, cs_cache)
2307 self.updated_on = last_change
2307 self.updated_on = last_change
2308 self.changeset_cache = cs_cache
2308 self.changeset_cache = cs_cache
2309 Session().add(self)
2309 Session().add(self)
2310 Session().commit()
2310 Session().commit()
2311 else:
2311 else:
2312 log.debug('Skipping update_commit_cache for repo:`%s` '
2312 log.debug('Skipping update_commit_cache for repo:`%s` '
2313 'commit already with latest changes', self.repo_name)
2313 'commit already with latest changes', self.repo_name)
2314
2314
2315 @property
2315 @property
2316 def tip(self):
2316 def tip(self):
2317 return self.get_commit('tip')
2317 return self.get_commit('tip')
2318
2318
2319 @property
2319 @property
2320 def author(self):
2320 def author(self):
2321 return self.tip.author
2321 return self.tip.author
2322
2322
2323 @property
2323 @property
2324 def last_change(self):
2324 def last_change(self):
2325 return self.scm_instance().last_change
2325 return self.scm_instance().last_change
2326
2326
2327 def get_comments(self, revisions=None):
2327 def get_comments(self, revisions=None):
2328 """
2328 """
2329 Returns comments for this repository grouped by revisions
2329 Returns comments for this repository grouped by revisions
2330
2330
2331 :param revisions: filter query by revisions only
2331 :param revisions: filter query by revisions only
2332 """
2332 """
2333 cmts = ChangesetComment.query()\
2333 cmts = ChangesetComment.query()\
2334 .filter(ChangesetComment.repo == self)
2334 .filter(ChangesetComment.repo == self)
2335 if revisions:
2335 if revisions:
2336 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2336 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2337 grouped = collections.defaultdict(list)
2337 grouped = collections.defaultdict(list)
2338 for cmt in cmts.all():
2338 for cmt in cmts.all():
2339 grouped[cmt.revision].append(cmt)
2339 grouped[cmt.revision].append(cmt)
2340 return grouped
2340 return grouped
2341
2341
2342 def statuses(self, revisions=None):
2342 def statuses(self, revisions=None):
2343 """
2343 """
2344 Returns statuses for this repository
2344 Returns statuses for this repository
2345
2345
2346 :param revisions: list of revisions to get statuses for
2346 :param revisions: list of revisions to get statuses for
2347 """
2347 """
2348 statuses = ChangesetStatus.query()\
2348 statuses = ChangesetStatus.query()\
2349 .filter(ChangesetStatus.repo == self)\
2349 .filter(ChangesetStatus.repo == self)\
2350 .filter(ChangesetStatus.version == 0)
2350 .filter(ChangesetStatus.version == 0)
2351
2351
2352 if revisions:
2352 if revisions:
2353 # Try doing the filtering in chunks to avoid hitting limits
2353 # Try doing the filtering in chunks to avoid hitting limits
2354 size = 500
2354 size = 500
2355 status_results = []
2355 status_results = []
2356 for chunk in xrange(0, len(revisions), size):
2356 for chunk in xrange(0, len(revisions), size):
2357 status_results += statuses.filter(
2357 status_results += statuses.filter(
2358 ChangesetStatus.revision.in_(
2358 ChangesetStatus.revision.in_(
2359 revisions[chunk: chunk+size])
2359 revisions[chunk: chunk+size])
2360 ).all()
2360 ).all()
2361 else:
2361 else:
2362 status_results = statuses.all()
2362 status_results = statuses.all()
2363
2363
2364 grouped = {}
2364 grouped = {}
2365
2365
2366 # maybe we have open new pullrequest without a status?
2366 # maybe we have open new pullrequest without a status?
2367 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2367 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2368 status_lbl = ChangesetStatus.get_status_lbl(stat)
2368 status_lbl = ChangesetStatus.get_status_lbl(stat)
2369 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2369 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2370 for rev in pr.revisions:
2370 for rev in pr.revisions:
2371 pr_id = pr.pull_request_id
2371 pr_id = pr.pull_request_id
2372 pr_repo = pr.target_repo.repo_name
2372 pr_repo = pr.target_repo.repo_name
2373 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2373 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2374
2374
2375 for stat in status_results:
2375 for stat in status_results:
2376 pr_id = pr_repo = None
2376 pr_id = pr_repo = None
2377 if stat.pull_request:
2377 if stat.pull_request:
2378 pr_id = stat.pull_request.pull_request_id
2378 pr_id = stat.pull_request.pull_request_id
2379 pr_repo = stat.pull_request.target_repo.repo_name
2379 pr_repo = stat.pull_request.target_repo.repo_name
2380 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2380 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2381 pr_id, pr_repo]
2381 pr_id, pr_repo]
2382 return grouped
2382 return grouped
2383
2383
2384 # ==========================================================================
2384 # ==========================================================================
2385 # SCM CACHE INSTANCE
2385 # SCM CACHE INSTANCE
2386 # ==========================================================================
2386 # ==========================================================================
2387
2387
2388 def scm_instance(self, **kwargs):
2388 def scm_instance(self, **kwargs):
2389 import rhodecode
2389 import rhodecode
2390
2390
2391 # Passing a config will not hit the cache currently only used
2391 # Passing a config will not hit the cache currently only used
2392 # for repo2dbmapper
2392 # for repo2dbmapper
2393 config = kwargs.pop('config', None)
2393 config = kwargs.pop('config', None)
2394 cache = kwargs.pop('cache', None)
2394 cache = kwargs.pop('cache', None)
2395 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2395 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2396 # if cache is NOT defined use default global, else we have a full
2396 # if cache is NOT defined use default global, else we have a full
2397 # control over cache behaviour
2397 # control over cache behaviour
2398 if cache is None and full_cache and not config:
2398 if cache is None and full_cache and not config:
2399 return self._get_instance_cached()
2399 return self._get_instance_cached()
2400 return self._get_instance(cache=bool(cache), config=config)
2400 return self._get_instance(cache=bool(cache), config=config)
2401
2401
2402 def _get_instance_cached(self):
2402 def _get_instance_cached(self):
2403 from rhodecode.lib import rc_cache
2403 from rhodecode.lib import rc_cache
2404
2404
2405 cache_namespace_uid = 'cache_repo_instance.{}'.format(self.repo_id)
2405 cache_namespace_uid = 'cache_repo_instance.{}'.format(self.repo_id)
2406 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2406 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2407 repo_id=self.repo_id)
2407 repo_id=self.repo_id)
2408 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2408 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2409
2409
2410 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2410 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2411 def get_instance_cached(repo_id, context_id):
2411 def get_instance_cached(repo_id, context_id):
2412 return self._get_instance()
2412 return self._get_instance()
2413
2413
2414 # we must use thread scoped cache here,
2414 # we must use thread scoped cache here,
2415 # because each thread of gevent needs it's own not shared connection and cache
2415 # because each thread of gevent needs it's own not shared connection and cache
2416 # we also alter `args` so the cache key is individual for every green thread.
2416 # we also alter `args` so the cache key is individual for every green thread.
2417 inv_context_manager = rc_cache.InvalidationContext(
2417 inv_context_manager = rc_cache.InvalidationContext(
2418 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace,
2418 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace,
2419 thread_scoped=True)
2419 thread_scoped=True)
2420 with inv_context_manager as invalidation_context:
2420 with inv_context_manager as invalidation_context:
2421 args = (self.repo_id, inv_context_manager.cache_key)
2421 args = (self.repo_id, inv_context_manager.cache_key)
2422 # re-compute and store cache if we get invalidate signal
2422 # re-compute and store cache if we get invalidate signal
2423 if invalidation_context.should_invalidate():
2423 if invalidation_context.should_invalidate():
2424 instance = get_instance_cached.refresh(*args)
2424 instance = get_instance_cached.refresh(*args)
2425 else:
2425 else:
2426 instance = get_instance_cached(*args)
2426 instance = get_instance_cached(*args)
2427
2427
2428 log.debug(
2428 log.debug(
2429 'Repo instance fetched in %.3fs', inv_context_manager.compute_time)
2429 'Repo instance fetched in %.3fs', inv_context_manager.compute_time)
2430 return instance
2430 return instance
2431
2431
2432 def _get_instance(self, cache=True, config=None):
2432 def _get_instance(self, cache=True, config=None):
2433 config = config or self._config
2433 config = config or self._config
2434 custom_wire = {
2434 custom_wire = {
2435 'cache': cache # controls the vcs.remote cache
2435 'cache': cache # controls the vcs.remote cache
2436 }
2436 }
2437 repo = get_vcs_instance(
2437 repo = get_vcs_instance(
2438 repo_path=safe_str(self.repo_full_path),
2438 repo_path=safe_str(self.repo_full_path),
2439 config=config,
2439 config=config,
2440 with_wire=custom_wire,
2440 with_wire=custom_wire,
2441 create=False,
2441 create=False,
2442 _vcs_alias=self.repo_type)
2442 _vcs_alias=self.repo_type)
2443
2443
2444 return repo
2444 return repo
2445
2445
2446 def __json__(self):
2446 def __json__(self):
2447 return {'landing_rev': self.landing_rev}
2447 return {'landing_rev': self.landing_rev}
2448
2448
2449 def get_dict(self):
2449 def get_dict(self):
2450
2450
2451 # Since we transformed `repo_name` to a hybrid property, we need to
2451 # Since we transformed `repo_name` to a hybrid property, we need to
2452 # keep compatibility with the code which uses `repo_name` field.
2452 # keep compatibility with the code which uses `repo_name` field.
2453
2453
2454 result = super(Repository, self).get_dict()
2454 result = super(Repository, self).get_dict()
2455 result['repo_name'] = result.pop('_repo_name', None)
2455 result['repo_name'] = result.pop('_repo_name', None)
2456 return result
2456 return result
2457
2457
2458
2458
2459 class RepoGroup(Base, BaseModel):
2459 class RepoGroup(Base, BaseModel):
2460 __tablename__ = 'groups'
2460 __tablename__ = 'groups'
2461 __table_args__ = (
2461 __table_args__ = (
2462 UniqueConstraint('group_name', 'group_parent_id'),
2462 UniqueConstraint('group_name', 'group_parent_id'),
2463 base_table_args,
2463 base_table_args,
2464 )
2464 )
2465 __mapper_args__ = {'order_by': 'group_name'}
2465 __mapper_args__ = {'order_by': 'group_name'}
2466
2466
2467 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2467 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2468
2468
2469 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2469 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2470 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2470 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2471 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2471 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2472 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2472 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2473 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2473 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2474 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2474 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2475 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2475 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2476 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2476 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2477 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2477 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2478
2478
2479 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2479 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2480 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2480 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2481 parent_group = relationship('RepoGroup', remote_side=group_id)
2481 parent_group = relationship('RepoGroup', remote_side=group_id)
2482 user = relationship('User')
2482 user = relationship('User')
2483 integrations = relationship('Integration', cascade="all, delete, delete-orphan")
2483 integrations = relationship('Integration', cascade="all, delete, delete-orphan")
2484
2484
2485 def __init__(self, group_name='', parent_group=None):
2485 def __init__(self, group_name='', parent_group=None):
2486 self.group_name = group_name
2486 self.group_name = group_name
2487 self.parent_group = parent_group
2487 self.parent_group = parent_group
2488
2488
2489 def __unicode__(self):
2489 def __unicode__(self):
2490 return u"<%s('id:%s:%s')>" % (
2490 return u"<%s('id:%s:%s')>" % (
2491 self.__class__.__name__, self.group_id, self.group_name)
2491 self.__class__.__name__, self.group_id, self.group_name)
2492
2492
2493 @validates('group_parent_id')
2493 @validates('group_parent_id')
2494 def validate_group_parent_id(self, key, val):
2494 def validate_group_parent_id(self, key, val):
2495 """
2495 """
2496 Check cycle references for a parent group to self
2496 Check cycle references for a parent group to self
2497 """
2497 """
2498 if self.group_id and val:
2498 if self.group_id and val:
2499 assert val != self.group_id
2499 assert val != self.group_id
2500
2500
2501 return val
2501 return val
2502
2502
2503 @hybrid_property
2503 @hybrid_property
2504 def description_safe(self):
2504 def description_safe(self):
2505 from rhodecode.lib import helpers as h
2505 from rhodecode.lib import helpers as h
2506 return h.escape(self.group_description)
2506 return h.escape(self.group_description)
2507
2507
2508 @classmethod
2508 @classmethod
2509 def _generate_choice(cls, repo_group):
2509 def _generate_choice(cls, repo_group):
2510 from webhelpers.html import literal as _literal
2510 from webhelpers.html import literal as _literal
2511 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2511 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2512 return repo_group.group_id, _name(repo_group.full_path_splitted)
2512 return repo_group.group_id, _name(repo_group.full_path_splitted)
2513
2513
2514 @classmethod
2514 @classmethod
2515 def groups_choices(cls, groups=None, show_empty_group=True):
2515 def groups_choices(cls, groups=None, show_empty_group=True):
2516 if not groups:
2516 if not groups:
2517 groups = cls.query().all()
2517 groups = cls.query().all()
2518
2518
2519 repo_groups = []
2519 repo_groups = []
2520 if show_empty_group:
2520 if show_empty_group:
2521 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2521 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2522
2522
2523 repo_groups.extend([cls._generate_choice(x) for x in groups])
2523 repo_groups.extend([cls._generate_choice(x) for x in groups])
2524
2524
2525 repo_groups = sorted(
2525 repo_groups = sorted(
2526 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2526 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2527 return repo_groups
2527 return repo_groups
2528
2528
2529 @classmethod
2529 @classmethod
2530 def url_sep(cls):
2530 def url_sep(cls):
2531 return URL_SEP
2531 return URL_SEP
2532
2532
2533 @classmethod
2533 @classmethod
2534 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2534 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2535 if case_insensitive:
2535 if case_insensitive:
2536 gr = cls.query().filter(func.lower(cls.group_name)
2536 gr = cls.query().filter(func.lower(cls.group_name)
2537 == func.lower(group_name))
2537 == func.lower(group_name))
2538 else:
2538 else:
2539 gr = cls.query().filter(cls.group_name == group_name)
2539 gr = cls.query().filter(cls.group_name == group_name)
2540 if cache:
2540 if cache:
2541 name_key = _hash_key(group_name)
2541 name_key = _hash_key(group_name)
2542 gr = gr.options(
2542 gr = gr.options(
2543 FromCache("sql_cache_short", "get_group_%s" % name_key))
2543 FromCache("sql_cache_short", "get_group_%s" % name_key))
2544 return gr.scalar()
2544 return gr.scalar()
2545
2545
2546 @classmethod
2546 @classmethod
2547 def get_user_personal_repo_group(cls, user_id):
2547 def get_user_personal_repo_group(cls, user_id):
2548 user = User.get(user_id)
2548 user = User.get(user_id)
2549 if user.username == User.DEFAULT_USER:
2549 if user.username == User.DEFAULT_USER:
2550 return None
2550 return None
2551
2551
2552 return cls.query()\
2552 return cls.query()\
2553 .filter(cls.personal == true()) \
2553 .filter(cls.personal == true()) \
2554 .filter(cls.user == user) \
2554 .filter(cls.user == user) \
2555 .order_by(cls.group_id.asc()) \
2555 .order_by(cls.group_id.asc()) \
2556 .first()
2556 .first()
2557
2557
2558 @classmethod
2558 @classmethod
2559 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2559 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2560 case_insensitive=True):
2560 case_insensitive=True):
2561 q = RepoGroup.query()
2561 q = RepoGroup.query()
2562
2562
2563 if not isinstance(user_id, Optional):
2563 if not isinstance(user_id, Optional):
2564 q = q.filter(RepoGroup.user_id == user_id)
2564 q = q.filter(RepoGroup.user_id == user_id)
2565
2565
2566 if not isinstance(group_id, Optional):
2566 if not isinstance(group_id, Optional):
2567 q = q.filter(RepoGroup.group_parent_id == group_id)
2567 q = q.filter(RepoGroup.group_parent_id == group_id)
2568
2568
2569 if case_insensitive:
2569 if case_insensitive:
2570 q = q.order_by(func.lower(RepoGroup.group_name))
2570 q = q.order_by(func.lower(RepoGroup.group_name))
2571 else:
2571 else:
2572 q = q.order_by(RepoGroup.group_name)
2572 q = q.order_by(RepoGroup.group_name)
2573 return q.all()
2573 return q.all()
2574
2574
2575 @property
2575 @property
2576 def parents(self):
2576 def parents(self):
2577 parents_recursion_limit = 10
2577 parents_recursion_limit = 10
2578 groups = []
2578 groups = []
2579 if self.parent_group is None:
2579 if self.parent_group is None:
2580 return groups
2580 return groups
2581 cur_gr = self.parent_group
2581 cur_gr = self.parent_group
2582 groups.insert(0, cur_gr)
2582 groups.insert(0, cur_gr)
2583 cnt = 0
2583 cnt = 0
2584 while 1:
2584 while 1:
2585 cnt += 1
2585 cnt += 1
2586 gr = getattr(cur_gr, 'parent_group', None)
2586 gr = getattr(cur_gr, 'parent_group', None)
2587 cur_gr = cur_gr.parent_group
2587 cur_gr = cur_gr.parent_group
2588 if gr is None:
2588 if gr is None:
2589 break
2589 break
2590 if cnt == parents_recursion_limit:
2590 if cnt == parents_recursion_limit:
2591 # this will prevent accidental infinit loops
2591 # this will prevent accidental infinit loops
2592 log.error('more than %s parents found for group %s, stopping '
2592 log.error('more than %s parents found for group %s, stopping '
2593 'recursive parent fetching', parents_recursion_limit, self)
2593 'recursive parent fetching', parents_recursion_limit, self)
2594 break
2594 break
2595
2595
2596 groups.insert(0, gr)
2596 groups.insert(0, gr)
2597 return groups
2597 return groups
2598
2598
2599 @property
2599 @property
2600 def last_db_change(self):
2600 def last_db_change(self):
2601 return self.updated_on
2601 return self.updated_on
2602
2602
2603 @property
2603 @property
2604 def children(self):
2604 def children(self):
2605 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2605 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2606
2606
2607 @property
2607 @property
2608 def name(self):
2608 def name(self):
2609 return self.group_name.split(RepoGroup.url_sep())[-1]
2609 return self.group_name.split(RepoGroup.url_sep())[-1]
2610
2610
2611 @property
2611 @property
2612 def full_path(self):
2612 def full_path(self):
2613 return self.group_name
2613 return self.group_name
2614
2614
2615 @property
2615 @property
2616 def full_path_splitted(self):
2616 def full_path_splitted(self):
2617 return self.group_name.split(RepoGroup.url_sep())
2617 return self.group_name.split(RepoGroup.url_sep())
2618
2618
2619 @property
2619 @property
2620 def repositories(self):
2620 def repositories(self):
2621 return Repository.query()\
2621 return Repository.query()\
2622 .filter(Repository.group == self)\
2622 .filter(Repository.group == self)\
2623 .order_by(Repository.repo_name)
2623 .order_by(Repository.repo_name)
2624
2624
2625 @property
2625 @property
2626 def repositories_recursive_count(self):
2626 def repositories_recursive_count(self):
2627 cnt = self.repositories.count()
2627 cnt = self.repositories.count()
2628
2628
2629 def children_count(group):
2629 def children_count(group):
2630 cnt = 0
2630 cnt = 0
2631 for child in group.children:
2631 for child in group.children:
2632 cnt += child.repositories.count()
2632 cnt += child.repositories.count()
2633 cnt += children_count(child)
2633 cnt += children_count(child)
2634 return cnt
2634 return cnt
2635
2635
2636 return cnt + children_count(self)
2636 return cnt + children_count(self)
2637
2637
2638 def _recursive_objects(self, include_repos=True):
2638 def _recursive_objects(self, include_repos=True):
2639 all_ = []
2639 all_ = []
2640
2640
2641 def _get_members(root_gr):
2641 def _get_members(root_gr):
2642 if include_repos:
2642 if include_repos:
2643 for r in root_gr.repositories:
2643 for r in root_gr.repositories:
2644 all_.append(r)
2644 all_.append(r)
2645 childs = root_gr.children.all()
2645 childs = root_gr.children.all()
2646 if childs:
2646 if childs:
2647 for gr in childs:
2647 for gr in childs:
2648 all_.append(gr)
2648 all_.append(gr)
2649 _get_members(gr)
2649 _get_members(gr)
2650
2650
2651 _get_members(self)
2651 _get_members(self)
2652 return [self] + all_
2652 return [self] + all_
2653
2653
2654 def recursive_groups_and_repos(self):
2654 def recursive_groups_and_repos(self):
2655 """
2655 """
2656 Recursive return all groups, with repositories in those groups
2656 Recursive return all groups, with repositories in those groups
2657 """
2657 """
2658 return self._recursive_objects()
2658 return self._recursive_objects()
2659
2659
2660 def recursive_groups(self):
2660 def recursive_groups(self):
2661 """
2661 """
2662 Returns all children groups for this group including children of children
2662 Returns all children groups for this group including children of children
2663 """
2663 """
2664 return self._recursive_objects(include_repos=False)
2664 return self._recursive_objects(include_repos=False)
2665
2665
2666 def get_new_name(self, group_name):
2666 def get_new_name(self, group_name):
2667 """
2667 """
2668 returns new full group name based on parent and new name
2668 returns new full group name based on parent and new name
2669
2669
2670 :param group_name:
2670 :param group_name:
2671 """
2671 """
2672 path_prefix = (self.parent_group.full_path_splitted if
2672 path_prefix = (self.parent_group.full_path_splitted if
2673 self.parent_group else [])
2673 self.parent_group else [])
2674 return RepoGroup.url_sep().join(path_prefix + [group_name])
2674 return RepoGroup.url_sep().join(path_prefix + [group_name])
2675
2675
2676 def permissions(self, with_admins=True, with_owner=True,
2676 def permissions(self, with_admins=True, with_owner=True,
2677 expand_from_user_groups=False):
2677 expand_from_user_groups=False):
2678 """
2678 """
2679 Permissions for repository groups
2679 Permissions for repository groups
2680 """
2680 """
2681 _admin_perm = 'group.admin'
2681 _admin_perm = 'group.admin'
2682
2682
2683 owner_row = []
2683 owner_row = []
2684 if with_owner:
2684 if with_owner:
2685 usr = AttributeDict(self.user.get_dict())
2685 usr = AttributeDict(self.user.get_dict())
2686 usr.owner_row = True
2686 usr.owner_row = True
2687 usr.permission = _admin_perm
2687 usr.permission = _admin_perm
2688 owner_row.append(usr)
2688 owner_row.append(usr)
2689
2689
2690 super_admin_ids = []
2690 super_admin_ids = []
2691 super_admin_rows = []
2691 super_admin_rows = []
2692 if with_admins:
2692 if with_admins:
2693 for usr in User.get_all_super_admins():
2693 for usr in User.get_all_super_admins():
2694 super_admin_ids.append(usr.user_id)
2694 super_admin_ids.append(usr.user_id)
2695 # if this admin is also owner, don't double the record
2695 # if this admin is also owner, don't double the record
2696 if usr.user_id == owner_row[0].user_id:
2696 if usr.user_id == owner_row[0].user_id:
2697 owner_row[0].admin_row = True
2697 owner_row[0].admin_row = True
2698 else:
2698 else:
2699 usr = AttributeDict(usr.get_dict())
2699 usr = AttributeDict(usr.get_dict())
2700 usr.admin_row = True
2700 usr.admin_row = True
2701 usr.permission = _admin_perm
2701 usr.permission = _admin_perm
2702 super_admin_rows.append(usr)
2702 super_admin_rows.append(usr)
2703
2703
2704 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2704 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2705 q = q.options(joinedload(UserRepoGroupToPerm.group),
2705 q = q.options(joinedload(UserRepoGroupToPerm.group),
2706 joinedload(UserRepoGroupToPerm.user),
2706 joinedload(UserRepoGroupToPerm.user),
2707 joinedload(UserRepoGroupToPerm.permission),)
2707 joinedload(UserRepoGroupToPerm.permission),)
2708
2708
2709 # get owners and admins and permissions. We do a trick of re-writing
2709 # get owners and admins and permissions. We do a trick of re-writing
2710 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2710 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2711 # has a global reference and changing one object propagates to all
2711 # has a global reference and changing one object propagates to all
2712 # others. This means if admin is also an owner admin_row that change
2712 # others. This means if admin is also an owner admin_row that change
2713 # would propagate to both objects
2713 # would propagate to both objects
2714 perm_rows = []
2714 perm_rows = []
2715 for _usr in q.all():
2715 for _usr in q.all():
2716 usr = AttributeDict(_usr.user.get_dict())
2716 usr = AttributeDict(_usr.user.get_dict())
2717 # if this user is also owner/admin, mark as duplicate record
2717 # if this user is also owner/admin, mark as duplicate record
2718 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2718 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2719 usr.duplicate_perm = True
2719 usr.duplicate_perm = True
2720 usr.permission = _usr.permission.permission_name
2720 usr.permission = _usr.permission.permission_name
2721 perm_rows.append(usr)
2721 perm_rows.append(usr)
2722
2722
2723 # filter the perm rows by 'default' first and then sort them by
2723 # filter the perm rows by 'default' first and then sort them by
2724 # admin,write,read,none permissions sorted again alphabetically in
2724 # admin,write,read,none permissions sorted again alphabetically in
2725 # each group
2725 # each group
2726 perm_rows = sorted(perm_rows, key=display_user_sort)
2726 perm_rows = sorted(perm_rows, key=display_user_sort)
2727
2727
2728 user_groups_rows = []
2728 user_groups_rows = []
2729 if expand_from_user_groups:
2729 if expand_from_user_groups:
2730 for ug in self.permission_user_groups(with_members=True):
2730 for ug in self.permission_user_groups(with_members=True):
2731 for user_data in ug.members:
2731 for user_data in ug.members:
2732 user_groups_rows.append(user_data)
2732 user_groups_rows.append(user_data)
2733
2733
2734 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2734 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2735
2735
2736 def permission_user_groups(self, with_members=False):
2736 def permission_user_groups(self, with_members=False):
2737 q = UserGroupRepoGroupToPerm.query()\
2737 q = UserGroupRepoGroupToPerm.query()\
2738 .filter(UserGroupRepoGroupToPerm.group == self)
2738 .filter(UserGroupRepoGroupToPerm.group == self)
2739 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2739 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2740 joinedload(UserGroupRepoGroupToPerm.users_group),
2740 joinedload(UserGroupRepoGroupToPerm.users_group),
2741 joinedload(UserGroupRepoGroupToPerm.permission),)
2741 joinedload(UserGroupRepoGroupToPerm.permission),)
2742
2742
2743 perm_rows = []
2743 perm_rows = []
2744 for _user_group in q.all():
2744 for _user_group in q.all():
2745 entry = AttributeDict(_user_group.users_group.get_dict())
2745 entry = AttributeDict(_user_group.users_group.get_dict())
2746 entry.permission = _user_group.permission.permission_name
2746 entry.permission = _user_group.permission.permission_name
2747 if with_members:
2747 if with_members:
2748 entry.members = [x.user.get_dict()
2748 entry.members = [x.user.get_dict()
2749 for x in _user_group.users_group.members]
2749 for x in _user_group.users_group.members]
2750 perm_rows.append(entry)
2750 perm_rows.append(entry)
2751
2751
2752 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2752 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2753 return perm_rows
2753 return perm_rows
2754
2754
2755 def get_api_data(self):
2755 def get_api_data(self):
2756 """
2756 """
2757 Common function for generating api data
2757 Common function for generating api data
2758
2758
2759 """
2759 """
2760 group = self
2760 group = self
2761 data = {
2761 data = {
2762 'group_id': group.group_id,
2762 'group_id': group.group_id,
2763 'group_name': group.group_name,
2763 'group_name': group.group_name,
2764 'group_description': group.description_safe,
2764 'group_description': group.description_safe,
2765 'parent_group': group.parent_group.group_name if group.parent_group else None,
2765 'parent_group': group.parent_group.group_name if group.parent_group else None,
2766 'repositories': [x.repo_name for x in group.repositories],
2766 'repositories': [x.repo_name for x in group.repositories],
2767 'owner': group.user.username,
2767 'owner': group.user.username,
2768 }
2768 }
2769 return data
2769 return data
2770
2770
2771
2771
2772 class Permission(Base, BaseModel):
2772 class Permission(Base, BaseModel):
2773 __tablename__ = 'permissions'
2773 __tablename__ = 'permissions'
2774 __table_args__ = (
2774 __table_args__ = (
2775 Index('p_perm_name_idx', 'permission_name'),
2775 Index('p_perm_name_idx', 'permission_name'),
2776 base_table_args,
2776 base_table_args,
2777 )
2777 )
2778
2778
2779 PERMS = [
2779 PERMS = [
2780 ('hg.admin', _('RhodeCode Super Administrator')),
2780 ('hg.admin', _('RhodeCode Super Administrator')),
2781
2781
2782 ('repository.none', _('Repository no access')),
2782 ('repository.none', _('Repository no access')),
2783 ('repository.read', _('Repository read access')),
2783 ('repository.read', _('Repository read access')),
2784 ('repository.write', _('Repository write access')),
2784 ('repository.write', _('Repository write access')),
2785 ('repository.admin', _('Repository admin access')),
2785 ('repository.admin', _('Repository admin access')),
2786
2786
2787 ('group.none', _('Repository group no access')),
2787 ('group.none', _('Repository group no access')),
2788 ('group.read', _('Repository group read access')),
2788 ('group.read', _('Repository group read access')),
2789 ('group.write', _('Repository group write access')),
2789 ('group.write', _('Repository group write access')),
2790 ('group.admin', _('Repository group admin access')),
2790 ('group.admin', _('Repository group admin access')),
2791
2791
2792 ('usergroup.none', _('User group no access')),
2792 ('usergroup.none', _('User group no access')),
2793 ('usergroup.read', _('User group read access')),
2793 ('usergroup.read', _('User group read access')),
2794 ('usergroup.write', _('User group write access')),
2794 ('usergroup.write', _('User group write access')),
2795 ('usergroup.admin', _('User group admin access')),
2795 ('usergroup.admin', _('User group admin access')),
2796
2796
2797 ('branch.none', _('Branch no permissions')),
2797 ('branch.none', _('Branch no permissions')),
2798 ('branch.merge', _('Branch access by web merge')),
2798 ('branch.merge', _('Branch access by web merge')),
2799 ('branch.push', _('Branch access by push')),
2799 ('branch.push', _('Branch access by push')),
2800 ('branch.push_force', _('Branch access by push with force')),
2800 ('branch.push_force', _('Branch access by push with force')),
2801
2801
2802 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2802 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2803 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2803 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2804
2804
2805 ('hg.usergroup.create.false', _('User Group creation disabled')),
2805 ('hg.usergroup.create.false', _('User Group creation disabled')),
2806 ('hg.usergroup.create.true', _('User Group creation enabled')),
2806 ('hg.usergroup.create.true', _('User Group creation enabled')),
2807
2807
2808 ('hg.create.none', _('Repository creation disabled')),
2808 ('hg.create.none', _('Repository creation disabled')),
2809 ('hg.create.repository', _('Repository creation enabled')),
2809 ('hg.create.repository', _('Repository creation enabled')),
2810 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2810 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2811 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2811 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2812
2812
2813 ('hg.fork.none', _('Repository forking disabled')),
2813 ('hg.fork.none', _('Repository forking disabled')),
2814 ('hg.fork.repository', _('Repository forking enabled')),
2814 ('hg.fork.repository', _('Repository forking enabled')),
2815
2815
2816 ('hg.register.none', _('Registration disabled')),
2816 ('hg.register.none', _('Registration disabled')),
2817 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2817 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2818 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2818 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2819
2819
2820 ('hg.password_reset.enabled', _('Password reset enabled')),
2820 ('hg.password_reset.enabled', _('Password reset enabled')),
2821 ('hg.password_reset.hidden', _('Password reset hidden')),
2821 ('hg.password_reset.hidden', _('Password reset hidden')),
2822 ('hg.password_reset.disabled', _('Password reset disabled')),
2822 ('hg.password_reset.disabled', _('Password reset disabled')),
2823
2823
2824 ('hg.extern_activate.manual', _('Manual activation of external account')),
2824 ('hg.extern_activate.manual', _('Manual activation of external account')),
2825 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2825 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2826
2826
2827 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2827 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2828 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2828 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2829 ]
2829 ]
2830
2830
2831 # definition of system default permissions for DEFAULT user, created on
2831 # definition of system default permissions for DEFAULT user, created on
2832 # system setup
2832 # system setup
2833 DEFAULT_USER_PERMISSIONS = [
2833 DEFAULT_USER_PERMISSIONS = [
2834 # object perms
2834 # object perms
2835 'repository.read',
2835 'repository.read',
2836 'group.read',
2836 'group.read',
2837 'usergroup.read',
2837 'usergroup.read',
2838 # branch, for backward compat we need same value as before so forced pushed
2838 # branch, for backward compat we need same value as before so forced pushed
2839 'branch.push_force',
2839 'branch.push_force',
2840 # global
2840 # global
2841 'hg.create.repository',
2841 'hg.create.repository',
2842 'hg.repogroup.create.false',
2842 'hg.repogroup.create.false',
2843 'hg.usergroup.create.false',
2843 'hg.usergroup.create.false',
2844 'hg.create.write_on_repogroup.true',
2844 'hg.create.write_on_repogroup.true',
2845 'hg.fork.repository',
2845 'hg.fork.repository',
2846 'hg.register.manual_activate',
2846 'hg.register.manual_activate',
2847 'hg.password_reset.enabled',
2847 'hg.password_reset.enabled',
2848 'hg.extern_activate.auto',
2848 'hg.extern_activate.auto',
2849 'hg.inherit_default_perms.true',
2849 'hg.inherit_default_perms.true',
2850 ]
2850 ]
2851
2851
2852 # defines which permissions are more important higher the more important
2852 # defines which permissions are more important higher the more important
2853 # Weight defines which permissions are more important.
2853 # Weight defines which permissions are more important.
2854 # The higher number the more important.
2854 # The higher number the more important.
2855 PERM_WEIGHTS = {
2855 PERM_WEIGHTS = {
2856 'repository.none': 0,
2856 'repository.none': 0,
2857 'repository.read': 1,
2857 'repository.read': 1,
2858 'repository.write': 3,
2858 'repository.write': 3,
2859 'repository.admin': 4,
2859 'repository.admin': 4,
2860
2860
2861 'group.none': 0,
2861 'group.none': 0,
2862 'group.read': 1,
2862 'group.read': 1,
2863 'group.write': 3,
2863 'group.write': 3,
2864 'group.admin': 4,
2864 'group.admin': 4,
2865
2865
2866 'usergroup.none': 0,
2866 'usergroup.none': 0,
2867 'usergroup.read': 1,
2867 'usergroup.read': 1,
2868 'usergroup.write': 3,
2868 'usergroup.write': 3,
2869 'usergroup.admin': 4,
2869 'usergroup.admin': 4,
2870
2870
2871 'branch.none': 0,
2871 'branch.none': 0,
2872 'branch.merge': 1,
2872 'branch.merge': 1,
2873 'branch.push': 3,
2873 'branch.push': 3,
2874 'branch.push_force': 4,
2874 'branch.push_force': 4,
2875
2875
2876 'hg.repogroup.create.false': 0,
2876 'hg.repogroup.create.false': 0,
2877 'hg.repogroup.create.true': 1,
2877 'hg.repogroup.create.true': 1,
2878
2878
2879 'hg.usergroup.create.false': 0,
2879 'hg.usergroup.create.false': 0,
2880 'hg.usergroup.create.true': 1,
2880 'hg.usergroup.create.true': 1,
2881
2881
2882 'hg.fork.none': 0,
2882 'hg.fork.none': 0,
2883 'hg.fork.repository': 1,
2883 'hg.fork.repository': 1,
2884 'hg.create.none': 0,
2884 'hg.create.none': 0,
2885 'hg.create.repository': 1
2885 'hg.create.repository': 1
2886 }
2886 }
2887
2887
2888 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2888 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2889 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2889 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2890 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2890 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2891
2891
2892 def __unicode__(self):
2892 def __unicode__(self):
2893 return u"<%s('%s:%s')>" % (
2893 return u"<%s('%s:%s')>" % (
2894 self.__class__.__name__, self.permission_id, self.permission_name
2894 self.__class__.__name__, self.permission_id, self.permission_name
2895 )
2895 )
2896
2896
2897 @classmethod
2897 @classmethod
2898 def get_by_key(cls, key):
2898 def get_by_key(cls, key):
2899 return cls.query().filter(cls.permission_name == key).scalar()
2899 return cls.query().filter(cls.permission_name == key).scalar()
2900
2900
2901 @classmethod
2901 @classmethod
2902 def get_default_repo_perms(cls, user_id, repo_id=None):
2902 def get_default_repo_perms(cls, user_id, repo_id=None):
2903 q = Session().query(UserRepoToPerm, Repository, Permission)\
2903 q = Session().query(UserRepoToPerm, Repository, Permission)\
2904 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2904 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2905 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2905 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2906 .filter(UserRepoToPerm.user_id == user_id)
2906 .filter(UserRepoToPerm.user_id == user_id)
2907 if repo_id:
2907 if repo_id:
2908 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2908 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2909 return q.all()
2909 return q.all()
2910
2910
2911 @classmethod
2911 @classmethod
2912 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
2912 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
2913 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
2913 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
2914 .join(
2914 .join(
2915 Permission,
2915 Permission,
2916 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
2916 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
2917 .join(
2917 .join(
2918 UserRepoToPerm,
2918 UserRepoToPerm,
2919 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
2919 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
2920 .filter(UserRepoToPerm.user_id == user_id)
2920 .filter(UserRepoToPerm.user_id == user_id)
2921
2921
2922 if repo_id:
2922 if repo_id:
2923 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
2923 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
2924 return q.order_by(UserToRepoBranchPermission.rule_order).all()
2924 return q.order_by(UserToRepoBranchPermission.rule_order).all()
2925
2925
2926 @classmethod
2926 @classmethod
2927 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2927 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2928 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2928 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2929 .join(
2929 .join(
2930 Permission,
2930 Permission,
2931 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2931 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2932 .join(
2932 .join(
2933 Repository,
2933 Repository,
2934 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2934 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2935 .join(
2935 .join(
2936 UserGroup,
2936 UserGroup,
2937 UserGroupRepoToPerm.users_group_id ==
2937 UserGroupRepoToPerm.users_group_id ==
2938 UserGroup.users_group_id)\
2938 UserGroup.users_group_id)\
2939 .join(
2939 .join(
2940 UserGroupMember,
2940 UserGroupMember,
2941 UserGroupRepoToPerm.users_group_id ==
2941 UserGroupRepoToPerm.users_group_id ==
2942 UserGroupMember.users_group_id)\
2942 UserGroupMember.users_group_id)\
2943 .filter(
2943 .filter(
2944 UserGroupMember.user_id == user_id,
2944 UserGroupMember.user_id == user_id,
2945 UserGroup.users_group_active == true())
2945 UserGroup.users_group_active == true())
2946 if repo_id:
2946 if repo_id:
2947 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2947 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2948 return q.all()
2948 return q.all()
2949
2949
2950 @classmethod
2950 @classmethod
2951 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
2951 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
2952 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
2952 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
2953 .join(
2953 .join(
2954 Permission,
2954 Permission,
2955 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
2955 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
2956 .join(
2956 .join(
2957 UserGroupRepoToPerm,
2957 UserGroupRepoToPerm,
2958 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
2958 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
2959 .join(
2959 .join(
2960 UserGroup,
2960 UserGroup,
2961 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
2961 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
2962 .join(
2962 .join(
2963 UserGroupMember,
2963 UserGroupMember,
2964 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
2964 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
2965 .filter(
2965 .filter(
2966 UserGroupMember.user_id == user_id,
2966 UserGroupMember.user_id == user_id,
2967 UserGroup.users_group_active == true())
2967 UserGroup.users_group_active == true())
2968
2968
2969 if repo_id:
2969 if repo_id:
2970 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
2970 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
2971 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
2971 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
2972
2972
2973 @classmethod
2973 @classmethod
2974 def get_default_group_perms(cls, user_id, repo_group_id=None):
2974 def get_default_group_perms(cls, user_id, repo_group_id=None):
2975 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2975 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2976 .join(
2976 .join(
2977 Permission,
2977 Permission,
2978 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
2978 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
2979 .join(
2979 .join(
2980 RepoGroup,
2980 RepoGroup,
2981 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
2981 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
2982 .filter(UserRepoGroupToPerm.user_id == user_id)
2982 .filter(UserRepoGroupToPerm.user_id == user_id)
2983 if repo_group_id:
2983 if repo_group_id:
2984 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2984 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2985 return q.all()
2985 return q.all()
2986
2986
2987 @classmethod
2987 @classmethod
2988 def get_default_group_perms_from_user_group(
2988 def get_default_group_perms_from_user_group(
2989 cls, user_id, repo_group_id=None):
2989 cls, user_id, repo_group_id=None):
2990 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2990 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2991 .join(
2991 .join(
2992 Permission,
2992 Permission,
2993 UserGroupRepoGroupToPerm.permission_id ==
2993 UserGroupRepoGroupToPerm.permission_id ==
2994 Permission.permission_id)\
2994 Permission.permission_id)\
2995 .join(
2995 .join(
2996 RepoGroup,
2996 RepoGroup,
2997 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2997 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2998 .join(
2998 .join(
2999 UserGroup,
2999 UserGroup,
3000 UserGroupRepoGroupToPerm.users_group_id ==
3000 UserGroupRepoGroupToPerm.users_group_id ==
3001 UserGroup.users_group_id)\
3001 UserGroup.users_group_id)\
3002 .join(
3002 .join(
3003 UserGroupMember,
3003 UserGroupMember,
3004 UserGroupRepoGroupToPerm.users_group_id ==
3004 UserGroupRepoGroupToPerm.users_group_id ==
3005 UserGroupMember.users_group_id)\
3005 UserGroupMember.users_group_id)\
3006 .filter(
3006 .filter(
3007 UserGroupMember.user_id == user_id,
3007 UserGroupMember.user_id == user_id,
3008 UserGroup.users_group_active == true())
3008 UserGroup.users_group_active == true())
3009 if repo_group_id:
3009 if repo_group_id:
3010 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
3010 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
3011 return q.all()
3011 return q.all()
3012
3012
3013 @classmethod
3013 @classmethod
3014 def get_default_user_group_perms(cls, user_id, user_group_id=None):
3014 def get_default_user_group_perms(cls, user_id, user_group_id=None):
3015 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
3015 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
3016 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
3016 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
3017 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
3017 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
3018 .filter(UserUserGroupToPerm.user_id == user_id)
3018 .filter(UserUserGroupToPerm.user_id == user_id)
3019 if user_group_id:
3019 if user_group_id:
3020 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
3020 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
3021 return q.all()
3021 return q.all()
3022
3022
3023 @classmethod
3023 @classmethod
3024 def get_default_user_group_perms_from_user_group(
3024 def get_default_user_group_perms_from_user_group(
3025 cls, user_id, user_group_id=None):
3025 cls, user_id, user_group_id=None):
3026 TargetUserGroup = aliased(UserGroup, name='target_user_group')
3026 TargetUserGroup = aliased(UserGroup, name='target_user_group')
3027 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
3027 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
3028 .join(
3028 .join(
3029 Permission,
3029 Permission,
3030 UserGroupUserGroupToPerm.permission_id ==
3030 UserGroupUserGroupToPerm.permission_id ==
3031 Permission.permission_id)\
3031 Permission.permission_id)\
3032 .join(
3032 .join(
3033 TargetUserGroup,
3033 TargetUserGroup,
3034 UserGroupUserGroupToPerm.target_user_group_id ==
3034 UserGroupUserGroupToPerm.target_user_group_id ==
3035 TargetUserGroup.users_group_id)\
3035 TargetUserGroup.users_group_id)\
3036 .join(
3036 .join(
3037 UserGroup,
3037 UserGroup,
3038 UserGroupUserGroupToPerm.user_group_id ==
3038 UserGroupUserGroupToPerm.user_group_id ==
3039 UserGroup.users_group_id)\
3039 UserGroup.users_group_id)\
3040 .join(
3040 .join(
3041 UserGroupMember,
3041 UserGroupMember,
3042 UserGroupUserGroupToPerm.user_group_id ==
3042 UserGroupUserGroupToPerm.user_group_id ==
3043 UserGroupMember.users_group_id)\
3043 UserGroupMember.users_group_id)\
3044 .filter(
3044 .filter(
3045 UserGroupMember.user_id == user_id,
3045 UserGroupMember.user_id == user_id,
3046 UserGroup.users_group_active == true())
3046 UserGroup.users_group_active == true())
3047 if user_group_id:
3047 if user_group_id:
3048 q = q.filter(
3048 q = q.filter(
3049 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3049 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3050
3050
3051 return q.all()
3051 return q.all()
3052
3052
3053
3053
3054 class UserRepoToPerm(Base, BaseModel):
3054 class UserRepoToPerm(Base, BaseModel):
3055 __tablename__ = 'repo_to_perm'
3055 __tablename__ = 'repo_to_perm'
3056 __table_args__ = (
3056 __table_args__ = (
3057 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3057 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3058 base_table_args
3058 base_table_args
3059 )
3059 )
3060
3060
3061 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3061 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3062 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3062 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3063 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3063 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3064 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3064 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3065
3065
3066 user = relationship('User')
3066 user = relationship('User')
3067 repository = relationship('Repository')
3067 repository = relationship('Repository')
3068 permission = relationship('Permission')
3068 permission = relationship('Permission')
3069
3069
3070 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete, delete-orphan", lazy='joined')
3070 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete, delete-orphan", lazy='joined')
3071
3071
3072 @classmethod
3072 @classmethod
3073 def create(cls, user, repository, permission):
3073 def create(cls, user, repository, permission):
3074 n = cls()
3074 n = cls()
3075 n.user = user
3075 n.user = user
3076 n.repository = repository
3076 n.repository = repository
3077 n.permission = permission
3077 n.permission = permission
3078 Session().add(n)
3078 Session().add(n)
3079 return n
3079 return n
3080
3080
3081 def __unicode__(self):
3081 def __unicode__(self):
3082 return u'<%s => %s >' % (self.user, self.repository)
3082 return u'<%s => %s >' % (self.user, self.repository)
3083
3083
3084
3084
3085 class UserUserGroupToPerm(Base, BaseModel):
3085 class UserUserGroupToPerm(Base, BaseModel):
3086 __tablename__ = 'user_user_group_to_perm'
3086 __tablename__ = 'user_user_group_to_perm'
3087 __table_args__ = (
3087 __table_args__ = (
3088 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3088 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3089 base_table_args
3089 base_table_args
3090 )
3090 )
3091
3091
3092 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3092 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3093 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3093 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3094 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3094 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3095 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3095 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3096
3096
3097 user = relationship('User')
3097 user = relationship('User')
3098 user_group = relationship('UserGroup')
3098 user_group = relationship('UserGroup')
3099 permission = relationship('Permission')
3099 permission = relationship('Permission')
3100
3100
3101 @classmethod
3101 @classmethod
3102 def create(cls, user, user_group, permission):
3102 def create(cls, user, user_group, permission):
3103 n = cls()
3103 n = cls()
3104 n.user = user
3104 n.user = user
3105 n.user_group = user_group
3105 n.user_group = user_group
3106 n.permission = permission
3106 n.permission = permission
3107 Session().add(n)
3107 Session().add(n)
3108 return n
3108 return n
3109
3109
3110 def __unicode__(self):
3110 def __unicode__(self):
3111 return u'<%s => %s >' % (self.user, self.user_group)
3111 return u'<%s => %s >' % (self.user, self.user_group)
3112
3112
3113
3113
3114 class UserToPerm(Base, BaseModel):
3114 class UserToPerm(Base, BaseModel):
3115 __tablename__ = 'user_to_perm'
3115 __tablename__ = 'user_to_perm'
3116 __table_args__ = (
3116 __table_args__ = (
3117 UniqueConstraint('user_id', 'permission_id'),
3117 UniqueConstraint('user_id', 'permission_id'),
3118 base_table_args
3118 base_table_args
3119 )
3119 )
3120
3120
3121 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3121 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3122 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3122 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3123 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3123 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3124
3124
3125 user = relationship('User')
3125 user = relationship('User')
3126 permission = relationship('Permission', lazy='joined')
3126 permission = relationship('Permission', lazy='joined')
3127
3127
3128 def __unicode__(self):
3128 def __unicode__(self):
3129 return u'<%s => %s >' % (self.user, self.permission)
3129 return u'<%s => %s >' % (self.user, self.permission)
3130
3130
3131
3131
3132 class UserGroupRepoToPerm(Base, BaseModel):
3132 class UserGroupRepoToPerm(Base, BaseModel):
3133 __tablename__ = 'users_group_repo_to_perm'
3133 __tablename__ = 'users_group_repo_to_perm'
3134 __table_args__ = (
3134 __table_args__ = (
3135 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3135 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3136 base_table_args
3136 base_table_args
3137 )
3137 )
3138
3138
3139 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3139 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3140 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3140 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3141 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3141 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3142 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3142 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3143
3143
3144 users_group = relationship('UserGroup')
3144 users_group = relationship('UserGroup')
3145 permission = relationship('Permission')
3145 permission = relationship('Permission')
3146 repository = relationship('Repository')
3146 repository = relationship('Repository')
3147 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all')
3147 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all')
3148
3148
3149 @classmethod
3149 @classmethod
3150 def create(cls, users_group, repository, permission):
3150 def create(cls, users_group, repository, permission):
3151 n = cls()
3151 n = cls()
3152 n.users_group = users_group
3152 n.users_group = users_group
3153 n.repository = repository
3153 n.repository = repository
3154 n.permission = permission
3154 n.permission = permission
3155 Session().add(n)
3155 Session().add(n)
3156 return n
3156 return n
3157
3157
3158 def __unicode__(self):
3158 def __unicode__(self):
3159 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
3159 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
3160
3160
3161
3161
3162 class UserGroupUserGroupToPerm(Base, BaseModel):
3162 class UserGroupUserGroupToPerm(Base, BaseModel):
3163 __tablename__ = 'user_group_user_group_to_perm'
3163 __tablename__ = 'user_group_user_group_to_perm'
3164 __table_args__ = (
3164 __table_args__ = (
3165 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3165 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3166 CheckConstraint('target_user_group_id != user_group_id'),
3166 CheckConstraint('target_user_group_id != user_group_id'),
3167 base_table_args
3167 base_table_args
3168 )
3168 )
3169
3169
3170 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)
3170 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)
3171 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3171 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3172 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3172 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3173 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3173 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3174
3174
3175 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3175 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3176 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3176 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3177 permission = relationship('Permission')
3177 permission = relationship('Permission')
3178
3178
3179 @classmethod
3179 @classmethod
3180 def create(cls, target_user_group, user_group, permission):
3180 def create(cls, target_user_group, user_group, permission):
3181 n = cls()
3181 n = cls()
3182 n.target_user_group = target_user_group
3182 n.target_user_group = target_user_group
3183 n.user_group = user_group
3183 n.user_group = user_group
3184 n.permission = permission
3184 n.permission = permission
3185 Session().add(n)
3185 Session().add(n)
3186 return n
3186 return n
3187
3187
3188 def __unicode__(self):
3188 def __unicode__(self):
3189 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3189 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3190
3190
3191
3191
3192 class UserGroupToPerm(Base, BaseModel):
3192 class UserGroupToPerm(Base, BaseModel):
3193 __tablename__ = 'users_group_to_perm'
3193 __tablename__ = 'users_group_to_perm'
3194 __table_args__ = (
3194 __table_args__ = (
3195 UniqueConstraint('users_group_id', 'permission_id',),
3195 UniqueConstraint('users_group_id', 'permission_id',),
3196 base_table_args
3196 base_table_args
3197 )
3197 )
3198
3198
3199 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3199 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3200 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3200 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3201 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3201 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3202
3202
3203 users_group = relationship('UserGroup')
3203 users_group = relationship('UserGroup')
3204 permission = relationship('Permission')
3204 permission = relationship('Permission')
3205
3205
3206
3206
3207 class UserRepoGroupToPerm(Base, BaseModel):
3207 class UserRepoGroupToPerm(Base, BaseModel):
3208 __tablename__ = 'user_repo_group_to_perm'
3208 __tablename__ = 'user_repo_group_to_perm'
3209 __table_args__ = (
3209 __table_args__ = (
3210 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3210 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3211 base_table_args
3211 base_table_args
3212 )
3212 )
3213
3213
3214 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3214 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3215 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3215 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3216 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3216 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3217 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3217 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3218
3218
3219 user = relationship('User')
3219 user = relationship('User')
3220 group = relationship('RepoGroup')
3220 group = relationship('RepoGroup')
3221 permission = relationship('Permission')
3221 permission = relationship('Permission')
3222
3222
3223 @classmethod
3223 @classmethod
3224 def create(cls, user, repository_group, permission):
3224 def create(cls, user, repository_group, permission):
3225 n = cls()
3225 n = cls()
3226 n.user = user
3226 n.user = user
3227 n.group = repository_group
3227 n.group = repository_group
3228 n.permission = permission
3228 n.permission = permission
3229 Session().add(n)
3229 Session().add(n)
3230 return n
3230 return n
3231
3231
3232
3232
3233 class UserGroupRepoGroupToPerm(Base, BaseModel):
3233 class UserGroupRepoGroupToPerm(Base, BaseModel):
3234 __tablename__ = 'users_group_repo_group_to_perm'
3234 __tablename__ = 'users_group_repo_group_to_perm'
3235 __table_args__ = (
3235 __table_args__ = (
3236 UniqueConstraint('users_group_id', 'group_id'),
3236 UniqueConstraint('users_group_id', 'group_id'),
3237 base_table_args
3237 base_table_args
3238 )
3238 )
3239
3239
3240 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)
3240 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)
3241 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3241 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3242 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3242 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3243 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3243 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3244
3244
3245 users_group = relationship('UserGroup')
3245 users_group = relationship('UserGroup')
3246 permission = relationship('Permission')
3246 permission = relationship('Permission')
3247 group = relationship('RepoGroup')
3247 group = relationship('RepoGroup')
3248
3248
3249 @classmethod
3249 @classmethod
3250 def create(cls, user_group, repository_group, permission):
3250 def create(cls, user_group, repository_group, permission):
3251 n = cls()
3251 n = cls()
3252 n.users_group = user_group
3252 n.users_group = user_group
3253 n.group = repository_group
3253 n.group = repository_group
3254 n.permission = permission
3254 n.permission = permission
3255 Session().add(n)
3255 Session().add(n)
3256 return n
3256 return n
3257
3257
3258 def __unicode__(self):
3258 def __unicode__(self):
3259 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3259 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3260
3260
3261
3261
3262 class Statistics(Base, BaseModel):
3262 class Statistics(Base, BaseModel):
3263 __tablename__ = 'statistics'
3263 __tablename__ = 'statistics'
3264 __table_args__ = (
3264 __table_args__ = (
3265 base_table_args
3265 base_table_args
3266 )
3266 )
3267
3267
3268 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3268 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3269 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3269 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3270 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3270 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3271 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3271 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3272 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3272 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3273 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3273 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3274
3274
3275 repository = relationship('Repository', single_parent=True)
3275 repository = relationship('Repository', single_parent=True)
3276
3276
3277
3277
3278 class UserFollowing(Base, BaseModel):
3278 class UserFollowing(Base, BaseModel):
3279 __tablename__ = 'user_followings'
3279 __tablename__ = 'user_followings'
3280 __table_args__ = (
3280 __table_args__ = (
3281 UniqueConstraint('user_id', 'follows_repository_id'),
3281 UniqueConstraint('user_id', 'follows_repository_id'),
3282 UniqueConstraint('user_id', 'follows_user_id'),
3282 UniqueConstraint('user_id', 'follows_user_id'),
3283 base_table_args
3283 base_table_args
3284 )
3284 )
3285
3285
3286 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3286 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3287 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3287 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3288 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3288 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3289 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3289 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3290 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3290 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3291
3291
3292 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3292 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3293
3293
3294 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3294 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3295 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3295 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3296
3296
3297 @classmethod
3297 @classmethod
3298 def get_repo_followers(cls, repo_id):
3298 def get_repo_followers(cls, repo_id):
3299 return cls.query().filter(cls.follows_repo_id == repo_id)
3299 return cls.query().filter(cls.follows_repo_id == repo_id)
3300
3300
3301
3301
3302 class CacheKey(Base, BaseModel):
3302 class CacheKey(Base, BaseModel):
3303 __tablename__ = 'cache_invalidation'
3303 __tablename__ = 'cache_invalidation'
3304 __table_args__ = (
3304 __table_args__ = (
3305 UniqueConstraint('cache_key'),
3305 UniqueConstraint('cache_key'),
3306 Index('key_idx', 'cache_key'),
3306 Index('key_idx', 'cache_key'),
3307 base_table_args,
3307 base_table_args,
3308 )
3308 )
3309
3309
3310 CACHE_TYPE_FEED = 'FEED'
3310 CACHE_TYPE_FEED = 'FEED'
3311 CACHE_TYPE_README = 'README'
3311 CACHE_TYPE_README = 'README'
3312 # namespaces used to register process/thread aware caches
3312 # namespaces used to register process/thread aware caches
3313 REPO_INVALIDATION_NAMESPACE = 'repo_cache:{repo_id}'
3313 REPO_INVALIDATION_NAMESPACE = 'repo_cache:{repo_id}'
3314 SETTINGS_INVALIDATION_NAMESPACE = 'system_settings'
3314 SETTINGS_INVALIDATION_NAMESPACE = 'system_settings'
3315
3315
3316 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3316 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3317 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3317 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3318 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3318 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3319 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3319 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3320
3320
3321 def __init__(self, cache_key, cache_args=''):
3321 def __init__(self, cache_key, cache_args=''):
3322 self.cache_key = cache_key
3322 self.cache_key = cache_key
3323 self.cache_args = cache_args
3323 self.cache_args = cache_args
3324 self.cache_active = False
3324 self.cache_active = False
3325
3325
3326 def __unicode__(self):
3326 def __unicode__(self):
3327 return u"<%s('%s:%s[%s]')>" % (
3327 return u"<%s('%s:%s[%s]')>" % (
3328 self.__class__.__name__,
3328 self.__class__.__name__,
3329 self.cache_id, self.cache_key, self.cache_active)
3329 self.cache_id, self.cache_key, self.cache_active)
3330
3330
3331 def _cache_key_partition(self):
3331 def _cache_key_partition(self):
3332 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3332 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3333 return prefix, repo_name, suffix
3333 return prefix, repo_name, suffix
3334
3334
3335 def get_prefix(self):
3335 def get_prefix(self):
3336 """
3336 """
3337 Try to extract prefix from existing cache key. The key could consist
3337 Try to extract prefix from existing cache key. The key could consist
3338 of prefix, repo_name, suffix
3338 of prefix, repo_name, suffix
3339 """
3339 """
3340 # this returns prefix, repo_name, suffix
3340 # this returns prefix, repo_name, suffix
3341 return self._cache_key_partition()[0]
3341 return self._cache_key_partition()[0]
3342
3342
3343 def get_suffix(self):
3343 def get_suffix(self):
3344 """
3344 """
3345 get suffix that might have been used in _get_cache_key to
3345 get suffix that might have been used in _get_cache_key to
3346 generate self.cache_key. Only used for informational purposes
3346 generate self.cache_key. Only used for informational purposes
3347 in repo_edit.mako.
3347 in repo_edit.mako.
3348 """
3348 """
3349 # prefix, repo_name, suffix
3349 # prefix, repo_name, suffix
3350 return self._cache_key_partition()[2]
3350 return self._cache_key_partition()[2]
3351
3351
3352 @classmethod
3352 @classmethod
3353 def delete_all_cache(cls):
3353 def delete_all_cache(cls):
3354 """
3354 """
3355 Delete all cache keys from database.
3355 Delete all cache keys from database.
3356 Should only be run when all instances are down and all entries
3356 Should only be run when all instances are down and all entries
3357 thus stale.
3357 thus stale.
3358 """
3358 """
3359 cls.query().delete()
3359 cls.query().delete()
3360 Session().commit()
3360 Session().commit()
3361
3361
3362 @classmethod
3362 @classmethod
3363 def set_invalidate(cls, cache_uid, delete=False):
3363 def set_invalidate(cls, cache_uid, delete=False):
3364 """
3364 """
3365 Mark all caches of a repo as invalid in the database.
3365 Mark all caches of a repo as invalid in the database.
3366 """
3366 """
3367
3367
3368 try:
3368 try:
3369 qry = Session().query(cls).filter(cls.cache_args == cache_uid)
3369 qry = Session().query(cls).filter(cls.cache_args == cache_uid)
3370 if delete:
3370 if delete:
3371 qry.delete()
3371 qry.delete()
3372 log.debug('cache objects deleted for cache args %s',
3372 log.debug('cache objects deleted for cache args %s',
3373 safe_str(cache_uid))
3373 safe_str(cache_uid))
3374 else:
3374 else:
3375 qry.update({"cache_active": False})
3375 qry.update({"cache_active": False})
3376 log.debug('cache objects marked as invalid for cache args %s',
3376 log.debug('cache objects marked as invalid for cache args %s',
3377 safe_str(cache_uid))
3377 safe_str(cache_uid))
3378
3378
3379 Session().commit()
3379 Session().commit()
3380 except Exception:
3380 except Exception:
3381 log.exception(
3381 log.exception(
3382 'Cache key invalidation failed for cache args %s',
3382 'Cache key invalidation failed for cache args %s',
3383 safe_str(cache_uid))
3383 safe_str(cache_uid))
3384 Session().rollback()
3384 Session().rollback()
3385
3385
3386 @classmethod
3386 @classmethod
3387 def get_active_cache(cls, cache_key):
3387 def get_active_cache(cls, cache_key):
3388 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3388 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3389 if inv_obj:
3389 if inv_obj:
3390 return inv_obj
3390 return inv_obj
3391 return None
3391 return None
3392
3392
3393
3393
3394 class ChangesetComment(Base, BaseModel):
3394 class ChangesetComment(Base, BaseModel):
3395 __tablename__ = 'changeset_comments'
3395 __tablename__ = 'changeset_comments'
3396 __table_args__ = (
3396 __table_args__ = (
3397 Index('cc_revision_idx', 'revision'),
3397 Index('cc_revision_idx', 'revision'),
3398 base_table_args,
3398 base_table_args,
3399 )
3399 )
3400
3400
3401 COMMENT_OUTDATED = u'comment_outdated'
3401 COMMENT_OUTDATED = u'comment_outdated'
3402 COMMENT_TYPE_NOTE = u'note'
3402 COMMENT_TYPE_NOTE = u'note'
3403 COMMENT_TYPE_TODO = u'todo'
3403 COMMENT_TYPE_TODO = u'todo'
3404 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3404 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3405
3405
3406 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3406 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3407 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3407 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3408 revision = Column('revision', String(40), nullable=True)
3408 revision = Column('revision', String(40), nullable=True)
3409 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3409 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3410 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3410 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3411 line_no = Column('line_no', Unicode(10), nullable=True)
3411 line_no = Column('line_no', Unicode(10), nullable=True)
3412 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3412 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3413 f_path = Column('f_path', Unicode(1000), nullable=True)
3413 f_path = Column('f_path', Unicode(1000), nullable=True)
3414 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3414 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3415 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3415 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3416 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3416 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3417 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3417 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3418 renderer = Column('renderer', Unicode(64), nullable=True)
3418 renderer = Column('renderer', Unicode(64), nullable=True)
3419 display_state = Column('display_state', Unicode(128), nullable=True)
3419 display_state = Column('display_state', Unicode(128), nullable=True)
3420
3420
3421 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3421 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3422 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3422 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3423
3423
3424 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3424 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3425 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3425 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3426
3426
3427 author = relationship('User', lazy='joined')
3427 author = relationship('User', lazy='joined')
3428 repo = relationship('Repository')
3428 repo = relationship('Repository')
3429 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3429 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3430 pull_request = relationship('PullRequest', lazy='joined')
3430 pull_request = relationship('PullRequest', lazy='joined')
3431 pull_request_version = relationship('PullRequestVersion')
3431 pull_request_version = relationship('PullRequestVersion')
3432
3432
3433 @classmethod
3433 @classmethod
3434 def get_users(cls, revision=None, pull_request_id=None):
3434 def get_users(cls, revision=None, pull_request_id=None):
3435 """
3435 """
3436 Returns user associated with this ChangesetComment. ie those
3436 Returns user associated with this ChangesetComment. ie those
3437 who actually commented
3437 who actually commented
3438
3438
3439 :param cls:
3439 :param cls:
3440 :param revision:
3440 :param revision:
3441 """
3441 """
3442 q = Session().query(User)\
3442 q = Session().query(User)\
3443 .join(ChangesetComment.author)
3443 .join(ChangesetComment.author)
3444 if revision:
3444 if revision:
3445 q = q.filter(cls.revision == revision)
3445 q = q.filter(cls.revision == revision)
3446 elif pull_request_id:
3446 elif pull_request_id:
3447 q = q.filter(cls.pull_request_id == pull_request_id)
3447 q = q.filter(cls.pull_request_id == pull_request_id)
3448 return q.all()
3448 return q.all()
3449
3449
3450 @classmethod
3450 @classmethod
3451 def get_index_from_version(cls, pr_version, versions):
3451 def get_index_from_version(cls, pr_version, versions):
3452 num_versions = [x.pull_request_version_id for x in versions]
3452 num_versions = [x.pull_request_version_id for x in versions]
3453 try:
3453 try:
3454 return num_versions.index(pr_version) +1
3454 return num_versions.index(pr_version) +1
3455 except (IndexError, ValueError):
3455 except (IndexError, ValueError):
3456 return
3456 return
3457
3457
3458 @property
3458 @property
3459 def outdated(self):
3459 def outdated(self):
3460 return self.display_state == self.COMMENT_OUTDATED
3460 return self.display_state == self.COMMENT_OUTDATED
3461
3461
3462 def outdated_at_version(self, version):
3462 def outdated_at_version(self, version):
3463 """
3463 """
3464 Checks if comment is outdated for given pull request version
3464 Checks if comment is outdated for given pull request version
3465 """
3465 """
3466 return self.outdated and self.pull_request_version_id != version
3466 return self.outdated and self.pull_request_version_id != version
3467
3467
3468 def older_than_version(self, version):
3468 def older_than_version(self, version):
3469 """
3469 """
3470 Checks if comment is made from previous version than given
3470 Checks if comment is made from previous version than given
3471 """
3471 """
3472 if version is None:
3472 if version is None:
3473 return self.pull_request_version_id is not None
3473 return self.pull_request_version_id is not None
3474
3474
3475 return self.pull_request_version_id < version
3475 return self.pull_request_version_id < version
3476
3476
3477 @property
3477 @property
3478 def resolved(self):
3478 def resolved(self):
3479 return self.resolved_by[0] if self.resolved_by else None
3479 return self.resolved_by[0] if self.resolved_by else None
3480
3480
3481 @property
3481 @property
3482 def is_todo(self):
3482 def is_todo(self):
3483 return self.comment_type == self.COMMENT_TYPE_TODO
3483 return self.comment_type == self.COMMENT_TYPE_TODO
3484
3484
3485 @property
3485 @property
3486 def is_inline(self):
3486 def is_inline(self):
3487 return self.line_no and self.f_path
3487 return self.line_no and self.f_path
3488
3488
3489 def get_index_version(self, versions):
3489 def get_index_version(self, versions):
3490 return self.get_index_from_version(
3490 return self.get_index_from_version(
3491 self.pull_request_version_id, versions)
3491 self.pull_request_version_id, versions)
3492
3492
3493 def __repr__(self):
3493 def __repr__(self):
3494 if self.comment_id:
3494 if self.comment_id:
3495 return '<DB:Comment #%s>' % self.comment_id
3495 return '<DB:Comment #%s>' % self.comment_id
3496 else:
3496 else:
3497 return '<DB:Comment at %#x>' % id(self)
3497 return '<DB:Comment at %#x>' % id(self)
3498
3498
3499 def get_api_data(self):
3499 def get_api_data(self):
3500 comment = self
3500 comment = self
3501 data = {
3501 data = {
3502 'comment_id': comment.comment_id,
3502 'comment_id': comment.comment_id,
3503 'comment_type': comment.comment_type,
3503 'comment_type': comment.comment_type,
3504 'comment_text': comment.text,
3504 'comment_text': comment.text,
3505 'comment_status': comment.status_change,
3505 'comment_status': comment.status_change,
3506 'comment_f_path': comment.f_path,
3506 'comment_f_path': comment.f_path,
3507 'comment_lineno': comment.line_no,
3507 'comment_lineno': comment.line_no,
3508 'comment_author': comment.author,
3508 'comment_author': comment.author,
3509 'comment_created_on': comment.created_on,
3509 'comment_created_on': comment.created_on,
3510 'comment_resolved_by': self.resolved
3510 'comment_resolved_by': self.resolved
3511 }
3511 }
3512 return data
3512 return data
3513
3513
3514 def __json__(self):
3514 def __json__(self):
3515 data = dict()
3515 data = dict()
3516 data.update(self.get_api_data())
3516 data.update(self.get_api_data())
3517 return data
3517 return data
3518
3518
3519
3519
3520 class ChangesetStatus(Base, BaseModel):
3520 class ChangesetStatus(Base, BaseModel):
3521 __tablename__ = 'changeset_statuses'
3521 __tablename__ = 'changeset_statuses'
3522 __table_args__ = (
3522 __table_args__ = (
3523 Index('cs_revision_idx', 'revision'),
3523 Index('cs_revision_idx', 'revision'),
3524 Index('cs_version_idx', 'version'),
3524 Index('cs_version_idx', 'version'),
3525 UniqueConstraint('repo_id', 'revision', 'version'),
3525 UniqueConstraint('repo_id', 'revision', 'version'),
3526 base_table_args
3526 base_table_args
3527 )
3527 )
3528
3528
3529 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3529 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3530 STATUS_APPROVED = 'approved'
3530 STATUS_APPROVED = 'approved'
3531 STATUS_REJECTED = 'rejected'
3531 STATUS_REJECTED = 'rejected'
3532 STATUS_UNDER_REVIEW = 'under_review'
3532 STATUS_UNDER_REVIEW = 'under_review'
3533
3533
3534 STATUSES = [
3534 STATUSES = [
3535 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3535 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3536 (STATUS_APPROVED, _("Approved")),
3536 (STATUS_APPROVED, _("Approved")),
3537 (STATUS_REJECTED, _("Rejected")),
3537 (STATUS_REJECTED, _("Rejected")),
3538 (STATUS_UNDER_REVIEW, _("Under Review")),
3538 (STATUS_UNDER_REVIEW, _("Under Review")),
3539 ]
3539 ]
3540
3540
3541 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3541 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3542 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3542 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3543 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3543 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3544 revision = Column('revision', String(40), nullable=False)
3544 revision = Column('revision', String(40), nullable=False)
3545 status = Column('status', String(128), nullable=False, default=DEFAULT)
3545 status = Column('status', String(128), nullable=False, default=DEFAULT)
3546 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3546 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3547 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3547 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3548 version = Column('version', Integer(), nullable=False, default=0)
3548 version = Column('version', Integer(), nullable=False, default=0)
3549 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3549 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3550
3550
3551 author = relationship('User', lazy='joined')
3551 author = relationship('User', lazy='joined')
3552 repo = relationship('Repository')
3552 repo = relationship('Repository')
3553 comment = relationship('ChangesetComment', lazy='joined')
3553 comment = relationship('ChangesetComment', lazy='joined')
3554 pull_request = relationship('PullRequest', lazy='joined')
3554 pull_request = relationship('PullRequest', lazy='joined')
3555
3555
3556 def __unicode__(self):
3556 def __unicode__(self):
3557 return u"<%s('%s[v%s]:%s')>" % (
3557 return u"<%s('%s[v%s]:%s')>" % (
3558 self.__class__.__name__,
3558 self.__class__.__name__,
3559 self.status, self.version, self.author
3559 self.status, self.version, self.author
3560 )
3560 )
3561
3561
3562 @classmethod
3562 @classmethod
3563 def get_status_lbl(cls, value):
3563 def get_status_lbl(cls, value):
3564 return dict(cls.STATUSES).get(value)
3564 return dict(cls.STATUSES).get(value)
3565
3565
3566 @property
3566 @property
3567 def status_lbl(self):
3567 def status_lbl(self):
3568 return ChangesetStatus.get_status_lbl(self.status)
3568 return ChangesetStatus.get_status_lbl(self.status)
3569
3569
3570 def get_api_data(self):
3570 def get_api_data(self):
3571 status = self
3571 status = self
3572 data = {
3572 data = {
3573 'status_id': status.changeset_status_id,
3573 'status_id': status.changeset_status_id,
3574 'status': status.status,
3574 'status': status.status,
3575 }
3575 }
3576 return data
3576 return data
3577
3577
3578 def __json__(self):
3578 def __json__(self):
3579 data = dict()
3579 data = dict()
3580 data.update(self.get_api_data())
3580 data.update(self.get_api_data())
3581 return data
3581 return data
3582
3582
3583
3583
3584 class _SetState(object):
3584 class _SetState(object):
3585 """
3585 """
3586 Context processor allowing changing state for sensitive operation such as
3586 Context processor allowing changing state for sensitive operation such as
3587 pull request update or merge
3587 pull request update or merge
3588 """
3588 """
3589
3589
3590 def __init__(self, pull_request, pr_state, back_state=None):
3590 def __init__(self, pull_request, pr_state, back_state=None):
3591 self._pr = pull_request
3591 self._pr = pull_request
3592 self._org_state = back_state or pull_request.pull_request_state
3592 self._org_state = back_state or pull_request.pull_request_state
3593 self._pr_state = pr_state
3593 self._pr_state = pr_state
3594
3594
3595 def __enter__(self):
3595 def __enter__(self):
3596 log.debug('StateLock: entering set state context, setting state to: `%s`',
3596 log.debug('StateLock: entering set state context, setting state to: `%s`',
3597 self._pr_state)
3597 self._pr_state)
3598 self._pr.pull_request_state = self._pr_state
3598 self._pr.pull_request_state = self._pr_state
3599 Session().add(self._pr)
3599 Session().add(self._pr)
3600 Session().commit()
3600 Session().commit()
3601
3601
3602 def __exit__(self, exc_type, exc_val, exc_tb):
3602 def __exit__(self, exc_type, exc_val, exc_tb):
3603 log.debug('StateLock: exiting set state context, setting state to: `%s`',
3603 log.debug('StateLock: exiting set state context, setting state to: `%s`',
3604 self._org_state)
3604 self._org_state)
3605 self._pr.pull_request_state = self._org_state
3605 self._pr.pull_request_state = self._org_state
3606 Session().add(self._pr)
3606 Session().add(self._pr)
3607 Session().commit()
3607 Session().commit()
3608
3608
3609
3609
3610 class _PullRequestBase(BaseModel):
3610 class _PullRequestBase(BaseModel):
3611 """
3611 """
3612 Common attributes of pull request and version entries.
3612 Common attributes of pull request and version entries.
3613 """
3613 """
3614
3614
3615 # .status values
3615 # .status values
3616 STATUS_NEW = u'new'
3616 STATUS_NEW = u'new'
3617 STATUS_OPEN = u'open'
3617 STATUS_OPEN = u'open'
3618 STATUS_CLOSED = u'closed'
3618 STATUS_CLOSED = u'closed'
3619
3619
3620 # available states
3620 # available states
3621 STATE_CREATING = u'creating'
3621 STATE_CREATING = u'creating'
3622 STATE_UPDATING = u'updating'
3622 STATE_UPDATING = u'updating'
3623 STATE_MERGING = u'merging'
3623 STATE_MERGING = u'merging'
3624 STATE_CREATED = u'created'
3624 STATE_CREATED = u'created'
3625
3625
3626 title = Column('title', Unicode(255), nullable=True)
3626 title = Column('title', Unicode(255), nullable=True)
3627 description = Column(
3627 description = Column(
3628 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3628 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3629 nullable=True)
3629 nullable=True)
3630 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3630 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3631
3631
3632 # new/open/closed status of pull request (not approve/reject/etc)
3632 # new/open/closed status of pull request (not approve/reject/etc)
3633 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3633 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3634 created_on = Column(
3634 created_on = Column(
3635 'created_on', DateTime(timezone=False), nullable=False,
3635 'created_on', DateTime(timezone=False), nullable=False,
3636 default=datetime.datetime.now)
3636 default=datetime.datetime.now)
3637 updated_on = Column(
3637 updated_on = Column(
3638 'updated_on', DateTime(timezone=False), nullable=False,
3638 'updated_on', DateTime(timezone=False), nullable=False,
3639 default=datetime.datetime.now)
3639 default=datetime.datetime.now)
3640
3640
3641 pull_request_state = Column("pull_request_state", String(255), nullable=True)
3641 pull_request_state = Column("pull_request_state", String(255), nullable=True)
3642
3642
3643 @declared_attr
3643 @declared_attr
3644 def user_id(cls):
3644 def user_id(cls):
3645 return Column(
3645 return Column(
3646 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3646 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3647 unique=None)
3647 unique=None)
3648
3648
3649 # 500 revisions max
3649 # 500 revisions max
3650 _revisions = Column(
3650 _revisions = Column(
3651 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3651 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3652
3652
3653 @declared_attr
3653 @declared_attr
3654 def source_repo_id(cls):
3654 def source_repo_id(cls):
3655 # TODO: dan: rename column to source_repo_id
3655 # TODO: dan: rename column to source_repo_id
3656 return Column(
3656 return Column(
3657 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3657 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3658 nullable=False)
3658 nullable=False)
3659
3659
3660 _source_ref = Column('org_ref', Unicode(255), nullable=False)
3660 _source_ref = Column('org_ref', Unicode(255), nullable=False)
3661
3661
3662 @hybrid_property
3662 @hybrid_property
3663 def source_ref(self):
3663 def source_ref(self):
3664 return self._source_ref
3664 return self._source_ref
3665
3665
3666 @source_ref.setter
3666 @source_ref.setter
3667 def source_ref(self, val):
3667 def source_ref(self, val):
3668 parts = (val or '').split(':')
3668 parts = (val or '').split(':')
3669 if len(parts) != 3:
3669 if len(parts) != 3:
3670 raise ValueError(
3670 raise ValueError(
3671 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3671 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3672 self._source_ref = safe_unicode(val)
3672 self._source_ref = safe_unicode(val)
3673
3673
3674 _target_ref = Column('other_ref', Unicode(255), nullable=False)
3674 _target_ref = Column('other_ref', Unicode(255), nullable=False)
3675
3675
3676 @hybrid_property
3676 @hybrid_property
3677 def target_ref(self):
3677 def target_ref(self):
3678 return self._target_ref
3678 return self._target_ref
3679
3679
3680 @target_ref.setter
3680 @target_ref.setter
3681 def target_ref(self, val):
3681 def target_ref(self, val):
3682 parts = (val or '').split(':')
3682 parts = (val or '').split(':')
3683 if len(parts) != 3:
3683 if len(parts) != 3:
3684 raise ValueError(
3684 raise ValueError(
3685 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3685 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3686 self._target_ref = safe_unicode(val)
3686 self._target_ref = safe_unicode(val)
3687
3687
3688 @declared_attr
3688 @declared_attr
3689 def target_repo_id(cls):
3689 def target_repo_id(cls):
3690 # TODO: dan: rename column to target_repo_id
3690 # TODO: dan: rename column to target_repo_id
3691 return Column(
3691 return Column(
3692 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3692 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3693 nullable=False)
3693 nullable=False)
3694
3694
3695 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3695 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3696
3696
3697 # TODO: dan: rename column to last_merge_source_rev
3697 # TODO: dan: rename column to last_merge_source_rev
3698 _last_merge_source_rev = Column(
3698 _last_merge_source_rev = Column(
3699 'last_merge_org_rev', String(40), nullable=True)
3699 'last_merge_org_rev', String(40), nullable=True)
3700 # TODO: dan: rename column to last_merge_target_rev
3700 # TODO: dan: rename column to last_merge_target_rev
3701 _last_merge_target_rev = Column(
3701 _last_merge_target_rev = Column(
3702 'last_merge_other_rev', String(40), nullable=True)
3702 'last_merge_other_rev', String(40), nullable=True)
3703 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3703 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3704 merge_rev = Column('merge_rev', String(40), nullable=True)
3704 merge_rev = Column('merge_rev', String(40), nullable=True)
3705
3705
3706 reviewer_data = Column(
3706 reviewer_data = Column(
3707 'reviewer_data_json', MutationObj.as_mutable(
3707 'reviewer_data_json', MutationObj.as_mutable(
3708 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3708 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3709
3709
3710 @property
3710 @property
3711 def reviewer_data_json(self):
3711 def reviewer_data_json(self):
3712 return json.dumps(self.reviewer_data)
3712 return json.dumps(self.reviewer_data)
3713
3713
3714 @hybrid_property
3714 @hybrid_property
3715 def description_safe(self):
3715 def description_safe(self):
3716 from rhodecode.lib import helpers as h
3716 from rhodecode.lib import helpers as h
3717 return h.escape(self.description)
3717 return h.escape(self.description)
3718
3718
3719 @hybrid_property
3719 @hybrid_property
3720 def revisions(self):
3720 def revisions(self):
3721 return self._revisions.split(':') if self._revisions else []
3721 return self._revisions.split(':') if self._revisions else []
3722
3722
3723 @revisions.setter
3723 @revisions.setter
3724 def revisions(self, val):
3724 def revisions(self, val):
3725 self._revisions = ':'.join(val)
3725 self._revisions = ':'.join(val)
3726
3726
3727 @hybrid_property
3727 @hybrid_property
3728 def last_merge_status(self):
3728 def last_merge_status(self):
3729 return safe_int(self._last_merge_status)
3729 return safe_int(self._last_merge_status)
3730
3730
3731 @last_merge_status.setter
3731 @last_merge_status.setter
3732 def last_merge_status(self, val):
3732 def last_merge_status(self, val):
3733 self._last_merge_status = val
3733 self._last_merge_status = val
3734
3734
3735 @declared_attr
3735 @declared_attr
3736 def author(cls):
3736 def author(cls):
3737 return relationship('User', lazy='joined')
3737 return relationship('User', lazy='joined')
3738
3738
3739 @declared_attr
3739 @declared_attr
3740 def source_repo(cls):
3740 def source_repo(cls):
3741 return relationship(
3741 return relationship(
3742 'Repository',
3742 'Repository',
3743 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3743 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3744
3744
3745 @property
3745 @property
3746 def source_ref_parts(self):
3746 def source_ref_parts(self):
3747 return self.unicode_to_reference(self.source_ref)
3747 return self.unicode_to_reference(self.source_ref)
3748
3748
3749 @declared_attr
3749 @declared_attr
3750 def target_repo(cls):
3750 def target_repo(cls):
3751 return relationship(
3751 return relationship(
3752 'Repository',
3752 'Repository',
3753 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3753 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3754
3754
3755 @property
3755 @property
3756 def target_ref_parts(self):
3756 def target_ref_parts(self):
3757 return self.unicode_to_reference(self.target_ref)
3757 return self.unicode_to_reference(self.target_ref)
3758
3758
3759 @property
3759 @property
3760 def shadow_merge_ref(self):
3760 def shadow_merge_ref(self):
3761 return self.unicode_to_reference(self._shadow_merge_ref)
3761 return self.unicode_to_reference(self._shadow_merge_ref)
3762
3762
3763 @shadow_merge_ref.setter
3763 @shadow_merge_ref.setter
3764 def shadow_merge_ref(self, ref):
3764 def shadow_merge_ref(self, ref):
3765 self._shadow_merge_ref = self.reference_to_unicode(ref)
3765 self._shadow_merge_ref = self.reference_to_unicode(ref)
3766
3766
3767 @staticmethod
3767 @staticmethod
3768 def unicode_to_reference(raw):
3768 def unicode_to_reference(raw):
3769 """
3769 """
3770 Convert a unicode (or string) to a reference object.
3770 Convert a unicode (or string) to a reference object.
3771 If unicode evaluates to False it returns None.
3771 If unicode evaluates to False it returns None.
3772 """
3772 """
3773 if raw:
3773 if raw:
3774 refs = raw.split(':')
3774 refs = raw.split(':')
3775 return Reference(*refs)
3775 return Reference(*refs)
3776 else:
3776 else:
3777 return None
3777 return None
3778
3778
3779 @staticmethod
3779 @staticmethod
3780 def reference_to_unicode(ref):
3780 def reference_to_unicode(ref):
3781 """
3781 """
3782 Convert a reference object to unicode.
3782 Convert a reference object to unicode.
3783 If reference is None it returns None.
3783 If reference is None it returns None.
3784 """
3784 """
3785 if ref:
3785 if ref:
3786 return u':'.join(ref)
3786 return u':'.join(ref)
3787 else:
3787 else:
3788 return None
3788 return None
3789
3789
3790 def get_api_data(self, with_merge_state=True):
3790 def get_api_data(self, with_merge_state=True):
3791 from rhodecode.model.pull_request import PullRequestModel
3791 from rhodecode.model.pull_request import PullRequestModel
3792
3792
3793 pull_request = self
3793 pull_request = self
3794 if with_merge_state:
3794 if with_merge_state:
3795 merge_status = PullRequestModel().merge_status(pull_request)
3795 merge_status = PullRequestModel().merge_status(pull_request)
3796 merge_state = {
3796 merge_state = {
3797 'status': merge_status[0],
3797 'status': merge_status[0],
3798 'message': safe_unicode(merge_status[1]),
3798 'message': safe_unicode(merge_status[1]),
3799 }
3799 }
3800 else:
3800 else:
3801 merge_state = {'status': 'not_available',
3801 merge_state = {'status': 'not_available',
3802 'message': 'not_available'}
3802 'message': 'not_available'}
3803
3803
3804 merge_data = {
3804 merge_data = {
3805 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3805 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3806 'reference': (
3806 'reference': (
3807 pull_request.shadow_merge_ref._asdict()
3807 pull_request.shadow_merge_ref._asdict()
3808 if pull_request.shadow_merge_ref else None),
3808 if pull_request.shadow_merge_ref else None),
3809 }
3809 }
3810
3810
3811 data = {
3811 data = {
3812 'pull_request_id': pull_request.pull_request_id,
3812 'pull_request_id': pull_request.pull_request_id,
3813 'url': PullRequestModel().get_url(pull_request),
3813 'url': PullRequestModel().get_url(pull_request),
3814 'title': pull_request.title,
3814 'title': pull_request.title,
3815 'description': pull_request.description,
3815 'description': pull_request.description,
3816 'status': pull_request.status,
3816 'status': pull_request.status,
3817 'state': pull_request.pull_request_state,
3817 'state': pull_request.pull_request_state,
3818 'created_on': pull_request.created_on,
3818 'created_on': pull_request.created_on,
3819 'updated_on': pull_request.updated_on,
3819 'updated_on': pull_request.updated_on,
3820 'commit_ids': pull_request.revisions,
3820 'commit_ids': pull_request.revisions,
3821 'review_status': pull_request.calculated_review_status(),
3821 'review_status': pull_request.calculated_review_status(),
3822 'mergeable': merge_state,
3822 'mergeable': merge_state,
3823 'source': {
3823 'source': {
3824 'clone_url': pull_request.source_repo.clone_url(),
3824 'clone_url': pull_request.source_repo.clone_url(),
3825 'repository': pull_request.source_repo.repo_name,
3825 'repository': pull_request.source_repo.repo_name,
3826 'reference': {
3826 'reference': {
3827 'name': pull_request.source_ref_parts.name,
3827 'name': pull_request.source_ref_parts.name,
3828 'type': pull_request.source_ref_parts.type,
3828 'type': pull_request.source_ref_parts.type,
3829 'commit_id': pull_request.source_ref_parts.commit_id,
3829 'commit_id': pull_request.source_ref_parts.commit_id,
3830 },
3830 },
3831 },
3831 },
3832 'target': {
3832 'target': {
3833 'clone_url': pull_request.target_repo.clone_url(),
3833 'clone_url': pull_request.target_repo.clone_url(),
3834 'repository': pull_request.target_repo.repo_name,
3834 'repository': pull_request.target_repo.repo_name,
3835 'reference': {
3835 'reference': {
3836 'name': pull_request.target_ref_parts.name,
3836 'name': pull_request.target_ref_parts.name,
3837 'type': pull_request.target_ref_parts.type,
3837 'type': pull_request.target_ref_parts.type,
3838 'commit_id': pull_request.target_ref_parts.commit_id,
3838 'commit_id': pull_request.target_ref_parts.commit_id,
3839 },
3839 },
3840 },
3840 },
3841 'merge': merge_data,
3841 'merge': merge_data,
3842 'author': pull_request.author.get_api_data(include_secrets=False,
3842 'author': pull_request.author.get_api_data(include_secrets=False,
3843 details='basic'),
3843 details='basic'),
3844 'reviewers': [
3844 'reviewers': [
3845 {
3845 {
3846 'user': reviewer.get_api_data(include_secrets=False,
3846 'user': reviewer.get_api_data(include_secrets=False,
3847 details='basic'),
3847 details='basic'),
3848 'reasons': reasons,
3848 'reasons': reasons,
3849 'review_status': st[0][1].status if st else 'not_reviewed',
3849 'review_status': st[0][1].status if st else 'not_reviewed',
3850 }
3850 }
3851 for obj, reviewer, reasons, mandatory, st in
3851 for obj, reviewer, reasons, mandatory, st in
3852 pull_request.reviewers_statuses()
3852 pull_request.reviewers_statuses()
3853 ]
3853 ]
3854 }
3854 }
3855
3855
3856 return data
3856 return data
3857
3857
3858 def set_state(self, pull_request_state, final_state=None):
3858 def set_state(self, pull_request_state, final_state=None):
3859 """
3859 """
3860 # goes from initial state to updating to initial state.
3860 # goes from initial state to updating to initial state.
3861 # initial state can be changed by specifying back_state=
3861 # initial state can be changed by specifying back_state=
3862 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
3862 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
3863 pull_request.merge()
3863 pull_request.merge()
3864
3864
3865 :param pull_request_state:
3865 :param pull_request_state:
3866 :param final_state:
3866 :param final_state:
3867
3867
3868 """
3868 """
3869
3869
3870 return _SetState(self, pull_request_state, back_state=final_state)
3870 return _SetState(self, pull_request_state, back_state=final_state)
3871
3871
3872
3872
3873 class PullRequest(Base, _PullRequestBase):
3873 class PullRequest(Base, _PullRequestBase):
3874 __tablename__ = 'pull_requests'
3874 __tablename__ = 'pull_requests'
3875 __table_args__ = (
3875 __table_args__ = (
3876 base_table_args,
3876 base_table_args,
3877 )
3877 )
3878
3878
3879 pull_request_id = Column(
3879 pull_request_id = Column(
3880 'pull_request_id', Integer(), nullable=False, primary_key=True)
3880 'pull_request_id', Integer(), nullable=False, primary_key=True)
3881
3881
3882 def __repr__(self):
3882 def __repr__(self):
3883 if self.pull_request_id:
3883 if self.pull_request_id:
3884 return '<DB:PullRequest #%s>' % self.pull_request_id
3884 return '<DB:PullRequest #%s>' % self.pull_request_id
3885 else:
3885 else:
3886 return '<DB:PullRequest at %#x>' % id(self)
3886 return '<DB:PullRequest at %#x>' % id(self)
3887
3887
3888 reviewers = relationship('PullRequestReviewers',
3888 reviewers = relationship('PullRequestReviewers',
3889 cascade="all, delete, delete-orphan")
3889 cascade="all, delete, delete-orphan")
3890 statuses = relationship('ChangesetStatus',
3890 statuses = relationship('ChangesetStatus',
3891 cascade="all, delete, delete-orphan")
3891 cascade="all, delete, delete-orphan")
3892 comments = relationship('ChangesetComment',
3892 comments = relationship('ChangesetComment',
3893 cascade="all, delete, delete-orphan")
3893 cascade="all, delete, delete-orphan")
3894 versions = relationship('PullRequestVersion',
3894 versions = relationship('PullRequestVersion',
3895 cascade="all, delete, delete-orphan",
3895 cascade="all, delete, delete-orphan",
3896 lazy='dynamic')
3896 lazy='dynamic')
3897
3897
3898 @classmethod
3898 @classmethod
3899 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3899 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3900 internal_methods=None):
3900 internal_methods=None):
3901
3901
3902 class PullRequestDisplay(object):
3902 class PullRequestDisplay(object):
3903 """
3903 """
3904 Special object wrapper for showing PullRequest data via Versions
3904 Special object wrapper for showing PullRequest data via Versions
3905 It mimics PR object as close as possible. This is read only object
3905 It mimics PR object as close as possible. This is read only object
3906 just for display
3906 just for display
3907 """
3907 """
3908
3908
3909 def __init__(self, attrs, internal=None):
3909 def __init__(self, attrs, internal=None):
3910 self.attrs = attrs
3910 self.attrs = attrs
3911 # internal have priority over the given ones via attrs
3911 # internal have priority over the given ones via attrs
3912 self.internal = internal or ['versions']
3912 self.internal = internal or ['versions']
3913
3913
3914 def __getattr__(self, item):
3914 def __getattr__(self, item):
3915 if item in self.internal:
3915 if item in self.internal:
3916 return getattr(self, item)
3916 return getattr(self, item)
3917 try:
3917 try:
3918 return self.attrs[item]
3918 return self.attrs[item]
3919 except KeyError:
3919 except KeyError:
3920 raise AttributeError(
3920 raise AttributeError(
3921 '%s object has no attribute %s' % (self, item))
3921 '%s object has no attribute %s' % (self, item))
3922
3922
3923 def __repr__(self):
3923 def __repr__(self):
3924 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3924 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3925
3925
3926 def versions(self):
3926 def versions(self):
3927 return pull_request_obj.versions.order_by(
3927 return pull_request_obj.versions.order_by(
3928 PullRequestVersion.pull_request_version_id).all()
3928 PullRequestVersion.pull_request_version_id).all()
3929
3929
3930 def is_closed(self):
3930 def is_closed(self):
3931 return pull_request_obj.is_closed()
3931 return pull_request_obj.is_closed()
3932
3932
3933 @property
3933 @property
3934 def pull_request_version_id(self):
3934 def pull_request_version_id(self):
3935 return getattr(pull_request_obj, 'pull_request_version_id', None)
3935 return getattr(pull_request_obj, 'pull_request_version_id', None)
3936
3936
3937 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3937 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3938
3938
3939 attrs.author = StrictAttributeDict(
3939 attrs.author = StrictAttributeDict(
3940 pull_request_obj.author.get_api_data())
3940 pull_request_obj.author.get_api_data())
3941 if pull_request_obj.target_repo:
3941 if pull_request_obj.target_repo:
3942 attrs.target_repo = StrictAttributeDict(
3942 attrs.target_repo = StrictAttributeDict(
3943 pull_request_obj.target_repo.get_api_data())
3943 pull_request_obj.target_repo.get_api_data())
3944 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3944 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3945
3945
3946 if pull_request_obj.source_repo:
3946 if pull_request_obj.source_repo:
3947 attrs.source_repo = StrictAttributeDict(
3947 attrs.source_repo = StrictAttributeDict(
3948 pull_request_obj.source_repo.get_api_data())
3948 pull_request_obj.source_repo.get_api_data())
3949 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3949 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3950
3950
3951 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3951 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3952 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3952 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3953 attrs.revisions = pull_request_obj.revisions
3953 attrs.revisions = pull_request_obj.revisions
3954
3954
3955 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3955 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3956 attrs.reviewer_data = org_pull_request_obj.reviewer_data
3956 attrs.reviewer_data = org_pull_request_obj.reviewer_data
3957 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
3957 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
3958
3958
3959 return PullRequestDisplay(attrs, internal=internal_methods)
3959 return PullRequestDisplay(attrs, internal=internal_methods)
3960
3960
3961 def is_closed(self):
3961 def is_closed(self):
3962 return self.status == self.STATUS_CLOSED
3962 return self.status == self.STATUS_CLOSED
3963
3963
3964 def __json__(self):
3964 def __json__(self):
3965 return {
3965 return {
3966 'revisions': self.revisions,
3966 'revisions': self.revisions,
3967 }
3967 }
3968
3968
3969 def calculated_review_status(self):
3969 def calculated_review_status(self):
3970 from rhodecode.model.changeset_status import ChangesetStatusModel
3970 from rhodecode.model.changeset_status import ChangesetStatusModel
3971 return ChangesetStatusModel().calculated_review_status(self)
3971 return ChangesetStatusModel().calculated_review_status(self)
3972
3972
3973 def reviewers_statuses(self):
3973 def reviewers_statuses(self):
3974 from rhodecode.model.changeset_status import ChangesetStatusModel
3974 from rhodecode.model.changeset_status import ChangesetStatusModel
3975 return ChangesetStatusModel().reviewers_statuses(self)
3975 return ChangesetStatusModel().reviewers_statuses(self)
3976
3976
3977 @property
3977 @property
3978 def workspace_id(self):
3978 def workspace_id(self):
3979 from rhodecode.model.pull_request import PullRequestModel
3979 from rhodecode.model.pull_request import PullRequestModel
3980 return PullRequestModel()._workspace_id(self)
3980 return PullRequestModel()._workspace_id(self)
3981
3981
3982 def get_shadow_repo(self):
3982 def get_shadow_repo(self):
3983 workspace_id = self.workspace_id
3983 workspace_id = self.workspace_id
3984 vcs_obj = self.target_repo.scm_instance()
3984 vcs_obj = self.target_repo.scm_instance()
3985 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3985 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3986 self.target_repo.repo_id, workspace_id)
3986 self.target_repo.repo_id, workspace_id)
3987 if os.path.isdir(shadow_repository_path):
3987 if os.path.isdir(shadow_repository_path):
3988 return vcs_obj._get_shadow_instance(shadow_repository_path)
3988 return vcs_obj._get_shadow_instance(shadow_repository_path)
3989
3989
3990
3990
3991 class PullRequestVersion(Base, _PullRequestBase):
3991 class PullRequestVersion(Base, _PullRequestBase):
3992 __tablename__ = 'pull_request_versions'
3992 __tablename__ = 'pull_request_versions'
3993 __table_args__ = (
3993 __table_args__ = (
3994 base_table_args,
3994 base_table_args,
3995 )
3995 )
3996
3996
3997 pull_request_version_id = Column(
3997 pull_request_version_id = Column(
3998 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3998 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3999 pull_request_id = Column(
3999 pull_request_id = Column(
4000 'pull_request_id', Integer(),
4000 'pull_request_id', Integer(),
4001 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4001 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4002 pull_request = relationship('PullRequest')
4002 pull_request = relationship('PullRequest')
4003
4003
4004 def __repr__(self):
4004 def __repr__(self):
4005 if self.pull_request_version_id:
4005 if self.pull_request_version_id:
4006 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
4006 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
4007 else:
4007 else:
4008 return '<DB:PullRequestVersion at %#x>' % id(self)
4008 return '<DB:PullRequestVersion at %#x>' % id(self)
4009
4009
4010 @property
4010 @property
4011 def reviewers(self):
4011 def reviewers(self):
4012 return self.pull_request.reviewers
4012 return self.pull_request.reviewers
4013
4013
4014 @property
4014 @property
4015 def versions(self):
4015 def versions(self):
4016 return self.pull_request.versions
4016 return self.pull_request.versions
4017
4017
4018 def is_closed(self):
4018 def is_closed(self):
4019 # calculate from original
4019 # calculate from original
4020 return self.pull_request.status == self.STATUS_CLOSED
4020 return self.pull_request.status == self.STATUS_CLOSED
4021
4021
4022 def calculated_review_status(self):
4022 def calculated_review_status(self):
4023 return self.pull_request.calculated_review_status()
4023 return self.pull_request.calculated_review_status()
4024
4024
4025 def reviewers_statuses(self):
4025 def reviewers_statuses(self):
4026 return self.pull_request.reviewers_statuses()
4026 return self.pull_request.reviewers_statuses()
4027
4027
4028
4028
4029 class PullRequestReviewers(Base, BaseModel):
4029 class PullRequestReviewers(Base, BaseModel):
4030 __tablename__ = 'pull_request_reviewers'
4030 __tablename__ = 'pull_request_reviewers'
4031 __table_args__ = (
4031 __table_args__ = (
4032 base_table_args,
4032 base_table_args,
4033 )
4033 )
4034
4034
4035 @hybrid_property
4035 @hybrid_property
4036 def reasons(self):
4036 def reasons(self):
4037 if not self._reasons:
4037 if not self._reasons:
4038 return []
4038 return []
4039 return self._reasons
4039 return self._reasons
4040
4040
4041 @reasons.setter
4041 @reasons.setter
4042 def reasons(self, val):
4042 def reasons(self, val):
4043 val = val or []
4043 val = val or []
4044 if any(not isinstance(x, compat.string_types) for x in val):
4044 if any(not isinstance(x, compat.string_types) for x in val):
4045 raise Exception('invalid reasons type, must be list of strings')
4045 raise Exception('invalid reasons type, must be list of strings')
4046 self._reasons = val
4046 self._reasons = val
4047
4047
4048 pull_requests_reviewers_id = Column(
4048 pull_requests_reviewers_id = Column(
4049 'pull_requests_reviewers_id', Integer(), nullable=False,
4049 'pull_requests_reviewers_id', Integer(), nullable=False,
4050 primary_key=True)
4050 primary_key=True)
4051 pull_request_id = Column(
4051 pull_request_id = Column(
4052 "pull_request_id", Integer(),
4052 "pull_request_id", Integer(),
4053 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4053 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4054 user_id = Column(
4054 user_id = Column(
4055 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4055 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4056 _reasons = Column(
4056 _reasons = Column(
4057 'reason', MutationList.as_mutable(
4057 'reason', MutationList.as_mutable(
4058 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4058 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4059
4059
4060 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4060 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4061 user = relationship('User')
4061 user = relationship('User')
4062 pull_request = relationship('PullRequest')
4062 pull_request = relationship('PullRequest')
4063
4063
4064 rule_data = Column(
4064 rule_data = Column(
4065 'rule_data_json',
4065 'rule_data_json',
4066 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4066 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4067
4067
4068 def rule_user_group_data(self):
4068 def rule_user_group_data(self):
4069 """
4069 """
4070 Returns the voting user group rule data for this reviewer
4070 Returns the voting user group rule data for this reviewer
4071 """
4071 """
4072
4072
4073 if self.rule_data and 'vote_rule' in self.rule_data:
4073 if self.rule_data and 'vote_rule' in self.rule_data:
4074 user_group_data = {}
4074 user_group_data = {}
4075 if 'rule_user_group_entry_id' in self.rule_data:
4075 if 'rule_user_group_entry_id' in self.rule_data:
4076 # means a group with voting rules !
4076 # means a group with voting rules !
4077 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4077 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4078 user_group_data['name'] = self.rule_data['rule_name']
4078 user_group_data['name'] = self.rule_data['rule_name']
4079 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4079 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4080
4080
4081 return user_group_data
4081 return user_group_data
4082
4082
4083 def __unicode__(self):
4083 def __unicode__(self):
4084 return u"<%s('id:%s')>" % (self.__class__.__name__,
4084 return u"<%s('id:%s')>" % (self.__class__.__name__,
4085 self.pull_requests_reviewers_id)
4085 self.pull_requests_reviewers_id)
4086
4086
4087
4087
4088 class Notification(Base, BaseModel):
4088 class Notification(Base, BaseModel):
4089 __tablename__ = 'notifications'
4089 __tablename__ = 'notifications'
4090 __table_args__ = (
4090 __table_args__ = (
4091 Index('notification_type_idx', 'type'),
4091 Index('notification_type_idx', 'type'),
4092 base_table_args,
4092 base_table_args,
4093 )
4093 )
4094
4094
4095 TYPE_CHANGESET_COMMENT = u'cs_comment'
4095 TYPE_CHANGESET_COMMENT = u'cs_comment'
4096 TYPE_MESSAGE = u'message'
4096 TYPE_MESSAGE = u'message'
4097 TYPE_MENTION = u'mention'
4097 TYPE_MENTION = u'mention'
4098 TYPE_REGISTRATION = u'registration'
4098 TYPE_REGISTRATION = u'registration'
4099 TYPE_PULL_REQUEST = u'pull_request'
4099 TYPE_PULL_REQUEST = u'pull_request'
4100 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
4100 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
4101
4101
4102 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4102 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4103 subject = Column('subject', Unicode(512), nullable=True)
4103 subject = Column('subject', Unicode(512), nullable=True)
4104 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4104 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4105 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4105 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4106 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4106 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4107 type_ = Column('type', Unicode(255))
4107 type_ = Column('type', Unicode(255))
4108
4108
4109 created_by_user = relationship('User')
4109 created_by_user = relationship('User')
4110 notifications_to_users = relationship('UserNotification', lazy='joined',
4110 notifications_to_users = relationship('UserNotification', lazy='joined',
4111 cascade="all, delete, delete-orphan")
4111 cascade="all, delete, delete-orphan")
4112
4112
4113 @property
4113 @property
4114 def recipients(self):
4114 def recipients(self):
4115 return [x.user for x in UserNotification.query()\
4115 return [x.user for x in UserNotification.query()\
4116 .filter(UserNotification.notification == self)\
4116 .filter(UserNotification.notification == self)\
4117 .order_by(UserNotification.user_id.asc()).all()]
4117 .order_by(UserNotification.user_id.asc()).all()]
4118
4118
4119 @classmethod
4119 @classmethod
4120 def create(cls, created_by, subject, body, recipients, type_=None):
4120 def create(cls, created_by, subject, body, recipients, type_=None):
4121 if type_ is None:
4121 if type_ is None:
4122 type_ = Notification.TYPE_MESSAGE
4122 type_ = Notification.TYPE_MESSAGE
4123
4123
4124 notification = cls()
4124 notification = cls()
4125 notification.created_by_user = created_by
4125 notification.created_by_user = created_by
4126 notification.subject = subject
4126 notification.subject = subject
4127 notification.body = body
4127 notification.body = body
4128 notification.type_ = type_
4128 notification.type_ = type_
4129 notification.created_on = datetime.datetime.now()
4129 notification.created_on = datetime.datetime.now()
4130
4130
4131 # For each recipient link the created notification to his account
4131 # For each recipient link the created notification to his account
4132 for u in recipients:
4132 for u in recipients:
4133 assoc = UserNotification()
4133 assoc = UserNotification()
4134 assoc.user_id = u.user_id
4134 assoc.user_id = u.user_id
4135 assoc.notification = notification
4135 assoc.notification = notification
4136
4136
4137 # if created_by is inside recipients mark his notification
4137 # if created_by is inside recipients mark his notification
4138 # as read
4138 # as read
4139 if u.user_id == created_by.user_id:
4139 if u.user_id == created_by.user_id:
4140 assoc.read = True
4140 assoc.read = True
4141 Session().add(assoc)
4141 Session().add(assoc)
4142
4142
4143 Session().add(notification)
4143 Session().add(notification)
4144
4144
4145 return notification
4145 return notification
4146
4146
4147
4147
4148 class UserNotification(Base, BaseModel):
4148 class UserNotification(Base, BaseModel):
4149 __tablename__ = 'user_to_notification'
4149 __tablename__ = 'user_to_notification'
4150 __table_args__ = (
4150 __table_args__ = (
4151 UniqueConstraint('user_id', 'notification_id'),
4151 UniqueConstraint('user_id', 'notification_id'),
4152 base_table_args
4152 base_table_args
4153 )
4153 )
4154
4154
4155 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4155 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4156 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4156 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4157 read = Column('read', Boolean, default=False)
4157 read = Column('read', Boolean, default=False)
4158 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4158 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4159
4159
4160 user = relationship('User', lazy="joined")
4160 user = relationship('User', lazy="joined")
4161 notification = relationship('Notification', lazy="joined",
4161 notification = relationship('Notification', lazy="joined",
4162 order_by=lambda: Notification.created_on.desc(),)
4162 order_by=lambda: Notification.created_on.desc(),)
4163
4163
4164 def mark_as_read(self):
4164 def mark_as_read(self):
4165 self.read = True
4165 self.read = True
4166 Session().add(self)
4166 Session().add(self)
4167
4167
4168
4168
4169 class Gist(Base, BaseModel):
4169 class Gist(Base, BaseModel):
4170 __tablename__ = 'gists'
4170 __tablename__ = 'gists'
4171 __table_args__ = (
4171 __table_args__ = (
4172 Index('g_gist_access_id_idx', 'gist_access_id'),
4172 Index('g_gist_access_id_idx', 'gist_access_id'),
4173 Index('g_created_on_idx', 'created_on'),
4173 Index('g_created_on_idx', 'created_on'),
4174 base_table_args
4174 base_table_args
4175 )
4175 )
4176
4176
4177 GIST_PUBLIC = u'public'
4177 GIST_PUBLIC = u'public'
4178 GIST_PRIVATE = u'private'
4178 GIST_PRIVATE = u'private'
4179 DEFAULT_FILENAME = u'gistfile1.txt'
4179 DEFAULT_FILENAME = u'gistfile1.txt'
4180
4180
4181 ACL_LEVEL_PUBLIC = u'acl_public'
4181 ACL_LEVEL_PUBLIC = u'acl_public'
4182 ACL_LEVEL_PRIVATE = u'acl_private'
4182 ACL_LEVEL_PRIVATE = u'acl_private'
4183
4183
4184 gist_id = Column('gist_id', Integer(), primary_key=True)
4184 gist_id = Column('gist_id', Integer(), primary_key=True)
4185 gist_access_id = Column('gist_access_id', Unicode(250))
4185 gist_access_id = Column('gist_access_id', Unicode(250))
4186 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4186 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4187 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4187 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4188 gist_expires = Column('gist_expires', Float(53), nullable=False)
4188 gist_expires = Column('gist_expires', Float(53), nullable=False)
4189 gist_type = Column('gist_type', Unicode(128), nullable=False)
4189 gist_type = Column('gist_type', Unicode(128), nullable=False)
4190 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4190 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4191 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4191 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4192 acl_level = Column('acl_level', Unicode(128), nullable=True)
4192 acl_level = Column('acl_level', Unicode(128), nullable=True)
4193
4193
4194 owner = relationship('User')
4194 owner = relationship('User')
4195
4195
4196 def __repr__(self):
4196 def __repr__(self):
4197 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4197 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4198
4198
4199 @hybrid_property
4199 @hybrid_property
4200 def description_safe(self):
4200 def description_safe(self):
4201 from rhodecode.lib import helpers as h
4201 from rhodecode.lib import helpers as h
4202 return h.escape(self.gist_description)
4202 return h.escape(self.gist_description)
4203
4203
4204 @classmethod
4204 @classmethod
4205 def get_or_404(cls, id_):
4205 def get_or_404(cls, id_):
4206 from pyramid.httpexceptions import HTTPNotFound
4206 from pyramid.httpexceptions import HTTPNotFound
4207
4207
4208 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4208 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4209 if not res:
4209 if not res:
4210 raise HTTPNotFound()
4210 raise HTTPNotFound()
4211 return res
4211 return res
4212
4212
4213 @classmethod
4213 @classmethod
4214 def get_by_access_id(cls, gist_access_id):
4214 def get_by_access_id(cls, gist_access_id):
4215 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4215 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4216
4216
4217 def gist_url(self):
4217 def gist_url(self):
4218 from rhodecode.model.gist import GistModel
4218 from rhodecode.model.gist import GistModel
4219 return GistModel().get_url(self)
4219 return GistModel().get_url(self)
4220
4220
4221 @classmethod
4221 @classmethod
4222 def base_path(cls):
4222 def base_path(cls):
4223 """
4223 """
4224 Returns base path when all gists are stored
4224 Returns base path when all gists are stored
4225
4225
4226 :param cls:
4226 :param cls:
4227 """
4227 """
4228 from rhodecode.model.gist import GIST_STORE_LOC
4228 from rhodecode.model.gist import GIST_STORE_LOC
4229 q = Session().query(RhodeCodeUi)\
4229 q = Session().query(RhodeCodeUi)\
4230 .filter(RhodeCodeUi.ui_key == URL_SEP)
4230 .filter(RhodeCodeUi.ui_key == URL_SEP)
4231 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4231 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4232 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4232 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4233
4233
4234 def get_api_data(self):
4234 def get_api_data(self):
4235 """
4235 """
4236 Common function for generating gist related data for API
4236 Common function for generating gist related data for API
4237 """
4237 """
4238 gist = self
4238 gist = self
4239 data = {
4239 data = {
4240 'gist_id': gist.gist_id,
4240 'gist_id': gist.gist_id,
4241 'type': gist.gist_type,
4241 'type': gist.gist_type,
4242 'access_id': gist.gist_access_id,
4242 'access_id': gist.gist_access_id,
4243 'description': gist.gist_description,
4243 'description': gist.gist_description,
4244 'url': gist.gist_url(),
4244 'url': gist.gist_url(),
4245 'expires': gist.gist_expires,
4245 'expires': gist.gist_expires,
4246 'created_on': gist.created_on,
4246 'created_on': gist.created_on,
4247 'modified_at': gist.modified_at,
4247 'modified_at': gist.modified_at,
4248 'content': None,
4248 'content': None,
4249 'acl_level': gist.acl_level,
4249 'acl_level': gist.acl_level,
4250 }
4250 }
4251 return data
4251 return data
4252
4252
4253 def __json__(self):
4253 def __json__(self):
4254 data = dict(
4254 data = dict(
4255 )
4255 )
4256 data.update(self.get_api_data())
4256 data.update(self.get_api_data())
4257 return data
4257 return data
4258 # SCM functions
4258 # SCM functions
4259
4259
4260 def scm_instance(self, **kwargs):
4260 def scm_instance(self, **kwargs):
4261 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4261 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4262 return get_vcs_instance(
4262 return get_vcs_instance(
4263 repo_path=safe_str(full_repo_path), create=False)
4263 repo_path=safe_str(full_repo_path), create=False)
4264
4264
4265
4265
4266 class ExternalIdentity(Base, BaseModel):
4266 class ExternalIdentity(Base, BaseModel):
4267 __tablename__ = 'external_identities'
4267 __tablename__ = 'external_identities'
4268 __table_args__ = (
4268 __table_args__ = (
4269 Index('local_user_id_idx', 'local_user_id'),
4269 Index('local_user_id_idx', 'local_user_id'),
4270 Index('external_id_idx', 'external_id'),
4270 Index('external_id_idx', 'external_id'),
4271 base_table_args
4271 base_table_args
4272 )
4272 )
4273
4273
4274 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4274 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4275 external_username = Column('external_username', Unicode(1024), default=u'')
4275 external_username = Column('external_username', Unicode(1024), default=u'')
4276 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4276 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4277 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4277 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4278 access_token = Column('access_token', String(1024), default=u'')
4278 access_token = Column('access_token', String(1024), default=u'')
4279 alt_token = Column('alt_token', String(1024), default=u'')
4279 alt_token = Column('alt_token', String(1024), default=u'')
4280 token_secret = Column('token_secret', String(1024), default=u'')
4280 token_secret = Column('token_secret', String(1024), default=u'')
4281
4281
4282 @classmethod
4282 @classmethod
4283 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4283 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4284 """
4284 """
4285 Returns ExternalIdentity instance based on search params
4285 Returns ExternalIdentity instance based on search params
4286
4286
4287 :param external_id:
4287 :param external_id:
4288 :param provider_name:
4288 :param provider_name:
4289 :return: ExternalIdentity
4289 :return: ExternalIdentity
4290 """
4290 """
4291 query = cls.query()
4291 query = cls.query()
4292 query = query.filter(cls.external_id == external_id)
4292 query = query.filter(cls.external_id == external_id)
4293 query = query.filter(cls.provider_name == provider_name)
4293 query = query.filter(cls.provider_name == provider_name)
4294 if local_user_id:
4294 if local_user_id:
4295 query = query.filter(cls.local_user_id == local_user_id)
4295 query = query.filter(cls.local_user_id == local_user_id)
4296 return query.first()
4296 return query.first()
4297
4297
4298 @classmethod
4298 @classmethod
4299 def user_by_external_id_and_provider(cls, external_id, provider_name):
4299 def user_by_external_id_and_provider(cls, external_id, provider_name):
4300 """
4300 """
4301 Returns User instance based on search params
4301 Returns User instance based on search params
4302
4302
4303 :param external_id:
4303 :param external_id:
4304 :param provider_name:
4304 :param provider_name:
4305 :return: User
4305 :return: User
4306 """
4306 """
4307 query = User.query()
4307 query = User.query()
4308 query = query.filter(cls.external_id == external_id)
4308 query = query.filter(cls.external_id == external_id)
4309 query = query.filter(cls.provider_name == provider_name)
4309 query = query.filter(cls.provider_name == provider_name)
4310 query = query.filter(User.user_id == cls.local_user_id)
4310 query = query.filter(User.user_id == cls.local_user_id)
4311 return query.first()
4311 return query.first()
4312
4312
4313 @classmethod
4313 @classmethod
4314 def by_local_user_id(cls, local_user_id):
4314 def by_local_user_id(cls, local_user_id):
4315 """
4315 """
4316 Returns all tokens for user
4316 Returns all tokens for user
4317
4317
4318 :param local_user_id:
4318 :param local_user_id:
4319 :return: ExternalIdentity
4319 :return: ExternalIdentity
4320 """
4320 """
4321 query = cls.query()
4321 query = cls.query()
4322 query = query.filter(cls.local_user_id == local_user_id)
4322 query = query.filter(cls.local_user_id == local_user_id)
4323 return query
4323 return query
4324
4324
4325 @classmethod
4325 @classmethod
4326 def load_provider_plugin(cls, plugin_id):
4326 def load_provider_plugin(cls, plugin_id):
4327 from rhodecode.authentication.base import loadplugin
4327 from rhodecode.authentication.base import loadplugin
4328 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4328 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4329 auth_plugin = loadplugin(_plugin_id)
4329 auth_plugin = loadplugin(_plugin_id)
4330 return auth_plugin
4330 return auth_plugin
4331
4331
4332
4332
4333 class Integration(Base, BaseModel):
4333 class Integration(Base, BaseModel):
4334 __tablename__ = 'integrations'
4334 __tablename__ = 'integrations'
4335 __table_args__ = (
4335 __table_args__ = (
4336 base_table_args
4336 base_table_args
4337 )
4337 )
4338
4338
4339 integration_id = Column('integration_id', Integer(), primary_key=True)
4339 integration_id = Column('integration_id', Integer(), primary_key=True)
4340 integration_type = Column('integration_type', String(255))
4340 integration_type = Column('integration_type', String(255))
4341 enabled = Column('enabled', Boolean(), nullable=False)
4341 enabled = Column('enabled', Boolean(), nullable=False)
4342 name = Column('name', String(255), nullable=False)
4342 name = Column('name', String(255), nullable=False)
4343 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4343 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4344 default=False)
4344 default=False)
4345
4345
4346 settings = Column(
4346 settings = Column(
4347 'settings_json', MutationObj.as_mutable(
4347 'settings_json', MutationObj.as_mutable(
4348 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4348 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4349 repo_id = Column(
4349 repo_id = Column(
4350 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4350 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4351 nullable=True, unique=None, default=None)
4351 nullable=True, unique=None, default=None)
4352 repo = relationship('Repository', lazy='joined')
4352 repo = relationship('Repository', lazy='joined')
4353
4353
4354 repo_group_id = Column(
4354 repo_group_id = Column(
4355 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4355 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4356 nullable=True, unique=None, default=None)
4356 nullable=True, unique=None, default=None)
4357 repo_group = relationship('RepoGroup', lazy='joined')
4357 repo_group = relationship('RepoGroup', lazy='joined')
4358
4358
4359 @property
4359 @property
4360 def scope(self):
4360 def scope(self):
4361 if self.repo:
4361 if self.repo:
4362 return repr(self.repo)
4362 return repr(self.repo)
4363 if self.repo_group:
4363 if self.repo_group:
4364 if self.child_repos_only:
4364 if self.child_repos_only:
4365 return repr(self.repo_group) + ' (child repos only)'
4365 return repr(self.repo_group) + ' (child repos only)'
4366 else:
4366 else:
4367 return repr(self.repo_group) + ' (recursive)'
4367 return repr(self.repo_group) + ' (recursive)'
4368 if self.child_repos_only:
4368 if self.child_repos_only:
4369 return 'root_repos'
4369 return 'root_repos'
4370 return 'global'
4370 return 'global'
4371
4371
4372 def __repr__(self):
4372 def __repr__(self):
4373 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4373 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4374
4374
4375
4375
4376 class RepoReviewRuleUser(Base, BaseModel):
4376 class RepoReviewRuleUser(Base, BaseModel):
4377 __tablename__ = 'repo_review_rules_users'
4377 __tablename__ = 'repo_review_rules_users'
4378 __table_args__ = (
4378 __table_args__ = (
4379 base_table_args
4379 base_table_args
4380 )
4380 )
4381
4381
4382 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4382 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4383 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4383 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4384 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4384 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4385 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4385 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4386 user = relationship('User')
4386 user = relationship('User')
4387
4387
4388 def rule_data(self):
4388 def rule_data(self):
4389 return {
4389 return {
4390 'mandatory': self.mandatory
4390 'mandatory': self.mandatory
4391 }
4391 }
4392
4392
4393
4393
4394 class RepoReviewRuleUserGroup(Base, BaseModel):
4394 class RepoReviewRuleUserGroup(Base, BaseModel):
4395 __tablename__ = 'repo_review_rules_users_groups'
4395 __tablename__ = 'repo_review_rules_users_groups'
4396 __table_args__ = (
4396 __table_args__ = (
4397 base_table_args
4397 base_table_args
4398 )
4398 )
4399
4399
4400 VOTE_RULE_ALL = -1
4400 VOTE_RULE_ALL = -1
4401
4401
4402 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4402 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4403 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4403 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4404 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4404 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4405 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4405 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4406 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4406 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4407 users_group = relationship('UserGroup')
4407 users_group = relationship('UserGroup')
4408
4408
4409 def rule_data(self):
4409 def rule_data(self):
4410 return {
4410 return {
4411 'mandatory': self.mandatory,
4411 'mandatory': self.mandatory,
4412 'vote_rule': self.vote_rule
4412 'vote_rule': self.vote_rule
4413 }
4413 }
4414
4414
4415 @property
4415 @property
4416 def vote_rule_label(self):
4416 def vote_rule_label(self):
4417 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4417 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4418 return 'all must vote'
4418 return 'all must vote'
4419 else:
4419 else:
4420 return 'min. vote {}'.format(self.vote_rule)
4420 return 'min. vote {}'.format(self.vote_rule)
4421
4421
4422
4422
4423 class RepoReviewRule(Base, BaseModel):
4423 class RepoReviewRule(Base, BaseModel):
4424 __tablename__ = 'repo_review_rules'
4424 __tablename__ = 'repo_review_rules'
4425 __table_args__ = (
4425 __table_args__ = (
4426 base_table_args
4426 base_table_args
4427 )
4427 )
4428
4428
4429 repo_review_rule_id = Column(
4429 repo_review_rule_id = Column(
4430 'repo_review_rule_id', Integer(), primary_key=True)
4430 'repo_review_rule_id', Integer(), primary_key=True)
4431 repo_id = Column(
4431 repo_id = Column(
4432 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4432 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4433 repo = relationship('Repository', backref='review_rules')
4433 repo = relationship('Repository', backref='review_rules')
4434
4434
4435 review_rule_name = Column('review_rule_name', String(255))
4435 review_rule_name = Column('review_rule_name', String(255))
4436 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4436 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4437 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4437 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4438 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4438 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4439
4439
4440 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4440 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4441 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4441 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4442 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4442 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4443 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4443 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4444
4444
4445 rule_users = relationship('RepoReviewRuleUser')
4445 rule_users = relationship('RepoReviewRuleUser')
4446 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4446 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4447
4447
4448 def _validate_pattern(self, value):
4448 def _validate_pattern(self, value):
4449 re.compile('^' + glob2re(value) + '$')
4449 re.compile('^' + glob2re(value) + '$')
4450
4450
4451 @hybrid_property
4451 @hybrid_property
4452 def source_branch_pattern(self):
4452 def source_branch_pattern(self):
4453 return self._branch_pattern or '*'
4453 return self._branch_pattern or '*'
4454
4454
4455 @source_branch_pattern.setter
4455 @source_branch_pattern.setter
4456 def source_branch_pattern(self, value):
4456 def source_branch_pattern(self, value):
4457 self._validate_pattern(value)
4457 self._validate_pattern(value)
4458 self._branch_pattern = value or '*'
4458 self._branch_pattern = value or '*'
4459
4459
4460 @hybrid_property
4460 @hybrid_property
4461 def target_branch_pattern(self):
4461 def target_branch_pattern(self):
4462 return self._target_branch_pattern or '*'
4462 return self._target_branch_pattern or '*'
4463
4463
4464 @target_branch_pattern.setter
4464 @target_branch_pattern.setter
4465 def target_branch_pattern(self, value):
4465 def target_branch_pattern(self, value):
4466 self._validate_pattern(value)
4466 self._validate_pattern(value)
4467 self._target_branch_pattern = value or '*'
4467 self._target_branch_pattern = value or '*'
4468
4468
4469 @hybrid_property
4469 @hybrid_property
4470 def file_pattern(self):
4470 def file_pattern(self):
4471 return self._file_pattern or '*'
4471 return self._file_pattern or '*'
4472
4472
4473 @file_pattern.setter
4473 @file_pattern.setter
4474 def file_pattern(self, value):
4474 def file_pattern(self, value):
4475 self._validate_pattern(value)
4475 self._validate_pattern(value)
4476 self._file_pattern = value or '*'
4476 self._file_pattern = value or '*'
4477
4477
4478 def matches(self, source_branch, target_branch, files_changed):
4478 def matches(self, source_branch, target_branch, files_changed):
4479 """
4479 """
4480 Check if this review rule matches a branch/files in a pull request
4480 Check if this review rule matches a branch/files in a pull request
4481
4481
4482 :param source_branch: source branch name for the commit
4482 :param source_branch: source branch name for the commit
4483 :param target_branch: target branch name for the commit
4483 :param target_branch: target branch name for the commit
4484 :param files_changed: list of file paths changed in the pull request
4484 :param files_changed: list of file paths changed in the pull request
4485 """
4485 """
4486
4486
4487 source_branch = source_branch or ''
4487 source_branch = source_branch or ''
4488 target_branch = target_branch or ''
4488 target_branch = target_branch or ''
4489 files_changed = files_changed or []
4489 files_changed = files_changed or []
4490
4490
4491 branch_matches = True
4491 branch_matches = True
4492 if source_branch or target_branch:
4492 if source_branch or target_branch:
4493 if self.source_branch_pattern == '*':
4493 if self.source_branch_pattern == '*':
4494 source_branch_match = True
4494 source_branch_match = True
4495 else:
4495 else:
4496 if self.source_branch_pattern.startswith('re:'):
4496 if self.source_branch_pattern.startswith('re:'):
4497 source_pattern = self.source_branch_pattern[3:]
4497 source_pattern = self.source_branch_pattern[3:]
4498 else:
4498 else:
4499 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4499 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4500 source_branch_regex = re.compile(source_pattern)
4500 source_branch_regex = re.compile(source_pattern)
4501 source_branch_match = bool(source_branch_regex.search(source_branch))
4501 source_branch_match = bool(source_branch_regex.search(source_branch))
4502 if self.target_branch_pattern == '*':
4502 if self.target_branch_pattern == '*':
4503 target_branch_match = True
4503 target_branch_match = True
4504 else:
4504 else:
4505 if self.target_branch_pattern.startswith('re:'):
4505 if self.target_branch_pattern.startswith('re:'):
4506 target_pattern = self.target_branch_pattern[3:]
4506 target_pattern = self.target_branch_pattern[3:]
4507 else:
4507 else:
4508 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4508 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4509 target_branch_regex = re.compile(target_pattern)
4509 target_branch_regex = re.compile(target_pattern)
4510 target_branch_match = bool(target_branch_regex.search(target_branch))
4510 target_branch_match = bool(target_branch_regex.search(target_branch))
4511
4511
4512 branch_matches = source_branch_match and target_branch_match
4512 branch_matches = source_branch_match and target_branch_match
4513
4513
4514 files_matches = True
4514 files_matches = True
4515 if self.file_pattern != '*':
4515 if self.file_pattern != '*':
4516 files_matches = False
4516 files_matches = False
4517 if self.file_pattern.startswith('re:'):
4517 if self.file_pattern.startswith('re:'):
4518 file_pattern = self.file_pattern[3:]
4518 file_pattern = self.file_pattern[3:]
4519 else:
4519 else:
4520 file_pattern = glob2re(self.file_pattern)
4520 file_pattern = glob2re(self.file_pattern)
4521 file_regex = re.compile(file_pattern)
4521 file_regex = re.compile(file_pattern)
4522 for filename in files_changed:
4522 for filename in files_changed:
4523 if file_regex.search(filename):
4523 if file_regex.search(filename):
4524 files_matches = True
4524 files_matches = True
4525 break
4525 break
4526
4526
4527 return branch_matches and files_matches
4527 return branch_matches and files_matches
4528
4528
4529 @property
4529 @property
4530 def review_users(self):
4530 def review_users(self):
4531 """ Returns the users which this rule applies to """
4531 """ Returns the users which this rule applies to """
4532
4532
4533 users = collections.OrderedDict()
4533 users = collections.OrderedDict()
4534
4534
4535 for rule_user in self.rule_users:
4535 for rule_user in self.rule_users:
4536 if rule_user.user.active:
4536 if rule_user.user.active:
4537 if rule_user.user not in users:
4537 if rule_user.user not in users:
4538 users[rule_user.user.username] = {
4538 users[rule_user.user.username] = {
4539 'user': rule_user.user,
4539 'user': rule_user.user,
4540 'source': 'user',
4540 'source': 'user',
4541 'source_data': {},
4541 'source_data': {},
4542 'data': rule_user.rule_data()
4542 'data': rule_user.rule_data()
4543 }
4543 }
4544
4544
4545 for rule_user_group in self.rule_user_groups:
4545 for rule_user_group in self.rule_user_groups:
4546 source_data = {
4546 source_data = {
4547 'user_group_id': rule_user_group.users_group.users_group_id,
4547 'user_group_id': rule_user_group.users_group.users_group_id,
4548 'name': rule_user_group.users_group.users_group_name,
4548 'name': rule_user_group.users_group.users_group_name,
4549 'members': len(rule_user_group.users_group.members)
4549 'members': len(rule_user_group.users_group.members)
4550 }
4550 }
4551 for member in rule_user_group.users_group.members:
4551 for member in rule_user_group.users_group.members:
4552 if member.user.active:
4552 if member.user.active:
4553 key = member.user.username
4553 key = member.user.username
4554 if key in users:
4554 if key in users:
4555 # skip this member as we have him already
4555 # skip this member as we have him already
4556 # this prevents from override the "first" matched
4556 # this prevents from override the "first" matched
4557 # users with duplicates in multiple groups
4557 # users with duplicates in multiple groups
4558 continue
4558 continue
4559
4559
4560 users[key] = {
4560 users[key] = {
4561 'user': member.user,
4561 'user': member.user,
4562 'source': 'user_group',
4562 'source': 'user_group',
4563 'source_data': source_data,
4563 'source_data': source_data,
4564 'data': rule_user_group.rule_data()
4564 'data': rule_user_group.rule_data()
4565 }
4565 }
4566
4566
4567 return users
4567 return users
4568
4568
4569 def user_group_vote_rule(self, user_id):
4569 def user_group_vote_rule(self, user_id):
4570
4570
4571 rules = []
4571 rules = []
4572 if not self.rule_user_groups:
4572 if not self.rule_user_groups:
4573 return rules
4573 return rules
4574
4574
4575 for user_group in self.rule_user_groups:
4575 for user_group in self.rule_user_groups:
4576 user_group_members = [x.user_id for x in user_group.users_group.members]
4576 user_group_members = [x.user_id for x in user_group.users_group.members]
4577 if user_id in user_group_members:
4577 if user_id in user_group_members:
4578 rules.append(user_group)
4578 rules.append(user_group)
4579 return rules
4579 return rules
4580
4580
4581 def __repr__(self):
4581 def __repr__(self):
4582 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4582 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4583 self.repo_review_rule_id, self.repo)
4583 self.repo_review_rule_id, self.repo)
4584
4584
4585
4585
4586 class ScheduleEntry(Base, BaseModel):
4586 class ScheduleEntry(Base, BaseModel):
4587 __tablename__ = 'schedule_entries'
4587 __tablename__ = 'schedule_entries'
4588 __table_args__ = (
4588 __table_args__ = (
4589 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4589 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4590 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4590 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4591 base_table_args,
4591 base_table_args,
4592 )
4592 )
4593
4593
4594 schedule_types = ['crontab', 'timedelta', 'integer']
4594 schedule_types = ['crontab', 'timedelta', 'integer']
4595 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4595 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4596
4596
4597 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4597 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4598 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4598 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4599 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4599 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4600
4600
4601 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4601 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4602 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4602 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4603
4603
4604 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4604 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4605 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4605 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4606
4606
4607 # task
4607 # task
4608 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4608 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4609 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4609 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4610 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4610 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4611 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4611 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4612
4612
4613 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4613 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4614 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4614 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4615
4615
4616 @hybrid_property
4616 @hybrid_property
4617 def schedule_type(self):
4617 def schedule_type(self):
4618 return self._schedule_type
4618 return self._schedule_type
4619
4619
4620 @schedule_type.setter
4620 @schedule_type.setter
4621 def schedule_type(self, val):
4621 def schedule_type(self, val):
4622 if val not in self.schedule_types:
4622 if val not in self.schedule_types:
4623 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4623 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4624 val, self.schedule_type))
4624 val, self.schedule_type))
4625
4625
4626 self._schedule_type = val
4626 self._schedule_type = val
4627
4627
4628 @classmethod
4628 @classmethod
4629 def get_uid(cls, obj):
4629 def get_uid(cls, obj):
4630 args = obj.task_args
4630 args = obj.task_args
4631 kwargs = obj.task_kwargs
4631 kwargs = obj.task_kwargs
4632 if isinstance(args, JsonRaw):
4632 if isinstance(args, JsonRaw):
4633 try:
4633 try:
4634 args = json.loads(args)
4634 args = json.loads(args)
4635 except ValueError:
4635 except ValueError:
4636 args = tuple()
4636 args = tuple()
4637
4637
4638 if isinstance(kwargs, JsonRaw):
4638 if isinstance(kwargs, JsonRaw):
4639 try:
4639 try:
4640 kwargs = json.loads(kwargs)
4640 kwargs = json.loads(kwargs)
4641 except ValueError:
4641 except ValueError:
4642 kwargs = dict()
4642 kwargs = dict()
4643
4643
4644 dot_notation = obj.task_dot_notation
4644 dot_notation = obj.task_dot_notation
4645 val = '.'.join(map(safe_str, [
4645 val = '.'.join(map(safe_str, [
4646 sorted(dot_notation), args, sorted(kwargs.items())]))
4646 sorted(dot_notation), args, sorted(kwargs.items())]))
4647 return hashlib.sha1(val).hexdigest()
4647 return hashlib.sha1(val).hexdigest()
4648
4648
4649 @classmethod
4649 @classmethod
4650 def get_by_schedule_name(cls, schedule_name):
4650 def get_by_schedule_name(cls, schedule_name):
4651 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4651 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4652
4652
4653 @classmethod
4653 @classmethod
4654 def get_by_schedule_id(cls, schedule_id):
4654 def get_by_schedule_id(cls, schedule_id):
4655 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4655 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4656
4656
4657 @property
4657 @property
4658 def task(self):
4658 def task(self):
4659 return self.task_dot_notation
4659 return self.task_dot_notation
4660
4660
4661 @property
4661 @property
4662 def schedule(self):
4662 def schedule(self):
4663 from rhodecode.lib.celerylib.utils import raw_2_schedule
4663 from rhodecode.lib.celerylib.utils import raw_2_schedule
4664 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4664 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4665 return schedule
4665 return schedule
4666
4666
4667 @property
4667 @property
4668 def args(self):
4668 def args(self):
4669 try:
4669 try:
4670 return list(self.task_args or [])
4670 return list(self.task_args or [])
4671 except ValueError:
4671 except ValueError:
4672 return list()
4672 return list()
4673
4673
4674 @property
4674 @property
4675 def kwargs(self):
4675 def kwargs(self):
4676 try:
4676 try:
4677 return dict(self.task_kwargs or {})
4677 return dict(self.task_kwargs or {})
4678 except ValueError:
4678 except ValueError:
4679 return dict()
4679 return dict()
4680
4680
4681 def _as_raw(self, val):
4681 def _as_raw(self, val):
4682 if hasattr(val, 'de_coerce'):
4682 if hasattr(val, 'de_coerce'):
4683 val = val.de_coerce()
4683 val = val.de_coerce()
4684 if val:
4684 if val:
4685 val = json.dumps(val)
4685 val = json.dumps(val)
4686
4686
4687 return val
4687 return val
4688
4688
4689 @property
4689 @property
4690 def schedule_definition_raw(self):
4690 def schedule_definition_raw(self):
4691 return self._as_raw(self.schedule_definition)
4691 return self._as_raw(self.schedule_definition)
4692
4692
4693 @property
4693 @property
4694 def args_raw(self):
4694 def args_raw(self):
4695 return self._as_raw(self.task_args)
4695 return self._as_raw(self.task_args)
4696
4696
4697 @property
4697 @property
4698 def kwargs_raw(self):
4698 def kwargs_raw(self):
4699 return self._as_raw(self.task_kwargs)
4699 return self._as_raw(self.task_kwargs)
4700
4700
4701 def __repr__(self):
4701 def __repr__(self):
4702 return '<DB:ScheduleEntry({}:{})>'.format(
4702 return '<DB:ScheduleEntry({}:{})>'.format(
4703 self.schedule_entry_id, self.schedule_name)
4703 self.schedule_entry_id, self.schedule_name)
4704
4704
4705
4705
4706 @event.listens_for(ScheduleEntry, 'before_update')
4706 @event.listens_for(ScheduleEntry, 'before_update')
4707 def update_task_uid(mapper, connection, target):
4707 def update_task_uid(mapper, connection, target):
4708 target.task_uid = ScheduleEntry.get_uid(target)
4708 target.task_uid = ScheduleEntry.get_uid(target)
4709
4709
4710
4710
4711 @event.listens_for(ScheduleEntry, 'before_insert')
4711 @event.listens_for(ScheduleEntry, 'before_insert')
4712 def set_task_uid(mapper, connection, target):
4712 def set_task_uid(mapper, connection, target):
4713 target.task_uid = ScheduleEntry.get_uid(target)
4713 target.task_uid = ScheduleEntry.get_uid(target)
4714
4714
4715
4715
4716 class _BaseBranchPerms(BaseModel):
4716 class _BaseBranchPerms(BaseModel):
4717 @classmethod
4717 @classmethod
4718 def compute_hash(cls, value):
4718 def compute_hash(cls, value):
4719 return sha1_safe(value)
4719 return sha1_safe(value)
4720
4720
4721 @hybrid_property
4721 @hybrid_property
4722 def branch_pattern(self):
4722 def branch_pattern(self):
4723 return self._branch_pattern or '*'
4723 return self._branch_pattern or '*'
4724
4724
4725 @hybrid_property
4725 @hybrid_property
4726 def branch_hash(self):
4726 def branch_hash(self):
4727 return self._branch_hash
4727 return self._branch_hash
4728
4728
4729 def _validate_glob(self, value):
4729 def _validate_glob(self, value):
4730 re.compile('^' + glob2re(value) + '$')
4730 re.compile('^' + glob2re(value) + '$')
4731
4731
4732 @branch_pattern.setter
4732 @branch_pattern.setter
4733 def branch_pattern(self, value):
4733 def branch_pattern(self, value):
4734 self._validate_glob(value)
4734 self._validate_glob(value)
4735 self._branch_pattern = value or '*'
4735 self._branch_pattern = value or '*'
4736 # set the Hash when setting the branch pattern
4736 # set the Hash when setting the branch pattern
4737 self._branch_hash = self.compute_hash(self._branch_pattern)
4737 self._branch_hash = self.compute_hash(self._branch_pattern)
4738
4738
4739 def matches(self, branch):
4739 def matches(self, branch):
4740 """
4740 """
4741 Check if this the branch matches entry
4741 Check if this the branch matches entry
4742
4742
4743 :param branch: branch name for the commit
4743 :param branch: branch name for the commit
4744 """
4744 """
4745
4745
4746 branch = branch or ''
4746 branch = branch or ''
4747
4747
4748 branch_matches = True
4748 branch_matches = True
4749 if branch:
4749 if branch:
4750 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
4750 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
4751 branch_matches = bool(branch_regex.search(branch))
4751 branch_matches = bool(branch_regex.search(branch))
4752
4752
4753 return branch_matches
4753 return branch_matches
4754
4754
4755
4755
4756 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
4756 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
4757 __tablename__ = 'user_to_repo_branch_permissions'
4757 __tablename__ = 'user_to_repo_branch_permissions'
4758 __table_args__ = (
4758 __table_args__ = (
4759 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4759 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4760 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4760 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4761 )
4761 )
4762
4762
4763 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4763 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4764
4764
4765 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4765 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4766 repo = relationship('Repository', backref='user_branch_perms')
4766 repo = relationship('Repository', backref='user_branch_perms')
4767
4767
4768 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4768 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4769 permission = relationship('Permission')
4769 permission = relationship('Permission')
4770
4770
4771 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
4771 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
4772 user_repo_to_perm = relationship('UserRepoToPerm')
4772 user_repo_to_perm = relationship('UserRepoToPerm')
4773
4773
4774 rule_order = Column('rule_order', Integer(), nullable=False)
4774 rule_order = Column('rule_order', Integer(), nullable=False)
4775 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4775 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4776 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4776 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4777
4777
4778 def __unicode__(self):
4778 def __unicode__(self):
4779 return u'<UserBranchPermission(%s => %r)>' % (
4779 return u'<UserBranchPermission(%s => %r)>' % (
4780 self.user_repo_to_perm, self.branch_pattern)
4780 self.user_repo_to_perm, self.branch_pattern)
4781
4781
4782
4782
4783 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
4783 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
4784 __tablename__ = 'user_group_to_repo_branch_permissions'
4784 __tablename__ = 'user_group_to_repo_branch_permissions'
4785 __table_args__ = (
4785 __table_args__ = (
4786 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4786 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4787 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4787 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4788 )
4788 )
4789
4789
4790 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4790 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4791
4791
4792 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4792 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4793 repo = relationship('Repository', backref='user_group_branch_perms')
4793 repo = relationship('Repository', backref='user_group_branch_perms')
4794
4794
4795 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4795 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4796 permission = relationship('Permission')
4796 permission = relationship('Permission')
4797
4797
4798 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)
4798 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)
4799 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
4799 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
4800
4800
4801 rule_order = Column('rule_order', Integer(), nullable=False)
4801 rule_order = Column('rule_order', Integer(), nullable=False)
4802 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4802 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4803 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4803 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4804
4804
4805 def __unicode__(self):
4805 def __unicode__(self):
4806 return u'<UserBranchPermission(%s => %r)>' % (
4806 return u'<UserBranchPermission(%s => %r)>' % (
4807 self.user_group_repo_to_perm, self.branch_pattern)
4807 self.user_group_repo_to_perm, self.branch_pattern)
4808
4808
4809
4809
4810 class UserBookmark(Base, BaseModel):
4810 class UserBookmark(Base, BaseModel):
4811 __tablename__ = 'user_bookmarks'
4811 __tablename__ = 'user_bookmarks'
4812 __table_args__ = (
4812 __table_args__ = (
4813 UniqueConstraint('user_id', 'bookmark_repo_id'),
4813 UniqueConstraint('user_id', 'bookmark_repo_id'),
4814 UniqueConstraint('user_id', 'bookmark_repo_group_id'),
4814 UniqueConstraint('user_id', 'bookmark_repo_group_id'),
4815 UniqueConstraint('user_id', 'bookmark_position'),
4815 UniqueConstraint('user_id', 'bookmark_position'),
4816 base_table_args
4816 base_table_args
4817 )
4817 )
4818
4818
4819 user_bookmark_id = Column("user_bookmark_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
4819 user_bookmark_id = Column("user_bookmark_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
4820 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
4820 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
4821 position = Column("bookmark_position", Integer(), nullable=False)
4821 position = Column("bookmark_position", Integer(), nullable=False)
4822 title = Column("bookmark_title", String(255), nullable=True, unique=None, default=None)
4822 title = Column("bookmark_title", String(255), nullable=True, unique=None, default=None)
4823 redirect_url = Column("bookmark_redirect_url", String(10240), nullable=True, unique=None, default=None)
4823 redirect_url = Column("bookmark_redirect_url", String(10240), nullable=True, unique=None, default=None)
4824 created_on = Column("created_on", DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4824 created_on = Column("created_on", DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4825
4825
4826 bookmark_repo_id = Column("bookmark_repo_id", Integer(), ForeignKey("repositories.repo_id"), nullable=True, unique=None, default=None)
4826 bookmark_repo_id = Column("bookmark_repo_id", Integer(), ForeignKey("repositories.repo_id"), nullable=True, unique=None, default=None)
4827 bookmark_repo_group_id = Column("bookmark_repo_group_id", Integer(), ForeignKey("groups.group_id"), nullable=True, unique=None, default=None)
4827 bookmark_repo_group_id = Column("bookmark_repo_group_id", Integer(), ForeignKey("groups.group_id"), nullable=True, unique=None, default=None)
4828
4828
4829 user = relationship("User")
4829 user = relationship("User")
4830
4830
4831 repository = relationship("Repository")
4831 repository = relationship("Repository")
4832 repository_group = relationship("RepoGroup")
4832 repository_group = relationship("RepoGroup")
4833
4833
4834 @classmethod
4834 @classmethod
4835 def get_by_position_for_user(cls, position, user_id):
4835 def get_by_position_for_user(cls, position, user_id):
4836 return cls.query() \
4836 return cls.query() \
4837 .filter(UserBookmark.user_id == user_id) \
4837 .filter(UserBookmark.user_id == user_id) \
4838 .filter(UserBookmark.position == position).scalar()
4838 .filter(UserBookmark.position == position).scalar()
4839
4839
4840 @classmethod
4840 @classmethod
4841 def get_bookmarks_for_user(cls, user_id):
4841 def get_bookmarks_for_user(cls, user_id):
4842 return cls.query() \
4842 return cls.query() \
4843 .filter(UserBookmark.user_id == user_id) \
4843 .filter(UserBookmark.user_id == user_id) \
4844 .options(joinedload(UserBookmark.repository)) \
4844 .options(joinedload(UserBookmark.repository)) \
4845 .options(joinedload(UserBookmark.repository_group)) \
4845 .options(joinedload(UserBookmark.repository_group)) \
4846 .order_by(UserBookmark.position.asc()) \
4846 .order_by(UserBookmark.position.asc()) \
4847 .all()
4847 .all()
4848
4848
4849 def __unicode__(self):
4849 def __unicode__(self):
4850 return u'<UserBookmark(%d @ %r)>' % (self.position, self.redirect_url)
4850 return u'<UserBookmark(%d @ %r)>' % (self.position, self.redirect_url)
4851
4851
4852
4852
4853 class FileStore(Base, BaseModel):
4853 class FileStore(Base, BaseModel):
4854 __tablename__ = 'file_store'
4854 __tablename__ = 'file_store'
4855 __table_args__ = (
4855 __table_args__ = (
4856 base_table_args
4856 base_table_args
4857 )
4857 )
4858
4858
4859 file_store_id = Column('file_store_id', Integer(), primary_key=True)
4859 file_store_id = Column('file_store_id', Integer(), primary_key=True)
4860 file_uid = Column('file_uid', String(1024), nullable=False)
4860 file_uid = Column('file_uid', String(1024), nullable=False)
4861 file_display_name = Column('file_display_name', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), nullable=True)
4861 file_display_name = Column('file_display_name', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), nullable=True)
4862 file_description = Column('file_description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=True)
4862 file_description = Column('file_description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=True)
4863 file_org_name = Column('file_org_name', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=False)
4863 file_org_name = Column('file_org_name', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=False)
4864
4864
4865 # sha256 hash
4865 # sha256 hash
4866 file_hash = Column('file_hash', String(512), nullable=False)
4866 file_hash = Column('file_hash', String(512), nullable=False)
4867 file_size = Column('file_size', Integer(), nullable=False)
4867 file_size = Column('file_size', Integer(), nullable=False)
4868
4868
4869 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4869 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4870 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True)
4870 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True)
4871 accessed_count = Column('accessed_count', Integer(), default=0)
4871 accessed_count = Column('accessed_count', Integer(), default=0)
4872
4872
4873 enabled = Column('enabled', Boolean(), nullable=False, default=True)
4873 enabled = Column('enabled', Boolean(), nullable=False, default=True)
4874
4874
4875 # if repo/repo_group reference is set, check for permissions
4875 # if repo/repo_group reference is set, check for permissions
4876 check_acl = Column('check_acl', Boolean(), nullable=False, default=True)
4876 check_acl = Column('check_acl', Boolean(), nullable=False, default=True)
4877
4877
4878 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
4878 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
4879 upload_user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.user_id')
4879 upload_user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.user_id')
4880
4880
4881 # scope limited to user, which requester have access to
4881 # scope limited to user, which requester have access to
4882 scope_user_id = Column(
4882 scope_user_id = Column(
4883 'scope_user_id', Integer(), ForeignKey('users.user_id'),
4883 'scope_user_id', Integer(), ForeignKey('users.user_id'),
4884 nullable=True, unique=None, default=None)
4884 nullable=True, unique=None, default=None)
4885 user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.scope_user_id')
4885 user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.scope_user_id')
4886
4886
4887 # scope limited to user group, which requester have access to
4887 # scope limited to user group, which requester have access to
4888 scope_user_group_id = Column(
4888 scope_user_group_id = Column(
4889 'scope_user_group_id', Integer(), ForeignKey('users_groups.users_group_id'),
4889 'scope_user_group_id', Integer(), ForeignKey('users_groups.users_group_id'),
4890 nullable=True, unique=None, default=None)
4890 nullable=True, unique=None, default=None)
4891 user_group = relationship('UserGroup', lazy='joined')
4891 user_group = relationship('UserGroup', lazy='joined')
4892
4892
4893 # scope limited to repo, which requester have access to
4893 # scope limited to repo, which requester have access to
4894 scope_repo_id = Column(
4894 scope_repo_id = Column(
4895 'scope_repo_id', Integer(), ForeignKey('repositories.repo_id'),
4895 'scope_repo_id', Integer(), ForeignKey('repositories.repo_id'),
4896 nullable=True, unique=None, default=None)
4896 nullable=True, unique=None, default=None)
4897 repo = relationship('Repository', lazy='joined')
4897 repo = relationship('Repository', lazy='joined')
4898
4898
4899 # scope limited to repo group, which requester have access to
4899 # scope limited to repo group, which requester have access to
4900 scope_repo_group_id = Column(
4900 scope_repo_group_id = Column(
4901 'scope_repo_group_id', Integer(), ForeignKey('groups.group_id'),
4901 'scope_repo_group_id', Integer(), ForeignKey('groups.group_id'),
4902 nullable=True, unique=None, default=None)
4902 nullable=True, unique=None, default=None)
4903 repo_group = relationship('RepoGroup', lazy='joined')
4903 repo_group = relationship('RepoGroup', lazy='joined')
4904
4904
4905 @classmethod
4905 @classmethod
4906 def create(cls, file_uid, filename, file_hash, file_size, file_display_name='',
4906 def create(cls, file_uid, filename, file_hash, file_size, file_display_name='',
4907 file_description='', enabled=True, check_acl=True,
4907 file_description='', enabled=True, check_acl=True,
4908 user_id=None, scope_repo_id=None, scope_repo_group_id=None):
4908 user_id=None, scope_repo_id=None, scope_repo_group_id=None):
4909
4909
4910 store_entry = FileStore()
4910 store_entry = FileStore()
4911 store_entry.file_uid = file_uid
4911 store_entry.file_uid = file_uid
4912 store_entry.file_display_name = file_display_name
4912 store_entry.file_display_name = file_display_name
4913 store_entry.file_org_name = filename
4913 store_entry.file_org_name = filename
4914 store_entry.file_size = file_size
4914 store_entry.file_size = file_size
4915 store_entry.file_hash = file_hash
4915 store_entry.file_hash = file_hash
4916 store_entry.file_description = file_description
4916 store_entry.file_description = file_description
4917
4917
4918 store_entry.check_acl = check_acl
4918 store_entry.check_acl = check_acl
4919 store_entry.enabled = enabled
4919 store_entry.enabled = enabled
4920
4920
4921 store_entry.user_id = user_id
4921 store_entry.user_id = user_id
4922 store_entry.scope_repo_id = scope_repo_id
4922 store_entry.scope_repo_id = scope_repo_id
4923 store_entry.scope_repo_group_id = scope_repo_group_id
4923 store_entry.scope_repo_group_id = scope_repo_group_id
4924 return store_entry
4924 return store_entry
4925
4925
4926 @classmethod
4926 @classmethod
4927 def bump_access_counter(cls, file_uid, commit=True):
4927 def bump_access_counter(cls, file_uid, commit=True):
4928 FileStore().query()\
4928 FileStore().query()\
4929 .filter(FileStore.file_uid == file_uid)\
4929 .filter(FileStore.file_uid == file_uid)\
4930 .update({FileStore.accessed_count: (FileStore.accessed_count + 1),
4930 .update({FileStore.accessed_count: (FileStore.accessed_count + 1),
4931 FileStore.accessed_on: datetime.datetime.now()})
4931 FileStore.accessed_on: datetime.datetime.now()})
4932 if commit:
4932 if commit:
4933 Session().commit()
4933 Session().commit()
4934
4934
4935 def __repr__(self):
4935 def __repr__(self):
4936 return '<FileStore({})>'.format(self.file_store_id)
4936 return '<FileStore({})>'.format(self.file_store_id)
4937
4937
4938
4938
4939 class DbMigrateVersion(Base, BaseModel):
4939 class DbMigrateVersion(Base, BaseModel):
4940 __tablename__ = 'db_migrate_version'
4940 __tablename__ = 'db_migrate_version'
4941 __table_args__ = (
4941 __table_args__ = (
4942 base_table_args,
4942 base_table_args,
4943 )
4943 )
4944
4944
4945 repository_id = Column('repository_id', String(250), primary_key=True)
4945 repository_id = Column('repository_id', String(250), primary_key=True)
4946 repository_path = Column('repository_path', Text)
4946 repository_path = Column('repository_path', Text)
4947 version = Column('version', Integer)
4947 version = Column('version', Integer)
4948
4948
4949 @classmethod
4949 @classmethod
4950 def set_version(cls, version):
4950 def set_version(cls, version):
4951 """
4951 """
4952 Helper for forcing a different version, usually for debugging purposes via ishell.
4952 Helper for forcing a different version, usually for debugging purposes via ishell.
4953 """
4953 """
4954 ver = DbMigrateVersion.query().first()
4954 ver = DbMigrateVersion.query().first()
4955 ver.version = version
4955 ver.version = version
4956 Session().commit()
4956 Session().commit()
4957
4957
4958
4958
4959 class DbSession(Base, BaseModel):
4959 class DbSession(Base, BaseModel):
4960 __tablename__ = 'db_session'
4960 __tablename__ = 'db_session'
4961 __table_args__ = (
4961 __table_args__ = (
4962 base_table_args,
4962 base_table_args,
4963 )
4963 )
4964
4964
4965 def __repr__(self):
4965 def __repr__(self):
4966 return '<DB:DbSession({})>'.format(self.id)
4966 return '<DB:DbSession({})>'.format(self.id)
4967
4967
4968 id = Column('id', Integer())
4968 id = Column('id', Integer())
4969 namespace = Column('namespace', String(255), primary_key=True)
4969 namespace = Column('namespace', String(255), primary_key=True)
4970 accessed = Column('accessed', DateTime, nullable=False)
4970 accessed = Column('accessed', DateTime, nullable=False)
4971 created = Column('created', DateTime, nullable=False)
4971 created = Column('created', DateTime, nullable=False)
4972 data = Column('data', PickleType, nullable=False)
4972 data = Column('data', PickleType, nullable=False)
General Comments 0
You need to be logged in to leave comments. Login now