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