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