##// END OF EJS Templates
user: indicate missing super admin or default as fatal errors.
marcink -
r279:79b652b8 default
parent child Browse files
Show More
@@ -1,3462 +1,3462 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2016 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 os
26 26 import sys
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
38 38 from sqlalchemy import *
39 39 from sqlalchemy.exc import IntegrityError
40 40 from sqlalchemy.ext.declarative import declared_attr
41 41 from sqlalchemy.ext.hybrid import hybrid_property
42 42 from sqlalchemy.orm import (
43 43 relationship, joinedload, class_mapper, validates, aliased)
44 44 from sqlalchemy.sql.expression import true
45 45 from beaker.cache import cache_region, region_invalidate
46 46 from webob.exc import HTTPNotFound
47 47 from zope.cachedescriptors.property import Lazy as LazyProperty
48 48
49 49 from pylons import url
50 50 from pylons.i18n.translation import lazy_ugettext as _
51 51
52 52 from rhodecode.lib.vcs import get_backend
53 53 from rhodecode.lib.vcs.utils.helpers import get_scm
54 54 from rhodecode.lib.vcs.exceptions import VCSError
55 55 from rhodecode.lib.vcs.backends.base import (
56 56 EmptyCommit, Reference, MergeFailureReason)
57 57 from rhodecode.lib.utils2 import (
58 58 str2bool, safe_str, get_commit_safe, safe_unicode, remove_prefix, md5_safe,
59 59 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict)
60 60 from rhodecode.lib.ext_json import json
61 61 from rhodecode.lib.caching_query import FromCache
62 62 from rhodecode.lib.encrypt import AESCipher
63 63
64 64 from rhodecode.model.meta import Base, Session
65 65
66 66 URL_SEP = '/'
67 67 log = logging.getLogger(__name__)
68 68
69 69 # =============================================================================
70 70 # BASE CLASSES
71 71 # =============================================================================
72 72
73 73 # this is propagated from .ini file beaker.session.secret
74 74 # and initialized at environment.py
75 75 ENCRYPTION_KEY = None
76 76
77 77 # used to sort permissions by types, '#' used here is not allowed to be in
78 78 # usernames, and it's very early in sorted string.printable table.
79 79 PERMISSION_TYPE_SORT = {
80 80 'admin': '####',
81 81 'write': '###',
82 82 'read': '##',
83 83 'none': '#',
84 84 }
85 85
86 86
87 87 def display_sort(obj):
88 88 """
89 89 Sort function used to sort permissions in .permissions() function of
90 90 Repository, RepoGroup, UserGroup. Also it put the default user in front
91 91 of all other resources
92 92 """
93 93
94 94 if obj.username == User.DEFAULT_USER:
95 95 return '#####'
96 96 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
97 97 return prefix + obj.username
98 98
99 99
100 100 def _hash_key(k):
101 101 return md5_safe(k)
102 102
103 103
104 104 class EncryptedTextValue(TypeDecorator):
105 105 """
106 106 Special column for encrypted long text data, use like::
107 107
108 108 value = Column("encrypted_value", EncryptedValue(), nullable=False)
109 109
110 110 This column is intelligent so if value is in unencrypted form it return
111 111 unencrypted form, but on save it always encrypts
112 112 """
113 113 impl = Text
114 114
115 115 def process_bind_param(self, value, dialect):
116 116 if not value:
117 117 return value
118 118 if value.startswith('enc$aes$'):
119 119 # protect against double encrypting if someone manually starts
120 120 # doing
121 121 raise ValueError('value needs to be in unencrypted format, ie. '
122 122 'not starting with enc$aes$')
123 123 return 'enc$aes$%s' % AESCipher(ENCRYPTION_KEY).encrypt(value)
124 124
125 125 def process_result_value(self, value, dialect):
126 126 if not value:
127 127 return value
128 128
129 129 parts = value.split('$', 3)
130 130 if not len(parts) == 3:
131 131 # probably not encrypted values
132 132 return value
133 133 else:
134 134 if parts[0] != 'enc':
135 135 # parts ok but without our header ?
136 136 return value
137 137
138 138 # at that stage we know it's our encryption
139 139 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
140 140 return decrypted_data
141 141
142 142
143 143 class BaseModel(object):
144 144 """
145 145 Base Model for all classes
146 146 """
147 147
148 148 @classmethod
149 149 def _get_keys(cls):
150 150 """return column names for this model """
151 151 return class_mapper(cls).c.keys()
152 152
153 153 def get_dict(self):
154 154 """
155 155 return dict with keys and values corresponding
156 156 to this model data """
157 157
158 158 d = {}
159 159 for k in self._get_keys():
160 160 d[k] = getattr(self, k)
161 161
162 162 # also use __json__() if present to get additional fields
163 163 _json_attr = getattr(self, '__json__', None)
164 164 if _json_attr:
165 165 # update with attributes from __json__
166 166 if callable(_json_attr):
167 167 _json_attr = _json_attr()
168 168 for k, val in _json_attr.iteritems():
169 169 d[k] = val
170 170 return d
171 171
172 172 def get_appstruct(self):
173 173 """return list with keys and values tuples corresponding
174 174 to this model data """
175 175
176 176 l = []
177 177 for k in self._get_keys():
178 178 l.append((k, getattr(self, k),))
179 179 return l
180 180
181 181 def populate_obj(self, populate_dict):
182 182 """populate model with data from given populate_dict"""
183 183
184 184 for k in self._get_keys():
185 185 if k in populate_dict:
186 186 setattr(self, k, populate_dict[k])
187 187
188 188 @classmethod
189 189 def query(cls):
190 190 return Session().query(cls)
191 191
192 192 @classmethod
193 193 def get(cls, id_):
194 194 if id_:
195 195 return cls.query().get(id_)
196 196
197 197 @classmethod
198 198 def get_or_404(cls, id_):
199 199 try:
200 200 id_ = int(id_)
201 201 except (TypeError, ValueError):
202 202 raise HTTPNotFound
203 203
204 204 res = cls.query().get(id_)
205 205 if not res:
206 206 raise HTTPNotFound
207 207 return res
208 208
209 209 @classmethod
210 210 def getAll(cls):
211 211 # deprecated and left for backward compatibility
212 212 return cls.get_all()
213 213
214 214 @classmethod
215 215 def get_all(cls):
216 216 return cls.query().all()
217 217
218 218 @classmethod
219 219 def delete(cls, id_):
220 220 obj = cls.query().get(id_)
221 221 Session().delete(obj)
222 222
223 223 @classmethod
224 224 def identity_cache(cls, session, attr_name, value):
225 225 exist_in_session = []
226 226 for (item_cls, pkey), instance in session.identity_map.items():
227 227 if cls == item_cls and getattr(instance, attr_name) == value:
228 228 exist_in_session.append(instance)
229 229 if exist_in_session:
230 230 if len(exist_in_session) == 1:
231 231 return exist_in_session[0]
232 232 log.exception(
233 233 'multiple objects with attr %s and '
234 234 'value %s found with same name: %r',
235 235 attr_name, value, exist_in_session)
236 236
237 237 def __repr__(self):
238 238 if hasattr(self, '__unicode__'):
239 239 # python repr needs to return str
240 240 try:
241 241 return safe_str(self.__unicode__())
242 242 except UnicodeDecodeError:
243 243 pass
244 244 return '<DB:%s>' % (self.__class__.__name__)
245 245
246 246
247 247 class RhodeCodeSetting(Base, BaseModel):
248 248 __tablename__ = 'rhodecode_settings'
249 249 __table_args__ = (
250 250 UniqueConstraint('app_settings_name'),
251 251 {'extend_existing': True, 'mysql_engine': 'InnoDB',
252 252 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
253 253 )
254 254
255 255 SETTINGS_TYPES = {
256 256 'str': safe_str,
257 257 'int': safe_int,
258 258 'unicode': safe_unicode,
259 259 'bool': str2bool,
260 260 'list': functools.partial(aslist, sep=',')
261 261 }
262 262 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
263 263 GLOBAL_CONF_KEY = 'app_settings'
264 264
265 265 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
266 266 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
267 267 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
268 268 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
269 269
270 270 def __init__(self, key='', val='', type='unicode'):
271 271 self.app_settings_name = key
272 272 self.app_settings_type = type
273 273 self.app_settings_value = val
274 274
275 275 @validates('_app_settings_value')
276 276 def validate_settings_value(self, key, val):
277 277 assert type(val) == unicode
278 278 return val
279 279
280 280 @hybrid_property
281 281 def app_settings_value(self):
282 282 v = self._app_settings_value
283 283 _type = self.app_settings_type
284 284 if _type:
285 285 _type = self.app_settings_type.split('.')[0]
286 286 # decode the encrypted value
287 287 if 'encrypted' in self.app_settings_type:
288 288 cipher = EncryptedTextValue()
289 289 v = safe_unicode(cipher.process_result_value(v, None))
290 290
291 291 converter = self.SETTINGS_TYPES.get(_type) or \
292 292 self.SETTINGS_TYPES['unicode']
293 293 return converter(v)
294 294
295 295 @app_settings_value.setter
296 296 def app_settings_value(self, val):
297 297 """
298 298 Setter that will always make sure we use unicode in app_settings_value
299 299
300 300 :param val:
301 301 """
302 302 val = safe_unicode(val)
303 303 # encode the encrypted value
304 304 if 'encrypted' in self.app_settings_type:
305 305 cipher = EncryptedTextValue()
306 306 val = safe_unicode(cipher.process_bind_param(val, None))
307 307 self._app_settings_value = val
308 308
309 309 @hybrid_property
310 310 def app_settings_type(self):
311 311 return self._app_settings_type
312 312
313 313 @app_settings_type.setter
314 314 def app_settings_type(self, val):
315 315 if val.split('.')[0] not in self.SETTINGS_TYPES:
316 316 raise Exception('type must be one of %s got %s'
317 317 % (self.SETTINGS_TYPES.keys(), val))
318 318 self._app_settings_type = val
319 319
320 320 def __unicode__(self):
321 321 return u"<%s('%s:%s[%s]')>" % (
322 322 self.__class__.__name__,
323 323 self.app_settings_name, self.app_settings_value,
324 324 self.app_settings_type
325 325 )
326 326
327 327
328 328 class RhodeCodeUi(Base, BaseModel):
329 329 __tablename__ = 'rhodecode_ui'
330 330 __table_args__ = (
331 331 UniqueConstraint('ui_key'),
332 332 {'extend_existing': True, 'mysql_engine': 'InnoDB',
333 333 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
334 334 )
335 335
336 336 HOOK_REPO_SIZE = 'changegroup.repo_size'
337 337 # HG
338 338 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
339 339 HOOK_PULL = 'outgoing.pull_logger'
340 340 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
341 341 HOOK_PUSH = 'changegroup.push_logger'
342 342
343 343 # TODO: johbo: Unify way how hooks are configured for git and hg,
344 344 # git part is currently hardcoded.
345 345
346 346 # SVN PATTERNS
347 347 SVN_BRANCH_ID = 'vcs_svn_branch'
348 348 SVN_TAG_ID = 'vcs_svn_tag'
349 349
350 350 ui_id = Column(
351 351 "ui_id", Integer(), nullable=False, unique=True, default=None,
352 352 primary_key=True)
353 353 ui_section = Column(
354 354 "ui_section", String(255), nullable=True, unique=None, default=None)
355 355 ui_key = Column(
356 356 "ui_key", String(255), nullable=True, unique=None, default=None)
357 357 ui_value = Column(
358 358 "ui_value", String(255), nullable=True, unique=None, default=None)
359 359 ui_active = Column(
360 360 "ui_active", Boolean(), nullable=True, unique=None, default=True)
361 361
362 362 def __repr__(self):
363 363 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
364 364 self.ui_key, self.ui_value)
365 365
366 366
367 367 class RepoRhodeCodeSetting(Base, BaseModel):
368 368 __tablename__ = 'repo_rhodecode_settings'
369 369 __table_args__ = (
370 370 UniqueConstraint(
371 371 'app_settings_name', 'repository_id',
372 372 name='uq_repo_rhodecode_setting_name_repo_id'),
373 373 {'extend_existing': True, 'mysql_engine': 'InnoDB',
374 374 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
375 375 )
376 376
377 377 repository_id = Column(
378 378 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
379 379 nullable=False)
380 380 app_settings_id = Column(
381 381 "app_settings_id", Integer(), nullable=False, unique=True,
382 382 default=None, primary_key=True)
383 383 app_settings_name = Column(
384 384 "app_settings_name", String(255), nullable=True, unique=None,
385 385 default=None)
386 386 _app_settings_value = Column(
387 387 "app_settings_value", String(4096), nullable=True, unique=None,
388 388 default=None)
389 389 _app_settings_type = Column(
390 390 "app_settings_type", String(255), nullable=True, unique=None,
391 391 default=None)
392 392
393 393 repository = relationship('Repository')
394 394
395 395 def __init__(self, repository_id, key='', val='', type='unicode'):
396 396 self.repository_id = repository_id
397 397 self.app_settings_name = key
398 398 self.app_settings_type = type
399 399 self.app_settings_value = val
400 400
401 401 @validates('_app_settings_value')
402 402 def validate_settings_value(self, key, val):
403 403 assert type(val) == unicode
404 404 return val
405 405
406 406 @hybrid_property
407 407 def app_settings_value(self):
408 408 v = self._app_settings_value
409 409 type_ = self.app_settings_type
410 410 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
411 411 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
412 412 return converter(v)
413 413
414 414 @app_settings_value.setter
415 415 def app_settings_value(self, val):
416 416 """
417 417 Setter that will always make sure we use unicode in app_settings_value
418 418
419 419 :param val:
420 420 """
421 421 self._app_settings_value = safe_unicode(val)
422 422
423 423 @hybrid_property
424 424 def app_settings_type(self):
425 425 return self._app_settings_type
426 426
427 427 @app_settings_type.setter
428 428 def app_settings_type(self, val):
429 429 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
430 430 if val not in SETTINGS_TYPES:
431 431 raise Exception('type must be one of %s got %s'
432 432 % (SETTINGS_TYPES.keys(), val))
433 433 self._app_settings_type = val
434 434
435 435 def __unicode__(self):
436 436 return u"<%s('%s:%s:%s[%s]')>" % (
437 437 self.__class__.__name__, self.repository.repo_name,
438 438 self.app_settings_name, self.app_settings_value,
439 439 self.app_settings_type
440 440 )
441 441
442 442
443 443 class RepoRhodeCodeUi(Base, BaseModel):
444 444 __tablename__ = 'repo_rhodecode_ui'
445 445 __table_args__ = (
446 446 UniqueConstraint(
447 447 'repository_id', 'ui_section', 'ui_key',
448 448 name='uq_repo_rhodecode_ui_repository_id_section_key'),
449 449 {'extend_existing': True, 'mysql_engine': 'InnoDB',
450 450 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
451 451 )
452 452
453 453 repository_id = Column(
454 454 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
455 455 nullable=False)
456 456 ui_id = Column(
457 457 "ui_id", Integer(), nullable=False, unique=True, default=None,
458 458 primary_key=True)
459 459 ui_section = Column(
460 460 "ui_section", String(255), nullable=True, unique=None, default=None)
461 461 ui_key = Column(
462 462 "ui_key", String(255), nullable=True, unique=None, default=None)
463 463 ui_value = Column(
464 464 "ui_value", String(255), nullable=True, unique=None, default=None)
465 465 ui_active = Column(
466 466 "ui_active", Boolean(), nullable=True, unique=None, default=True)
467 467
468 468 repository = relationship('Repository')
469 469
470 470 def __repr__(self):
471 471 return '<%s[%s:%s]%s=>%s]>' % (
472 472 self.__class__.__name__, self.repository.repo_name,
473 473 self.ui_section, self.ui_key, self.ui_value)
474 474
475 475
476 476 class User(Base, BaseModel):
477 477 __tablename__ = 'users'
478 478 __table_args__ = (
479 479 UniqueConstraint('username'), UniqueConstraint('email'),
480 480 Index('u_username_idx', 'username'),
481 481 Index('u_email_idx', 'email'),
482 482 {'extend_existing': True, 'mysql_engine': 'InnoDB',
483 483 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
484 484 )
485 485 DEFAULT_USER = 'default'
486 486 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
487 487 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
488 488
489 489 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
490 490 username = Column("username", String(255), nullable=True, unique=None, default=None)
491 491 password = Column("password", String(255), nullable=True, unique=None, default=None)
492 492 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
493 493 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
494 494 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
495 495 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
496 496 _email = Column("email", String(255), nullable=True, unique=None, default=None)
497 497 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
498 498 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
499 499 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
500 500 api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
501 501 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
502 502 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
503 503 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
504 504
505 505 user_log = relationship('UserLog')
506 506 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
507 507
508 508 repositories = relationship('Repository')
509 509 repository_groups = relationship('RepoGroup')
510 510 user_groups = relationship('UserGroup')
511 511
512 512 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
513 513 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
514 514
515 515 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
516 516 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
517 517 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
518 518
519 519 group_member = relationship('UserGroupMember', cascade='all')
520 520
521 521 notifications = relationship('UserNotification', cascade='all')
522 522 # notifications assigned to this user
523 523 user_created_notifications = relationship('Notification', cascade='all')
524 524 # comments created by this user
525 525 user_comments = relationship('ChangesetComment', cascade='all')
526 526 # user profile extra info
527 527 user_emails = relationship('UserEmailMap', cascade='all')
528 528 user_ip_map = relationship('UserIpMap', cascade='all')
529 529 user_auth_tokens = relationship('UserApiKeys', cascade='all')
530 530 # gists
531 531 user_gists = relationship('Gist', cascade='all')
532 532 # user pull requests
533 533 user_pull_requests = relationship('PullRequest', cascade='all')
534 534 # external identities
535 535 extenal_identities = relationship(
536 536 'ExternalIdentity',
537 537 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
538 538 cascade='all')
539 539
540 540 def __unicode__(self):
541 541 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
542 542 self.user_id, self.username)
543 543
544 544 @hybrid_property
545 545 def email(self):
546 546 return self._email
547 547
548 548 @email.setter
549 549 def email(self, val):
550 550 self._email = val.lower() if val else None
551 551
552 552 @property
553 553 def firstname(self):
554 554 # alias for future
555 555 return self.name
556 556
557 557 @property
558 558 def emails(self):
559 559 other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
560 560 return [self.email] + [x.email for x in other]
561 561
562 562 @property
563 563 def auth_tokens(self):
564 564 return [self.api_key] + [x.api_key for x in self.extra_auth_tokens]
565 565
566 566 @property
567 567 def extra_auth_tokens(self):
568 568 return UserApiKeys.query().filter(UserApiKeys.user == self).all()
569 569
570 570 @property
571 571 def feed_token(self):
572 572 feed_tokens = UserApiKeys.query()\
573 573 .filter(UserApiKeys.user == self)\
574 574 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)\
575 575 .all()
576 576 if feed_tokens:
577 577 return feed_tokens[0].api_key
578 578 else:
579 579 # use the main token so we don't end up with nothing...
580 580 return self.api_key
581 581
582 582 @classmethod
583 583 def extra_valid_auth_tokens(cls, user, role=None):
584 584 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
585 585 .filter(or_(UserApiKeys.expires == -1,
586 586 UserApiKeys.expires >= time.time()))
587 587 if role:
588 588 tokens = tokens.filter(or_(UserApiKeys.role == role,
589 589 UserApiKeys.role == UserApiKeys.ROLE_ALL))
590 590 return tokens.all()
591 591
592 592 @property
593 593 def ip_addresses(self):
594 594 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
595 595 return [x.ip_addr for x in ret]
596 596
597 597 @property
598 598 def username_and_name(self):
599 599 return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
600 600
601 601 @property
602 602 def username_or_name_or_email(self):
603 603 full_name = self.full_name if self.full_name is not ' ' else None
604 604 return self.username or full_name or self.email
605 605
606 606 @property
607 607 def full_name(self):
608 608 return '%s %s' % (self.firstname, self.lastname)
609 609
610 610 @property
611 611 def full_name_or_username(self):
612 612 return ('%s %s' % (self.firstname, self.lastname)
613 613 if (self.firstname and self.lastname) else self.username)
614 614
615 615 @property
616 616 def full_contact(self):
617 617 return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
618 618
619 619 @property
620 620 def short_contact(self):
621 621 return '%s %s' % (self.firstname, self.lastname)
622 622
623 623 @property
624 624 def is_admin(self):
625 625 return self.admin
626 626
627 627 @property
628 628 def AuthUser(self):
629 629 """
630 630 Returns instance of AuthUser for this user
631 631 """
632 632 from rhodecode.lib.auth import AuthUser
633 633 return AuthUser(user_id=self.user_id, api_key=self.api_key,
634 634 username=self.username)
635 635
636 636 @hybrid_property
637 637 def user_data(self):
638 638 if not self._user_data:
639 639 return {}
640 640
641 641 try:
642 642 return json.loads(self._user_data)
643 643 except TypeError:
644 644 return {}
645 645
646 646 @user_data.setter
647 647 def user_data(self, val):
648 648 if not isinstance(val, dict):
649 649 raise Exception('user_data must be dict, got %s' % type(val))
650 650 try:
651 651 self._user_data = json.dumps(val)
652 652 except Exception:
653 653 log.error(traceback.format_exc())
654 654
655 655 @classmethod
656 656 def get_by_username(cls, username, case_insensitive=False,
657 657 cache=False, identity_cache=False):
658 658 session = Session()
659 659
660 660 if case_insensitive:
661 661 q = cls.query().filter(
662 662 func.lower(cls.username) == func.lower(username))
663 663 else:
664 664 q = cls.query().filter(cls.username == username)
665 665
666 666 if cache:
667 667 if identity_cache:
668 668 val = cls.identity_cache(session, 'username', username)
669 669 if val:
670 670 return val
671 671 else:
672 672 q = q.options(
673 673 FromCache("sql_cache_short",
674 674 "get_user_by_name_%s" % _hash_key(username)))
675 675
676 676 return q.scalar()
677 677
678 678 @classmethod
679 679 def get_by_auth_token(cls, auth_token, cache=False, fallback=True):
680 680 q = cls.query().filter(cls.api_key == auth_token)
681 681
682 682 if cache:
683 683 q = q.options(FromCache("sql_cache_short",
684 684 "get_auth_token_%s" % auth_token))
685 685 res = q.scalar()
686 686
687 687 if fallback and not res:
688 688 #fallback to additional keys
689 689 _res = UserApiKeys.query()\
690 690 .filter(UserApiKeys.api_key == auth_token)\
691 691 .filter(or_(UserApiKeys.expires == -1,
692 692 UserApiKeys.expires >= time.time()))\
693 693 .first()
694 694 if _res:
695 695 res = _res.user
696 696 return res
697 697
698 698 @classmethod
699 699 def get_by_email(cls, email, case_insensitive=False, cache=False):
700 700
701 701 if case_insensitive:
702 702 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
703 703
704 704 else:
705 705 q = cls.query().filter(cls.email == email)
706 706
707 707 if cache:
708 708 q = q.options(FromCache("sql_cache_short",
709 709 "get_email_key_%s" % email))
710 710
711 711 ret = q.scalar()
712 712 if ret is None:
713 713 q = UserEmailMap.query()
714 714 # try fetching in alternate email map
715 715 if case_insensitive:
716 716 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
717 717 else:
718 718 q = q.filter(UserEmailMap.email == email)
719 719 q = q.options(joinedload(UserEmailMap.user))
720 720 if cache:
721 721 q = q.options(FromCache("sql_cache_short",
722 722 "get_email_map_key_%s" % email))
723 723 ret = getattr(q.scalar(), 'user', None)
724 724
725 725 return ret
726 726
727 727 @classmethod
728 728 def get_from_cs_author(cls, author):
729 729 """
730 730 Tries to get User objects out of commit author string
731 731
732 732 :param author:
733 733 """
734 734 from rhodecode.lib.helpers import email, author_name
735 735 # Valid email in the attribute passed, see if they're in the system
736 736 _email = email(author)
737 737 if _email:
738 738 user = cls.get_by_email(_email, case_insensitive=True)
739 739 if user:
740 740 return user
741 741 # Maybe we can match by username?
742 742 _author = author_name(author)
743 743 user = cls.get_by_username(_author, case_insensitive=True)
744 744 if user:
745 745 return user
746 746
747 747 def update_userdata(self, **kwargs):
748 748 usr = self
749 749 old = usr.user_data
750 750 old.update(**kwargs)
751 751 usr.user_data = old
752 752 Session().add(usr)
753 753 log.debug('updated userdata with ', kwargs)
754 754
755 755 def update_lastlogin(self):
756 756 """Update user lastlogin"""
757 757 self.last_login = datetime.datetime.now()
758 758 Session().add(self)
759 759 log.debug('updated user %s lastlogin', self.username)
760 760
761 761 def update_lastactivity(self):
762 762 """Update user lastactivity"""
763 763 usr = self
764 764 old = usr.user_data
765 765 old.update({'last_activity': time.time()})
766 766 usr.user_data = old
767 767 Session().add(usr)
768 768 log.debug('updated user %s lastactivity', usr.username)
769 769
770 770 def update_password(self, new_password, change_api_key=False):
771 771 from rhodecode.lib.auth import get_crypt_password,generate_auth_token
772 772
773 773 self.password = get_crypt_password(new_password)
774 774 if change_api_key:
775 775 self.api_key = generate_auth_token(self.username)
776 776 Session().add(self)
777 777
778 778 @classmethod
779 779 def get_first_super_admin(cls):
780 780 user = User.query().filter(User.admin == true()).first()
781 781 if user is None:
782 raise Exception('Missing administrative account!')
782 raise Exception('FATAL: Missing administrative account!')
783 783 return user
784 784
785 785 @classmethod
786 786 def get_all_super_admins(cls):
787 787 """
788 788 Returns all admin accounts sorted by username
789 789 """
790 790 return User.query().filter(User.admin == true())\
791 791 .order_by(User.username.asc()).all()
792 792
793 793 @classmethod
794 794 def get_default_user(cls, cache=False):
795 795 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
796 796 if user is None:
797 raise Exception('Missing default account!')
797 raise Exception('FATAL: Missing default account!')
798 798 return user
799 799
800 800 def _get_default_perms(self, user, suffix=''):
801 801 from rhodecode.model.permission import PermissionModel
802 802 return PermissionModel().get_default_perms(user.user_perms, suffix)
803 803
804 804 def get_default_perms(self, suffix=''):
805 805 return self._get_default_perms(self, suffix)
806 806
807 807 def get_api_data(self, include_secrets=False, details='full'):
808 808 """
809 809 Common function for generating user related data for API
810 810
811 811 :param include_secrets: By default secrets in the API data will be replaced
812 812 by a placeholder value to prevent exposing this data by accident. In case
813 813 this data shall be exposed, set this flag to ``True``.
814 814
815 815 :param details: details can be 'basic|full' basic gives only a subset of
816 816 the available user information that includes user_id, name and emails.
817 817 """
818 818 user = self
819 819 user_data = self.user_data
820 820 data = {
821 821 'user_id': user.user_id,
822 822 'username': user.username,
823 823 'firstname': user.name,
824 824 'lastname': user.lastname,
825 825 'email': user.email,
826 826 'emails': user.emails,
827 827 }
828 828 if details == 'basic':
829 829 return data
830 830
831 831 api_key_length = 40
832 832 api_key_replacement = '*' * api_key_length
833 833
834 834 extras = {
835 835 'api_key': api_key_replacement,
836 836 'api_keys': [api_key_replacement],
837 837 'active': user.active,
838 838 'admin': user.admin,
839 839 'extern_type': user.extern_type,
840 840 'extern_name': user.extern_name,
841 841 'last_login': user.last_login,
842 842 'ip_addresses': user.ip_addresses,
843 843 'language': user_data.get('language')
844 844 }
845 845 data.update(extras)
846 846
847 847 if include_secrets:
848 848 data['api_key'] = user.api_key
849 849 data['api_keys'] = user.auth_tokens
850 850 return data
851 851
852 852 def __json__(self):
853 853 data = {
854 854 'full_name': self.full_name,
855 855 'full_name_or_username': self.full_name_or_username,
856 856 'short_contact': self.short_contact,
857 857 'full_contact': self.full_contact,
858 858 }
859 859 data.update(self.get_api_data())
860 860 return data
861 861
862 862
863 863 class UserApiKeys(Base, BaseModel):
864 864 __tablename__ = 'user_api_keys'
865 865 __table_args__ = (
866 866 Index('uak_api_key_idx', 'api_key'),
867 867 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
868 868 UniqueConstraint('api_key'),
869 869 {'extend_existing': True, 'mysql_engine': 'InnoDB',
870 870 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
871 871 )
872 872 __mapper_args__ = {}
873 873
874 874 # ApiKey role
875 875 ROLE_ALL = 'token_role_all'
876 876 ROLE_HTTP = 'token_role_http'
877 877 ROLE_VCS = 'token_role_vcs'
878 878 ROLE_API = 'token_role_api'
879 879 ROLE_FEED = 'token_role_feed'
880 880 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
881 881
882 882 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
883 883 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
884 884 api_key = Column("api_key", String(255), nullable=False, unique=True)
885 885 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
886 886 expires = Column('expires', Float(53), nullable=False)
887 887 role = Column('role', String(255), nullable=True)
888 888 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
889 889
890 890 user = relationship('User', lazy='joined')
891 891
892 892 @classmethod
893 893 def _get_role_name(cls, role):
894 894 return {
895 895 cls.ROLE_ALL: _('all'),
896 896 cls.ROLE_HTTP: _('http/web interface'),
897 897 cls.ROLE_VCS: _('vcs (git/hg protocol)'),
898 898 cls.ROLE_API: _('api calls'),
899 899 cls.ROLE_FEED: _('feed access'),
900 900 }.get(role, role)
901 901
902 902 @property
903 903 def expired(self):
904 904 if self.expires == -1:
905 905 return False
906 906 return time.time() > self.expires
907 907
908 908 @property
909 909 def role_humanized(self):
910 910 return self._get_role_name(self.role)
911 911
912 912
913 913 class UserEmailMap(Base, BaseModel):
914 914 __tablename__ = 'user_email_map'
915 915 __table_args__ = (
916 916 Index('uem_email_idx', 'email'),
917 917 UniqueConstraint('email'),
918 918 {'extend_existing': True, 'mysql_engine': 'InnoDB',
919 919 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
920 920 )
921 921 __mapper_args__ = {}
922 922
923 923 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
924 924 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
925 925 _email = Column("email", String(255), nullable=True, unique=False, default=None)
926 926 user = relationship('User', lazy='joined')
927 927
928 928 @validates('_email')
929 929 def validate_email(self, key, email):
930 930 # check if this email is not main one
931 931 main_email = Session().query(User).filter(User.email == email).scalar()
932 932 if main_email is not None:
933 933 raise AttributeError('email %s is present is user table' % email)
934 934 return email
935 935
936 936 @hybrid_property
937 937 def email(self):
938 938 return self._email
939 939
940 940 @email.setter
941 941 def email(self, val):
942 942 self._email = val.lower() if val else None
943 943
944 944
945 945 class UserIpMap(Base, BaseModel):
946 946 __tablename__ = 'user_ip_map'
947 947 __table_args__ = (
948 948 UniqueConstraint('user_id', 'ip_addr'),
949 949 {'extend_existing': True, 'mysql_engine': 'InnoDB',
950 950 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
951 951 )
952 952 __mapper_args__ = {}
953 953
954 954 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
955 955 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
956 956 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
957 957 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
958 958 description = Column("description", String(10000), nullable=True, unique=None, default=None)
959 959 user = relationship('User', lazy='joined')
960 960
961 961 @classmethod
962 962 def _get_ip_range(cls, ip_addr):
963 963 net = ipaddress.ip_network(ip_addr, strict=False)
964 964 return [str(net.network_address), str(net.broadcast_address)]
965 965
966 966 def __json__(self):
967 967 return {
968 968 'ip_addr': self.ip_addr,
969 969 'ip_range': self._get_ip_range(self.ip_addr),
970 970 }
971 971
972 972 def __unicode__(self):
973 973 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
974 974 self.user_id, self.ip_addr)
975 975
976 976 class UserLog(Base, BaseModel):
977 977 __tablename__ = 'user_logs'
978 978 __table_args__ = (
979 979 {'extend_existing': True, 'mysql_engine': 'InnoDB',
980 980 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
981 981 )
982 982 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
983 983 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
984 984 username = Column("username", String(255), nullable=True, unique=None, default=None)
985 985 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
986 986 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
987 987 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
988 988 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
989 989 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
990 990
991 991 def __unicode__(self):
992 992 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
993 993 self.repository_name,
994 994 self.action)
995 995
996 996 @property
997 997 def action_as_day(self):
998 998 return datetime.date(*self.action_date.timetuple()[:3])
999 999
1000 1000 user = relationship('User')
1001 1001 repository = relationship('Repository', cascade='')
1002 1002
1003 1003
1004 1004 class UserGroup(Base, BaseModel):
1005 1005 __tablename__ = 'users_groups'
1006 1006 __table_args__ = (
1007 1007 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1008 1008 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1009 1009 )
1010 1010
1011 1011 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1012 1012 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1013 1013 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1014 1014 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1015 1015 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1016 1016 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1017 1017 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1018 1018 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1019 1019
1020 1020 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1021 1021 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1022 1022 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1023 1023 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1024 1024 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1025 1025 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1026 1026
1027 1027 user = relationship('User')
1028 1028
1029 1029 @hybrid_property
1030 1030 def group_data(self):
1031 1031 if not self._group_data:
1032 1032 return {}
1033 1033
1034 1034 try:
1035 1035 return json.loads(self._group_data)
1036 1036 except TypeError:
1037 1037 return {}
1038 1038
1039 1039 @group_data.setter
1040 1040 def group_data(self, val):
1041 1041 try:
1042 1042 self._group_data = json.dumps(val)
1043 1043 except Exception:
1044 1044 log.error(traceback.format_exc())
1045 1045
1046 1046 def __unicode__(self):
1047 1047 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1048 1048 self.users_group_id,
1049 1049 self.users_group_name)
1050 1050
1051 1051 @classmethod
1052 1052 def get_by_group_name(cls, group_name, cache=False,
1053 1053 case_insensitive=False):
1054 1054 if case_insensitive:
1055 1055 q = cls.query().filter(func.lower(cls.users_group_name) ==
1056 1056 func.lower(group_name))
1057 1057
1058 1058 else:
1059 1059 q = cls.query().filter(cls.users_group_name == group_name)
1060 1060 if cache:
1061 1061 q = q.options(FromCache(
1062 1062 "sql_cache_short",
1063 1063 "get_group_%s" % _hash_key(group_name)))
1064 1064 return q.scalar()
1065 1065
1066 1066 @classmethod
1067 1067 def get(cls, user_group_id, cache=False):
1068 1068 user_group = cls.query()
1069 1069 if cache:
1070 1070 user_group = user_group.options(FromCache("sql_cache_short",
1071 1071 "get_users_group_%s" % user_group_id))
1072 1072 return user_group.get(user_group_id)
1073 1073
1074 1074 def permissions(self, with_admins=True, with_owner=True):
1075 1075 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1076 1076 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1077 1077 joinedload(UserUserGroupToPerm.user),
1078 1078 joinedload(UserUserGroupToPerm.permission),)
1079 1079
1080 1080 # get owners and admins and permissions. We do a trick of re-writing
1081 1081 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1082 1082 # has a global reference and changing one object propagates to all
1083 1083 # others. This means if admin is also an owner admin_row that change
1084 1084 # would propagate to both objects
1085 1085 perm_rows = []
1086 1086 for _usr in q.all():
1087 1087 usr = AttributeDict(_usr.user.get_dict())
1088 1088 usr.permission = _usr.permission.permission_name
1089 1089 perm_rows.append(usr)
1090 1090
1091 1091 # filter the perm rows by 'default' first and then sort them by
1092 1092 # admin,write,read,none permissions sorted again alphabetically in
1093 1093 # each group
1094 1094 perm_rows = sorted(perm_rows, key=display_sort)
1095 1095
1096 1096 _admin_perm = 'usergroup.admin'
1097 1097 owner_row = []
1098 1098 if with_owner:
1099 1099 usr = AttributeDict(self.user.get_dict())
1100 1100 usr.owner_row = True
1101 1101 usr.permission = _admin_perm
1102 1102 owner_row.append(usr)
1103 1103
1104 1104 super_admin_rows = []
1105 1105 if with_admins:
1106 1106 for usr in User.get_all_super_admins():
1107 1107 # if this admin is also owner, don't double the record
1108 1108 if usr.user_id == owner_row[0].user_id:
1109 1109 owner_row[0].admin_row = True
1110 1110 else:
1111 1111 usr = AttributeDict(usr.get_dict())
1112 1112 usr.admin_row = True
1113 1113 usr.permission = _admin_perm
1114 1114 super_admin_rows.append(usr)
1115 1115
1116 1116 return super_admin_rows + owner_row + perm_rows
1117 1117
1118 1118 def permission_user_groups(self):
1119 1119 q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self)
1120 1120 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1121 1121 joinedload(UserGroupUserGroupToPerm.target_user_group),
1122 1122 joinedload(UserGroupUserGroupToPerm.permission),)
1123 1123
1124 1124 perm_rows = []
1125 1125 for _user_group in q.all():
1126 1126 usr = AttributeDict(_user_group.user_group.get_dict())
1127 1127 usr.permission = _user_group.permission.permission_name
1128 1128 perm_rows.append(usr)
1129 1129
1130 1130 return perm_rows
1131 1131
1132 1132 def _get_default_perms(self, user_group, suffix=''):
1133 1133 from rhodecode.model.permission import PermissionModel
1134 1134 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1135 1135
1136 1136 def get_default_perms(self, suffix=''):
1137 1137 return self._get_default_perms(self, suffix)
1138 1138
1139 1139 def get_api_data(self, with_group_members=True, include_secrets=False):
1140 1140 """
1141 1141 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1142 1142 basically forwarded.
1143 1143
1144 1144 """
1145 1145 user_group = self
1146 1146
1147 1147 data = {
1148 1148 'users_group_id': user_group.users_group_id,
1149 1149 'group_name': user_group.users_group_name,
1150 1150 'group_description': user_group.user_group_description,
1151 1151 'active': user_group.users_group_active,
1152 1152 'owner': user_group.user.username,
1153 1153 }
1154 1154 if with_group_members:
1155 1155 users = []
1156 1156 for user in user_group.members:
1157 1157 user = user.user
1158 1158 users.append(user.get_api_data(include_secrets=include_secrets))
1159 1159 data['users'] = users
1160 1160
1161 1161 return data
1162 1162
1163 1163
1164 1164 class UserGroupMember(Base, BaseModel):
1165 1165 __tablename__ = 'users_groups_members'
1166 1166 __table_args__ = (
1167 1167 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1168 1168 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1169 1169 )
1170 1170
1171 1171 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1172 1172 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1173 1173 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1174 1174
1175 1175 user = relationship('User', lazy='joined')
1176 1176 users_group = relationship('UserGroup')
1177 1177
1178 1178 def __init__(self, gr_id='', u_id=''):
1179 1179 self.users_group_id = gr_id
1180 1180 self.user_id = u_id
1181 1181
1182 1182
1183 1183 class RepositoryField(Base, BaseModel):
1184 1184 __tablename__ = 'repositories_fields'
1185 1185 __table_args__ = (
1186 1186 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1187 1187 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1188 1188 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1189 1189 )
1190 1190 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1191 1191
1192 1192 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1193 1193 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1194 1194 field_key = Column("field_key", String(250))
1195 1195 field_label = Column("field_label", String(1024), nullable=False)
1196 1196 field_value = Column("field_value", String(10000), nullable=False)
1197 1197 field_desc = Column("field_desc", String(1024), nullable=False)
1198 1198 field_type = Column("field_type", String(255), nullable=False, unique=None)
1199 1199 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1200 1200
1201 1201 repository = relationship('Repository')
1202 1202
1203 1203 @property
1204 1204 def field_key_prefixed(self):
1205 1205 return 'ex_%s' % self.field_key
1206 1206
1207 1207 @classmethod
1208 1208 def un_prefix_key(cls, key):
1209 1209 if key.startswith(cls.PREFIX):
1210 1210 return key[len(cls.PREFIX):]
1211 1211 return key
1212 1212
1213 1213 @classmethod
1214 1214 def get_by_key_name(cls, key, repo):
1215 1215 row = cls.query()\
1216 1216 .filter(cls.repository == repo)\
1217 1217 .filter(cls.field_key == key).scalar()
1218 1218 return row
1219 1219
1220 1220
1221 1221 class Repository(Base, BaseModel):
1222 1222 __tablename__ = 'repositories'
1223 1223 __table_args__ = (
1224 1224 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1225 1225 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1226 1226 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1227 1227 )
1228 1228 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1229 1229 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1230 1230
1231 1231 STATE_CREATED = 'repo_state_created'
1232 1232 STATE_PENDING = 'repo_state_pending'
1233 1233 STATE_ERROR = 'repo_state_error'
1234 1234
1235 1235 LOCK_AUTOMATIC = 'lock_auto'
1236 1236 LOCK_API = 'lock_api'
1237 1237 LOCK_WEB = 'lock_web'
1238 1238 LOCK_PULL = 'lock_pull'
1239 1239
1240 1240 NAME_SEP = URL_SEP
1241 1241
1242 1242 repo_id = Column(
1243 1243 "repo_id", Integer(), nullable=False, unique=True, default=None,
1244 1244 primary_key=True)
1245 1245 _repo_name = Column(
1246 1246 "repo_name", Text(), nullable=False, default=None)
1247 1247 _repo_name_hash = Column(
1248 1248 "repo_name_hash", String(255), nullable=False, unique=True)
1249 1249 repo_state = Column("repo_state", String(255), nullable=True)
1250 1250
1251 1251 clone_uri = Column(
1252 1252 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1253 1253 default=None)
1254 1254 repo_type = Column(
1255 1255 "repo_type", String(255), nullable=False, unique=False, default=None)
1256 1256 user_id = Column(
1257 1257 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1258 1258 unique=False, default=None)
1259 1259 private = Column(
1260 1260 "private", Boolean(), nullable=True, unique=None, default=None)
1261 1261 enable_statistics = Column(
1262 1262 "statistics", Boolean(), nullable=True, unique=None, default=True)
1263 1263 enable_downloads = Column(
1264 1264 "downloads", Boolean(), nullable=True, unique=None, default=True)
1265 1265 description = Column(
1266 1266 "description", String(10000), nullable=True, unique=None, default=None)
1267 1267 created_on = Column(
1268 1268 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1269 1269 default=datetime.datetime.now)
1270 1270 updated_on = Column(
1271 1271 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1272 1272 default=datetime.datetime.now)
1273 1273 _landing_revision = Column(
1274 1274 "landing_revision", String(255), nullable=False, unique=False,
1275 1275 default=None)
1276 1276 enable_locking = Column(
1277 1277 "enable_locking", Boolean(), nullable=False, unique=None,
1278 1278 default=False)
1279 1279 _locked = Column(
1280 1280 "locked", String(255), nullable=True, unique=False, default=None)
1281 1281 _changeset_cache = Column(
1282 1282 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1283 1283
1284 1284 fork_id = Column(
1285 1285 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1286 1286 nullable=True, unique=False, default=None)
1287 1287 group_id = Column(
1288 1288 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1289 1289 unique=False, default=None)
1290 1290
1291 1291 user = relationship('User', lazy='joined')
1292 1292 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1293 1293 group = relationship('RepoGroup', lazy='joined')
1294 1294 repo_to_perm = relationship(
1295 1295 'UserRepoToPerm', cascade='all',
1296 1296 order_by='UserRepoToPerm.repo_to_perm_id')
1297 1297 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1298 1298 stats = relationship('Statistics', cascade='all', uselist=False)
1299 1299
1300 1300 followers = relationship(
1301 1301 'UserFollowing',
1302 1302 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1303 1303 cascade='all')
1304 1304 extra_fields = relationship(
1305 1305 'RepositoryField', cascade="all, delete, delete-orphan")
1306 1306 logs = relationship('UserLog')
1307 1307 comments = relationship(
1308 1308 'ChangesetComment', cascade="all, delete, delete-orphan")
1309 1309 pull_requests_source = relationship(
1310 1310 'PullRequest',
1311 1311 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1312 1312 cascade="all, delete, delete-orphan")
1313 1313 pull_requests_target = relationship(
1314 1314 'PullRequest',
1315 1315 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1316 1316 cascade="all, delete, delete-orphan")
1317 1317 ui = relationship('RepoRhodeCodeUi', cascade="all")
1318 1318 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1319 1319
1320 1320 def __unicode__(self):
1321 1321 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1322 1322 safe_unicode(self.repo_name))
1323 1323
1324 1324 @hybrid_property
1325 1325 def landing_rev(self):
1326 1326 # always should return [rev_type, rev]
1327 1327 if self._landing_revision:
1328 1328 _rev_info = self._landing_revision.split(':')
1329 1329 if len(_rev_info) < 2:
1330 1330 _rev_info.insert(0, 'rev')
1331 1331 return [_rev_info[0], _rev_info[1]]
1332 1332 return [None, None]
1333 1333
1334 1334 @landing_rev.setter
1335 1335 def landing_rev(self, val):
1336 1336 if ':' not in val:
1337 1337 raise ValueError('value must be delimited with `:` and consist '
1338 1338 'of <rev_type>:<rev>, got %s instead' % val)
1339 1339 self._landing_revision = val
1340 1340
1341 1341 @hybrid_property
1342 1342 def locked(self):
1343 1343 if self._locked:
1344 1344 user_id, timelocked, reason = self._locked.split(':')
1345 1345 lock_values = int(user_id), timelocked, reason
1346 1346 else:
1347 1347 lock_values = [None, None, None]
1348 1348 return lock_values
1349 1349
1350 1350 @locked.setter
1351 1351 def locked(self, val):
1352 1352 if val and isinstance(val, (list, tuple)):
1353 1353 self._locked = ':'.join(map(str, val))
1354 1354 else:
1355 1355 self._locked = None
1356 1356
1357 1357 @hybrid_property
1358 1358 def changeset_cache(self):
1359 1359 from rhodecode.lib.vcs.backends.base import EmptyCommit
1360 1360 dummy = EmptyCommit().__json__()
1361 1361 if not self._changeset_cache:
1362 1362 return dummy
1363 1363 try:
1364 1364 return json.loads(self._changeset_cache)
1365 1365 except TypeError:
1366 1366 return dummy
1367 1367 except Exception:
1368 1368 log.error(traceback.format_exc())
1369 1369 return dummy
1370 1370
1371 1371 @changeset_cache.setter
1372 1372 def changeset_cache(self, val):
1373 1373 try:
1374 1374 self._changeset_cache = json.dumps(val)
1375 1375 except Exception:
1376 1376 log.error(traceback.format_exc())
1377 1377
1378 1378 @hybrid_property
1379 1379 def repo_name(self):
1380 1380 return self._repo_name
1381 1381
1382 1382 @repo_name.setter
1383 1383 def repo_name(self, value):
1384 1384 self._repo_name = value
1385 1385 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1386 1386
1387 1387 @classmethod
1388 1388 def normalize_repo_name(cls, repo_name):
1389 1389 """
1390 1390 Normalizes os specific repo_name to the format internally stored inside
1391 1391 database using URL_SEP
1392 1392
1393 1393 :param cls:
1394 1394 :param repo_name:
1395 1395 """
1396 1396 return cls.NAME_SEP.join(repo_name.split(os.sep))
1397 1397
1398 1398 @classmethod
1399 1399 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1400 1400 session = Session()
1401 1401 q = session.query(cls).filter(cls.repo_name == repo_name)
1402 1402
1403 1403 if cache:
1404 1404 if identity_cache:
1405 1405 val = cls.identity_cache(session, 'repo_name', repo_name)
1406 1406 if val:
1407 1407 return val
1408 1408 else:
1409 1409 q = q.options(
1410 1410 FromCache("sql_cache_short",
1411 1411 "get_repo_by_name_%s" % _hash_key(repo_name)))
1412 1412
1413 1413 return q.scalar()
1414 1414
1415 1415 @classmethod
1416 1416 def get_by_full_path(cls, repo_full_path):
1417 1417 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1418 1418 repo_name = cls.normalize_repo_name(repo_name)
1419 1419 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1420 1420
1421 1421 @classmethod
1422 1422 def get_repo_forks(cls, repo_id):
1423 1423 return cls.query().filter(Repository.fork_id == repo_id)
1424 1424
1425 1425 @classmethod
1426 1426 def base_path(cls):
1427 1427 """
1428 1428 Returns base path when all repos are stored
1429 1429
1430 1430 :param cls:
1431 1431 """
1432 1432 q = Session().query(RhodeCodeUi)\
1433 1433 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1434 1434 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1435 1435 return q.one().ui_value
1436 1436
1437 1437 @classmethod
1438 1438 def is_valid(cls, repo_name):
1439 1439 """
1440 1440 returns True if given repo name is a valid filesystem repository
1441 1441
1442 1442 :param cls:
1443 1443 :param repo_name:
1444 1444 """
1445 1445 from rhodecode.lib.utils import is_valid_repo
1446 1446
1447 1447 return is_valid_repo(repo_name, cls.base_path())
1448 1448
1449 1449 @classmethod
1450 1450 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1451 1451 case_insensitive=True):
1452 1452 q = Repository.query()
1453 1453
1454 1454 if not isinstance(user_id, Optional):
1455 1455 q = q.filter(Repository.user_id == user_id)
1456 1456
1457 1457 if not isinstance(group_id, Optional):
1458 1458 q = q.filter(Repository.group_id == group_id)
1459 1459
1460 1460 if case_insensitive:
1461 1461 q = q.order_by(func.lower(Repository.repo_name))
1462 1462 else:
1463 1463 q = q.order_by(Repository.repo_name)
1464 1464 return q.all()
1465 1465
1466 1466 @property
1467 1467 def forks(self):
1468 1468 """
1469 1469 Return forks of this repo
1470 1470 """
1471 1471 return Repository.get_repo_forks(self.repo_id)
1472 1472
1473 1473 @property
1474 1474 def parent(self):
1475 1475 """
1476 1476 Returns fork parent
1477 1477 """
1478 1478 return self.fork
1479 1479
1480 1480 @property
1481 1481 def just_name(self):
1482 1482 return self.repo_name.split(self.NAME_SEP)[-1]
1483 1483
1484 1484 @property
1485 1485 def groups_with_parents(self):
1486 1486 groups = []
1487 1487 if self.group is None:
1488 1488 return groups
1489 1489
1490 1490 cur_gr = self.group
1491 1491 groups.insert(0, cur_gr)
1492 1492 while 1:
1493 1493 gr = getattr(cur_gr, 'parent_group', None)
1494 1494 cur_gr = cur_gr.parent_group
1495 1495 if gr is None:
1496 1496 break
1497 1497 groups.insert(0, gr)
1498 1498
1499 1499 return groups
1500 1500
1501 1501 @property
1502 1502 def groups_and_repo(self):
1503 1503 return self.groups_with_parents, self
1504 1504
1505 1505 @LazyProperty
1506 1506 def repo_path(self):
1507 1507 """
1508 1508 Returns base full path for that repository means where it actually
1509 1509 exists on a filesystem
1510 1510 """
1511 1511 q = Session().query(RhodeCodeUi).filter(
1512 1512 RhodeCodeUi.ui_key == self.NAME_SEP)
1513 1513 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1514 1514 return q.one().ui_value
1515 1515
1516 1516 @property
1517 1517 def repo_full_path(self):
1518 1518 p = [self.repo_path]
1519 1519 # we need to split the name by / since this is how we store the
1520 1520 # names in the database, but that eventually needs to be converted
1521 1521 # into a valid system path
1522 1522 p += self.repo_name.split(self.NAME_SEP)
1523 1523 return os.path.join(*map(safe_unicode, p))
1524 1524
1525 1525 @property
1526 1526 def cache_keys(self):
1527 1527 """
1528 1528 Returns associated cache keys for that repo
1529 1529 """
1530 1530 return CacheKey.query()\
1531 1531 .filter(CacheKey.cache_args == self.repo_name)\
1532 1532 .order_by(CacheKey.cache_key)\
1533 1533 .all()
1534 1534
1535 1535 def get_new_name(self, repo_name):
1536 1536 """
1537 1537 returns new full repository name based on assigned group and new new
1538 1538
1539 1539 :param group_name:
1540 1540 """
1541 1541 path_prefix = self.group.full_path_splitted if self.group else []
1542 1542 return self.NAME_SEP.join(path_prefix + [repo_name])
1543 1543
1544 1544 @property
1545 1545 def _config(self):
1546 1546 """
1547 1547 Returns db based config object.
1548 1548 """
1549 1549 from rhodecode.lib.utils import make_db_config
1550 1550 return make_db_config(clear_session=False, repo=self)
1551 1551
1552 1552 def permissions(self, with_admins=True, with_owner=True):
1553 1553 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1554 1554 q = q.options(joinedload(UserRepoToPerm.repository),
1555 1555 joinedload(UserRepoToPerm.user),
1556 1556 joinedload(UserRepoToPerm.permission),)
1557 1557
1558 1558 # get owners and admins and permissions. We do a trick of re-writing
1559 1559 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1560 1560 # has a global reference and changing one object propagates to all
1561 1561 # others. This means if admin is also an owner admin_row that change
1562 1562 # would propagate to both objects
1563 1563 perm_rows = []
1564 1564 for _usr in q.all():
1565 1565 usr = AttributeDict(_usr.user.get_dict())
1566 1566 usr.permission = _usr.permission.permission_name
1567 1567 perm_rows.append(usr)
1568 1568
1569 1569 # filter the perm rows by 'default' first and then sort them by
1570 1570 # admin,write,read,none permissions sorted again alphabetically in
1571 1571 # each group
1572 1572 perm_rows = sorted(perm_rows, key=display_sort)
1573 1573
1574 1574 _admin_perm = 'repository.admin'
1575 1575 owner_row = []
1576 1576 if with_owner:
1577 1577 usr = AttributeDict(self.user.get_dict())
1578 1578 usr.owner_row = True
1579 1579 usr.permission = _admin_perm
1580 1580 owner_row.append(usr)
1581 1581
1582 1582 super_admin_rows = []
1583 1583 if with_admins:
1584 1584 for usr in User.get_all_super_admins():
1585 1585 # if this admin is also owner, don't double the record
1586 1586 if usr.user_id == owner_row[0].user_id:
1587 1587 owner_row[0].admin_row = True
1588 1588 else:
1589 1589 usr = AttributeDict(usr.get_dict())
1590 1590 usr.admin_row = True
1591 1591 usr.permission = _admin_perm
1592 1592 super_admin_rows.append(usr)
1593 1593
1594 1594 return super_admin_rows + owner_row + perm_rows
1595 1595
1596 1596 def permission_user_groups(self):
1597 1597 q = UserGroupRepoToPerm.query().filter(
1598 1598 UserGroupRepoToPerm.repository == self)
1599 1599 q = q.options(joinedload(UserGroupRepoToPerm.repository),
1600 1600 joinedload(UserGroupRepoToPerm.users_group),
1601 1601 joinedload(UserGroupRepoToPerm.permission),)
1602 1602
1603 1603 perm_rows = []
1604 1604 for _user_group in q.all():
1605 1605 usr = AttributeDict(_user_group.users_group.get_dict())
1606 1606 usr.permission = _user_group.permission.permission_name
1607 1607 perm_rows.append(usr)
1608 1608
1609 1609 return perm_rows
1610 1610
1611 1611 def get_api_data(self, include_secrets=False):
1612 1612 """
1613 1613 Common function for generating repo api data
1614 1614
1615 1615 :param include_secrets: See :meth:`User.get_api_data`.
1616 1616
1617 1617 """
1618 1618 # TODO: mikhail: Here there is an anti-pattern, we probably need to
1619 1619 # move this methods on models level.
1620 1620 from rhodecode.model.settings import SettingsModel
1621 1621
1622 1622 repo = self
1623 1623 _user_id, _time, _reason = self.locked
1624 1624
1625 1625 data = {
1626 1626 'repo_id': repo.repo_id,
1627 1627 'repo_name': repo.repo_name,
1628 1628 'repo_type': repo.repo_type,
1629 1629 'clone_uri': repo.clone_uri or '',
1630 1630 'private': repo.private,
1631 1631 'created_on': repo.created_on,
1632 1632 'description': repo.description,
1633 1633 'landing_rev': repo.landing_rev,
1634 1634 'owner': repo.user.username,
1635 1635 'fork_of': repo.fork.repo_name if repo.fork else None,
1636 1636 'enable_statistics': repo.enable_statistics,
1637 1637 'enable_locking': repo.enable_locking,
1638 1638 'enable_downloads': repo.enable_downloads,
1639 1639 'last_changeset': repo.changeset_cache,
1640 1640 'locked_by': User.get(_user_id).get_api_data(
1641 1641 include_secrets=include_secrets) if _user_id else None,
1642 1642 'locked_date': time_to_datetime(_time) if _time else None,
1643 1643 'lock_reason': _reason if _reason else None,
1644 1644 }
1645 1645
1646 1646 # TODO: mikhail: should be per-repo settings here
1647 1647 rc_config = SettingsModel().get_all_settings()
1648 1648 repository_fields = str2bool(
1649 1649 rc_config.get('rhodecode_repository_fields'))
1650 1650 if repository_fields:
1651 1651 for f in self.extra_fields:
1652 1652 data[f.field_key_prefixed] = f.field_value
1653 1653
1654 1654 return data
1655 1655
1656 1656 @classmethod
1657 1657 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
1658 1658 if not lock_time:
1659 1659 lock_time = time.time()
1660 1660 if not lock_reason:
1661 1661 lock_reason = cls.LOCK_AUTOMATIC
1662 1662 repo.locked = [user_id, lock_time, lock_reason]
1663 1663 Session().add(repo)
1664 1664 Session().commit()
1665 1665
1666 1666 @classmethod
1667 1667 def unlock(cls, repo):
1668 1668 repo.locked = None
1669 1669 Session().add(repo)
1670 1670 Session().commit()
1671 1671
1672 1672 @classmethod
1673 1673 def getlock(cls, repo):
1674 1674 return repo.locked
1675 1675
1676 1676 def is_user_lock(self, user_id):
1677 1677 if self.lock[0]:
1678 1678 lock_user_id = safe_int(self.lock[0])
1679 1679 user_id = safe_int(user_id)
1680 1680 # both are ints, and they are equal
1681 1681 return all([lock_user_id, user_id]) and lock_user_id == user_id
1682 1682
1683 1683 return False
1684 1684
1685 1685 def get_locking_state(self, action, user_id, only_when_enabled=True):
1686 1686 """
1687 1687 Checks locking on this repository, if locking is enabled and lock is
1688 1688 present returns a tuple of make_lock, locked, locked_by.
1689 1689 make_lock can have 3 states None (do nothing) True, make lock
1690 1690 False release lock, This value is later propagated to hooks, which
1691 1691 do the locking. Think about this as signals passed to hooks what to do.
1692 1692
1693 1693 """
1694 1694 # TODO: johbo: This is part of the business logic and should be moved
1695 1695 # into the RepositoryModel.
1696 1696
1697 1697 if action not in ('push', 'pull'):
1698 1698 raise ValueError("Invalid action value: %s" % repr(action))
1699 1699
1700 1700 # defines if locked error should be thrown to user
1701 1701 currently_locked = False
1702 1702 # defines if new lock should be made, tri-state
1703 1703 make_lock = None
1704 1704 repo = self
1705 1705 user = User.get(user_id)
1706 1706
1707 1707 lock_info = repo.locked
1708 1708
1709 1709 if repo and (repo.enable_locking or not only_when_enabled):
1710 1710 if action == 'push':
1711 1711 # check if it's already locked !, if it is compare users
1712 1712 locked_by_user_id = lock_info[0]
1713 1713 if user.user_id == locked_by_user_id:
1714 1714 log.debug(
1715 1715 'Got `push` action from user %s, now unlocking', user)
1716 1716 # unlock if we have push from user who locked
1717 1717 make_lock = False
1718 1718 else:
1719 1719 # we're not the same user who locked, ban with
1720 1720 # code defined in settings (default is 423 HTTP Locked) !
1721 1721 log.debug('Repo %s is currently locked by %s', repo, user)
1722 1722 currently_locked = True
1723 1723 elif action == 'pull':
1724 1724 # [0] user [1] date
1725 1725 if lock_info[0] and lock_info[1]:
1726 1726 log.debug('Repo %s is currently locked by %s', repo, user)
1727 1727 currently_locked = True
1728 1728 else:
1729 1729 log.debug('Setting lock on repo %s by %s', repo, user)
1730 1730 make_lock = True
1731 1731
1732 1732 else:
1733 1733 log.debug('Repository %s do not have locking enabled', repo)
1734 1734
1735 1735 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
1736 1736 make_lock, currently_locked, lock_info)
1737 1737
1738 1738 from rhodecode.lib.auth import HasRepoPermissionAny
1739 1739 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
1740 1740 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
1741 1741 # if we don't have at least write permission we cannot make a lock
1742 1742 log.debug('lock state reset back to FALSE due to lack '
1743 1743 'of at least read permission')
1744 1744 make_lock = False
1745 1745
1746 1746 return make_lock, currently_locked, lock_info
1747 1747
1748 1748 @property
1749 1749 def last_db_change(self):
1750 1750 return self.updated_on
1751 1751
1752 1752 @property
1753 1753 def clone_uri_hidden(self):
1754 1754 clone_uri = self.clone_uri
1755 1755 if clone_uri:
1756 1756 import urlobject
1757 1757 url_obj = urlobject.URLObject(self.clone_uri)
1758 1758 if url_obj.password:
1759 1759 clone_uri = url_obj.with_password('*****')
1760 1760 return clone_uri
1761 1761
1762 1762 def clone_url(self, **override):
1763 1763 qualified_home_url = url('home', qualified=True)
1764 1764
1765 1765 uri_tmpl = None
1766 1766 if 'with_id' in override:
1767 1767 uri_tmpl = self.DEFAULT_CLONE_URI_ID
1768 1768 del override['with_id']
1769 1769
1770 1770 if 'uri_tmpl' in override:
1771 1771 uri_tmpl = override['uri_tmpl']
1772 1772 del override['uri_tmpl']
1773 1773
1774 1774 # we didn't override our tmpl from **overrides
1775 1775 if not uri_tmpl:
1776 1776 uri_tmpl = self.DEFAULT_CLONE_URI
1777 1777 try:
1778 1778 from pylons import tmpl_context as c
1779 1779 uri_tmpl = c.clone_uri_tmpl
1780 1780 except Exception:
1781 1781 # in any case if we call this outside of request context,
1782 1782 # ie, not having tmpl_context set up
1783 1783 pass
1784 1784
1785 1785 return get_clone_url(uri_tmpl=uri_tmpl,
1786 1786 qualifed_home_url=qualified_home_url,
1787 1787 repo_name=self.repo_name,
1788 1788 repo_id=self.repo_id, **override)
1789 1789
1790 1790 def set_state(self, state):
1791 1791 self.repo_state = state
1792 1792 Session().add(self)
1793 1793 #==========================================================================
1794 1794 # SCM PROPERTIES
1795 1795 #==========================================================================
1796 1796
1797 1797 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
1798 1798 return get_commit_safe(
1799 1799 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
1800 1800
1801 1801 def get_changeset(self, rev=None, pre_load=None):
1802 1802 warnings.warn("Use get_commit", DeprecationWarning)
1803 1803 commit_id = None
1804 1804 commit_idx = None
1805 1805 if isinstance(rev, basestring):
1806 1806 commit_id = rev
1807 1807 else:
1808 1808 commit_idx = rev
1809 1809 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
1810 1810 pre_load=pre_load)
1811 1811
1812 1812 def get_landing_commit(self):
1813 1813 """
1814 1814 Returns landing commit, or if that doesn't exist returns the tip
1815 1815 """
1816 1816 _rev_type, _rev = self.landing_rev
1817 1817 commit = self.get_commit(_rev)
1818 1818 if isinstance(commit, EmptyCommit):
1819 1819 return self.get_commit()
1820 1820 return commit
1821 1821
1822 1822 def update_commit_cache(self, cs_cache=None, config=None):
1823 1823 """
1824 1824 Update cache of last changeset for repository, keys should be::
1825 1825
1826 1826 short_id
1827 1827 raw_id
1828 1828 revision
1829 1829 parents
1830 1830 message
1831 1831 date
1832 1832 author
1833 1833
1834 1834 :param cs_cache:
1835 1835 """
1836 1836 from rhodecode.lib.vcs.backends.base import BaseChangeset
1837 1837 if cs_cache is None:
1838 1838 # use no-cache version here
1839 1839 scm_repo = self.scm_instance(cache=False, config=config)
1840 1840 if scm_repo:
1841 1841 cs_cache = scm_repo.get_commit(
1842 1842 pre_load=["author", "date", "message", "parents"])
1843 1843 else:
1844 1844 cs_cache = EmptyCommit()
1845 1845
1846 1846 if isinstance(cs_cache, BaseChangeset):
1847 1847 cs_cache = cs_cache.__json__()
1848 1848
1849 1849 def is_outdated(new_cs_cache):
1850 1850 if new_cs_cache['raw_id'] != self.changeset_cache['raw_id']:
1851 1851 return True
1852 1852 return False
1853 1853
1854 1854 # check if we have maybe already latest cached revision
1855 1855 if is_outdated(cs_cache) or not self.changeset_cache:
1856 1856 _default = datetime.datetime.fromtimestamp(0)
1857 1857 last_change = cs_cache.get('date') or _default
1858 1858 log.debug('updated repo %s with new cs cache %s',
1859 1859 self.repo_name, cs_cache)
1860 1860 self.updated_on = last_change
1861 1861 self.changeset_cache = cs_cache
1862 1862 Session().add(self)
1863 1863 Session().commit()
1864 1864 else:
1865 1865 log.debug('Skipping update_commit_cache for repo:`%s` '
1866 1866 'commit already with latest changes', self.repo_name)
1867 1867
1868 1868 @property
1869 1869 def tip(self):
1870 1870 return self.get_commit('tip')
1871 1871
1872 1872 @property
1873 1873 def author(self):
1874 1874 return self.tip.author
1875 1875
1876 1876 @property
1877 1877 def last_change(self):
1878 1878 return self.scm_instance().last_change
1879 1879
1880 1880 def get_comments(self, revisions=None):
1881 1881 """
1882 1882 Returns comments for this repository grouped by revisions
1883 1883
1884 1884 :param revisions: filter query by revisions only
1885 1885 """
1886 1886 cmts = ChangesetComment.query()\
1887 1887 .filter(ChangesetComment.repo == self)
1888 1888 if revisions:
1889 1889 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
1890 1890 grouped = collections.defaultdict(list)
1891 1891 for cmt in cmts.all():
1892 1892 grouped[cmt.revision].append(cmt)
1893 1893 return grouped
1894 1894
1895 1895 def statuses(self, revisions=None):
1896 1896 """
1897 1897 Returns statuses for this repository
1898 1898
1899 1899 :param revisions: list of revisions to get statuses for
1900 1900 """
1901 1901 statuses = ChangesetStatus.query()\
1902 1902 .filter(ChangesetStatus.repo == self)\
1903 1903 .filter(ChangesetStatus.version == 0)
1904 1904
1905 1905 if revisions:
1906 1906 # Try doing the filtering in chunks to avoid hitting limits
1907 1907 size = 500
1908 1908 status_results = []
1909 1909 for chunk in xrange(0, len(revisions), size):
1910 1910 status_results += statuses.filter(
1911 1911 ChangesetStatus.revision.in_(
1912 1912 revisions[chunk: chunk+size])
1913 1913 ).all()
1914 1914 else:
1915 1915 status_results = statuses.all()
1916 1916
1917 1917 grouped = {}
1918 1918
1919 1919 # maybe we have open new pullrequest without a status?
1920 1920 stat = ChangesetStatus.STATUS_UNDER_REVIEW
1921 1921 status_lbl = ChangesetStatus.get_status_lbl(stat)
1922 1922 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
1923 1923 for rev in pr.revisions:
1924 1924 pr_id = pr.pull_request_id
1925 1925 pr_repo = pr.target_repo.repo_name
1926 1926 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
1927 1927
1928 1928 for stat in status_results:
1929 1929 pr_id = pr_repo = None
1930 1930 if stat.pull_request:
1931 1931 pr_id = stat.pull_request.pull_request_id
1932 1932 pr_repo = stat.pull_request.target_repo.repo_name
1933 1933 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
1934 1934 pr_id, pr_repo]
1935 1935 return grouped
1936 1936
1937 1937 # ==========================================================================
1938 1938 # SCM CACHE INSTANCE
1939 1939 # ==========================================================================
1940 1940
1941 1941 def scm_instance(self, **kwargs):
1942 1942 import rhodecode
1943 1943
1944 1944 # Passing a config will not hit the cache currently only used
1945 1945 # for repo2dbmapper
1946 1946 config = kwargs.pop('config', None)
1947 1947 cache = kwargs.pop('cache', None)
1948 1948 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
1949 1949 # if cache is NOT defined use default global, else we have a full
1950 1950 # control over cache behaviour
1951 1951 if cache is None and full_cache and not config:
1952 1952 return self._get_instance_cached()
1953 1953 return self._get_instance(cache=bool(cache), config=config)
1954 1954
1955 1955 def _get_instance_cached(self):
1956 1956 @cache_region('long_term')
1957 1957 def _get_repo(cache_key):
1958 1958 return self._get_instance()
1959 1959
1960 1960 invalidator_context = CacheKey.repo_context_cache(
1961 1961 _get_repo, self.repo_name, None)
1962 1962
1963 1963 with invalidator_context as context:
1964 1964 context.invalidate()
1965 1965 repo = context.compute()
1966 1966
1967 1967 return repo
1968 1968
1969 1969 def _get_instance(self, cache=True, config=None):
1970 1970 repo_full_path = self.repo_full_path
1971 1971 try:
1972 1972 vcs_alias = get_scm(repo_full_path)[0]
1973 1973 log.debug(
1974 1974 'Creating instance of %s repository from %s',
1975 1975 vcs_alias, repo_full_path)
1976 1976 backend = get_backend(vcs_alias)
1977 1977 except VCSError:
1978 1978 log.exception(
1979 1979 'Perhaps this repository is in db and not in '
1980 1980 'filesystem run rescan repositories with '
1981 1981 '"destroy old data" option from admin panel')
1982 1982 return
1983 1983
1984 1984 config = config or self._config
1985 1985 custom_wire = {
1986 1986 'cache': cache # controls the vcs.remote cache
1987 1987 }
1988 1988 repo = backend(
1989 1989 safe_str(repo_full_path), config=config, create=False,
1990 1990 with_wire=custom_wire)
1991 1991
1992 1992 return repo
1993 1993
1994 1994 def __json__(self):
1995 1995 return {'landing_rev': self.landing_rev}
1996 1996
1997 1997 def get_dict(self):
1998 1998
1999 1999 # Since we transformed `repo_name` to a hybrid property, we need to
2000 2000 # keep compatibility with the code which uses `repo_name` field.
2001 2001
2002 2002 result = super(Repository, self).get_dict()
2003 2003 result['repo_name'] = result.pop('_repo_name', None)
2004 2004 return result
2005 2005
2006 2006
2007 2007 class RepoGroup(Base, BaseModel):
2008 2008 __tablename__ = 'groups'
2009 2009 __table_args__ = (
2010 2010 UniqueConstraint('group_name', 'group_parent_id'),
2011 2011 CheckConstraint('group_id != group_parent_id'),
2012 2012 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2013 2013 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2014 2014 )
2015 2015 __mapper_args__ = {'order_by': 'group_name'}
2016 2016
2017 2017 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2018 2018
2019 2019 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2020 2020 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2021 2021 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2022 2022 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2023 2023 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2024 2024 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2025 2025 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2026 2026
2027 2027 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2028 2028 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2029 2029 parent_group = relationship('RepoGroup', remote_side=group_id)
2030 2030 user = relationship('User')
2031 2031
2032 2032 def __init__(self, group_name='', parent_group=None):
2033 2033 self.group_name = group_name
2034 2034 self.parent_group = parent_group
2035 2035
2036 2036 def __unicode__(self):
2037 2037 return u"<%s('id:%s:%s')>" % (self.__class__.__name__, self.group_id,
2038 2038 self.group_name)
2039 2039
2040 2040 @classmethod
2041 2041 def _generate_choice(cls, repo_group):
2042 2042 from webhelpers.html import literal as _literal
2043 2043 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2044 2044 return repo_group.group_id, _name(repo_group.full_path_splitted)
2045 2045
2046 2046 @classmethod
2047 2047 def groups_choices(cls, groups=None, show_empty_group=True):
2048 2048 if not groups:
2049 2049 groups = cls.query().all()
2050 2050
2051 2051 repo_groups = []
2052 2052 if show_empty_group:
2053 2053 repo_groups = [('-1', u'-- %s --' % _('No parent'))]
2054 2054
2055 2055 repo_groups.extend([cls._generate_choice(x) for x in groups])
2056 2056
2057 2057 repo_groups = sorted(
2058 2058 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2059 2059 return repo_groups
2060 2060
2061 2061 @classmethod
2062 2062 def url_sep(cls):
2063 2063 return URL_SEP
2064 2064
2065 2065 @classmethod
2066 2066 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2067 2067 if case_insensitive:
2068 2068 gr = cls.query().filter(func.lower(cls.group_name)
2069 2069 == func.lower(group_name))
2070 2070 else:
2071 2071 gr = cls.query().filter(cls.group_name == group_name)
2072 2072 if cache:
2073 2073 gr = gr.options(FromCache(
2074 2074 "sql_cache_short",
2075 2075 "get_group_%s" % _hash_key(group_name)))
2076 2076 return gr.scalar()
2077 2077
2078 2078 @classmethod
2079 2079 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2080 2080 case_insensitive=True):
2081 2081 q = RepoGroup.query()
2082 2082
2083 2083 if not isinstance(user_id, Optional):
2084 2084 q = q.filter(RepoGroup.user_id == user_id)
2085 2085
2086 2086 if not isinstance(group_id, Optional):
2087 2087 q = q.filter(RepoGroup.group_parent_id == group_id)
2088 2088
2089 2089 if case_insensitive:
2090 2090 q = q.order_by(func.lower(RepoGroup.group_name))
2091 2091 else:
2092 2092 q = q.order_by(RepoGroup.group_name)
2093 2093 return q.all()
2094 2094
2095 2095 @property
2096 2096 def parents(self):
2097 2097 parents_recursion_limit = 10
2098 2098 groups = []
2099 2099 if self.parent_group is None:
2100 2100 return groups
2101 2101 cur_gr = self.parent_group
2102 2102 groups.insert(0, cur_gr)
2103 2103 cnt = 0
2104 2104 while 1:
2105 2105 cnt += 1
2106 2106 gr = getattr(cur_gr, 'parent_group', None)
2107 2107 cur_gr = cur_gr.parent_group
2108 2108 if gr is None:
2109 2109 break
2110 2110 if cnt == parents_recursion_limit:
2111 2111 # this will prevent accidental infinit loops
2112 2112 log.error(('more than %s parents found for group %s, stopping '
2113 2113 'recursive parent fetching' % (parents_recursion_limit, self)))
2114 2114 break
2115 2115
2116 2116 groups.insert(0, gr)
2117 2117 return groups
2118 2118
2119 2119 @property
2120 2120 def children(self):
2121 2121 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2122 2122
2123 2123 @property
2124 2124 def name(self):
2125 2125 return self.group_name.split(RepoGroup.url_sep())[-1]
2126 2126
2127 2127 @property
2128 2128 def full_path(self):
2129 2129 return self.group_name
2130 2130
2131 2131 @property
2132 2132 def full_path_splitted(self):
2133 2133 return self.group_name.split(RepoGroup.url_sep())
2134 2134
2135 2135 @property
2136 2136 def repositories(self):
2137 2137 return Repository.query()\
2138 2138 .filter(Repository.group == self)\
2139 2139 .order_by(Repository.repo_name)
2140 2140
2141 2141 @property
2142 2142 def repositories_recursive_count(self):
2143 2143 cnt = self.repositories.count()
2144 2144
2145 2145 def children_count(group):
2146 2146 cnt = 0
2147 2147 for child in group.children:
2148 2148 cnt += child.repositories.count()
2149 2149 cnt += children_count(child)
2150 2150 return cnt
2151 2151
2152 2152 return cnt + children_count(self)
2153 2153
2154 2154 def _recursive_objects(self, include_repos=True):
2155 2155 all_ = []
2156 2156
2157 2157 def _get_members(root_gr):
2158 2158 if include_repos:
2159 2159 for r in root_gr.repositories:
2160 2160 all_.append(r)
2161 2161 childs = root_gr.children.all()
2162 2162 if childs:
2163 2163 for gr in childs:
2164 2164 all_.append(gr)
2165 2165 _get_members(gr)
2166 2166
2167 2167 _get_members(self)
2168 2168 return [self] + all_
2169 2169
2170 2170 def recursive_groups_and_repos(self):
2171 2171 """
2172 2172 Recursive return all groups, with repositories in those groups
2173 2173 """
2174 2174 return self._recursive_objects()
2175 2175
2176 2176 def recursive_groups(self):
2177 2177 """
2178 2178 Returns all children groups for this group including children of children
2179 2179 """
2180 2180 return self._recursive_objects(include_repos=False)
2181 2181
2182 2182 def get_new_name(self, group_name):
2183 2183 """
2184 2184 returns new full group name based on parent and new name
2185 2185
2186 2186 :param group_name:
2187 2187 """
2188 2188 path_prefix = (self.parent_group.full_path_splitted if
2189 2189 self.parent_group else [])
2190 2190 return RepoGroup.url_sep().join(path_prefix + [group_name])
2191 2191
2192 2192 def permissions(self, with_admins=True, with_owner=True):
2193 2193 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2194 2194 q = q.options(joinedload(UserRepoGroupToPerm.group),
2195 2195 joinedload(UserRepoGroupToPerm.user),
2196 2196 joinedload(UserRepoGroupToPerm.permission),)
2197 2197
2198 2198 # get owners and admins and permissions. We do a trick of re-writing
2199 2199 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2200 2200 # has a global reference and changing one object propagates to all
2201 2201 # others. This means if admin is also an owner admin_row that change
2202 2202 # would propagate to both objects
2203 2203 perm_rows = []
2204 2204 for _usr in q.all():
2205 2205 usr = AttributeDict(_usr.user.get_dict())
2206 2206 usr.permission = _usr.permission.permission_name
2207 2207 perm_rows.append(usr)
2208 2208
2209 2209 # filter the perm rows by 'default' first and then sort them by
2210 2210 # admin,write,read,none permissions sorted again alphabetically in
2211 2211 # each group
2212 2212 perm_rows = sorted(perm_rows, key=display_sort)
2213 2213
2214 2214 _admin_perm = 'group.admin'
2215 2215 owner_row = []
2216 2216 if with_owner:
2217 2217 usr = AttributeDict(self.user.get_dict())
2218 2218 usr.owner_row = True
2219 2219 usr.permission = _admin_perm
2220 2220 owner_row.append(usr)
2221 2221
2222 2222 super_admin_rows = []
2223 2223 if with_admins:
2224 2224 for usr in User.get_all_super_admins():
2225 2225 # if this admin is also owner, don't double the record
2226 2226 if usr.user_id == owner_row[0].user_id:
2227 2227 owner_row[0].admin_row = True
2228 2228 else:
2229 2229 usr = AttributeDict(usr.get_dict())
2230 2230 usr.admin_row = True
2231 2231 usr.permission = _admin_perm
2232 2232 super_admin_rows.append(usr)
2233 2233
2234 2234 return super_admin_rows + owner_row + perm_rows
2235 2235
2236 2236 def permission_user_groups(self):
2237 2237 q = UserGroupRepoGroupToPerm.query().filter(UserGroupRepoGroupToPerm.group == self)
2238 2238 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2239 2239 joinedload(UserGroupRepoGroupToPerm.users_group),
2240 2240 joinedload(UserGroupRepoGroupToPerm.permission),)
2241 2241
2242 2242 perm_rows = []
2243 2243 for _user_group in q.all():
2244 2244 usr = AttributeDict(_user_group.users_group.get_dict())
2245 2245 usr.permission = _user_group.permission.permission_name
2246 2246 perm_rows.append(usr)
2247 2247
2248 2248 return perm_rows
2249 2249
2250 2250 def get_api_data(self):
2251 2251 """
2252 2252 Common function for generating api data
2253 2253
2254 2254 """
2255 2255 group = self
2256 2256 data = {
2257 2257 'group_id': group.group_id,
2258 2258 'group_name': group.group_name,
2259 2259 'group_description': group.group_description,
2260 2260 'parent_group': group.parent_group.group_name if group.parent_group else None,
2261 2261 'repositories': [x.repo_name for x in group.repositories],
2262 2262 'owner': group.user.username,
2263 2263 }
2264 2264 return data
2265 2265
2266 2266
2267 2267 class Permission(Base, BaseModel):
2268 2268 __tablename__ = 'permissions'
2269 2269 __table_args__ = (
2270 2270 Index('p_perm_name_idx', 'permission_name'),
2271 2271 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2272 2272 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2273 2273 )
2274 2274 PERMS = [
2275 2275 ('hg.admin', _('RhodeCode Super Administrator')),
2276 2276
2277 2277 ('repository.none', _('Repository no access')),
2278 2278 ('repository.read', _('Repository read access')),
2279 2279 ('repository.write', _('Repository write access')),
2280 2280 ('repository.admin', _('Repository admin access')),
2281 2281
2282 2282 ('group.none', _('Repository group no access')),
2283 2283 ('group.read', _('Repository group read access')),
2284 2284 ('group.write', _('Repository group write access')),
2285 2285 ('group.admin', _('Repository group admin access')),
2286 2286
2287 2287 ('usergroup.none', _('User group no access')),
2288 2288 ('usergroup.read', _('User group read access')),
2289 2289 ('usergroup.write', _('User group write access')),
2290 2290 ('usergroup.admin', _('User group admin access')),
2291 2291
2292 2292 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2293 2293 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2294 2294
2295 2295 ('hg.usergroup.create.false', _('User Group creation disabled')),
2296 2296 ('hg.usergroup.create.true', _('User Group creation enabled')),
2297 2297
2298 2298 ('hg.create.none', _('Repository creation disabled')),
2299 2299 ('hg.create.repository', _('Repository creation enabled')),
2300 2300 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2301 2301 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2302 2302
2303 2303 ('hg.fork.none', _('Repository forking disabled')),
2304 2304 ('hg.fork.repository', _('Repository forking enabled')),
2305 2305
2306 2306 ('hg.register.none', _('Registration disabled')),
2307 2307 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2308 2308 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2309 2309
2310 2310 ('hg.extern_activate.manual', _('Manual activation of external account')),
2311 2311 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2312 2312
2313 2313 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2314 2314 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2315 2315 ]
2316 2316
2317 2317 # definition of system default permissions for DEFAULT user
2318 2318 DEFAULT_USER_PERMISSIONS = [
2319 2319 'repository.read',
2320 2320 'group.read',
2321 2321 'usergroup.read',
2322 2322 'hg.create.repository',
2323 2323 'hg.repogroup.create.false',
2324 2324 'hg.usergroup.create.false',
2325 2325 'hg.create.write_on_repogroup.true',
2326 2326 'hg.fork.repository',
2327 2327 'hg.register.manual_activate',
2328 2328 'hg.extern_activate.auto',
2329 2329 'hg.inherit_default_perms.true',
2330 2330 ]
2331 2331
2332 2332 # defines which permissions are more important higher the more important
2333 2333 # Weight defines which permissions are more important.
2334 2334 # The higher number the more important.
2335 2335 PERM_WEIGHTS = {
2336 2336 'repository.none': 0,
2337 2337 'repository.read': 1,
2338 2338 'repository.write': 3,
2339 2339 'repository.admin': 4,
2340 2340
2341 2341 'group.none': 0,
2342 2342 'group.read': 1,
2343 2343 'group.write': 3,
2344 2344 'group.admin': 4,
2345 2345
2346 2346 'usergroup.none': 0,
2347 2347 'usergroup.read': 1,
2348 2348 'usergroup.write': 3,
2349 2349 'usergroup.admin': 4,
2350 2350
2351 2351 'hg.repogroup.create.false': 0,
2352 2352 'hg.repogroup.create.true': 1,
2353 2353
2354 2354 'hg.usergroup.create.false': 0,
2355 2355 'hg.usergroup.create.true': 1,
2356 2356
2357 2357 'hg.fork.none': 0,
2358 2358 'hg.fork.repository': 1,
2359 2359 'hg.create.none': 0,
2360 2360 'hg.create.repository': 1
2361 2361 }
2362 2362
2363 2363 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2364 2364 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2365 2365 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2366 2366
2367 2367 def __unicode__(self):
2368 2368 return u"<%s('%s:%s')>" % (
2369 2369 self.__class__.__name__, self.permission_id, self.permission_name
2370 2370 )
2371 2371
2372 2372 @classmethod
2373 2373 def get_by_key(cls, key):
2374 2374 return cls.query().filter(cls.permission_name == key).scalar()
2375 2375
2376 2376 @classmethod
2377 2377 def get_default_repo_perms(cls, user_id, repo_id=None):
2378 2378 q = Session().query(UserRepoToPerm, Repository, Permission)\
2379 2379 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2380 2380 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2381 2381 .filter(UserRepoToPerm.user_id == user_id)
2382 2382 if repo_id:
2383 2383 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2384 2384 return q.all()
2385 2385
2386 2386 @classmethod
2387 2387 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2388 2388 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2389 2389 .join(
2390 2390 Permission,
2391 2391 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2392 2392 .join(
2393 2393 Repository,
2394 2394 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2395 2395 .join(
2396 2396 UserGroup,
2397 2397 UserGroupRepoToPerm.users_group_id ==
2398 2398 UserGroup.users_group_id)\
2399 2399 .join(
2400 2400 UserGroupMember,
2401 2401 UserGroupRepoToPerm.users_group_id ==
2402 2402 UserGroupMember.users_group_id)\
2403 2403 .filter(
2404 2404 UserGroupMember.user_id == user_id,
2405 2405 UserGroup.users_group_active == true())
2406 2406 if repo_id:
2407 2407 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2408 2408 return q.all()
2409 2409
2410 2410 @classmethod
2411 2411 def get_default_group_perms(cls, user_id, repo_group_id=None):
2412 2412 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2413 2413 .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\
2414 2414 .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
2415 2415 .filter(UserRepoGroupToPerm.user_id == user_id)
2416 2416 if repo_group_id:
2417 2417 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2418 2418 return q.all()
2419 2419
2420 2420 @classmethod
2421 2421 def get_default_group_perms_from_user_group(
2422 2422 cls, user_id, repo_group_id=None):
2423 2423 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2424 2424 .join(
2425 2425 Permission,
2426 2426 UserGroupRepoGroupToPerm.permission_id ==
2427 2427 Permission.permission_id)\
2428 2428 .join(
2429 2429 RepoGroup,
2430 2430 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2431 2431 .join(
2432 2432 UserGroup,
2433 2433 UserGroupRepoGroupToPerm.users_group_id ==
2434 2434 UserGroup.users_group_id)\
2435 2435 .join(
2436 2436 UserGroupMember,
2437 2437 UserGroupRepoGroupToPerm.users_group_id ==
2438 2438 UserGroupMember.users_group_id)\
2439 2439 .filter(
2440 2440 UserGroupMember.user_id == user_id,
2441 2441 UserGroup.users_group_active == true())
2442 2442 if repo_group_id:
2443 2443 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
2444 2444 return q.all()
2445 2445
2446 2446 @classmethod
2447 2447 def get_default_user_group_perms(cls, user_id, user_group_id=None):
2448 2448 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
2449 2449 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
2450 2450 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
2451 2451 .filter(UserUserGroupToPerm.user_id == user_id)
2452 2452 if user_group_id:
2453 2453 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
2454 2454 return q.all()
2455 2455
2456 2456 @classmethod
2457 2457 def get_default_user_group_perms_from_user_group(
2458 2458 cls, user_id, user_group_id=None):
2459 2459 TargetUserGroup = aliased(UserGroup, name='target_user_group')
2460 2460 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
2461 2461 .join(
2462 2462 Permission,
2463 2463 UserGroupUserGroupToPerm.permission_id ==
2464 2464 Permission.permission_id)\
2465 2465 .join(
2466 2466 TargetUserGroup,
2467 2467 UserGroupUserGroupToPerm.target_user_group_id ==
2468 2468 TargetUserGroup.users_group_id)\
2469 2469 .join(
2470 2470 UserGroup,
2471 2471 UserGroupUserGroupToPerm.user_group_id ==
2472 2472 UserGroup.users_group_id)\
2473 2473 .join(
2474 2474 UserGroupMember,
2475 2475 UserGroupUserGroupToPerm.user_group_id ==
2476 2476 UserGroupMember.users_group_id)\
2477 2477 .filter(
2478 2478 UserGroupMember.user_id == user_id,
2479 2479 UserGroup.users_group_active == true())
2480 2480 if user_group_id:
2481 2481 q = q.filter(
2482 2482 UserGroupUserGroupToPerm.user_group_id == user_group_id)
2483 2483
2484 2484 return q.all()
2485 2485
2486 2486
2487 2487 class UserRepoToPerm(Base, BaseModel):
2488 2488 __tablename__ = 'repo_to_perm'
2489 2489 __table_args__ = (
2490 2490 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
2491 2491 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2492 2492 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2493 2493 )
2494 2494 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2495 2495 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2496 2496 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2497 2497 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2498 2498
2499 2499 user = relationship('User')
2500 2500 repository = relationship('Repository')
2501 2501 permission = relationship('Permission')
2502 2502
2503 2503 @classmethod
2504 2504 def create(cls, user, repository, permission):
2505 2505 n = cls()
2506 2506 n.user = user
2507 2507 n.repository = repository
2508 2508 n.permission = permission
2509 2509 Session().add(n)
2510 2510 return n
2511 2511
2512 2512 def __unicode__(self):
2513 2513 return u'<%s => %s >' % (self.user, self.repository)
2514 2514
2515 2515
2516 2516 class UserUserGroupToPerm(Base, BaseModel):
2517 2517 __tablename__ = 'user_user_group_to_perm'
2518 2518 __table_args__ = (
2519 2519 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
2520 2520 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2521 2521 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2522 2522 )
2523 2523 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2524 2524 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2525 2525 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2526 2526 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2527 2527
2528 2528 user = relationship('User')
2529 2529 user_group = relationship('UserGroup')
2530 2530 permission = relationship('Permission')
2531 2531
2532 2532 @classmethod
2533 2533 def create(cls, user, user_group, permission):
2534 2534 n = cls()
2535 2535 n.user = user
2536 2536 n.user_group = user_group
2537 2537 n.permission = permission
2538 2538 Session().add(n)
2539 2539 return n
2540 2540
2541 2541 def __unicode__(self):
2542 2542 return u'<%s => %s >' % (self.user, self.user_group)
2543 2543
2544 2544
2545 2545 class UserToPerm(Base, BaseModel):
2546 2546 __tablename__ = 'user_to_perm'
2547 2547 __table_args__ = (
2548 2548 UniqueConstraint('user_id', 'permission_id'),
2549 2549 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2550 2550 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2551 2551 )
2552 2552 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2553 2553 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2554 2554 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2555 2555
2556 2556 user = relationship('User')
2557 2557 permission = relationship('Permission', lazy='joined')
2558 2558
2559 2559 def __unicode__(self):
2560 2560 return u'<%s => %s >' % (self.user, self.permission)
2561 2561
2562 2562
2563 2563 class UserGroupRepoToPerm(Base, BaseModel):
2564 2564 __tablename__ = 'users_group_repo_to_perm'
2565 2565 __table_args__ = (
2566 2566 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
2567 2567 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2568 2568 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2569 2569 )
2570 2570 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2571 2571 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2572 2572 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2573 2573 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2574 2574
2575 2575 users_group = relationship('UserGroup')
2576 2576 permission = relationship('Permission')
2577 2577 repository = relationship('Repository')
2578 2578
2579 2579 @classmethod
2580 2580 def create(cls, users_group, repository, permission):
2581 2581 n = cls()
2582 2582 n.users_group = users_group
2583 2583 n.repository = repository
2584 2584 n.permission = permission
2585 2585 Session().add(n)
2586 2586 return n
2587 2587
2588 2588 def __unicode__(self):
2589 2589 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
2590 2590
2591 2591
2592 2592 class UserGroupUserGroupToPerm(Base, BaseModel):
2593 2593 __tablename__ = 'user_group_user_group_to_perm'
2594 2594 __table_args__ = (
2595 2595 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
2596 2596 CheckConstraint('target_user_group_id != user_group_id'),
2597 2597 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2598 2598 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2599 2599 )
2600 2600 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)
2601 2601 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2602 2602 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2603 2603 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2604 2604
2605 2605 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
2606 2606 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
2607 2607 permission = relationship('Permission')
2608 2608
2609 2609 @classmethod
2610 2610 def create(cls, target_user_group, user_group, permission):
2611 2611 n = cls()
2612 2612 n.target_user_group = target_user_group
2613 2613 n.user_group = user_group
2614 2614 n.permission = permission
2615 2615 Session().add(n)
2616 2616 return n
2617 2617
2618 2618 def __unicode__(self):
2619 2619 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
2620 2620
2621 2621
2622 2622 class UserGroupToPerm(Base, BaseModel):
2623 2623 __tablename__ = 'users_group_to_perm'
2624 2624 __table_args__ = (
2625 2625 UniqueConstraint('users_group_id', 'permission_id',),
2626 2626 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2627 2627 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2628 2628 )
2629 2629 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2630 2630 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2631 2631 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2632 2632
2633 2633 users_group = relationship('UserGroup')
2634 2634 permission = relationship('Permission')
2635 2635
2636 2636
2637 2637 class UserRepoGroupToPerm(Base, BaseModel):
2638 2638 __tablename__ = 'user_repo_group_to_perm'
2639 2639 __table_args__ = (
2640 2640 UniqueConstraint('user_id', 'group_id', 'permission_id'),
2641 2641 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2642 2642 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2643 2643 )
2644 2644
2645 2645 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2646 2646 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2647 2647 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2648 2648 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2649 2649
2650 2650 user = relationship('User')
2651 2651 group = relationship('RepoGroup')
2652 2652 permission = relationship('Permission')
2653 2653
2654 2654 @classmethod
2655 2655 def create(cls, user, repository_group, permission):
2656 2656 n = cls()
2657 2657 n.user = user
2658 2658 n.group = repository_group
2659 2659 n.permission = permission
2660 2660 Session().add(n)
2661 2661 return n
2662 2662
2663 2663
2664 2664 class UserGroupRepoGroupToPerm(Base, BaseModel):
2665 2665 __tablename__ = 'users_group_repo_group_to_perm'
2666 2666 __table_args__ = (
2667 2667 UniqueConstraint('users_group_id', 'group_id'),
2668 2668 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2669 2669 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2670 2670 )
2671 2671
2672 2672 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)
2673 2673 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2674 2674 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2675 2675 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2676 2676
2677 2677 users_group = relationship('UserGroup')
2678 2678 permission = relationship('Permission')
2679 2679 group = relationship('RepoGroup')
2680 2680
2681 2681 @classmethod
2682 2682 def create(cls, user_group, repository_group, permission):
2683 2683 n = cls()
2684 2684 n.users_group = user_group
2685 2685 n.group = repository_group
2686 2686 n.permission = permission
2687 2687 Session().add(n)
2688 2688 return n
2689 2689
2690 2690 def __unicode__(self):
2691 2691 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
2692 2692
2693 2693
2694 2694 class Statistics(Base, BaseModel):
2695 2695 __tablename__ = 'statistics'
2696 2696 __table_args__ = (
2697 2697 UniqueConstraint('repository_id'),
2698 2698 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2699 2699 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2700 2700 )
2701 2701 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2702 2702 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
2703 2703 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
2704 2704 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
2705 2705 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
2706 2706 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
2707 2707
2708 2708 repository = relationship('Repository', single_parent=True)
2709 2709
2710 2710
2711 2711 class UserFollowing(Base, BaseModel):
2712 2712 __tablename__ = 'user_followings'
2713 2713 __table_args__ = (
2714 2714 UniqueConstraint('user_id', 'follows_repository_id'),
2715 2715 UniqueConstraint('user_id', 'follows_user_id'),
2716 2716 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2717 2717 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2718 2718 )
2719 2719
2720 2720 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2721 2721 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2722 2722 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
2723 2723 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
2724 2724 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2725 2725
2726 2726 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
2727 2727
2728 2728 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
2729 2729 follows_repository = relationship('Repository', order_by='Repository.repo_name')
2730 2730
2731 2731 @classmethod
2732 2732 def get_repo_followers(cls, repo_id):
2733 2733 return cls.query().filter(cls.follows_repo_id == repo_id)
2734 2734
2735 2735
2736 2736 class CacheKey(Base, BaseModel):
2737 2737 __tablename__ = 'cache_invalidation'
2738 2738 __table_args__ = (
2739 2739 UniqueConstraint('cache_key'),
2740 2740 Index('key_idx', 'cache_key'),
2741 2741 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2742 2742 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2743 2743 )
2744 2744 CACHE_TYPE_ATOM = 'ATOM'
2745 2745 CACHE_TYPE_RSS = 'RSS'
2746 2746 CACHE_TYPE_README = 'README'
2747 2747
2748 2748 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2749 2749 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
2750 2750 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
2751 2751 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
2752 2752
2753 2753 def __init__(self, cache_key, cache_args=''):
2754 2754 self.cache_key = cache_key
2755 2755 self.cache_args = cache_args
2756 2756 self.cache_active = False
2757 2757
2758 2758 def __unicode__(self):
2759 2759 return u"<%s('%s:%s[%s]')>" % (
2760 2760 self.__class__.__name__,
2761 2761 self.cache_id, self.cache_key, self.cache_active)
2762 2762
2763 2763 def _cache_key_partition(self):
2764 2764 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
2765 2765 return prefix, repo_name, suffix
2766 2766
2767 2767 def get_prefix(self):
2768 2768 """
2769 2769 Try to extract prefix from existing cache key. The key could consist
2770 2770 of prefix, repo_name, suffix
2771 2771 """
2772 2772 # this returns prefix, repo_name, suffix
2773 2773 return self._cache_key_partition()[0]
2774 2774
2775 2775 def get_suffix(self):
2776 2776 """
2777 2777 get suffix that might have been used in _get_cache_key to
2778 2778 generate self.cache_key. Only used for informational purposes
2779 2779 in repo_edit.html.
2780 2780 """
2781 2781 # prefix, repo_name, suffix
2782 2782 return self._cache_key_partition()[2]
2783 2783
2784 2784 @classmethod
2785 2785 def delete_all_cache(cls):
2786 2786 """
2787 2787 Delete all cache keys from database.
2788 2788 Should only be run when all instances are down and all entries
2789 2789 thus stale.
2790 2790 """
2791 2791 cls.query().delete()
2792 2792 Session().commit()
2793 2793
2794 2794 @classmethod
2795 2795 def get_cache_key(cls, repo_name, cache_type):
2796 2796 """
2797 2797
2798 2798 Generate a cache key for this process of RhodeCode instance.
2799 2799 Prefix most likely will be process id or maybe explicitly set
2800 2800 instance_id from .ini file.
2801 2801 """
2802 2802 import rhodecode
2803 2803 prefix = safe_unicode(rhodecode.CONFIG.get('instance_id') or '')
2804 2804
2805 2805 repo_as_unicode = safe_unicode(repo_name)
2806 2806 key = u'{}_{}'.format(repo_as_unicode, cache_type) \
2807 2807 if cache_type else repo_as_unicode
2808 2808
2809 2809 return u'{}{}'.format(prefix, key)
2810 2810
2811 2811 @classmethod
2812 2812 def set_invalidate(cls, repo_name, delete=False):
2813 2813 """
2814 2814 Mark all caches of a repo as invalid in the database.
2815 2815 """
2816 2816
2817 2817 try:
2818 2818 qry = Session().query(cls).filter(cls.cache_args == repo_name)
2819 2819 if delete:
2820 2820 log.debug('cache objects deleted for repo %s',
2821 2821 safe_str(repo_name))
2822 2822 qry.delete()
2823 2823 else:
2824 2824 log.debug('cache objects marked as invalid for repo %s',
2825 2825 safe_str(repo_name))
2826 2826 qry.update({"cache_active": False})
2827 2827
2828 2828 Session().commit()
2829 2829 except Exception:
2830 2830 log.exception(
2831 2831 'Cache key invalidation failed for repository %s',
2832 2832 safe_str(repo_name))
2833 2833 Session().rollback()
2834 2834
2835 2835 @classmethod
2836 2836 def get_active_cache(cls, cache_key):
2837 2837 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
2838 2838 if inv_obj:
2839 2839 return inv_obj
2840 2840 return None
2841 2841
2842 2842 @classmethod
2843 2843 def repo_context_cache(cls, compute_func, repo_name, cache_type):
2844 2844 """
2845 2845 @cache_region('long_term')
2846 2846 def _heavy_calculation(cache_key):
2847 2847 return 'result'
2848 2848
2849 2849 cache_context = CacheKey.repo_context_cache(
2850 2850 _heavy_calculation, repo_name, cache_type)
2851 2851
2852 2852 with cache_context as context:
2853 2853 context.invalidate()
2854 2854 computed = context.compute()
2855 2855
2856 2856 assert computed == 'result'
2857 2857 """
2858 2858 from rhodecode.lib import caches
2859 2859 return caches.InvalidationContext(compute_func, repo_name, cache_type)
2860 2860
2861 2861
2862 2862 class ChangesetComment(Base, BaseModel):
2863 2863 __tablename__ = 'changeset_comments'
2864 2864 __table_args__ = (
2865 2865 Index('cc_revision_idx', 'revision'),
2866 2866 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2867 2867 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2868 2868 )
2869 2869
2870 2870 COMMENT_OUTDATED = u'comment_outdated'
2871 2871
2872 2872 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
2873 2873 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
2874 2874 revision = Column('revision', String(40), nullable=True)
2875 2875 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
2876 2876 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
2877 2877 line_no = Column('line_no', Unicode(10), nullable=True)
2878 2878 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
2879 2879 f_path = Column('f_path', Unicode(1000), nullable=True)
2880 2880 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
2881 2881 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
2882 2882 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2883 2883 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2884 2884 renderer = Column('renderer', Unicode(64), nullable=True)
2885 2885 display_state = Column('display_state', Unicode(128), nullable=True)
2886 2886
2887 2887 author = relationship('User', lazy='joined')
2888 2888 repo = relationship('Repository')
2889 2889 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan")
2890 2890 pull_request = relationship('PullRequest', lazy='joined')
2891 2891 pull_request_version = relationship('PullRequestVersion')
2892 2892
2893 2893 @classmethod
2894 2894 def get_users(cls, revision=None, pull_request_id=None):
2895 2895 """
2896 2896 Returns user associated with this ChangesetComment. ie those
2897 2897 who actually commented
2898 2898
2899 2899 :param cls:
2900 2900 :param revision:
2901 2901 """
2902 2902 q = Session().query(User)\
2903 2903 .join(ChangesetComment.author)
2904 2904 if revision:
2905 2905 q = q.filter(cls.revision == revision)
2906 2906 elif pull_request_id:
2907 2907 q = q.filter(cls.pull_request_id == pull_request_id)
2908 2908 return q.all()
2909 2909
2910 2910 def render(self, mentions=False):
2911 2911 from rhodecode.lib import helpers as h
2912 2912 return h.render(self.text, renderer=self.renderer, mentions=mentions)
2913 2913
2914 2914 def __repr__(self):
2915 2915 if self.comment_id:
2916 2916 return '<DB:ChangesetComment #%s>' % self.comment_id
2917 2917 else:
2918 2918 return '<DB:ChangesetComment at %#x>' % id(self)
2919 2919
2920 2920
2921 2921 class ChangesetStatus(Base, BaseModel):
2922 2922 __tablename__ = 'changeset_statuses'
2923 2923 __table_args__ = (
2924 2924 Index('cs_revision_idx', 'revision'),
2925 2925 Index('cs_version_idx', 'version'),
2926 2926 UniqueConstraint('repo_id', 'revision', 'version'),
2927 2927 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2928 2928 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2929 2929 )
2930 2930 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
2931 2931 STATUS_APPROVED = 'approved'
2932 2932 STATUS_REJECTED = 'rejected'
2933 2933 STATUS_UNDER_REVIEW = 'under_review'
2934 2934
2935 2935 STATUSES = [
2936 2936 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
2937 2937 (STATUS_APPROVED, _("Approved")),
2938 2938 (STATUS_REJECTED, _("Rejected")),
2939 2939 (STATUS_UNDER_REVIEW, _("Under Review")),
2940 2940 ]
2941 2941
2942 2942 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
2943 2943 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
2944 2944 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
2945 2945 revision = Column('revision', String(40), nullable=False)
2946 2946 status = Column('status', String(128), nullable=False, default=DEFAULT)
2947 2947 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
2948 2948 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
2949 2949 version = Column('version', Integer(), nullable=False, default=0)
2950 2950 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
2951 2951
2952 2952 author = relationship('User', lazy='joined')
2953 2953 repo = relationship('Repository')
2954 2954 comment = relationship('ChangesetComment', lazy='joined')
2955 2955 pull_request = relationship('PullRequest', lazy='joined')
2956 2956
2957 2957 def __unicode__(self):
2958 2958 return u"<%s('%s[%s]:%s')>" % (
2959 2959 self.__class__.__name__,
2960 2960 self.status, self.version, self.author
2961 2961 )
2962 2962
2963 2963 @classmethod
2964 2964 def get_status_lbl(cls, value):
2965 2965 return dict(cls.STATUSES).get(value)
2966 2966
2967 2967 @property
2968 2968 def status_lbl(self):
2969 2969 return ChangesetStatus.get_status_lbl(self.status)
2970 2970
2971 2971
2972 2972 class _PullRequestBase(BaseModel):
2973 2973 """
2974 2974 Common attributes of pull request and version entries.
2975 2975 """
2976 2976
2977 2977 # .status values
2978 2978 STATUS_NEW = u'new'
2979 2979 STATUS_OPEN = u'open'
2980 2980 STATUS_CLOSED = u'closed'
2981 2981
2982 2982 title = Column('title', Unicode(255), nullable=True)
2983 2983 description = Column(
2984 2984 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
2985 2985 nullable=True)
2986 2986 # new/open/closed status of pull request (not approve/reject/etc)
2987 2987 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
2988 2988 created_on = Column(
2989 2989 'created_on', DateTime(timezone=False), nullable=False,
2990 2990 default=datetime.datetime.now)
2991 2991 updated_on = Column(
2992 2992 'updated_on', DateTime(timezone=False), nullable=False,
2993 2993 default=datetime.datetime.now)
2994 2994
2995 2995 @declared_attr
2996 2996 def user_id(cls):
2997 2997 return Column(
2998 2998 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
2999 2999 unique=None)
3000 3000
3001 3001 # 500 revisions max
3002 3002 _revisions = Column(
3003 3003 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3004 3004
3005 3005 @declared_attr
3006 3006 def source_repo_id(cls):
3007 3007 # TODO: dan: rename column to source_repo_id
3008 3008 return Column(
3009 3009 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3010 3010 nullable=False)
3011 3011
3012 3012 source_ref = Column('org_ref', Unicode(255), nullable=False)
3013 3013
3014 3014 @declared_attr
3015 3015 def target_repo_id(cls):
3016 3016 # TODO: dan: rename column to target_repo_id
3017 3017 return Column(
3018 3018 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3019 3019 nullable=False)
3020 3020
3021 3021 target_ref = Column('other_ref', Unicode(255), nullable=False)
3022 3022
3023 3023 # TODO: dan: rename column to last_merge_source_rev
3024 3024 _last_merge_source_rev = Column(
3025 3025 'last_merge_org_rev', String(40), nullable=True)
3026 3026 # TODO: dan: rename column to last_merge_target_rev
3027 3027 _last_merge_target_rev = Column(
3028 3028 'last_merge_other_rev', String(40), nullable=True)
3029 3029 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3030 3030 merge_rev = Column('merge_rev', String(40), nullable=True)
3031 3031
3032 3032 @hybrid_property
3033 3033 def revisions(self):
3034 3034 return self._revisions.split(':') if self._revisions else []
3035 3035
3036 3036 @revisions.setter
3037 3037 def revisions(self, val):
3038 3038 self._revisions = ':'.join(val)
3039 3039
3040 3040 @declared_attr
3041 3041 def author(cls):
3042 3042 return relationship('User', lazy='joined')
3043 3043
3044 3044 @declared_attr
3045 3045 def source_repo(cls):
3046 3046 return relationship(
3047 3047 'Repository',
3048 3048 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3049 3049
3050 3050 @property
3051 3051 def source_ref_parts(self):
3052 3052 refs = self.source_ref.split(':')
3053 3053 return Reference(refs[0], refs[1], refs[2])
3054 3054
3055 3055 @declared_attr
3056 3056 def target_repo(cls):
3057 3057 return relationship(
3058 3058 'Repository',
3059 3059 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3060 3060
3061 3061 @property
3062 3062 def target_ref_parts(self):
3063 3063 refs = self.target_ref.split(':')
3064 3064 return Reference(refs[0], refs[1], refs[2])
3065 3065
3066 3066
3067 3067 class PullRequest(Base, _PullRequestBase):
3068 3068 __tablename__ = 'pull_requests'
3069 3069 __table_args__ = (
3070 3070 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3071 3071 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3072 3072 )
3073 3073
3074 3074 pull_request_id = Column(
3075 3075 'pull_request_id', Integer(), nullable=False, primary_key=True)
3076 3076
3077 3077 def __repr__(self):
3078 3078 if self.pull_request_id:
3079 3079 return '<DB:PullRequest #%s>' % self.pull_request_id
3080 3080 else:
3081 3081 return '<DB:PullRequest at %#x>' % id(self)
3082 3082
3083 3083 reviewers = relationship('PullRequestReviewers',
3084 3084 cascade="all, delete, delete-orphan")
3085 3085 statuses = relationship('ChangesetStatus')
3086 3086 comments = relationship('ChangesetComment',
3087 3087 cascade="all, delete, delete-orphan")
3088 3088 versions = relationship('PullRequestVersion',
3089 3089 cascade="all, delete, delete-orphan")
3090 3090
3091 3091 def is_closed(self):
3092 3092 return self.status == self.STATUS_CLOSED
3093 3093
3094 3094 def get_api_data(self):
3095 3095 from rhodecode.model.pull_request import PullRequestModel
3096 3096 pull_request = self
3097 3097 merge_status = PullRequestModel().merge_status(pull_request)
3098 3098 data = {
3099 3099 'pull_request_id': pull_request.pull_request_id,
3100 3100 'url': url('pullrequest_show',
3101 3101 repo_name=pull_request.target_repo.repo_name,
3102 3102 pull_request_id=pull_request.pull_request_id,
3103 3103 qualified=True),
3104 3104 'title': pull_request.title,
3105 3105 'description': pull_request.description,
3106 3106 'status': pull_request.status,
3107 3107 'created_on': pull_request.created_on,
3108 3108 'updated_on': pull_request.updated_on,
3109 3109 'commit_ids': pull_request.revisions,
3110 3110 'review_status': pull_request.calculated_review_status(),
3111 3111 'mergeable': {
3112 3112 'status': merge_status[0],
3113 3113 'message': unicode(merge_status[1]),
3114 3114 },
3115 3115 'source': {
3116 3116 'clone_url': pull_request.source_repo.clone_url(),
3117 3117 'repository': pull_request.source_repo.repo_name,
3118 3118 'reference': {
3119 3119 'name': pull_request.source_ref_parts.name,
3120 3120 'type': pull_request.source_ref_parts.type,
3121 3121 'commit_id': pull_request.source_ref_parts.commit_id,
3122 3122 },
3123 3123 },
3124 3124 'target': {
3125 3125 'clone_url': pull_request.target_repo.clone_url(),
3126 3126 'repository': pull_request.target_repo.repo_name,
3127 3127 'reference': {
3128 3128 'name': pull_request.target_ref_parts.name,
3129 3129 'type': pull_request.target_ref_parts.type,
3130 3130 'commit_id': pull_request.target_ref_parts.commit_id,
3131 3131 },
3132 3132 },
3133 3133 'author': pull_request.author.get_api_data(include_secrets=False,
3134 3134 details='basic'),
3135 3135 'reviewers': [
3136 3136 {
3137 3137 'user': reviewer.get_api_data(include_secrets=False,
3138 3138 details='basic'),
3139 3139 'review_status': st[0][1].status if st else 'not_reviewed',
3140 3140 }
3141 3141 for reviewer, st in pull_request.reviewers_statuses()
3142 3142 ]
3143 3143 }
3144 3144
3145 3145 return data
3146 3146
3147 3147 def __json__(self):
3148 3148 return {
3149 3149 'revisions': self.revisions,
3150 3150 }
3151 3151
3152 3152 def calculated_review_status(self):
3153 3153 # TODO: anderson: 13.05.15 Used only on templates/my_account_pullrequests.html
3154 3154 # because it's tricky on how to use ChangesetStatusModel from there
3155 3155 warnings.warn("Use calculated_review_status from ChangesetStatusModel", DeprecationWarning)
3156 3156 from rhodecode.model.changeset_status import ChangesetStatusModel
3157 3157 return ChangesetStatusModel().calculated_review_status(self)
3158 3158
3159 3159 def reviewers_statuses(self):
3160 3160 warnings.warn("Use reviewers_statuses from ChangesetStatusModel", DeprecationWarning)
3161 3161 from rhodecode.model.changeset_status import ChangesetStatusModel
3162 3162 return ChangesetStatusModel().reviewers_statuses(self)
3163 3163
3164 3164
3165 3165 class PullRequestVersion(Base, _PullRequestBase):
3166 3166 __tablename__ = 'pull_request_versions'
3167 3167 __table_args__ = (
3168 3168 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3169 3169 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3170 3170 )
3171 3171
3172 3172 pull_request_version_id = Column(
3173 3173 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3174 3174 pull_request_id = Column(
3175 3175 'pull_request_id', Integer(),
3176 3176 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3177 3177 pull_request = relationship('PullRequest')
3178 3178
3179 3179 def __repr__(self):
3180 3180 if self.pull_request_version_id:
3181 3181 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3182 3182 else:
3183 3183 return '<DB:PullRequestVersion at %#x>' % id(self)
3184 3184
3185 3185
3186 3186 class PullRequestReviewers(Base, BaseModel):
3187 3187 __tablename__ = 'pull_request_reviewers'
3188 3188 __table_args__ = (
3189 3189 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3190 3190 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3191 3191 )
3192 3192
3193 3193 def __init__(self, user=None, pull_request=None):
3194 3194 self.user = user
3195 3195 self.pull_request = pull_request
3196 3196
3197 3197 pull_requests_reviewers_id = Column(
3198 3198 'pull_requests_reviewers_id', Integer(), nullable=False,
3199 3199 primary_key=True)
3200 3200 pull_request_id = Column(
3201 3201 "pull_request_id", Integer(),
3202 3202 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3203 3203 user_id = Column(
3204 3204 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3205 3205
3206 3206 user = relationship('User')
3207 3207 pull_request = relationship('PullRequest')
3208 3208
3209 3209
3210 3210 class Notification(Base, BaseModel):
3211 3211 __tablename__ = 'notifications'
3212 3212 __table_args__ = (
3213 3213 Index('notification_type_idx', 'type'),
3214 3214 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3215 3215 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3216 3216 )
3217 3217
3218 3218 TYPE_CHANGESET_COMMENT = u'cs_comment'
3219 3219 TYPE_MESSAGE = u'message'
3220 3220 TYPE_MENTION = u'mention'
3221 3221 TYPE_REGISTRATION = u'registration'
3222 3222 TYPE_PULL_REQUEST = u'pull_request'
3223 3223 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
3224 3224
3225 3225 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
3226 3226 subject = Column('subject', Unicode(512), nullable=True)
3227 3227 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
3228 3228 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
3229 3229 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3230 3230 type_ = Column('type', Unicode(255))
3231 3231
3232 3232 created_by_user = relationship('User')
3233 3233 notifications_to_users = relationship('UserNotification', lazy='joined',
3234 3234 cascade="all, delete, delete-orphan")
3235 3235
3236 3236 @property
3237 3237 def recipients(self):
3238 3238 return [x.user for x in UserNotification.query()\
3239 3239 .filter(UserNotification.notification == self)\
3240 3240 .order_by(UserNotification.user_id.asc()).all()]
3241 3241
3242 3242 @classmethod
3243 3243 def create(cls, created_by, subject, body, recipients, type_=None):
3244 3244 if type_ is None:
3245 3245 type_ = Notification.TYPE_MESSAGE
3246 3246
3247 3247 notification = cls()
3248 3248 notification.created_by_user = created_by
3249 3249 notification.subject = subject
3250 3250 notification.body = body
3251 3251 notification.type_ = type_
3252 3252 notification.created_on = datetime.datetime.now()
3253 3253
3254 3254 for u in recipients:
3255 3255 assoc = UserNotification()
3256 3256 assoc.notification = notification
3257 3257
3258 3258 # if created_by is inside recipients mark his notification
3259 3259 # as read
3260 3260 if u.user_id == created_by.user_id:
3261 3261 assoc.read = True
3262 3262
3263 3263 u.notifications.append(assoc)
3264 3264 Session().add(notification)
3265 3265
3266 3266 return notification
3267 3267
3268 3268 @property
3269 3269 def description(self):
3270 3270 from rhodecode.model.notification import NotificationModel
3271 3271 return NotificationModel().make_description(self)
3272 3272
3273 3273
3274 3274 class UserNotification(Base, BaseModel):
3275 3275 __tablename__ = 'user_to_notification'
3276 3276 __table_args__ = (
3277 3277 UniqueConstraint('user_id', 'notification_id'),
3278 3278 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3279 3279 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3280 3280 )
3281 3281 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
3282 3282 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
3283 3283 read = Column('read', Boolean, default=False)
3284 3284 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
3285 3285
3286 3286 user = relationship('User', lazy="joined")
3287 3287 notification = relationship('Notification', lazy="joined",
3288 3288 order_by=lambda: Notification.created_on.desc(),)
3289 3289
3290 3290 def mark_as_read(self):
3291 3291 self.read = True
3292 3292 Session().add(self)
3293 3293
3294 3294
3295 3295 class Gist(Base, BaseModel):
3296 3296 __tablename__ = 'gists'
3297 3297 __table_args__ = (
3298 3298 Index('g_gist_access_id_idx', 'gist_access_id'),
3299 3299 Index('g_created_on_idx', 'created_on'),
3300 3300 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3301 3301 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3302 3302 )
3303 3303 GIST_PUBLIC = u'public'
3304 3304 GIST_PRIVATE = u'private'
3305 3305 DEFAULT_FILENAME = u'gistfile1.txt'
3306 3306
3307 3307 ACL_LEVEL_PUBLIC = u'acl_public'
3308 3308 ACL_LEVEL_PRIVATE = u'acl_private'
3309 3309
3310 3310 gist_id = Column('gist_id', Integer(), primary_key=True)
3311 3311 gist_access_id = Column('gist_access_id', Unicode(250))
3312 3312 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
3313 3313 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
3314 3314 gist_expires = Column('gist_expires', Float(53), nullable=False)
3315 3315 gist_type = Column('gist_type', Unicode(128), nullable=False)
3316 3316 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3317 3317 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3318 3318 acl_level = Column('acl_level', Unicode(128), nullable=True)
3319 3319
3320 3320 owner = relationship('User')
3321 3321
3322 3322 def __repr__(self):
3323 3323 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
3324 3324
3325 3325 @classmethod
3326 3326 def get_or_404(cls, id_):
3327 3327 res = cls.query().filter(cls.gist_access_id == id_).scalar()
3328 3328 if not res:
3329 3329 raise HTTPNotFound
3330 3330 return res
3331 3331
3332 3332 @classmethod
3333 3333 def get_by_access_id(cls, gist_access_id):
3334 3334 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
3335 3335
3336 3336 def gist_url(self):
3337 3337 import rhodecode
3338 3338 alias_url = rhodecode.CONFIG.get('gist_alias_url')
3339 3339 if alias_url:
3340 3340 return alias_url.replace('{gistid}', self.gist_access_id)
3341 3341
3342 3342 return url('gist', gist_id=self.gist_access_id, qualified=True)
3343 3343
3344 3344 @classmethod
3345 3345 def base_path(cls):
3346 3346 """
3347 3347 Returns base path when all gists are stored
3348 3348
3349 3349 :param cls:
3350 3350 """
3351 3351 from rhodecode.model.gist import GIST_STORE_LOC
3352 3352 q = Session().query(RhodeCodeUi)\
3353 3353 .filter(RhodeCodeUi.ui_key == URL_SEP)
3354 3354 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
3355 3355 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
3356 3356
3357 3357 def get_api_data(self):
3358 3358 """
3359 3359 Common function for generating gist related data for API
3360 3360 """
3361 3361 gist = self
3362 3362 data = {
3363 3363 'gist_id': gist.gist_id,
3364 3364 'type': gist.gist_type,
3365 3365 'access_id': gist.gist_access_id,
3366 3366 'description': gist.gist_description,
3367 3367 'url': gist.gist_url(),
3368 3368 'expires': gist.gist_expires,
3369 3369 'created_on': gist.created_on,
3370 3370 'modified_at': gist.modified_at,
3371 3371 'content': None,
3372 3372 'acl_level': gist.acl_level,
3373 3373 }
3374 3374 return data
3375 3375
3376 3376 def __json__(self):
3377 3377 data = dict(
3378 3378 )
3379 3379 data.update(self.get_api_data())
3380 3380 return data
3381 3381 # SCM functions
3382 3382
3383 3383 def scm_instance(self, **kwargs):
3384 3384 from rhodecode.lib.vcs import get_repo
3385 3385 base_path = self.base_path()
3386 3386 return get_repo(os.path.join(*map(safe_str,
3387 3387 [base_path, self.gist_access_id])))
3388 3388
3389 3389
3390 3390 class DbMigrateVersion(Base, BaseModel):
3391 3391 __tablename__ = 'db_migrate_version'
3392 3392 __table_args__ = (
3393 3393 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3394 3394 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3395 3395 )
3396 3396 repository_id = Column('repository_id', String(250), primary_key=True)
3397 3397 repository_path = Column('repository_path', Text)
3398 3398 version = Column('version', Integer)
3399 3399
3400 3400
3401 3401 class ExternalIdentity(Base, BaseModel):
3402 3402 __tablename__ = 'external_identities'
3403 3403 __table_args__ = (
3404 3404 Index('local_user_id_idx', 'local_user_id'),
3405 3405 Index('external_id_idx', 'external_id'),
3406 3406 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3407 3407 'mysql_charset': 'utf8'})
3408 3408
3409 3409 external_id = Column('external_id', Unicode(255), default=u'',
3410 3410 primary_key=True)
3411 3411 external_username = Column('external_username', Unicode(1024), default=u'')
3412 3412 local_user_id = Column('local_user_id', Integer(),
3413 3413 ForeignKey('users.user_id'), primary_key=True)
3414 3414 provider_name = Column('provider_name', Unicode(255), default=u'',
3415 3415 primary_key=True)
3416 3416 access_token = Column('access_token', String(1024), default=u'')
3417 3417 alt_token = Column('alt_token', String(1024), default=u'')
3418 3418 token_secret = Column('token_secret', String(1024), default=u'')
3419 3419
3420 3420 @classmethod
3421 3421 def by_external_id_and_provider(cls, external_id, provider_name,
3422 3422 local_user_id=None):
3423 3423 """
3424 3424 Returns ExternalIdentity instance based on search params
3425 3425
3426 3426 :param external_id:
3427 3427 :param provider_name:
3428 3428 :return: ExternalIdentity
3429 3429 """
3430 3430 query = cls.query()
3431 3431 query = query.filter(cls.external_id == external_id)
3432 3432 query = query.filter(cls.provider_name == provider_name)
3433 3433 if local_user_id:
3434 3434 query = query.filter(cls.local_user_id == local_user_id)
3435 3435 return query.first()
3436 3436
3437 3437 @classmethod
3438 3438 def user_by_external_id_and_provider(cls, external_id, provider_name):
3439 3439 """
3440 3440 Returns User instance based on search params
3441 3441
3442 3442 :param external_id:
3443 3443 :param provider_name:
3444 3444 :return: User
3445 3445 """
3446 3446 query = User.query()
3447 3447 query = query.filter(cls.external_id == external_id)
3448 3448 query = query.filter(cls.provider_name == provider_name)
3449 3449 query = query.filter(User.user_id == cls.local_user_id)
3450 3450 return query.first()
3451 3451
3452 3452 @classmethod
3453 3453 def by_local_user_id(cls, local_user_id):
3454 3454 """
3455 3455 Returns all tokens for user
3456 3456
3457 3457 :param local_user_id:
3458 3458 :return: ExternalIdentity
3459 3459 """
3460 3460 query = cls.query()
3461 3461 query = query.filter(cls.local_user_id == local_user_id)
3462 3462 return query
General Comments 0
You need to be logged in to leave comments. Login now