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