##// END OF EJS Templates
caches: ensure we don't use non-ascii characters in cache keys....
marcink -
r1749:8c35f24d default
parent child Browse files
Show More
@@ -1,1973 +1,1973 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 authentication and permission libraries
22 authentication and permission libraries
23 """
23 """
24
24
25 import os
25 import os
26 import inspect
26 import inspect
27 import collections
27 import collections
28 import fnmatch
28 import fnmatch
29 import hashlib
29 import hashlib
30 import itertools
30 import itertools
31 import logging
31 import logging
32 import random
32 import random
33 import traceback
33 import traceback
34 from functools import wraps
34 from functools import wraps
35
35
36 import ipaddress
36 import ipaddress
37 from pyramid.httpexceptions import HTTPForbidden, HTTPFound
37 from pyramid.httpexceptions import HTTPForbidden, HTTPFound
38 from pylons import url, request
38 from pylons import url, request
39 from pylons.controllers.util import abort, redirect
39 from pylons.controllers.util import abort, redirect
40 from pylons.i18n.translation import _
40 from pylons.i18n.translation import _
41 from sqlalchemy.orm.exc import ObjectDeletedError
41 from sqlalchemy.orm.exc import ObjectDeletedError
42 from sqlalchemy.orm import joinedload
42 from sqlalchemy.orm import joinedload
43 from zope.cachedescriptors.property import Lazy as LazyProperty
43 from zope.cachedescriptors.property import Lazy as LazyProperty
44
44
45 import rhodecode
45 import rhodecode
46 from rhodecode.model import meta
46 from rhodecode.model import meta
47 from rhodecode.model.meta import Session
47 from rhodecode.model.meta import Session
48 from rhodecode.model.user import UserModel
48 from rhodecode.model.user import UserModel
49 from rhodecode.model.db import (
49 from rhodecode.model.db import (
50 User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember,
50 User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember,
51 UserIpMap, UserApiKeys, RepoGroup)
51 UserIpMap, UserApiKeys, RepoGroup)
52 from rhodecode.lib import caches
52 from rhodecode.lib import caches
53 from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5
53 from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5
54 from rhodecode.lib.utils import (
54 from rhodecode.lib.utils import (
55 get_repo_slug, get_repo_group_slug, get_user_group_slug)
55 get_repo_slug, get_repo_group_slug, get_user_group_slug)
56 from rhodecode.lib.caching_query import FromCache
56 from rhodecode.lib.caching_query import FromCache
57
57
58
58
59 if rhodecode.is_unix:
59 if rhodecode.is_unix:
60 import bcrypt
60 import bcrypt
61
61
62 log = logging.getLogger(__name__)
62 log = logging.getLogger(__name__)
63
63
64 csrf_token_key = "csrf_token"
64 csrf_token_key = "csrf_token"
65
65
66
66
67 class PasswordGenerator(object):
67 class PasswordGenerator(object):
68 """
68 """
69 This is a simple class for generating password from different sets of
69 This is a simple class for generating password from different sets of
70 characters
70 characters
71 usage::
71 usage::
72
72
73 passwd_gen = PasswordGenerator()
73 passwd_gen = PasswordGenerator()
74 #print 8-letter password containing only big and small letters
74 #print 8-letter password containing only big and small letters
75 of alphabet
75 of alphabet
76 passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
76 passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
77 """
77 """
78 ALPHABETS_NUM = r'''1234567890'''
78 ALPHABETS_NUM = r'''1234567890'''
79 ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
79 ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
80 ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
80 ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
81 ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
81 ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
82 ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
82 ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
83 + ALPHABETS_NUM + ALPHABETS_SPECIAL
83 + ALPHABETS_NUM + ALPHABETS_SPECIAL
84 ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
84 ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
85 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
85 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
86 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
86 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
87 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
87 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
88
88
89 def __init__(self, passwd=''):
89 def __init__(self, passwd=''):
90 self.passwd = passwd
90 self.passwd = passwd
91
91
92 def gen_password(self, length, type_=None):
92 def gen_password(self, length, type_=None):
93 if type_ is None:
93 if type_ is None:
94 type_ = self.ALPHABETS_FULL
94 type_ = self.ALPHABETS_FULL
95 self.passwd = ''.join([random.choice(type_) for _ in xrange(length)])
95 self.passwd = ''.join([random.choice(type_) for _ in xrange(length)])
96 return self.passwd
96 return self.passwd
97
97
98
98
99 class _RhodeCodeCryptoBase(object):
99 class _RhodeCodeCryptoBase(object):
100 ENC_PREF = None
100 ENC_PREF = None
101
101
102 def hash_create(self, str_):
102 def hash_create(self, str_):
103 """
103 """
104 hash the string using
104 hash the string using
105
105
106 :param str_: password to hash
106 :param str_: password to hash
107 """
107 """
108 raise NotImplementedError
108 raise NotImplementedError
109
109
110 def hash_check_with_upgrade(self, password, hashed):
110 def hash_check_with_upgrade(self, password, hashed):
111 """
111 """
112 Returns tuple in which first element is boolean that states that
112 Returns tuple in which first element is boolean that states that
113 given password matches it's hashed version, and the second is new hash
113 given password matches it's hashed version, and the second is new hash
114 of the password, in case this password should be migrated to new
114 of the password, in case this password should be migrated to new
115 cipher.
115 cipher.
116 """
116 """
117 checked_hash = self.hash_check(password, hashed)
117 checked_hash = self.hash_check(password, hashed)
118 return checked_hash, None
118 return checked_hash, None
119
119
120 def hash_check(self, password, hashed):
120 def hash_check(self, password, hashed):
121 """
121 """
122 Checks matching password with it's hashed value.
122 Checks matching password with it's hashed value.
123
123
124 :param password: password
124 :param password: password
125 :param hashed: password in hashed form
125 :param hashed: password in hashed form
126 """
126 """
127 raise NotImplementedError
127 raise NotImplementedError
128
128
129 def _assert_bytes(self, value):
129 def _assert_bytes(self, value):
130 """
130 """
131 Passing in an `unicode` object can lead to hard to detect issues
131 Passing in an `unicode` object can lead to hard to detect issues
132 if passwords contain non-ascii characters. Doing a type check
132 if passwords contain non-ascii characters. Doing a type check
133 during runtime, so that such mistakes are detected early on.
133 during runtime, so that such mistakes are detected early on.
134 """
134 """
135 if not isinstance(value, str):
135 if not isinstance(value, str):
136 raise TypeError(
136 raise TypeError(
137 "Bytestring required as input, got %r." % (value, ))
137 "Bytestring required as input, got %r." % (value, ))
138
138
139
139
140 class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase):
140 class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase):
141 ENC_PREF = ('$2a$10', '$2b$10')
141 ENC_PREF = ('$2a$10', '$2b$10')
142
142
143 def hash_create(self, str_):
143 def hash_create(self, str_):
144 self._assert_bytes(str_)
144 self._assert_bytes(str_)
145 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
145 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
146
146
147 def hash_check_with_upgrade(self, password, hashed):
147 def hash_check_with_upgrade(self, password, hashed):
148 """
148 """
149 Returns tuple in which first element is boolean that states that
149 Returns tuple in which first element is boolean that states that
150 given password matches it's hashed version, and the second is new hash
150 given password matches it's hashed version, and the second is new hash
151 of the password, in case this password should be migrated to new
151 of the password, in case this password should be migrated to new
152 cipher.
152 cipher.
153
153
154 This implements special upgrade logic which works like that:
154 This implements special upgrade logic which works like that:
155 - check if the given password == bcrypted hash, if yes then we
155 - check if the given password == bcrypted hash, if yes then we
156 properly used password and it was already in bcrypt. Proceed
156 properly used password and it was already in bcrypt. Proceed
157 without any changes
157 without any changes
158 - if bcrypt hash check is not working try with sha256. If hash compare
158 - if bcrypt hash check is not working try with sha256. If hash compare
159 is ok, it means we using correct but old hashed password. indicate
159 is ok, it means we using correct but old hashed password. indicate
160 hash change and proceed
160 hash change and proceed
161 """
161 """
162
162
163 new_hash = None
163 new_hash = None
164
164
165 # regular pw check
165 # regular pw check
166 password_match_bcrypt = self.hash_check(password, hashed)
166 password_match_bcrypt = self.hash_check(password, hashed)
167
167
168 # now we want to know if the password was maybe from sha256
168 # now we want to know if the password was maybe from sha256
169 # basically calling _RhodeCodeCryptoSha256().hash_check()
169 # basically calling _RhodeCodeCryptoSha256().hash_check()
170 if not password_match_bcrypt:
170 if not password_match_bcrypt:
171 if _RhodeCodeCryptoSha256().hash_check(password, hashed):
171 if _RhodeCodeCryptoSha256().hash_check(password, hashed):
172 new_hash = self.hash_create(password) # make new bcrypt hash
172 new_hash = self.hash_create(password) # make new bcrypt hash
173 password_match_bcrypt = True
173 password_match_bcrypt = True
174
174
175 return password_match_bcrypt, new_hash
175 return password_match_bcrypt, new_hash
176
176
177 def hash_check(self, password, hashed):
177 def hash_check(self, password, hashed):
178 """
178 """
179 Checks matching password with it's hashed value.
179 Checks matching password with it's hashed value.
180
180
181 :param password: password
181 :param password: password
182 :param hashed: password in hashed form
182 :param hashed: password in hashed form
183 """
183 """
184 self._assert_bytes(password)
184 self._assert_bytes(password)
185 try:
185 try:
186 return bcrypt.hashpw(password, hashed) == hashed
186 return bcrypt.hashpw(password, hashed) == hashed
187 except ValueError as e:
187 except ValueError as e:
188 # we're having a invalid salt here probably, we should not crash
188 # we're having a invalid salt here probably, we should not crash
189 # just return with False as it would be a wrong password.
189 # just return with False as it would be a wrong password.
190 log.debug('Failed to check password hash using bcrypt %s',
190 log.debug('Failed to check password hash using bcrypt %s',
191 safe_str(e))
191 safe_str(e))
192
192
193 return False
193 return False
194
194
195
195
196 class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase):
196 class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase):
197 ENC_PREF = '_'
197 ENC_PREF = '_'
198
198
199 def hash_create(self, str_):
199 def hash_create(self, str_):
200 self._assert_bytes(str_)
200 self._assert_bytes(str_)
201 return hashlib.sha256(str_).hexdigest()
201 return hashlib.sha256(str_).hexdigest()
202
202
203 def hash_check(self, password, hashed):
203 def hash_check(self, password, hashed):
204 """
204 """
205 Checks matching password with it's hashed value.
205 Checks matching password with it's hashed value.
206
206
207 :param password: password
207 :param password: password
208 :param hashed: password in hashed form
208 :param hashed: password in hashed form
209 """
209 """
210 self._assert_bytes(password)
210 self._assert_bytes(password)
211 return hashlib.sha256(password).hexdigest() == hashed
211 return hashlib.sha256(password).hexdigest() == hashed
212
212
213
213
214 class _RhodeCodeCryptoMd5(_RhodeCodeCryptoBase):
214 class _RhodeCodeCryptoMd5(_RhodeCodeCryptoBase):
215 ENC_PREF = '_'
215 ENC_PREF = '_'
216
216
217 def hash_create(self, str_):
217 def hash_create(self, str_):
218 self._assert_bytes(str_)
218 self._assert_bytes(str_)
219 return hashlib.md5(str_).hexdigest()
219 return hashlib.md5(str_).hexdigest()
220
220
221 def hash_check(self, password, hashed):
221 def hash_check(self, password, hashed):
222 """
222 """
223 Checks matching password with it's hashed value.
223 Checks matching password with it's hashed value.
224
224
225 :param password: password
225 :param password: password
226 :param hashed: password in hashed form
226 :param hashed: password in hashed form
227 """
227 """
228 self._assert_bytes(password)
228 self._assert_bytes(password)
229 return hashlib.md5(password).hexdigest() == hashed
229 return hashlib.md5(password).hexdigest() == hashed
230
230
231
231
232 def crypto_backend():
232 def crypto_backend():
233 """
233 """
234 Return the matching crypto backend.
234 Return the matching crypto backend.
235
235
236 Selection is based on if we run tests or not, we pick md5 backend to run
236 Selection is based on if we run tests or not, we pick md5 backend to run
237 tests faster since BCRYPT is expensive to calculate
237 tests faster since BCRYPT is expensive to calculate
238 """
238 """
239 if rhodecode.is_test:
239 if rhodecode.is_test:
240 RhodeCodeCrypto = _RhodeCodeCryptoMd5()
240 RhodeCodeCrypto = _RhodeCodeCryptoMd5()
241 else:
241 else:
242 RhodeCodeCrypto = _RhodeCodeCryptoBCrypt()
242 RhodeCodeCrypto = _RhodeCodeCryptoBCrypt()
243
243
244 return RhodeCodeCrypto
244 return RhodeCodeCrypto
245
245
246
246
247 def get_crypt_password(password):
247 def get_crypt_password(password):
248 """
248 """
249 Create the hash of `password` with the active crypto backend.
249 Create the hash of `password` with the active crypto backend.
250
250
251 :param password: The cleartext password.
251 :param password: The cleartext password.
252 :type password: unicode
252 :type password: unicode
253 """
253 """
254 password = safe_str(password)
254 password = safe_str(password)
255 return crypto_backend().hash_create(password)
255 return crypto_backend().hash_create(password)
256
256
257
257
258 def check_password(password, hashed):
258 def check_password(password, hashed):
259 """
259 """
260 Check if the value in `password` matches the hash in `hashed`.
260 Check if the value in `password` matches the hash in `hashed`.
261
261
262 :param password: The cleartext password.
262 :param password: The cleartext password.
263 :type password: unicode
263 :type password: unicode
264
264
265 :param hashed: The expected hashed version of the password.
265 :param hashed: The expected hashed version of the password.
266 :type hashed: The hash has to be passed in in text representation.
266 :type hashed: The hash has to be passed in in text representation.
267 """
267 """
268 password = safe_str(password)
268 password = safe_str(password)
269 return crypto_backend().hash_check(password, hashed)
269 return crypto_backend().hash_check(password, hashed)
270
270
271
271
272 def generate_auth_token(data, salt=None):
272 def generate_auth_token(data, salt=None):
273 """
273 """
274 Generates API KEY from given string
274 Generates API KEY from given string
275 """
275 """
276
276
277 if salt is None:
277 if salt is None:
278 salt = os.urandom(16)
278 salt = os.urandom(16)
279 return hashlib.sha1(safe_str(data) + salt).hexdigest()
279 return hashlib.sha1(safe_str(data) + salt).hexdigest()
280
280
281
281
282 class CookieStoreWrapper(object):
282 class CookieStoreWrapper(object):
283
283
284 def __init__(self, cookie_store):
284 def __init__(self, cookie_store):
285 self.cookie_store = cookie_store
285 self.cookie_store = cookie_store
286
286
287 def __repr__(self):
287 def __repr__(self):
288 return 'CookieStore<%s>' % (self.cookie_store)
288 return 'CookieStore<%s>' % (self.cookie_store)
289
289
290 def get(self, key, other=None):
290 def get(self, key, other=None):
291 if isinstance(self.cookie_store, dict):
291 if isinstance(self.cookie_store, dict):
292 return self.cookie_store.get(key, other)
292 return self.cookie_store.get(key, other)
293 elif isinstance(self.cookie_store, AuthUser):
293 elif isinstance(self.cookie_store, AuthUser):
294 return self.cookie_store.__dict__.get(key, other)
294 return self.cookie_store.__dict__.get(key, other)
295
295
296
296
297 def _cached_perms_data(user_id, scope, user_is_admin,
297 def _cached_perms_data(user_id, scope, user_is_admin,
298 user_inherit_default_permissions, explicit, algo):
298 user_inherit_default_permissions, explicit, algo):
299
299
300 permissions = PermissionCalculator(
300 permissions = PermissionCalculator(
301 user_id, scope, user_is_admin, user_inherit_default_permissions,
301 user_id, scope, user_is_admin, user_inherit_default_permissions,
302 explicit, algo)
302 explicit, algo)
303 return permissions.calculate()
303 return permissions.calculate()
304
304
305 class PermOrigin:
305 class PermOrigin:
306 ADMIN = 'superadmin'
306 ADMIN = 'superadmin'
307
307
308 REPO_USER = 'user:%s'
308 REPO_USER = 'user:%s'
309 REPO_USERGROUP = 'usergroup:%s'
309 REPO_USERGROUP = 'usergroup:%s'
310 REPO_OWNER = 'repo.owner'
310 REPO_OWNER = 'repo.owner'
311 REPO_DEFAULT = 'repo.default'
311 REPO_DEFAULT = 'repo.default'
312 REPO_PRIVATE = 'repo.private'
312 REPO_PRIVATE = 'repo.private'
313
313
314 REPOGROUP_USER = 'user:%s'
314 REPOGROUP_USER = 'user:%s'
315 REPOGROUP_USERGROUP = 'usergroup:%s'
315 REPOGROUP_USERGROUP = 'usergroup:%s'
316 REPOGROUP_OWNER = 'group.owner'
316 REPOGROUP_OWNER = 'group.owner'
317 REPOGROUP_DEFAULT = 'group.default'
317 REPOGROUP_DEFAULT = 'group.default'
318
318
319 USERGROUP_USER = 'user:%s'
319 USERGROUP_USER = 'user:%s'
320 USERGROUP_USERGROUP = 'usergroup:%s'
320 USERGROUP_USERGROUP = 'usergroup:%s'
321 USERGROUP_OWNER = 'usergroup.owner'
321 USERGROUP_OWNER = 'usergroup.owner'
322 USERGROUP_DEFAULT = 'usergroup.default'
322 USERGROUP_DEFAULT = 'usergroup.default'
323
323
324
324
325 class PermOriginDict(dict):
325 class PermOriginDict(dict):
326 """
326 """
327 A special dict used for tracking permissions along with their origins.
327 A special dict used for tracking permissions along with their origins.
328
328
329 `__setitem__` has been overridden to expect a tuple(perm, origin)
329 `__setitem__` has been overridden to expect a tuple(perm, origin)
330 `__getitem__` will return only the perm
330 `__getitem__` will return only the perm
331 `.perm_origin_stack` will return the stack of (perm, origin) set per key
331 `.perm_origin_stack` will return the stack of (perm, origin) set per key
332
332
333 >>> perms = PermOriginDict()
333 >>> perms = PermOriginDict()
334 >>> perms['resource'] = 'read', 'default'
334 >>> perms['resource'] = 'read', 'default'
335 >>> perms['resource']
335 >>> perms['resource']
336 'read'
336 'read'
337 >>> perms['resource'] = 'write', 'admin'
337 >>> perms['resource'] = 'write', 'admin'
338 >>> perms['resource']
338 >>> perms['resource']
339 'write'
339 'write'
340 >>> perms.perm_origin_stack
340 >>> perms.perm_origin_stack
341 {'resource': [('read', 'default'), ('write', 'admin')]}
341 {'resource': [('read', 'default'), ('write', 'admin')]}
342 """
342 """
343
343
344
344
345 def __init__(self, *args, **kw):
345 def __init__(self, *args, **kw):
346 dict.__init__(self, *args, **kw)
346 dict.__init__(self, *args, **kw)
347 self.perm_origin_stack = {}
347 self.perm_origin_stack = {}
348
348
349 def __setitem__(self, key, (perm, origin)):
349 def __setitem__(self, key, (perm, origin)):
350 self.perm_origin_stack.setdefault(key, []).append((perm, origin))
350 self.perm_origin_stack.setdefault(key, []).append((perm, origin))
351 dict.__setitem__(self, key, perm)
351 dict.__setitem__(self, key, perm)
352
352
353
353
354 class PermissionCalculator(object):
354 class PermissionCalculator(object):
355
355
356 def __init__(
356 def __init__(
357 self, user_id, scope, user_is_admin,
357 self, user_id, scope, user_is_admin,
358 user_inherit_default_permissions, explicit, algo):
358 user_inherit_default_permissions, explicit, algo):
359 self.user_id = user_id
359 self.user_id = user_id
360 self.user_is_admin = user_is_admin
360 self.user_is_admin = user_is_admin
361 self.inherit_default_permissions = user_inherit_default_permissions
361 self.inherit_default_permissions = user_inherit_default_permissions
362 self.explicit = explicit
362 self.explicit = explicit
363 self.algo = algo
363 self.algo = algo
364
364
365 scope = scope or {}
365 scope = scope or {}
366 self.scope_repo_id = scope.get('repo_id')
366 self.scope_repo_id = scope.get('repo_id')
367 self.scope_repo_group_id = scope.get('repo_group_id')
367 self.scope_repo_group_id = scope.get('repo_group_id')
368 self.scope_user_group_id = scope.get('user_group_id')
368 self.scope_user_group_id = scope.get('user_group_id')
369
369
370 self.default_user_id = User.get_default_user(cache=True).user_id
370 self.default_user_id = User.get_default_user(cache=True).user_id
371
371
372 self.permissions_repositories = PermOriginDict()
372 self.permissions_repositories = PermOriginDict()
373 self.permissions_repository_groups = PermOriginDict()
373 self.permissions_repository_groups = PermOriginDict()
374 self.permissions_user_groups = PermOriginDict()
374 self.permissions_user_groups = PermOriginDict()
375 self.permissions_global = set()
375 self.permissions_global = set()
376
376
377 self.default_repo_perms = Permission.get_default_repo_perms(
377 self.default_repo_perms = Permission.get_default_repo_perms(
378 self.default_user_id, self.scope_repo_id)
378 self.default_user_id, self.scope_repo_id)
379 self.default_repo_groups_perms = Permission.get_default_group_perms(
379 self.default_repo_groups_perms = Permission.get_default_group_perms(
380 self.default_user_id, self.scope_repo_group_id)
380 self.default_user_id, self.scope_repo_group_id)
381 self.default_user_group_perms = \
381 self.default_user_group_perms = \
382 Permission.get_default_user_group_perms(
382 Permission.get_default_user_group_perms(
383 self.default_user_id, self.scope_user_group_id)
383 self.default_user_id, self.scope_user_group_id)
384
384
385 def calculate(self):
385 def calculate(self):
386 if self.user_is_admin:
386 if self.user_is_admin:
387 return self._admin_permissions()
387 return self._admin_permissions()
388
388
389 self._calculate_global_default_permissions()
389 self._calculate_global_default_permissions()
390 self._calculate_global_permissions()
390 self._calculate_global_permissions()
391 self._calculate_default_permissions()
391 self._calculate_default_permissions()
392 self._calculate_repository_permissions()
392 self._calculate_repository_permissions()
393 self._calculate_repository_group_permissions()
393 self._calculate_repository_group_permissions()
394 self._calculate_user_group_permissions()
394 self._calculate_user_group_permissions()
395 return self._permission_structure()
395 return self._permission_structure()
396
396
397 def _admin_permissions(self):
397 def _admin_permissions(self):
398 """
398 """
399 admin user have all default rights for repositories
399 admin user have all default rights for repositories
400 and groups set to admin
400 and groups set to admin
401 """
401 """
402 self.permissions_global.add('hg.admin')
402 self.permissions_global.add('hg.admin')
403 self.permissions_global.add('hg.create.write_on_repogroup.true')
403 self.permissions_global.add('hg.create.write_on_repogroup.true')
404
404
405 # repositories
405 # repositories
406 for perm in self.default_repo_perms:
406 for perm in self.default_repo_perms:
407 r_k = perm.UserRepoToPerm.repository.repo_name
407 r_k = perm.UserRepoToPerm.repository.repo_name
408 p = 'repository.admin'
408 p = 'repository.admin'
409 self.permissions_repositories[r_k] = p, PermOrigin.ADMIN
409 self.permissions_repositories[r_k] = p, PermOrigin.ADMIN
410
410
411 # repository groups
411 # repository groups
412 for perm in self.default_repo_groups_perms:
412 for perm in self.default_repo_groups_perms:
413 rg_k = perm.UserRepoGroupToPerm.group.group_name
413 rg_k = perm.UserRepoGroupToPerm.group.group_name
414 p = 'group.admin'
414 p = 'group.admin'
415 self.permissions_repository_groups[rg_k] = p, PermOrigin.ADMIN
415 self.permissions_repository_groups[rg_k] = p, PermOrigin.ADMIN
416
416
417 # user groups
417 # user groups
418 for perm in self.default_user_group_perms:
418 for perm in self.default_user_group_perms:
419 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
419 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
420 p = 'usergroup.admin'
420 p = 'usergroup.admin'
421 self.permissions_user_groups[u_k] = p, PermOrigin.ADMIN
421 self.permissions_user_groups[u_k] = p, PermOrigin.ADMIN
422
422
423 return self._permission_structure()
423 return self._permission_structure()
424
424
425 def _calculate_global_default_permissions(self):
425 def _calculate_global_default_permissions(self):
426 """
426 """
427 global permissions taken from the default user
427 global permissions taken from the default user
428 """
428 """
429 default_global_perms = UserToPerm.query()\
429 default_global_perms = UserToPerm.query()\
430 .filter(UserToPerm.user_id == self.default_user_id)\
430 .filter(UserToPerm.user_id == self.default_user_id)\
431 .options(joinedload(UserToPerm.permission))
431 .options(joinedload(UserToPerm.permission))
432
432
433 for perm in default_global_perms:
433 for perm in default_global_perms:
434 self.permissions_global.add(perm.permission.permission_name)
434 self.permissions_global.add(perm.permission.permission_name)
435
435
436 def _calculate_global_permissions(self):
436 def _calculate_global_permissions(self):
437 """
437 """
438 Set global system permissions with user permissions or permissions
438 Set global system permissions with user permissions or permissions
439 taken from the user groups of the current user.
439 taken from the user groups of the current user.
440
440
441 The permissions include repo creating, repo group creating, forking
441 The permissions include repo creating, repo group creating, forking
442 etc.
442 etc.
443 """
443 """
444
444
445 # now we read the defined permissions and overwrite what we have set
445 # now we read the defined permissions and overwrite what we have set
446 # before those can be configured from groups or users explicitly.
446 # before those can be configured from groups or users explicitly.
447
447
448 # TODO: johbo: This seems to be out of sync, find out the reason
448 # TODO: johbo: This seems to be out of sync, find out the reason
449 # for the comment below and update it.
449 # for the comment below and update it.
450
450
451 # In case we want to extend this list we should be always in sync with
451 # In case we want to extend this list we should be always in sync with
452 # User.DEFAULT_USER_PERMISSIONS definitions
452 # User.DEFAULT_USER_PERMISSIONS definitions
453 _configurable = frozenset([
453 _configurable = frozenset([
454 'hg.fork.none', 'hg.fork.repository',
454 'hg.fork.none', 'hg.fork.repository',
455 'hg.create.none', 'hg.create.repository',
455 'hg.create.none', 'hg.create.repository',
456 'hg.usergroup.create.false', 'hg.usergroup.create.true',
456 'hg.usergroup.create.false', 'hg.usergroup.create.true',
457 'hg.repogroup.create.false', 'hg.repogroup.create.true',
457 'hg.repogroup.create.false', 'hg.repogroup.create.true',
458 'hg.create.write_on_repogroup.false',
458 'hg.create.write_on_repogroup.false',
459 'hg.create.write_on_repogroup.true',
459 'hg.create.write_on_repogroup.true',
460 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true'
460 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true'
461 ])
461 ])
462
462
463 # USER GROUPS comes first user group global permissions
463 # USER GROUPS comes first user group global permissions
464 user_perms_from_users_groups = Session().query(UserGroupToPerm)\
464 user_perms_from_users_groups = Session().query(UserGroupToPerm)\
465 .options(joinedload(UserGroupToPerm.permission))\
465 .options(joinedload(UserGroupToPerm.permission))\
466 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
466 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
467 UserGroupMember.users_group_id))\
467 UserGroupMember.users_group_id))\
468 .filter(UserGroupMember.user_id == self.user_id)\
468 .filter(UserGroupMember.user_id == self.user_id)\
469 .order_by(UserGroupToPerm.users_group_id)\
469 .order_by(UserGroupToPerm.users_group_id)\
470 .all()
470 .all()
471
471
472 # need to group here by groups since user can be in more than
472 # need to group here by groups since user can be in more than
473 # one group, so we get all groups
473 # one group, so we get all groups
474 _explicit_grouped_perms = [
474 _explicit_grouped_perms = [
475 [x, list(y)] for x, y in
475 [x, list(y)] for x, y in
476 itertools.groupby(user_perms_from_users_groups,
476 itertools.groupby(user_perms_from_users_groups,
477 lambda _x: _x.users_group)]
477 lambda _x: _x.users_group)]
478
478
479 for gr, perms in _explicit_grouped_perms:
479 for gr, perms in _explicit_grouped_perms:
480 # since user can be in multiple groups iterate over them and
480 # since user can be in multiple groups iterate over them and
481 # select the lowest permissions first (more explicit)
481 # select the lowest permissions first (more explicit)
482 # TODO: marcink: do this^^
482 # TODO: marcink: do this^^
483
483
484 # group doesn't inherit default permissions so we actually set them
484 # group doesn't inherit default permissions so we actually set them
485 if not gr.inherit_default_permissions:
485 if not gr.inherit_default_permissions:
486 # NEED TO IGNORE all previously set configurable permissions
486 # NEED TO IGNORE all previously set configurable permissions
487 # and replace them with explicitly set from this user
487 # and replace them with explicitly set from this user
488 # group permissions
488 # group permissions
489 self.permissions_global = self.permissions_global.difference(
489 self.permissions_global = self.permissions_global.difference(
490 _configurable)
490 _configurable)
491 for perm in perms:
491 for perm in perms:
492 self.permissions_global.add(perm.permission.permission_name)
492 self.permissions_global.add(perm.permission.permission_name)
493
493
494 # user explicit global permissions
494 # user explicit global permissions
495 user_perms = Session().query(UserToPerm)\
495 user_perms = Session().query(UserToPerm)\
496 .options(joinedload(UserToPerm.permission))\
496 .options(joinedload(UserToPerm.permission))\
497 .filter(UserToPerm.user_id == self.user_id).all()
497 .filter(UserToPerm.user_id == self.user_id).all()
498
498
499 if not self.inherit_default_permissions:
499 if not self.inherit_default_permissions:
500 # NEED TO IGNORE all configurable permissions and
500 # NEED TO IGNORE all configurable permissions and
501 # replace them with explicitly set from this user permissions
501 # replace them with explicitly set from this user permissions
502 self.permissions_global = self.permissions_global.difference(
502 self.permissions_global = self.permissions_global.difference(
503 _configurable)
503 _configurable)
504 for perm in user_perms:
504 for perm in user_perms:
505 self.permissions_global.add(perm.permission.permission_name)
505 self.permissions_global.add(perm.permission.permission_name)
506
506
507 def _calculate_default_permissions(self):
507 def _calculate_default_permissions(self):
508 """
508 """
509 Set default user permissions for repositories, repository groups
509 Set default user permissions for repositories, repository groups
510 taken from the default user.
510 taken from the default user.
511
511
512 Calculate inheritance of object permissions based on what we have now
512 Calculate inheritance of object permissions based on what we have now
513 in GLOBAL permissions. We check if .false is in GLOBAL since this is
513 in GLOBAL permissions. We check if .false is in GLOBAL since this is
514 explicitly set. Inherit is the opposite of .false being there.
514 explicitly set. Inherit is the opposite of .false being there.
515
515
516 .. note::
516 .. note::
517
517
518 the syntax is little bit odd but what we need to check here is
518 the syntax is little bit odd but what we need to check here is
519 the opposite of .false permission being in the list so even for
519 the opposite of .false permission being in the list so even for
520 inconsistent state when both .true/.false is there
520 inconsistent state when both .true/.false is there
521 .false is more important
521 .false is more important
522
522
523 """
523 """
524 user_inherit_object_permissions = not ('hg.inherit_default_perms.false'
524 user_inherit_object_permissions = not ('hg.inherit_default_perms.false'
525 in self.permissions_global)
525 in self.permissions_global)
526
526
527 # defaults for repositories, taken from `default` user permissions
527 # defaults for repositories, taken from `default` user permissions
528 # on given repo
528 # on given repo
529 for perm in self.default_repo_perms:
529 for perm in self.default_repo_perms:
530 r_k = perm.UserRepoToPerm.repository.repo_name
530 r_k = perm.UserRepoToPerm.repository.repo_name
531 o = PermOrigin.REPO_DEFAULT
531 o = PermOrigin.REPO_DEFAULT
532 if perm.Repository.private and not (
532 if perm.Repository.private and not (
533 perm.Repository.user_id == self.user_id):
533 perm.Repository.user_id == self.user_id):
534 # disable defaults for private repos,
534 # disable defaults for private repos,
535 p = 'repository.none'
535 p = 'repository.none'
536 o = PermOrigin.REPO_PRIVATE
536 o = PermOrigin.REPO_PRIVATE
537 elif perm.Repository.user_id == self.user_id:
537 elif perm.Repository.user_id == self.user_id:
538 # set admin if owner
538 # set admin if owner
539 p = 'repository.admin'
539 p = 'repository.admin'
540 o = PermOrigin.REPO_OWNER
540 o = PermOrigin.REPO_OWNER
541 else:
541 else:
542 p = perm.Permission.permission_name
542 p = perm.Permission.permission_name
543 # if we decide this user isn't inheriting permissions from
543 # if we decide this user isn't inheriting permissions from
544 # default user we set him to .none so only explicit
544 # default user we set him to .none so only explicit
545 # permissions work
545 # permissions work
546 if not user_inherit_object_permissions:
546 if not user_inherit_object_permissions:
547 p = 'repository.none'
547 p = 'repository.none'
548 self.permissions_repositories[r_k] = p, o
548 self.permissions_repositories[r_k] = p, o
549
549
550 # defaults for repository groups taken from `default` user permission
550 # defaults for repository groups taken from `default` user permission
551 # on given group
551 # on given group
552 for perm in self.default_repo_groups_perms:
552 for perm in self.default_repo_groups_perms:
553 rg_k = perm.UserRepoGroupToPerm.group.group_name
553 rg_k = perm.UserRepoGroupToPerm.group.group_name
554 o = PermOrigin.REPOGROUP_DEFAULT
554 o = PermOrigin.REPOGROUP_DEFAULT
555 if perm.RepoGroup.user_id == self.user_id:
555 if perm.RepoGroup.user_id == self.user_id:
556 # set admin if owner
556 # set admin if owner
557 p = 'group.admin'
557 p = 'group.admin'
558 o = PermOrigin.REPOGROUP_OWNER
558 o = PermOrigin.REPOGROUP_OWNER
559 else:
559 else:
560 p = perm.Permission.permission_name
560 p = perm.Permission.permission_name
561
561
562 # if we decide this user isn't inheriting permissions from default
562 # if we decide this user isn't inheriting permissions from default
563 # user we set him to .none so only explicit permissions work
563 # user we set him to .none so only explicit permissions work
564 if not user_inherit_object_permissions:
564 if not user_inherit_object_permissions:
565 p = 'group.none'
565 p = 'group.none'
566 self.permissions_repository_groups[rg_k] = p, o
566 self.permissions_repository_groups[rg_k] = p, o
567
567
568 # defaults for user groups taken from `default` user permission
568 # defaults for user groups taken from `default` user permission
569 # on given user group
569 # on given user group
570 for perm in self.default_user_group_perms:
570 for perm in self.default_user_group_perms:
571 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
571 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
572 o = PermOrigin.USERGROUP_DEFAULT
572 o = PermOrigin.USERGROUP_DEFAULT
573 if perm.UserGroup.user_id == self.user_id:
573 if perm.UserGroup.user_id == self.user_id:
574 # set admin if owner
574 # set admin if owner
575 p = 'usergroup.admin'
575 p = 'usergroup.admin'
576 o = PermOrigin.USERGROUP_OWNER
576 o = PermOrigin.USERGROUP_OWNER
577 else:
577 else:
578 p = perm.Permission.permission_name
578 p = perm.Permission.permission_name
579
579
580 # if we decide this user isn't inheriting permissions from default
580 # if we decide this user isn't inheriting permissions from default
581 # user we set him to .none so only explicit permissions work
581 # user we set him to .none so only explicit permissions work
582 if not user_inherit_object_permissions:
582 if not user_inherit_object_permissions:
583 p = 'usergroup.none'
583 p = 'usergroup.none'
584 self.permissions_user_groups[u_k] = p, o
584 self.permissions_user_groups[u_k] = p, o
585
585
586 def _calculate_repository_permissions(self):
586 def _calculate_repository_permissions(self):
587 """
587 """
588 Repository permissions for the current user.
588 Repository permissions for the current user.
589
589
590 Check if the user is part of user groups for this repository and
590 Check if the user is part of user groups for this repository and
591 fill in the permission from it. `_choose_permission` decides of which
591 fill in the permission from it. `_choose_permission` decides of which
592 permission should be selected based on selected method.
592 permission should be selected based on selected method.
593 """
593 """
594
594
595 # user group for repositories permissions
595 # user group for repositories permissions
596 user_repo_perms_from_user_group = Permission\
596 user_repo_perms_from_user_group = Permission\
597 .get_default_repo_perms_from_user_group(
597 .get_default_repo_perms_from_user_group(
598 self.user_id, self.scope_repo_id)
598 self.user_id, self.scope_repo_id)
599
599
600 multiple_counter = collections.defaultdict(int)
600 multiple_counter = collections.defaultdict(int)
601 for perm in user_repo_perms_from_user_group:
601 for perm in user_repo_perms_from_user_group:
602 r_k = perm.UserGroupRepoToPerm.repository.repo_name
602 r_k = perm.UserGroupRepoToPerm.repository.repo_name
603 ug_k = perm.UserGroupRepoToPerm.users_group.users_group_name
603 ug_k = perm.UserGroupRepoToPerm.users_group.users_group_name
604 multiple_counter[r_k] += 1
604 multiple_counter[r_k] += 1
605 p = perm.Permission.permission_name
605 p = perm.Permission.permission_name
606 o = PermOrigin.REPO_USERGROUP % ug_k
606 o = PermOrigin.REPO_USERGROUP % ug_k
607
607
608 if perm.Repository.user_id == self.user_id:
608 if perm.Repository.user_id == self.user_id:
609 # set admin if owner
609 # set admin if owner
610 p = 'repository.admin'
610 p = 'repository.admin'
611 o = PermOrigin.REPO_OWNER
611 o = PermOrigin.REPO_OWNER
612 else:
612 else:
613 if multiple_counter[r_k] > 1:
613 if multiple_counter[r_k] > 1:
614 cur_perm = self.permissions_repositories[r_k]
614 cur_perm = self.permissions_repositories[r_k]
615 p = self._choose_permission(p, cur_perm)
615 p = self._choose_permission(p, cur_perm)
616 self.permissions_repositories[r_k] = p, o
616 self.permissions_repositories[r_k] = p, o
617
617
618 # user explicit permissions for repositories, overrides any specified
618 # user explicit permissions for repositories, overrides any specified
619 # by the group permission
619 # by the group permission
620 user_repo_perms = Permission.get_default_repo_perms(
620 user_repo_perms = Permission.get_default_repo_perms(
621 self.user_id, self.scope_repo_id)
621 self.user_id, self.scope_repo_id)
622 for perm in user_repo_perms:
622 for perm in user_repo_perms:
623 r_k = perm.UserRepoToPerm.repository.repo_name
623 r_k = perm.UserRepoToPerm.repository.repo_name
624 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
624 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
625 # set admin if owner
625 # set admin if owner
626 if perm.Repository.user_id == self.user_id:
626 if perm.Repository.user_id == self.user_id:
627 p = 'repository.admin'
627 p = 'repository.admin'
628 o = PermOrigin.REPO_OWNER
628 o = PermOrigin.REPO_OWNER
629 else:
629 else:
630 p = perm.Permission.permission_name
630 p = perm.Permission.permission_name
631 if not self.explicit:
631 if not self.explicit:
632 cur_perm = self.permissions_repositories.get(
632 cur_perm = self.permissions_repositories.get(
633 r_k, 'repository.none')
633 r_k, 'repository.none')
634 p = self._choose_permission(p, cur_perm)
634 p = self._choose_permission(p, cur_perm)
635 self.permissions_repositories[r_k] = p, o
635 self.permissions_repositories[r_k] = p, o
636
636
637 def _calculate_repository_group_permissions(self):
637 def _calculate_repository_group_permissions(self):
638 """
638 """
639 Repository group permissions for the current user.
639 Repository group permissions for the current user.
640
640
641 Check if the user is part of user groups for repository groups and
641 Check if the user is part of user groups for repository groups and
642 fill in the permissions from it. `_choose_permmission` decides of which
642 fill in the permissions from it. `_choose_permmission` decides of which
643 permission should be selected based on selected method.
643 permission should be selected based on selected method.
644 """
644 """
645 # user group for repo groups permissions
645 # user group for repo groups permissions
646 user_repo_group_perms_from_user_group = Permission\
646 user_repo_group_perms_from_user_group = Permission\
647 .get_default_group_perms_from_user_group(
647 .get_default_group_perms_from_user_group(
648 self.user_id, self.scope_repo_group_id)
648 self.user_id, self.scope_repo_group_id)
649
649
650 multiple_counter = collections.defaultdict(int)
650 multiple_counter = collections.defaultdict(int)
651 for perm in user_repo_group_perms_from_user_group:
651 for perm in user_repo_group_perms_from_user_group:
652 g_k = perm.UserGroupRepoGroupToPerm.group.group_name
652 g_k = perm.UserGroupRepoGroupToPerm.group.group_name
653 ug_k = perm.UserGroupRepoGroupToPerm.users_group.users_group_name
653 ug_k = perm.UserGroupRepoGroupToPerm.users_group.users_group_name
654 o = PermOrigin.REPOGROUP_USERGROUP % ug_k
654 o = PermOrigin.REPOGROUP_USERGROUP % ug_k
655 multiple_counter[g_k] += 1
655 multiple_counter[g_k] += 1
656 p = perm.Permission.permission_name
656 p = perm.Permission.permission_name
657 if perm.RepoGroup.user_id == self.user_id:
657 if perm.RepoGroup.user_id == self.user_id:
658 # set admin if owner, even for member of other user group
658 # set admin if owner, even for member of other user group
659 p = 'group.admin'
659 p = 'group.admin'
660 o = PermOrigin.REPOGROUP_OWNER
660 o = PermOrigin.REPOGROUP_OWNER
661 else:
661 else:
662 if multiple_counter[g_k] > 1:
662 if multiple_counter[g_k] > 1:
663 cur_perm = self.permissions_repository_groups[g_k]
663 cur_perm = self.permissions_repository_groups[g_k]
664 p = self._choose_permission(p, cur_perm)
664 p = self._choose_permission(p, cur_perm)
665 self.permissions_repository_groups[g_k] = p, o
665 self.permissions_repository_groups[g_k] = p, o
666
666
667 # user explicit permissions for repository groups
667 # user explicit permissions for repository groups
668 user_repo_groups_perms = Permission.get_default_group_perms(
668 user_repo_groups_perms = Permission.get_default_group_perms(
669 self.user_id, self.scope_repo_group_id)
669 self.user_id, self.scope_repo_group_id)
670 for perm in user_repo_groups_perms:
670 for perm in user_repo_groups_perms:
671 rg_k = perm.UserRepoGroupToPerm.group.group_name
671 rg_k = perm.UserRepoGroupToPerm.group.group_name
672 u_k = perm.UserRepoGroupToPerm.user.username
672 u_k = perm.UserRepoGroupToPerm.user.username
673 o = PermOrigin.REPOGROUP_USER % u_k
673 o = PermOrigin.REPOGROUP_USER % u_k
674
674
675 if perm.RepoGroup.user_id == self.user_id:
675 if perm.RepoGroup.user_id == self.user_id:
676 # set admin if owner
676 # set admin if owner
677 p = 'group.admin'
677 p = 'group.admin'
678 o = PermOrigin.REPOGROUP_OWNER
678 o = PermOrigin.REPOGROUP_OWNER
679 else:
679 else:
680 p = perm.Permission.permission_name
680 p = perm.Permission.permission_name
681 if not self.explicit:
681 if not self.explicit:
682 cur_perm = self.permissions_repository_groups.get(
682 cur_perm = self.permissions_repository_groups.get(
683 rg_k, 'group.none')
683 rg_k, 'group.none')
684 p = self._choose_permission(p, cur_perm)
684 p = self._choose_permission(p, cur_perm)
685 self.permissions_repository_groups[rg_k] = p, o
685 self.permissions_repository_groups[rg_k] = p, o
686
686
687 def _calculate_user_group_permissions(self):
687 def _calculate_user_group_permissions(self):
688 """
688 """
689 User group permissions for the current user.
689 User group permissions for the current user.
690 """
690 """
691 # user group for user group permissions
691 # user group for user group permissions
692 user_group_from_user_group = Permission\
692 user_group_from_user_group = Permission\
693 .get_default_user_group_perms_from_user_group(
693 .get_default_user_group_perms_from_user_group(
694 self.user_id, self.scope_user_group_id)
694 self.user_id, self.scope_user_group_id)
695
695
696 multiple_counter = collections.defaultdict(int)
696 multiple_counter = collections.defaultdict(int)
697 for perm in user_group_from_user_group:
697 for perm in user_group_from_user_group:
698 g_k = perm.UserGroupUserGroupToPerm\
698 g_k = perm.UserGroupUserGroupToPerm\
699 .target_user_group.users_group_name
699 .target_user_group.users_group_name
700 u_k = perm.UserGroupUserGroupToPerm\
700 u_k = perm.UserGroupUserGroupToPerm\
701 .user_group.users_group_name
701 .user_group.users_group_name
702 o = PermOrigin.USERGROUP_USERGROUP % u_k
702 o = PermOrigin.USERGROUP_USERGROUP % u_k
703 multiple_counter[g_k] += 1
703 multiple_counter[g_k] += 1
704 p = perm.Permission.permission_name
704 p = perm.Permission.permission_name
705
705
706 if perm.UserGroup.user_id == self.user_id:
706 if perm.UserGroup.user_id == self.user_id:
707 # set admin if owner, even for member of other user group
707 # set admin if owner, even for member of other user group
708 p = 'usergroup.admin'
708 p = 'usergroup.admin'
709 o = PermOrigin.USERGROUP_OWNER
709 o = PermOrigin.USERGROUP_OWNER
710 else:
710 else:
711 if multiple_counter[g_k] > 1:
711 if multiple_counter[g_k] > 1:
712 cur_perm = self.permissions_user_groups[g_k]
712 cur_perm = self.permissions_user_groups[g_k]
713 p = self._choose_permission(p, cur_perm)
713 p = self._choose_permission(p, cur_perm)
714 self.permissions_user_groups[g_k] = p, o
714 self.permissions_user_groups[g_k] = p, o
715
715
716 # user explicit permission for user groups
716 # user explicit permission for user groups
717 user_user_groups_perms = Permission.get_default_user_group_perms(
717 user_user_groups_perms = Permission.get_default_user_group_perms(
718 self.user_id, self.scope_user_group_id)
718 self.user_id, self.scope_user_group_id)
719 for perm in user_user_groups_perms:
719 for perm in user_user_groups_perms:
720 ug_k = perm.UserUserGroupToPerm.user_group.users_group_name
720 ug_k = perm.UserUserGroupToPerm.user_group.users_group_name
721 u_k = perm.UserUserGroupToPerm.user.username
721 u_k = perm.UserUserGroupToPerm.user.username
722 o = PermOrigin.USERGROUP_USER % u_k
722 o = PermOrigin.USERGROUP_USER % u_k
723
723
724 if perm.UserGroup.user_id == self.user_id:
724 if perm.UserGroup.user_id == self.user_id:
725 # set admin if owner
725 # set admin if owner
726 p = 'usergroup.admin'
726 p = 'usergroup.admin'
727 o = PermOrigin.USERGROUP_OWNER
727 o = PermOrigin.USERGROUP_OWNER
728 else:
728 else:
729 p = perm.Permission.permission_name
729 p = perm.Permission.permission_name
730 if not self.explicit:
730 if not self.explicit:
731 cur_perm = self.permissions_user_groups.get(
731 cur_perm = self.permissions_user_groups.get(
732 ug_k, 'usergroup.none')
732 ug_k, 'usergroup.none')
733 p = self._choose_permission(p, cur_perm)
733 p = self._choose_permission(p, cur_perm)
734 self.permissions_user_groups[ug_k] = p, o
734 self.permissions_user_groups[ug_k] = p, o
735
735
736 def _choose_permission(self, new_perm, cur_perm):
736 def _choose_permission(self, new_perm, cur_perm):
737 new_perm_val = Permission.PERM_WEIGHTS[new_perm]
737 new_perm_val = Permission.PERM_WEIGHTS[new_perm]
738 cur_perm_val = Permission.PERM_WEIGHTS[cur_perm]
738 cur_perm_val = Permission.PERM_WEIGHTS[cur_perm]
739 if self.algo == 'higherwin':
739 if self.algo == 'higherwin':
740 if new_perm_val > cur_perm_val:
740 if new_perm_val > cur_perm_val:
741 return new_perm
741 return new_perm
742 return cur_perm
742 return cur_perm
743 elif self.algo == 'lowerwin':
743 elif self.algo == 'lowerwin':
744 if new_perm_val < cur_perm_val:
744 if new_perm_val < cur_perm_val:
745 return new_perm
745 return new_perm
746 return cur_perm
746 return cur_perm
747
747
748 def _permission_structure(self):
748 def _permission_structure(self):
749 return {
749 return {
750 'global': self.permissions_global,
750 'global': self.permissions_global,
751 'repositories': self.permissions_repositories,
751 'repositories': self.permissions_repositories,
752 'repositories_groups': self.permissions_repository_groups,
752 'repositories_groups': self.permissions_repository_groups,
753 'user_groups': self.permissions_user_groups,
753 'user_groups': self.permissions_user_groups,
754 }
754 }
755
755
756
756
757 def allowed_auth_token_access(controller_name, whitelist=None, auth_token=None):
757 def allowed_auth_token_access(controller_name, whitelist=None, auth_token=None):
758 """
758 """
759 Check if given controller_name is in whitelist of auth token access
759 Check if given controller_name is in whitelist of auth token access
760 """
760 """
761 if not whitelist:
761 if not whitelist:
762 from rhodecode import CONFIG
762 from rhodecode import CONFIG
763 whitelist = aslist(
763 whitelist = aslist(
764 CONFIG.get('api_access_controllers_whitelist'), sep=',')
764 CONFIG.get('api_access_controllers_whitelist'), sep=',')
765 log.debug(
765 log.debug(
766 'Allowed controllers for AUTH TOKEN access: %s' % (whitelist,))
766 'Allowed controllers for AUTH TOKEN access: %s' % (whitelist,))
767
767
768 auth_token_access_valid = False
768 auth_token_access_valid = False
769 for entry in whitelist:
769 for entry in whitelist:
770 if fnmatch.fnmatch(controller_name, entry):
770 if fnmatch.fnmatch(controller_name, entry):
771 auth_token_access_valid = True
771 auth_token_access_valid = True
772 break
772 break
773
773
774 if auth_token_access_valid:
774 if auth_token_access_valid:
775 log.debug('controller:%s matches entry in whitelist'
775 log.debug('controller:%s matches entry in whitelist'
776 % (controller_name,))
776 % (controller_name,))
777 else:
777 else:
778 msg = ('controller: %s does *NOT* match any entry in whitelist'
778 msg = ('controller: %s does *NOT* match any entry in whitelist'
779 % (controller_name,))
779 % (controller_name,))
780 if auth_token:
780 if auth_token:
781 # if we use auth token key and don't have access it's a warning
781 # if we use auth token key and don't have access it's a warning
782 log.warning(msg)
782 log.warning(msg)
783 else:
783 else:
784 log.debug(msg)
784 log.debug(msg)
785
785
786 return auth_token_access_valid
786 return auth_token_access_valid
787
787
788
788
789 class AuthUser(object):
789 class AuthUser(object):
790 """
790 """
791 A simple object that handles all attributes of user in RhodeCode
791 A simple object that handles all attributes of user in RhodeCode
792
792
793 It does lookup based on API key,given user, or user present in session
793 It does lookup based on API key,given user, or user present in session
794 Then it fills all required information for such user. It also checks if
794 Then it fills all required information for such user. It also checks if
795 anonymous access is enabled and if so, it returns default user as logged in
795 anonymous access is enabled and if so, it returns default user as logged in
796 """
796 """
797 GLOBAL_PERMS = [x[0] for x in Permission.PERMS]
797 GLOBAL_PERMS = [x[0] for x in Permission.PERMS]
798
798
799 def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None):
799 def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None):
800
800
801 self.user_id = user_id
801 self.user_id = user_id
802 self._api_key = api_key
802 self._api_key = api_key
803
803
804 self.api_key = None
804 self.api_key = None
805 self.feed_token = ''
805 self.feed_token = ''
806 self.username = username
806 self.username = username
807 self.ip_addr = ip_addr
807 self.ip_addr = ip_addr
808 self.name = ''
808 self.name = ''
809 self.lastname = ''
809 self.lastname = ''
810 self.email = ''
810 self.email = ''
811 self.is_authenticated = False
811 self.is_authenticated = False
812 self.admin = False
812 self.admin = False
813 self.inherit_default_permissions = False
813 self.inherit_default_permissions = False
814 self.password = ''
814 self.password = ''
815
815
816 self.anonymous_user = None # propagated on propagate_data
816 self.anonymous_user = None # propagated on propagate_data
817 self.propagate_data()
817 self.propagate_data()
818 self._instance = None
818 self._instance = None
819 self._permissions_scoped_cache = {} # used to bind scoped calculation
819 self._permissions_scoped_cache = {} # used to bind scoped calculation
820
820
821 @LazyProperty
821 @LazyProperty
822 def permissions(self):
822 def permissions(self):
823 return self.get_perms(user=self, cache=False)
823 return self.get_perms(user=self, cache=False)
824
824
825 def permissions_with_scope(self, scope):
825 def permissions_with_scope(self, scope):
826 """
826 """
827 Call the get_perms function with scoped data. The scope in that function
827 Call the get_perms function with scoped data. The scope in that function
828 narrows the SQL calls to the given ID of objects resulting in fetching
828 narrows the SQL calls to the given ID of objects resulting in fetching
829 Just particular permission we want to obtain. If scope is an empty dict
829 Just particular permission we want to obtain. If scope is an empty dict
830 then it basically narrows the scope to GLOBAL permissions only.
830 then it basically narrows the scope to GLOBAL permissions only.
831
831
832 :param scope: dict
832 :param scope: dict
833 """
833 """
834 if 'repo_name' in scope:
834 if 'repo_name' in scope:
835 obj = Repository.get_by_repo_name(scope['repo_name'])
835 obj = Repository.get_by_repo_name(scope['repo_name'])
836 if obj:
836 if obj:
837 scope['repo_id'] = obj.repo_id
837 scope['repo_id'] = obj.repo_id
838 _scope = {
838 _scope = {
839 'repo_id': -1,
839 'repo_id': -1,
840 'user_group_id': -1,
840 'user_group_id': -1,
841 'repo_group_id': -1,
841 'repo_group_id': -1,
842 }
842 }
843 _scope.update(scope)
843 _scope.update(scope)
844 cache_key = "_".join(map(safe_str, reduce(lambda a, b: a+b,
844 cache_key = "_".join(map(safe_str, reduce(lambda a, b: a+b,
845 _scope.items())))
845 _scope.items())))
846 if cache_key not in self._permissions_scoped_cache:
846 if cache_key not in self._permissions_scoped_cache:
847 # store in cache to mimic how the @LazyProperty works,
847 # store in cache to mimic how the @LazyProperty works,
848 # the difference here is that we use the unique key calculated
848 # the difference here is that we use the unique key calculated
849 # from params and values
849 # from params and values
850 res = self.get_perms(user=self, cache=False, scope=_scope)
850 res = self.get_perms(user=self, cache=False, scope=_scope)
851 self._permissions_scoped_cache[cache_key] = res
851 self._permissions_scoped_cache[cache_key] = res
852 return self._permissions_scoped_cache[cache_key]
852 return self._permissions_scoped_cache[cache_key]
853
853
854 def get_instance(self):
854 def get_instance(self):
855 return User.get(self.user_id)
855 return User.get(self.user_id)
856
856
857 def update_lastactivity(self):
857 def update_lastactivity(self):
858 if self.user_id:
858 if self.user_id:
859 User.get(self.user_id).update_lastactivity()
859 User.get(self.user_id).update_lastactivity()
860
860
861 def propagate_data(self):
861 def propagate_data(self):
862 """
862 """
863 Fills in user data and propagates values to this instance. Maps fetched
863 Fills in user data and propagates values to this instance. Maps fetched
864 user attributes to this class instance attributes
864 user attributes to this class instance attributes
865 """
865 """
866 log.debug('starting data propagation for new potential AuthUser')
866 log.debug('starting data propagation for new potential AuthUser')
867 user_model = UserModel()
867 user_model = UserModel()
868 anon_user = self.anonymous_user = User.get_default_user(cache=True)
868 anon_user = self.anonymous_user = User.get_default_user(cache=True)
869 is_user_loaded = False
869 is_user_loaded = False
870
870
871 # lookup by userid
871 # lookup by userid
872 if self.user_id is not None and self.user_id != anon_user.user_id:
872 if self.user_id is not None and self.user_id != anon_user.user_id:
873 log.debug('Trying Auth User lookup by USER ID: `%s`' % self.user_id)
873 log.debug('Trying Auth User lookup by USER ID: `%s`' % self.user_id)
874 is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
874 is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
875
875
876 # try go get user by api key
876 # try go get user by api key
877 elif self._api_key and self._api_key != anon_user.api_key:
877 elif self._api_key and self._api_key != anon_user.api_key:
878 log.debug('Trying Auth User lookup by API KEY: `%s`' % self._api_key)
878 log.debug('Trying Auth User lookup by API KEY: `%s`' % self._api_key)
879 is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
879 is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
880
880
881 # lookup by username
881 # lookup by username
882 elif self.username:
882 elif self.username:
883 log.debug('Trying Auth User lookup by USER NAME: `%s`' % self.username)
883 log.debug('Trying Auth User lookup by USER NAME: `%s`' % self.username)
884 is_user_loaded = user_model.fill_data(self, username=self.username)
884 is_user_loaded = user_model.fill_data(self, username=self.username)
885 else:
885 else:
886 log.debug('No data in %s that could been used to log in' % self)
886 log.debug('No data in %s that could been used to log in' % self)
887
887
888 if not is_user_loaded:
888 if not is_user_loaded:
889 log.debug('Failed to load user. Fallback to default user')
889 log.debug('Failed to load user. Fallback to default user')
890 # if we cannot authenticate user try anonymous
890 # if we cannot authenticate user try anonymous
891 if anon_user.active:
891 if anon_user.active:
892 user_model.fill_data(self, user_id=anon_user.user_id)
892 user_model.fill_data(self, user_id=anon_user.user_id)
893 # then we set this user is logged in
893 # then we set this user is logged in
894 self.is_authenticated = True
894 self.is_authenticated = True
895 else:
895 else:
896 # in case of disabled anonymous user we reset some of the
896 # in case of disabled anonymous user we reset some of the
897 # parameters so such user is "corrupted", skipping the fill_data
897 # parameters so such user is "corrupted", skipping the fill_data
898 for attr in ['user_id', 'username', 'admin', 'active']:
898 for attr in ['user_id', 'username', 'admin', 'active']:
899 setattr(self, attr, None)
899 setattr(self, attr, None)
900 self.is_authenticated = False
900 self.is_authenticated = False
901
901
902 if not self.username:
902 if not self.username:
903 self.username = 'None'
903 self.username = 'None'
904
904
905 log.debug('Auth User is now %s' % self)
905 log.debug('Auth User is now %s' % self)
906
906
907 def get_perms(self, user, scope=None, explicit=True, algo='higherwin',
907 def get_perms(self, user, scope=None, explicit=True, algo='higherwin',
908 cache=False):
908 cache=False):
909 """
909 """
910 Fills user permission attribute with permissions taken from database
910 Fills user permission attribute with permissions taken from database
911 works for permissions given for repositories, and for permissions that
911 works for permissions given for repositories, and for permissions that
912 are granted to groups
912 are granted to groups
913
913
914 :param user: instance of User object from database
914 :param user: instance of User object from database
915 :param explicit: In case there are permissions both for user and a group
915 :param explicit: In case there are permissions both for user and a group
916 that user is part of, explicit flag will defiine if user will
916 that user is part of, explicit flag will defiine if user will
917 explicitly override permissions from group, if it's False it will
917 explicitly override permissions from group, if it's False it will
918 make decision based on the algo
918 make decision based on the algo
919 :param algo: algorithm to decide what permission should be choose if
919 :param algo: algorithm to decide what permission should be choose if
920 it's multiple defined, eg user in two different groups. It also
920 it's multiple defined, eg user in two different groups. It also
921 decides if explicit flag is turned off how to specify the permission
921 decides if explicit flag is turned off how to specify the permission
922 for case when user is in a group + have defined separate permission
922 for case when user is in a group + have defined separate permission
923 """
923 """
924 user_id = user.user_id
924 user_id = user.user_id
925 user_is_admin = user.is_admin
925 user_is_admin = user.is_admin
926
926
927 # inheritance of global permissions like create repo/fork repo etc
927 # inheritance of global permissions like create repo/fork repo etc
928 user_inherit_default_permissions = user.inherit_default_permissions
928 user_inherit_default_permissions = user.inherit_default_permissions
929
929
930 log.debug('Computing PERMISSION tree for scope %s' % (scope, ))
930 log.debug('Computing PERMISSION tree for scope %s' % (scope, ))
931 compute = caches.conditional_cache(
931 compute = caches.conditional_cache(
932 'short_term', 'cache_desc',
932 'short_term', 'cache_desc',
933 condition=cache, func=_cached_perms_data)
933 condition=cache, func=_cached_perms_data)
934 result = compute(user_id, scope, user_is_admin,
934 result = compute(user_id, scope, user_is_admin,
935 user_inherit_default_permissions, explicit, algo)
935 user_inherit_default_permissions, explicit, algo)
936
936
937 result_repr = []
937 result_repr = []
938 for k in result:
938 for k in result:
939 result_repr.append((k, len(result[k])))
939 result_repr.append((k, len(result[k])))
940
940
941 log.debug('PERMISSION tree computed %s' % (result_repr,))
941 log.debug('PERMISSION tree computed %s' % (result_repr,))
942 return result
942 return result
943
943
944 @property
944 @property
945 def is_default(self):
945 def is_default(self):
946 return self.username == User.DEFAULT_USER
946 return self.username == User.DEFAULT_USER
947
947
948 @property
948 @property
949 def is_admin(self):
949 def is_admin(self):
950 return self.admin
950 return self.admin
951
951
952 @property
952 @property
953 def is_user_object(self):
953 def is_user_object(self):
954 return self.user_id is not None
954 return self.user_id is not None
955
955
956 @property
956 @property
957 def repositories_admin(self):
957 def repositories_admin(self):
958 """
958 """
959 Returns list of repositories you're an admin of
959 Returns list of repositories you're an admin of
960 """
960 """
961 return [
961 return [
962 x[0] for x in self.permissions['repositories'].iteritems()
962 x[0] for x in self.permissions['repositories'].iteritems()
963 if x[1] == 'repository.admin']
963 if x[1] == 'repository.admin']
964
964
965 @property
965 @property
966 def repository_groups_admin(self):
966 def repository_groups_admin(self):
967 """
967 """
968 Returns list of repository groups you're an admin of
968 Returns list of repository groups you're an admin of
969 """
969 """
970 return [
970 return [
971 x[0] for x in self.permissions['repositories_groups'].iteritems()
971 x[0] for x in self.permissions['repositories_groups'].iteritems()
972 if x[1] == 'group.admin']
972 if x[1] == 'group.admin']
973
973
974 @property
974 @property
975 def user_groups_admin(self):
975 def user_groups_admin(self):
976 """
976 """
977 Returns list of user groups you're an admin of
977 Returns list of user groups you're an admin of
978 """
978 """
979 return [
979 return [
980 x[0] for x in self.permissions['user_groups'].iteritems()
980 x[0] for x in self.permissions['user_groups'].iteritems()
981 if x[1] == 'usergroup.admin']
981 if x[1] == 'usergroup.admin']
982
982
983 @property
983 @property
984 def ip_allowed(self):
984 def ip_allowed(self):
985 """
985 """
986 Checks if ip_addr used in constructor is allowed from defined list of
986 Checks if ip_addr used in constructor is allowed from defined list of
987 allowed ip_addresses for user
987 allowed ip_addresses for user
988
988
989 :returns: boolean, True if ip is in allowed ip range
989 :returns: boolean, True if ip is in allowed ip range
990 """
990 """
991 # check IP
991 # check IP
992 inherit = self.inherit_default_permissions
992 inherit = self.inherit_default_permissions
993 return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
993 return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
994 inherit_from_default=inherit)
994 inherit_from_default=inherit)
995 @property
995 @property
996 def personal_repo_group(self):
996 def personal_repo_group(self):
997 return RepoGroup.get_user_personal_repo_group(self.user_id)
997 return RepoGroup.get_user_personal_repo_group(self.user_id)
998
998
999 @classmethod
999 @classmethod
1000 def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
1000 def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
1001 allowed_ips = AuthUser.get_allowed_ips(
1001 allowed_ips = AuthUser.get_allowed_ips(
1002 user_id, cache=True, inherit_from_default=inherit_from_default)
1002 user_id, cache=True, inherit_from_default=inherit_from_default)
1003 if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
1003 if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
1004 log.debug('IP:%s is in range of %s' % (ip_addr, allowed_ips))
1004 log.debug('IP:%s is in range of %s' % (ip_addr, allowed_ips))
1005 return True
1005 return True
1006 else:
1006 else:
1007 log.info('Access for IP:%s forbidden, '
1007 log.info('Access for IP:%s forbidden, '
1008 'not in %s' % (ip_addr, allowed_ips))
1008 'not in %s' % (ip_addr, allowed_ips))
1009 return False
1009 return False
1010
1010
1011 def __repr__(self):
1011 def __repr__(self):
1012 return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
1012 return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
1013 % (self.user_id, self.username, self.ip_addr, self.is_authenticated)
1013 % (self.user_id, self.username, self.ip_addr, self.is_authenticated)
1014
1014
1015 def set_authenticated(self, authenticated=True):
1015 def set_authenticated(self, authenticated=True):
1016 if self.user_id != self.anonymous_user.user_id:
1016 if self.user_id != self.anonymous_user.user_id:
1017 self.is_authenticated = authenticated
1017 self.is_authenticated = authenticated
1018
1018
1019 def get_cookie_store(self):
1019 def get_cookie_store(self):
1020 return {
1020 return {
1021 'username': self.username,
1021 'username': self.username,
1022 'password': md5(self.password),
1022 'password': md5(self.password),
1023 'user_id': self.user_id,
1023 'user_id': self.user_id,
1024 'is_authenticated': self.is_authenticated
1024 'is_authenticated': self.is_authenticated
1025 }
1025 }
1026
1026
1027 @classmethod
1027 @classmethod
1028 def from_cookie_store(cls, cookie_store):
1028 def from_cookie_store(cls, cookie_store):
1029 """
1029 """
1030 Creates AuthUser from a cookie store
1030 Creates AuthUser from a cookie store
1031
1031
1032 :param cls:
1032 :param cls:
1033 :param cookie_store:
1033 :param cookie_store:
1034 """
1034 """
1035 user_id = cookie_store.get('user_id')
1035 user_id = cookie_store.get('user_id')
1036 username = cookie_store.get('username')
1036 username = cookie_store.get('username')
1037 api_key = cookie_store.get('api_key')
1037 api_key = cookie_store.get('api_key')
1038 return AuthUser(user_id, api_key, username)
1038 return AuthUser(user_id, api_key, username)
1039
1039
1040 @classmethod
1040 @classmethod
1041 def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
1041 def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
1042 _set = set()
1042 _set = set()
1043
1043
1044 if inherit_from_default:
1044 if inherit_from_default:
1045 default_ips = UserIpMap.query().filter(
1045 default_ips = UserIpMap.query().filter(
1046 UserIpMap.user == User.get_default_user(cache=True))
1046 UserIpMap.user == User.get_default_user(cache=True))
1047 if cache:
1047 if cache:
1048 default_ips = default_ips.options(FromCache("sql_cache_short",
1048 default_ips = default_ips.options(
1049 "get_user_ips_default"))
1049 FromCache("sql_cache_short", "get_user_ips_default"))
1050
1050
1051 # populate from default user
1051 # populate from default user
1052 for ip in default_ips:
1052 for ip in default_ips:
1053 try:
1053 try:
1054 _set.add(ip.ip_addr)
1054 _set.add(ip.ip_addr)
1055 except ObjectDeletedError:
1055 except ObjectDeletedError:
1056 # since we use heavy caching sometimes it happens that
1056 # since we use heavy caching sometimes it happens that
1057 # we get deleted objects here, we just skip them
1057 # we get deleted objects here, we just skip them
1058 pass
1058 pass
1059
1059
1060 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
1060 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
1061 if cache:
1061 if cache:
1062 user_ips = user_ips.options(FromCache("sql_cache_short",
1062 user_ips = user_ips.options(
1063 "get_user_ips_%s" % user_id))
1063 FromCache("sql_cache_short", "get_user_ips_%s" % user_id))
1064
1064
1065 for ip in user_ips:
1065 for ip in user_ips:
1066 try:
1066 try:
1067 _set.add(ip.ip_addr)
1067 _set.add(ip.ip_addr)
1068 except ObjectDeletedError:
1068 except ObjectDeletedError:
1069 # since we use heavy caching sometimes it happens that we get
1069 # since we use heavy caching sometimes it happens that we get
1070 # deleted objects here, we just skip them
1070 # deleted objects here, we just skip them
1071 pass
1071 pass
1072 return _set or set(['0.0.0.0/0', '::/0'])
1072 return _set or set(['0.0.0.0/0', '::/0'])
1073
1073
1074
1074
1075 def set_available_permissions(config):
1075 def set_available_permissions(config):
1076 """
1076 """
1077 This function will propagate pylons globals with all available defined
1077 This function will propagate pylons globals with all available defined
1078 permission given in db. We don't want to check each time from db for new
1078 permission given in db. We don't want to check each time from db for new
1079 permissions since adding a new permission also requires application restart
1079 permissions since adding a new permission also requires application restart
1080 ie. to decorate new views with the newly created permission
1080 ie. to decorate new views with the newly created permission
1081
1081
1082 :param config: current pylons config instance
1082 :param config: current pylons config instance
1083
1083
1084 """
1084 """
1085 log.info('getting information about all available permissions')
1085 log.info('getting information about all available permissions')
1086 try:
1086 try:
1087 sa = meta.Session
1087 sa = meta.Session
1088 all_perms = sa.query(Permission).all()
1088 all_perms = sa.query(Permission).all()
1089 config['available_permissions'] = [x.permission_name for x in all_perms]
1089 config['available_permissions'] = [x.permission_name for x in all_perms]
1090 except Exception:
1090 except Exception:
1091 log.error(traceback.format_exc())
1091 log.error(traceback.format_exc())
1092 finally:
1092 finally:
1093 meta.Session.remove()
1093 meta.Session.remove()
1094
1094
1095
1095
1096 def get_csrf_token(session=None, force_new=False, save_if_missing=True):
1096 def get_csrf_token(session=None, force_new=False, save_if_missing=True):
1097 """
1097 """
1098 Return the current authentication token, creating one if one doesn't
1098 Return the current authentication token, creating one if one doesn't
1099 already exist and the save_if_missing flag is present.
1099 already exist and the save_if_missing flag is present.
1100
1100
1101 :param session: pass in the pylons session, else we use the global ones
1101 :param session: pass in the pylons session, else we use the global ones
1102 :param force_new: force to re-generate the token and store it in session
1102 :param force_new: force to re-generate the token and store it in session
1103 :param save_if_missing: save the newly generated token if it's missing in
1103 :param save_if_missing: save the newly generated token if it's missing in
1104 session
1104 session
1105 """
1105 """
1106 if not session:
1106 if not session:
1107 from pylons import session
1107 from pylons import session
1108
1108
1109 if (csrf_token_key not in session and save_if_missing) or force_new:
1109 if (csrf_token_key not in session and save_if_missing) or force_new:
1110 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
1110 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
1111 session[csrf_token_key] = token
1111 session[csrf_token_key] = token
1112 if hasattr(session, 'save'):
1112 if hasattr(session, 'save'):
1113 session.save()
1113 session.save()
1114 return session.get(csrf_token_key)
1114 return session.get(csrf_token_key)
1115
1115
1116
1116
1117 # CHECK DECORATORS
1117 # CHECK DECORATORS
1118 class CSRFRequired(object):
1118 class CSRFRequired(object):
1119 """
1119 """
1120 Decorator for authenticating a form
1120 Decorator for authenticating a form
1121
1121
1122 This decorator uses an authorization token stored in the client's
1122 This decorator uses an authorization token stored in the client's
1123 session for prevention of certain Cross-site request forgery (CSRF)
1123 session for prevention of certain Cross-site request forgery (CSRF)
1124 attacks (See
1124 attacks (See
1125 http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
1125 http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
1126 information).
1126 information).
1127
1127
1128 For use with the ``webhelpers.secure_form`` helper functions.
1128 For use with the ``webhelpers.secure_form`` helper functions.
1129
1129
1130 """
1130 """
1131 def __init__(self, token=csrf_token_key, header='X-CSRF-Token',
1131 def __init__(self, token=csrf_token_key, header='X-CSRF-Token',
1132 except_methods=None):
1132 except_methods=None):
1133 self.token = token
1133 self.token = token
1134 self.header = header
1134 self.header = header
1135 self.except_methods = except_methods or []
1135 self.except_methods = except_methods or []
1136
1136
1137 def __call__(self, func):
1137 def __call__(self, func):
1138 return get_cython_compat_decorator(self.__wrapper, func)
1138 return get_cython_compat_decorator(self.__wrapper, func)
1139
1139
1140 def _get_csrf(self, _request):
1140 def _get_csrf(self, _request):
1141 return _request.POST.get(self.token, _request.headers.get(self.header))
1141 return _request.POST.get(self.token, _request.headers.get(self.header))
1142
1142
1143 def check_csrf(self, _request, cur_token):
1143 def check_csrf(self, _request, cur_token):
1144 supplied_token = self._get_csrf(_request)
1144 supplied_token = self._get_csrf(_request)
1145 return supplied_token and supplied_token == cur_token
1145 return supplied_token and supplied_token == cur_token
1146
1146
1147 def __wrapper(self, func, *fargs, **fkwargs):
1147 def __wrapper(self, func, *fargs, **fkwargs):
1148 if request.method in self.except_methods:
1148 if request.method in self.except_methods:
1149 return func(*fargs, **fkwargs)
1149 return func(*fargs, **fkwargs)
1150
1150
1151 cur_token = get_csrf_token(save_if_missing=False)
1151 cur_token = get_csrf_token(save_if_missing=False)
1152 if self.check_csrf(request, cur_token):
1152 if self.check_csrf(request, cur_token):
1153 if request.POST.get(self.token):
1153 if request.POST.get(self.token):
1154 del request.POST[self.token]
1154 del request.POST[self.token]
1155 return func(*fargs, **fkwargs)
1155 return func(*fargs, **fkwargs)
1156 else:
1156 else:
1157 reason = 'token-missing'
1157 reason = 'token-missing'
1158 supplied_token = self._get_csrf(request)
1158 supplied_token = self._get_csrf(request)
1159 if supplied_token and cur_token != supplied_token:
1159 if supplied_token and cur_token != supplied_token:
1160 reason = 'token-mismatch [%s:%s]' % (cur_token or ''[:6],
1160 reason = 'token-mismatch [%s:%s]' % (cur_token or ''[:6],
1161 supplied_token or ''[:6])
1161 supplied_token or ''[:6])
1162
1162
1163 csrf_message = \
1163 csrf_message = \
1164 ("Cross-site request forgery detected, request denied. See "
1164 ("Cross-site request forgery detected, request denied. See "
1165 "http://en.wikipedia.org/wiki/Cross-site_request_forgery for "
1165 "http://en.wikipedia.org/wiki/Cross-site_request_forgery for "
1166 "more information.")
1166 "more information.")
1167 log.warn('Cross-site request forgery detected, request %r DENIED: %s '
1167 log.warn('Cross-site request forgery detected, request %r DENIED: %s '
1168 'REMOTE_ADDR:%s, HEADERS:%s' % (
1168 'REMOTE_ADDR:%s, HEADERS:%s' % (
1169 request, reason, request.remote_addr, request.headers))
1169 request, reason, request.remote_addr, request.headers))
1170
1170
1171 raise HTTPForbidden(explanation=csrf_message)
1171 raise HTTPForbidden(explanation=csrf_message)
1172
1172
1173
1173
1174 class LoginRequired(object):
1174 class LoginRequired(object):
1175 """
1175 """
1176 Must be logged in to execute this function else
1176 Must be logged in to execute this function else
1177 redirect to login page
1177 redirect to login page
1178
1178
1179 :param api_access: if enabled this checks only for valid auth token
1179 :param api_access: if enabled this checks only for valid auth token
1180 and grants access based on valid token
1180 and grants access based on valid token
1181 """
1181 """
1182 def __init__(self, auth_token_access=None):
1182 def __init__(self, auth_token_access=None):
1183 self.auth_token_access = auth_token_access
1183 self.auth_token_access = auth_token_access
1184
1184
1185 def __call__(self, func):
1185 def __call__(self, func):
1186 return get_cython_compat_decorator(self.__wrapper, func)
1186 return get_cython_compat_decorator(self.__wrapper, func)
1187
1187
1188 def __wrapper(self, func, *fargs, **fkwargs):
1188 def __wrapper(self, func, *fargs, **fkwargs):
1189 from rhodecode.lib import helpers as h
1189 from rhodecode.lib import helpers as h
1190 cls = fargs[0]
1190 cls = fargs[0]
1191 user = cls._rhodecode_user
1191 user = cls._rhodecode_user
1192 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1192 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1193 log.debug('Starting login restriction checks for user: %s' % (user,))
1193 log.debug('Starting login restriction checks for user: %s' % (user,))
1194 # check if our IP is allowed
1194 # check if our IP is allowed
1195 ip_access_valid = True
1195 ip_access_valid = True
1196 if not user.ip_allowed:
1196 if not user.ip_allowed:
1197 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1197 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1198 category='warning')
1198 category='warning')
1199 ip_access_valid = False
1199 ip_access_valid = False
1200
1200
1201 # check if we used an APIKEY and it's a valid one
1201 # check if we used an APIKEY and it's a valid one
1202 # defined white-list of controllers which API access will be enabled
1202 # defined white-list of controllers which API access will be enabled
1203 _auth_token = request.GET.get(
1203 _auth_token = request.GET.get(
1204 'auth_token', '') or request.GET.get('api_key', '')
1204 'auth_token', '') or request.GET.get('api_key', '')
1205 auth_token_access_valid = allowed_auth_token_access(
1205 auth_token_access_valid = allowed_auth_token_access(
1206 loc, auth_token=_auth_token)
1206 loc, auth_token=_auth_token)
1207
1207
1208 # explicit controller is enabled or API is in our whitelist
1208 # explicit controller is enabled or API is in our whitelist
1209 if self.auth_token_access or auth_token_access_valid:
1209 if self.auth_token_access or auth_token_access_valid:
1210 log.debug('Checking AUTH TOKEN access for %s' % (cls,))
1210 log.debug('Checking AUTH TOKEN access for %s' % (cls,))
1211 db_user = user.get_instance()
1211 db_user = user.get_instance()
1212
1212
1213 if db_user:
1213 if db_user:
1214 if self.auth_token_access:
1214 if self.auth_token_access:
1215 roles = self.auth_token_access
1215 roles = self.auth_token_access
1216 else:
1216 else:
1217 roles = [UserApiKeys.ROLE_HTTP]
1217 roles = [UserApiKeys.ROLE_HTTP]
1218 token_match = db_user.authenticate_by_token(
1218 token_match = db_user.authenticate_by_token(
1219 _auth_token, roles=roles)
1219 _auth_token, roles=roles)
1220 else:
1220 else:
1221 log.debug('Unable to fetch db instance for auth user: %s', user)
1221 log.debug('Unable to fetch db instance for auth user: %s', user)
1222 token_match = False
1222 token_match = False
1223
1223
1224 if _auth_token and token_match:
1224 if _auth_token and token_match:
1225 auth_token_access_valid = True
1225 auth_token_access_valid = True
1226 log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],))
1226 log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],))
1227 else:
1227 else:
1228 auth_token_access_valid = False
1228 auth_token_access_valid = False
1229 if not _auth_token:
1229 if not _auth_token:
1230 log.debug("AUTH TOKEN *NOT* present in request")
1230 log.debug("AUTH TOKEN *NOT* present in request")
1231 else:
1231 else:
1232 log.warning(
1232 log.warning(
1233 "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:])
1233 "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:])
1234
1234
1235 log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
1235 log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
1236 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1236 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1237 else 'AUTH_TOKEN_AUTH'
1237 else 'AUTH_TOKEN_AUTH'
1238
1238
1239 if ip_access_valid and (
1239 if ip_access_valid and (
1240 user.is_authenticated or auth_token_access_valid):
1240 user.is_authenticated or auth_token_access_valid):
1241 log.info(
1241 log.info(
1242 'user %s authenticating with:%s IS authenticated on func %s'
1242 'user %s authenticating with:%s IS authenticated on func %s'
1243 % (user, reason, loc))
1243 % (user, reason, loc))
1244
1244
1245 # update user data to check last activity
1245 # update user data to check last activity
1246 user.update_lastactivity()
1246 user.update_lastactivity()
1247 Session().commit()
1247 Session().commit()
1248 return func(*fargs, **fkwargs)
1248 return func(*fargs, **fkwargs)
1249 else:
1249 else:
1250 log.warning(
1250 log.warning(
1251 'user %s authenticating with:%s NOT authenticated on '
1251 'user %s authenticating with:%s NOT authenticated on '
1252 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s'
1252 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s'
1253 % (user, reason, loc, ip_access_valid,
1253 % (user, reason, loc, ip_access_valid,
1254 auth_token_access_valid))
1254 auth_token_access_valid))
1255 # we preserve the get PARAM
1255 # we preserve the get PARAM
1256 came_from = request.path_qs
1256 came_from = request.path_qs
1257 log.debug('redirecting to login page with %s' % (came_from,))
1257 log.debug('redirecting to login page with %s' % (came_from,))
1258 return redirect(
1258 return redirect(
1259 h.route_path('login', _query={'came_from': came_from}))
1259 h.route_path('login', _query={'came_from': came_from}))
1260
1260
1261
1261
1262 class NotAnonymous(object):
1262 class NotAnonymous(object):
1263 """
1263 """
1264 Must be logged in to execute this function else
1264 Must be logged in to execute this function else
1265 redirect to login page"""
1265 redirect to login page"""
1266
1266
1267 def __call__(self, func):
1267 def __call__(self, func):
1268 return get_cython_compat_decorator(self.__wrapper, func)
1268 return get_cython_compat_decorator(self.__wrapper, func)
1269
1269
1270 def __wrapper(self, func, *fargs, **fkwargs):
1270 def __wrapper(self, func, *fargs, **fkwargs):
1271 import rhodecode.lib.helpers as h
1271 import rhodecode.lib.helpers as h
1272 cls = fargs[0]
1272 cls = fargs[0]
1273 self.user = cls._rhodecode_user
1273 self.user = cls._rhodecode_user
1274
1274
1275 log.debug('Checking if user is not anonymous @%s' % cls)
1275 log.debug('Checking if user is not anonymous @%s' % cls)
1276
1276
1277 anonymous = self.user.username == User.DEFAULT_USER
1277 anonymous = self.user.username == User.DEFAULT_USER
1278
1278
1279 if anonymous:
1279 if anonymous:
1280 came_from = request.path_qs
1280 came_from = request.path_qs
1281 h.flash(_('You need to be a registered user to '
1281 h.flash(_('You need to be a registered user to '
1282 'perform this action'),
1282 'perform this action'),
1283 category='warning')
1283 category='warning')
1284 return redirect(
1284 return redirect(
1285 h.route_path('login', _query={'came_from': came_from}))
1285 h.route_path('login', _query={'came_from': came_from}))
1286 else:
1286 else:
1287 return func(*fargs, **fkwargs)
1287 return func(*fargs, **fkwargs)
1288
1288
1289
1289
1290 class XHRRequired(object):
1290 class XHRRequired(object):
1291 def __call__(self, func):
1291 def __call__(self, func):
1292 return get_cython_compat_decorator(self.__wrapper, func)
1292 return get_cython_compat_decorator(self.__wrapper, func)
1293
1293
1294 def __wrapper(self, func, *fargs, **fkwargs):
1294 def __wrapper(self, func, *fargs, **fkwargs):
1295 log.debug('Checking if request is XMLHttpRequest (XHR)')
1295 log.debug('Checking if request is XMLHttpRequest (XHR)')
1296 xhr_message = 'This is not a valid XMLHttpRequest (XHR) request'
1296 xhr_message = 'This is not a valid XMLHttpRequest (XHR) request'
1297 if not request.is_xhr:
1297 if not request.is_xhr:
1298 abort(400, detail=xhr_message)
1298 abort(400, detail=xhr_message)
1299
1299
1300 return func(*fargs, **fkwargs)
1300 return func(*fargs, **fkwargs)
1301
1301
1302
1302
1303 class HasAcceptedRepoType(object):
1303 class HasAcceptedRepoType(object):
1304 """
1304 """
1305 Check if requested repo is within given repo type aliases
1305 Check if requested repo is within given repo type aliases
1306
1306
1307 TODO: anderson: not sure where to put this decorator
1307 TODO: anderson: not sure where to put this decorator
1308 """
1308 """
1309
1309
1310 def __init__(self, *repo_type_list):
1310 def __init__(self, *repo_type_list):
1311 self.repo_type_list = set(repo_type_list)
1311 self.repo_type_list = set(repo_type_list)
1312
1312
1313 def __call__(self, func):
1313 def __call__(self, func):
1314 return get_cython_compat_decorator(self.__wrapper, func)
1314 return get_cython_compat_decorator(self.__wrapper, func)
1315
1315
1316 def __wrapper(self, func, *fargs, **fkwargs):
1316 def __wrapper(self, func, *fargs, **fkwargs):
1317 import rhodecode.lib.helpers as h
1317 import rhodecode.lib.helpers as h
1318 cls = fargs[0]
1318 cls = fargs[0]
1319 rhodecode_repo = cls.rhodecode_repo
1319 rhodecode_repo = cls.rhodecode_repo
1320
1320
1321 log.debug('%s checking repo type for %s in %s',
1321 log.debug('%s checking repo type for %s in %s',
1322 self.__class__.__name__,
1322 self.__class__.__name__,
1323 rhodecode_repo.alias, self.repo_type_list)
1323 rhodecode_repo.alias, self.repo_type_list)
1324
1324
1325 if rhodecode_repo.alias in self.repo_type_list:
1325 if rhodecode_repo.alias in self.repo_type_list:
1326 return func(*fargs, **fkwargs)
1326 return func(*fargs, **fkwargs)
1327 else:
1327 else:
1328 h.flash(h.literal(
1328 h.flash(h.literal(
1329 _('Action not supported for %s.' % rhodecode_repo.alias)),
1329 _('Action not supported for %s.' % rhodecode_repo.alias)),
1330 category='warning')
1330 category='warning')
1331 return redirect(
1331 return redirect(
1332 url('summary_home', repo_name=cls.rhodecode_db_repo.repo_name))
1332 url('summary_home', repo_name=cls.rhodecode_db_repo.repo_name))
1333
1333
1334
1334
1335 class PermsDecorator(object):
1335 class PermsDecorator(object):
1336 """
1336 """
1337 Base class for controller decorators, we extract the current user from
1337 Base class for controller decorators, we extract the current user from
1338 the class itself, which has it stored in base controllers
1338 the class itself, which has it stored in base controllers
1339 """
1339 """
1340
1340
1341 def __init__(self, *required_perms):
1341 def __init__(self, *required_perms):
1342 self.required_perms = set(required_perms)
1342 self.required_perms = set(required_perms)
1343
1343
1344 def __call__(self, func):
1344 def __call__(self, func):
1345 return get_cython_compat_decorator(self.__wrapper, func)
1345 return get_cython_compat_decorator(self.__wrapper, func)
1346
1346
1347 def _get_request(self):
1347 def _get_request(self):
1348 from pyramid.threadlocal import get_current_request
1348 from pyramid.threadlocal import get_current_request
1349 pyramid_request = get_current_request()
1349 pyramid_request = get_current_request()
1350 if not pyramid_request:
1350 if not pyramid_request:
1351 # return global request of pylons in case pyramid isn't available
1351 # return global request of pylons in case pyramid isn't available
1352 return request
1352 return request
1353 return pyramid_request
1353 return pyramid_request
1354
1354
1355 def _get_came_from(self):
1355 def _get_came_from(self):
1356 _request = self._get_request()
1356 _request = self._get_request()
1357
1357
1358 # both pylons/pyramid has this attribute
1358 # both pylons/pyramid has this attribute
1359 return _request.path_qs
1359 return _request.path_qs
1360
1360
1361 def __wrapper(self, func, *fargs, **fkwargs):
1361 def __wrapper(self, func, *fargs, **fkwargs):
1362 import rhodecode.lib.helpers as h
1362 import rhodecode.lib.helpers as h
1363 cls = fargs[0]
1363 cls = fargs[0]
1364 _user = cls._rhodecode_user
1364 _user = cls._rhodecode_user
1365
1365
1366 log.debug('checking %s permissions %s for %s %s',
1366 log.debug('checking %s permissions %s for %s %s',
1367 self.__class__.__name__, self.required_perms, cls, _user)
1367 self.__class__.__name__, self.required_perms, cls, _user)
1368
1368
1369 if self.check_permissions(_user):
1369 if self.check_permissions(_user):
1370 log.debug('Permission granted for %s %s', cls, _user)
1370 log.debug('Permission granted for %s %s', cls, _user)
1371 return func(*fargs, **fkwargs)
1371 return func(*fargs, **fkwargs)
1372
1372
1373 else:
1373 else:
1374 log.debug('Permission denied for %s %s', cls, _user)
1374 log.debug('Permission denied for %s %s', cls, _user)
1375 anonymous = _user.username == User.DEFAULT_USER
1375 anonymous = _user.username == User.DEFAULT_USER
1376
1376
1377 if anonymous:
1377 if anonymous:
1378 came_from = self._get_came_from()
1378 came_from = self._get_came_from()
1379 h.flash(_('You need to be signed in to view this page'),
1379 h.flash(_('You need to be signed in to view this page'),
1380 category='warning')
1380 category='warning')
1381 raise HTTPFound(
1381 raise HTTPFound(
1382 h.route_path('login', _query={'came_from': came_from}))
1382 h.route_path('login', _query={'came_from': came_from}))
1383
1383
1384 else:
1384 else:
1385 # redirect with forbidden ret code
1385 # redirect with forbidden ret code
1386 raise HTTPForbidden()
1386 raise HTTPForbidden()
1387
1387
1388 def check_permissions(self, user):
1388 def check_permissions(self, user):
1389 """Dummy function for overriding"""
1389 """Dummy function for overriding"""
1390 raise NotImplementedError(
1390 raise NotImplementedError(
1391 'You have to write this function in child class')
1391 'You have to write this function in child class')
1392
1392
1393
1393
1394 class HasPermissionAllDecorator(PermsDecorator):
1394 class HasPermissionAllDecorator(PermsDecorator):
1395 """
1395 """
1396 Checks for access permission for all given predicates. All of them
1396 Checks for access permission for all given predicates. All of them
1397 have to be meet in order to fulfill the request
1397 have to be meet in order to fulfill the request
1398 """
1398 """
1399
1399
1400 def check_permissions(self, user):
1400 def check_permissions(self, user):
1401 perms = user.permissions_with_scope({})
1401 perms = user.permissions_with_scope({})
1402 if self.required_perms.issubset(perms['global']):
1402 if self.required_perms.issubset(perms['global']):
1403 return True
1403 return True
1404 return False
1404 return False
1405
1405
1406
1406
1407 class HasPermissionAnyDecorator(PermsDecorator):
1407 class HasPermissionAnyDecorator(PermsDecorator):
1408 """
1408 """
1409 Checks for access permission for any of given predicates. In order to
1409 Checks for access permission for any of given predicates. In order to
1410 fulfill the request any of predicates must be meet
1410 fulfill the request any of predicates must be meet
1411 """
1411 """
1412
1412
1413 def check_permissions(self, user):
1413 def check_permissions(self, user):
1414 perms = user.permissions_with_scope({})
1414 perms = user.permissions_with_scope({})
1415 if self.required_perms.intersection(perms['global']):
1415 if self.required_perms.intersection(perms['global']):
1416 return True
1416 return True
1417 return False
1417 return False
1418
1418
1419
1419
1420 class HasRepoPermissionAllDecorator(PermsDecorator):
1420 class HasRepoPermissionAllDecorator(PermsDecorator):
1421 """
1421 """
1422 Checks for access permission for all given predicates for specific
1422 Checks for access permission for all given predicates for specific
1423 repository. All of them have to be meet in order to fulfill the request
1423 repository. All of them have to be meet in order to fulfill the request
1424 """
1424 """
1425 def _get_repo_name(self):
1425 def _get_repo_name(self):
1426 _request = self._get_request()
1426 _request = self._get_request()
1427 return get_repo_slug(_request)
1427 return get_repo_slug(_request)
1428
1428
1429 def check_permissions(self, user):
1429 def check_permissions(self, user):
1430 perms = user.permissions
1430 perms = user.permissions
1431 repo_name = self._get_repo_name()
1431 repo_name = self._get_repo_name()
1432 try:
1432 try:
1433 user_perms = set([perms['repositories'][repo_name]])
1433 user_perms = set([perms['repositories'][repo_name]])
1434 except KeyError:
1434 except KeyError:
1435 return False
1435 return False
1436 if self.required_perms.issubset(user_perms):
1436 if self.required_perms.issubset(user_perms):
1437 return True
1437 return True
1438 return False
1438 return False
1439
1439
1440
1440
1441 class HasRepoPermissionAnyDecorator(PermsDecorator):
1441 class HasRepoPermissionAnyDecorator(PermsDecorator):
1442 """
1442 """
1443 Checks for access permission for any of given predicates for specific
1443 Checks for access permission for any of given predicates for specific
1444 repository. In order to fulfill the request any of predicates must be meet
1444 repository. In order to fulfill the request any of predicates must be meet
1445 """
1445 """
1446 def _get_repo_name(self):
1446 def _get_repo_name(self):
1447 _request = self._get_request()
1447 _request = self._get_request()
1448 return get_repo_slug(_request)
1448 return get_repo_slug(_request)
1449
1449
1450 def check_permissions(self, user):
1450 def check_permissions(self, user):
1451 perms = user.permissions
1451 perms = user.permissions
1452 repo_name = self._get_repo_name()
1452 repo_name = self._get_repo_name()
1453 try:
1453 try:
1454 user_perms = set([perms['repositories'][repo_name]])
1454 user_perms = set([perms['repositories'][repo_name]])
1455 except KeyError:
1455 except KeyError:
1456 return False
1456 return False
1457
1457
1458 if self.required_perms.intersection(user_perms):
1458 if self.required_perms.intersection(user_perms):
1459 return True
1459 return True
1460 return False
1460 return False
1461
1461
1462
1462
1463 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1463 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1464 """
1464 """
1465 Checks for access permission for all given predicates for specific
1465 Checks for access permission for all given predicates for specific
1466 repository group. All of them have to be meet in order to
1466 repository group. All of them have to be meet in order to
1467 fulfill the request
1467 fulfill the request
1468 """
1468 """
1469 def _get_repo_group_name(self):
1469 def _get_repo_group_name(self):
1470 _request = self._get_request()
1470 _request = self._get_request()
1471 return get_repo_group_slug(_request)
1471 return get_repo_group_slug(_request)
1472
1472
1473 def check_permissions(self, user):
1473 def check_permissions(self, user):
1474 perms = user.permissions
1474 perms = user.permissions
1475 group_name = self._get_repo_group_name()
1475 group_name = self._get_repo_group_name()
1476 try:
1476 try:
1477 user_perms = set([perms['repositories_groups'][group_name]])
1477 user_perms = set([perms['repositories_groups'][group_name]])
1478 except KeyError:
1478 except KeyError:
1479 return False
1479 return False
1480
1480
1481 if self.required_perms.issubset(user_perms):
1481 if self.required_perms.issubset(user_perms):
1482 return True
1482 return True
1483 return False
1483 return False
1484
1484
1485
1485
1486 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1486 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1487 """
1487 """
1488 Checks for access permission for any of given predicates for specific
1488 Checks for access permission for any of given predicates for specific
1489 repository group. In order to fulfill the request any
1489 repository group. In order to fulfill the request any
1490 of predicates must be met
1490 of predicates must be met
1491 """
1491 """
1492 def _get_repo_group_name(self):
1492 def _get_repo_group_name(self):
1493 _request = self._get_request()
1493 _request = self._get_request()
1494 return get_repo_group_slug(_request)
1494 return get_repo_group_slug(_request)
1495
1495
1496 def check_permissions(self, user):
1496 def check_permissions(self, user):
1497 perms = user.permissions
1497 perms = user.permissions
1498 group_name = self._get_repo_group_name()
1498 group_name = self._get_repo_group_name()
1499 try:
1499 try:
1500 user_perms = set([perms['repositories_groups'][group_name]])
1500 user_perms = set([perms['repositories_groups'][group_name]])
1501 except KeyError:
1501 except KeyError:
1502 return False
1502 return False
1503
1503
1504 if self.required_perms.intersection(user_perms):
1504 if self.required_perms.intersection(user_perms):
1505 return True
1505 return True
1506 return False
1506 return False
1507
1507
1508
1508
1509 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1509 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1510 """
1510 """
1511 Checks for access permission for all given predicates for specific
1511 Checks for access permission for all given predicates for specific
1512 user group. All of them have to be meet in order to fulfill the request
1512 user group. All of them have to be meet in order to fulfill the request
1513 """
1513 """
1514 def _get_user_group_name(self):
1514 def _get_user_group_name(self):
1515 _request = self._get_request()
1515 _request = self._get_request()
1516 return get_user_group_slug(_request)
1516 return get_user_group_slug(_request)
1517
1517
1518 def check_permissions(self, user):
1518 def check_permissions(self, user):
1519 perms = user.permissions
1519 perms = user.permissions
1520 group_name = self._get_user_group_name()
1520 group_name = self._get_user_group_name()
1521 try:
1521 try:
1522 user_perms = set([perms['user_groups'][group_name]])
1522 user_perms = set([perms['user_groups'][group_name]])
1523 except KeyError:
1523 except KeyError:
1524 return False
1524 return False
1525
1525
1526 if self.required_perms.issubset(user_perms):
1526 if self.required_perms.issubset(user_perms):
1527 return True
1527 return True
1528 return False
1528 return False
1529
1529
1530
1530
1531 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1531 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1532 """
1532 """
1533 Checks for access permission for any of given predicates for specific
1533 Checks for access permission for any of given predicates for specific
1534 user group. In order to fulfill the request any of predicates must be meet
1534 user group. In order to fulfill the request any of predicates must be meet
1535 """
1535 """
1536 def _get_user_group_name(self):
1536 def _get_user_group_name(self):
1537 _request = self._get_request()
1537 _request = self._get_request()
1538 return get_user_group_slug(_request)
1538 return get_user_group_slug(_request)
1539
1539
1540 def check_permissions(self, user):
1540 def check_permissions(self, user):
1541 perms = user.permissions
1541 perms = user.permissions
1542 group_name = self._get_user_group_name()
1542 group_name = self._get_user_group_name()
1543 try:
1543 try:
1544 user_perms = set([perms['user_groups'][group_name]])
1544 user_perms = set([perms['user_groups'][group_name]])
1545 except KeyError:
1545 except KeyError:
1546 return False
1546 return False
1547
1547
1548 if self.required_perms.intersection(user_perms):
1548 if self.required_perms.intersection(user_perms):
1549 return True
1549 return True
1550 return False
1550 return False
1551
1551
1552
1552
1553 # CHECK FUNCTIONS
1553 # CHECK FUNCTIONS
1554 class PermsFunction(object):
1554 class PermsFunction(object):
1555 """Base function for other check functions"""
1555 """Base function for other check functions"""
1556
1556
1557 def __init__(self, *perms):
1557 def __init__(self, *perms):
1558 self.required_perms = set(perms)
1558 self.required_perms = set(perms)
1559 self.repo_name = None
1559 self.repo_name = None
1560 self.repo_group_name = None
1560 self.repo_group_name = None
1561 self.user_group_name = None
1561 self.user_group_name = None
1562
1562
1563 def __bool__(self):
1563 def __bool__(self):
1564 frame = inspect.currentframe()
1564 frame = inspect.currentframe()
1565 stack_trace = traceback.format_stack(frame)
1565 stack_trace = traceback.format_stack(frame)
1566 log.error('Checking bool value on a class instance of perm '
1566 log.error('Checking bool value on a class instance of perm '
1567 'function is not allowed: %s' % ''.join(stack_trace))
1567 'function is not allowed: %s' % ''.join(stack_trace))
1568 # rather than throwing errors, here we always return False so if by
1568 # rather than throwing errors, here we always return False so if by
1569 # accident someone checks truth for just an instance it will always end
1569 # accident someone checks truth for just an instance it will always end
1570 # up in returning False
1570 # up in returning False
1571 return False
1571 return False
1572 __nonzero__ = __bool__
1572 __nonzero__ = __bool__
1573
1573
1574 def __call__(self, check_location='', user=None):
1574 def __call__(self, check_location='', user=None):
1575 if not user:
1575 if not user:
1576 log.debug('Using user attribute from global request')
1576 log.debug('Using user attribute from global request')
1577 # TODO: remove this someday,put as user as attribute here
1577 # TODO: remove this someday,put as user as attribute here
1578 user = request.user
1578 user = request.user
1579
1579
1580 # init auth user if not already given
1580 # init auth user if not already given
1581 if not isinstance(user, AuthUser):
1581 if not isinstance(user, AuthUser):
1582 log.debug('Wrapping user %s into AuthUser', user)
1582 log.debug('Wrapping user %s into AuthUser', user)
1583 user = AuthUser(user.user_id)
1583 user = AuthUser(user.user_id)
1584
1584
1585 cls_name = self.__class__.__name__
1585 cls_name = self.__class__.__name__
1586 check_scope = self._get_check_scope(cls_name)
1586 check_scope = self._get_check_scope(cls_name)
1587 check_location = check_location or 'unspecified location'
1587 check_location = check_location or 'unspecified location'
1588
1588
1589 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1589 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1590 self.required_perms, user, check_scope, check_location)
1590 self.required_perms, user, check_scope, check_location)
1591 if not user:
1591 if not user:
1592 log.warning('Empty user given for permission check')
1592 log.warning('Empty user given for permission check')
1593 return False
1593 return False
1594
1594
1595 if self.check_permissions(user):
1595 if self.check_permissions(user):
1596 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1596 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1597 check_scope, user, check_location)
1597 check_scope, user, check_location)
1598 return True
1598 return True
1599
1599
1600 else:
1600 else:
1601 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1601 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1602 check_scope, user, check_location)
1602 check_scope, user, check_location)
1603 return False
1603 return False
1604
1604
1605 def _get_request(self):
1605 def _get_request(self):
1606 from pyramid.threadlocal import get_current_request
1606 from pyramid.threadlocal import get_current_request
1607 pyramid_request = get_current_request()
1607 pyramid_request = get_current_request()
1608 if not pyramid_request:
1608 if not pyramid_request:
1609 # return global request of pylons incase pyramid one isn't available
1609 # return global request of pylons incase pyramid one isn't available
1610 return request
1610 return request
1611 return pyramid_request
1611 return pyramid_request
1612
1612
1613 def _get_check_scope(self, cls_name):
1613 def _get_check_scope(self, cls_name):
1614 return {
1614 return {
1615 'HasPermissionAll': 'GLOBAL',
1615 'HasPermissionAll': 'GLOBAL',
1616 'HasPermissionAny': 'GLOBAL',
1616 'HasPermissionAny': 'GLOBAL',
1617 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
1617 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
1618 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
1618 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
1619 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
1619 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
1620 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
1620 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
1621 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
1621 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
1622 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
1622 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
1623 }.get(cls_name, '?:%s' % cls_name)
1623 }.get(cls_name, '?:%s' % cls_name)
1624
1624
1625 def check_permissions(self, user):
1625 def check_permissions(self, user):
1626 """Dummy function for overriding"""
1626 """Dummy function for overriding"""
1627 raise Exception('You have to write this function in child class')
1627 raise Exception('You have to write this function in child class')
1628
1628
1629
1629
1630 class HasPermissionAll(PermsFunction):
1630 class HasPermissionAll(PermsFunction):
1631 def check_permissions(self, user):
1631 def check_permissions(self, user):
1632 perms = user.permissions_with_scope({})
1632 perms = user.permissions_with_scope({})
1633 if self.required_perms.issubset(perms.get('global')):
1633 if self.required_perms.issubset(perms.get('global')):
1634 return True
1634 return True
1635 return False
1635 return False
1636
1636
1637
1637
1638 class HasPermissionAny(PermsFunction):
1638 class HasPermissionAny(PermsFunction):
1639 def check_permissions(self, user):
1639 def check_permissions(self, user):
1640 perms = user.permissions_with_scope({})
1640 perms = user.permissions_with_scope({})
1641 if self.required_perms.intersection(perms.get('global')):
1641 if self.required_perms.intersection(perms.get('global')):
1642 return True
1642 return True
1643 return False
1643 return False
1644
1644
1645
1645
1646 class HasRepoPermissionAll(PermsFunction):
1646 class HasRepoPermissionAll(PermsFunction):
1647 def __call__(self, repo_name=None, check_location='', user=None):
1647 def __call__(self, repo_name=None, check_location='', user=None):
1648 self.repo_name = repo_name
1648 self.repo_name = repo_name
1649 return super(HasRepoPermissionAll, self).__call__(check_location, user)
1649 return super(HasRepoPermissionAll, self).__call__(check_location, user)
1650
1650
1651 def _get_repo_name(self):
1651 def _get_repo_name(self):
1652 if not self.repo_name:
1652 if not self.repo_name:
1653 _request = self._get_request()
1653 _request = self._get_request()
1654 self.repo_name = get_repo_slug(_request)
1654 self.repo_name = get_repo_slug(_request)
1655 return self.repo_name
1655 return self.repo_name
1656
1656
1657 def check_permissions(self, user):
1657 def check_permissions(self, user):
1658 self.repo_name = self._get_repo_name()
1658 self.repo_name = self._get_repo_name()
1659 perms = user.permissions
1659 perms = user.permissions
1660 try:
1660 try:
1661 user_perms = set([perms['repositories'][self.repo_name]])
1661 user_perms = set([perms['repositories'][self.repo_name]])
1662 except KeyError:
1662 except KeyError:
1663 return False
1663 return False
1664 if self.required_perms.issubset(user_perms):
1664 if self.required_perms.issubset(user_perms):
1665 return True
1665 return True
1666 return False
1666 return False
1667
1667
1668
1668
1669 class HasRepoPermissionAny(PermsFunction):
1669 class HasRepoPermissionAny(PermsFunction):
1670 def __call__(self, repo_name=None, check_location='', user=None):
1670 def __call__(self, repo_name=None, check_location='', user=None):
1671 self.repo_name = repo_name
1671 self.repo_name = repo_name
1672 return super(HasRepoPermissionAny, self).__call__(check_location, user)
1672 return super(HasRepoPermissionAny, self).__call__(check_location, user)
1673
1673
1674 def _get_repo_name(self):
1674 def _get_repo_name(self):
1675 if not self.repo_name:
1675 if not self.repo_name:
1676 self.repo_name = get_repo_slug(request)
1676 self.repo_name = get_repo_slug(request)
1677 return self.repo_name
1677 return self.repo_name
1678
1678
1679 def check_permissions(self, user):
1679 def check_permissions(self, user):
1680 self.repo_name = self._get_repo_name()
1680 self.repo_name = self._get_repo_name()
1681 perms = user.permissions
1681 perms = user.permissions
1682 try:
1682 try:
1683 user_perms = set([perms['repositories'][self.repo_name]])
1683 user_perms = set([perms['repositories'][self.repo_name]])
1684 except KeyError:
1684 except KeyError:
1685 return False
1685 return False
1686 if self.required_perms.intersection(user_perms):
1686 if self.required_perms.intersection(user_perms):
1687 return True
1687 return True
1688 return False
1688 return False
1689
1689
1690
1690
1691 class HasRepoGroupPermissionAny(PermsFunction):
1691 class HasRepoGroupPermissionAny(PermsFunction):
1692 def __call__(self, group_name=None, check_location='', user=None):
1692 def __call__(self, group_name=None, check_location='', user=None):
1693 self.repo_group_name = group_name
1693 self.repo_group_name = group_name
1694 return super(HasRepoGroupPermissionAny, self).__call__(
1694 return super(HasRepoGroupPermissionAny, self).__call__(
1695 check_location, user)
1695 check_location, user)
1696
1696
1697 def check_permissions(self, user):
1697 def check_permissions(self, user):
1698 perms = user.permissions
1698 perms = user.permissions
1699 try:
1699 try:
1700 user_perms = set(
1700 user_perms = set(
1701 [perms['repositories_groups'][self.repo_group_name]])
1701 [perms['repositories_groups'][self.repo_group_name]])
1702 except KeyError:
1702 except KeyError:
1703 return False
1703 return False
1704 if self.required_perms.intersection(user_perms):
1704 if self.required_perms.intersection(user_perms):
1705 return True
1705 return True
1706 return False
1706 return False
1707
1707
1708
1708
1709 class HasRepoGroupPermissionAll(PermsFunction):
1709 class HasRepoGroupPermissionAll(PermsFunction):
1710 def __call__(self, group_name=None, check_location='', user=None):
1710 def __call__(self, group_name=None, check_location='', user=None):
1711 self.repo_group_name = group_name
1711 self.repo_group_name = group_name
1712 return super(HasRepoGroupPermissionAll, self).__call__(
1712 return super(HasRepoGroupPermissionAll, self).__call__(
1713 check_location, user)
1713 check_location, user)
1714
1714
1715 def check_permissions(self, user):
1715 def check_permissions(self, user):
1716 perms = user.permissions
1716 perms = user.permissions
1717 try:
1717 try:
1718 user_perms = set(
1718 user_perms = set(
1719 [perms['repositories_groups'][self.repo_group_name]])
1719 [perms['repositories_groups'][self.repo_group_name]])
1720 except KeyError:
1720 except KeyError:
1721 return False
1721 return False
1722 if self.required_perms.issubset(user_perms):
1722 if self.required_perms.issubset(user_perms):
1723 return True
1723 return True
1724 return False
1724 return False
1725
1725
1726
1726
1727 class HasUserGroupPermissionAny(PermsFunction):
1727 class HasUserGroupPermissionAny(PermsFunction):
1728 def __call__(self, user_group_name=None, check_location='', user=None):
1728 def __call__(self, user_group_name=None, check_location='', user=None):
1729 self.user_group_name = user_group_name
1729 self.user_group_name = user_group_name
1730 return super(HasUserGroupPermissionAny, self).__call__(
1730 return super(HasUserGroupPermissionAny, self).__call__(
1731 check_location, user)
1731 check_location, user)
1732
1732
1733 def check_permissions(self, user):
1733 def check_permissions(self, user):
1734 perms = user.permissions
1734 perms = user.permissions
1735 try:
1735 try:
1736 user_perms = set([perms['user_groups'][self.user_group_name]])
1736 user_perms = set([perms['user_groups'][self.user_group_name]])
1737 except KeyError:
1737 except KeyError:
1738 return False
1738 return False
1739 if self.required_perms.intersection(user_perms):
1739 if self.required_perms.intersection(user_perms):
1740 return True
1740 return True
1741 return False
1741 return False
1742
1742
1743
1743
1744 class HasUserGroupPermissionAll(PermsFunction):
1744 class HasUserGroupPermissionAll(PermsFunction):
1745 def __call__(self, user_group_name=None, check_location='', user=None):
1745 def __call__(self, user_group_name=None, check_location='', user=None):
1746 self.user_group_name = user_group_name
1746 self.user_group_name = user_group_name
1747 return super(HasUserGroupPermissionAll, self).__call__(
1747 return super(HasUserGroupPermissionAll, self).__call__(
1748 check_location, user)
1748 check_location, user)
1749
1749
1750 def check_permissions(self, user):
1750 def check_permissions(self, user):
1751 perms = user.permissions
1751 perms = user.permissions
1752 try:
1752 try:
1753 user_perms = set([perms['user_groups'][self.user_group_name]])
1753 user_perms = set([perms['user_groups'][self.user_group_name]])
1754 except KeyError:
1754 except KeyError:
1755 return False
1755 return False
1756 if self.required_perms.issubset(user_perms):
1756 if self.required_perms.issubset(user_perms):
1757 return True
1757 return True
1758 return False
1758 return False
1759
1759
1760
1760
1761 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
1761 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
1762 class HasPermissionAnyMiddleware(object):
1762 class HasPermissionAnyMiddleware(object):
1763 def __init__(self, *perms):
1763 def __init__(self, *perms):
1764 self.required_perms = set(perms)
1764 self.required_perms = set(perms)
1765
1765
1766 def __call__(self, user, repo_name):
1766 def __call__(self, user, repo_name):
1767 # repo_name MUST be unicode, since we handle keys in permission
1767 # repo_name MUST be unicode, since we handle keys in permission
1768 # dict by unicode
1768 # dict by unicode
1769 repo_name = safe_unicode(repo_name)
1769 repo_name = safe_unicode(repo_name)
1770 user = AuthUser(user.user_id)
1770 user = AuthUser(user.user_id)
1771 log.debug(
1771 log.debug(
1772 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
1772 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
1773 self.required_perms, user, repo_name)
1773 self.required_perms, user, repo_name)
1774
1774
1775 if self.check_permissions(user, repo_name):
1775 if self.check_permissions(user, repo_name):
1776 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
1776 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
1777 repo_name, user, 'PermissionMiddleware')
1777 repo_name, user, 'PermissionMiddleware')
1778 return True
1778 return True
1779
1779
1780 else:
1780 else:
1781 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
1781 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
1782 repo_name, user, 'PermissionMiddleware')
1782 repo_name, user, 'PermissionMiddleware')
1783 return False
1783 return False
1784
1784
1785 def check_permissions(self, user, repo_name):
1785 def check_permissions(self, user, repo_name):
1786 perms = user.permissions_with_scope({'repo_name': repo_name})
1786 perms = user.permissions_with_scope({'repo_name': repo_name})
1787
1787
1788 try:
1788 try:
1789 user_perms = set([perms['repositories'][repo_name]])
1789 user_perms = set([perms['repositories'][repo_name]])
1790 except Exception:
1790 except Exception:
1791 log.exception('Error while accessing user permissions')
1791 log.exception('Error while accessing user permissions')
1792 return False
1792 return False
1793
1793
1794 if self.required_perms.intersection(user_perms):
1794 if self.required_perms.intersection(user_perms):
1795 return True
1795 return True
1796 return False
1796 return False
1797
1797
1798
1798
1799 # SPECIAL VERSION TO HANDLE API AUTH
1799 # SPECIAL VERSION TO HANDLE API AUTH
1800 class _BaseApiPerm(object):
1800 class _BaseApiPerm(object):
1801 def __init__(self, *perms):
1801 def __init__(self, *perms):
1802 self.required_perms = set(perms)
1802 self.required_perms = set(perms)
1803
1803
1804 def __call__(self, check_location=None, user=None, repo_name=None,
1804 def __call__(self, check_location=None, user=None, repo_name=None,
1805 group_name=None, user_group_name=None):
1805 group_name=None, user_group_name=None):
1806 cls_name = self.__class__.__name__
1806 cls_name = self.__class__.__name__
1807 check_scope = 'global:%s' % (self.required_perms,)
1807 check_scope = 'global:%s' % (self.required_perms,)
1808 if repo_name:
1808 if repo_name:
1809 check_scope += ', repo_name:%s' % (repo_name,)
1809 check_scope += ', repo_name:%s' % (repo_name,)
1810
1810
1811 if group_name:
1811 if group_name:
1812 check_scope += ', repo_group_name:%s' % (group_name,)
1812 check_scope += ', repo_group_name:%s' % (group_name,)
1813
1813
1814 if user_group_name:
1814 if user_group_name:
1815 check_scope += ', user_group_name:%s' % (user_group_name,)
1815 check_scope += ', user_group_name:%s' % (user_group_name,)
1816
1816
1817 log.debug(
1817 log.debug(
1818 'checking cls:%s %s %s @ %s'
1818 'checking cls:%s %s %s @ %s'
1819 % (cls_name, self.required_perms, check_scope, check_location))
1819 % (cls_name, self.required_perms, check_scope, check_location))
1820 if not user:
1820 if not user:
1821 log.debug('Empty User passed into arguments')
1821 log.debug('Empty User passed into arguments')
1822 return False
1822 return False
1823
1823
1824 # process user
1824 # process user
1825 if not isinstance(user, AuthUser):
1825 if not isinstance(user, AuthUser):
1826 user = AuthUser(user.user_id)
1826 user = AuthUser(user.user_id)
1827 if not check_location:
1827 if not check_location:
1828 check_location = 'unspecified'
1828 check_location = 'unspecified'
1829 if self.check_permissions(user.permissions, repo_name, group_name,
1829 if self.check_permissions(user.permissions, repo_name, group_name,
1830 user_group_name):
1830 user_group_name):
1831 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1831 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1832 check_scope, user, check_location)
1832 check_scope, user, check_location)
1833 return True
1833 return True
1834
1834
1835 else:
1835 else:
1836 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1836 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1837 check_scope, user, check_location)
1837 check_scope, user, check_location)
1838 return False
1838 return False
1839
1839
1840 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1840 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1841 user_group_name=None):
1841 user_group_name=None):
1842 """
1842 """
1843 implement in child class should return True if permissions are ok,
1843 implement in child class should return True if permissions are ok,
1844 False otherwise
1844 False otherwise
1845
1845
1846 :param perm_defs: dict with permission definitions
1846 :param perm_defs: dict with permission definitions
1847 :param repo_name: repo name
1847 :param repo_name: repo name
1848 """
1848 """
1849 raise NotImplementedError()
1849 raise NotImplementedError()
1850
1850
1851
1851
1852 class HasPermissionAllApi(_BaseApiPerm):
1852 class HasPermissionAllApi(_BaseApiPerm):
1853 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1853 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1854 user_group_name=None):
1854 user_group_name=None):
1855 if self.required_perms.issubset(perm_defs.get('global')):
1855 if self.required_perms.issubset(perm_defs.get('global')):
1856 return True
1856 return True
1857 return False
1857 return False
1858
1858
1859
1859
1860 class HasPermissionAnyApi(_BaseApiPerm):
1860 class HasPermissionAnyApi(_BaseApiPerm):
1861 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1861 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1862 user_group_name=None):
1862 user_group_name=None):
1863 if self.required_perms.intersection(perm_defs.get('global')):
1863 if self.required_perms.intersection(perm_defs.get('global')):
1864 return True
1864 return True
1865 return False
1865 return False
1866
1866
1867
1867
1868 class HasRepoPermissionAllApi(_BaseApiPerm):
1868 class HasRepoPermissionAllApi(_BaseApiPerm):
1869 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1869 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1870 user_group_name=None):
1870 user_group_name=None):
1871 try:
1871 try:
1872 _user_perms = set([perm_defs['repositories'][repo_name]])
1872 _user_perms = set([perm_defs['repositories'][repo_name]])
1873 except KeyError:
1873 except KeyError:
1874 log.warning(traceback.format_exc())
1874 log.warning(traceback.format_exc())
1875 return False
1875 return False
1876 if self.required_perms.issubset(_user_perms):
1876 if self.required_perms.issubset(_user_perms):
1877 return True
1877 return True
1878 return False
1878 return False
1879
1879
1880
1880
1881 class HasRepoPermissionAnyApi(_BaseApiPerm):
1881 class HasRepoPermissionAnyApi(_BaseApiPerm):
1882 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1882 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1883 user_group_name=None):
1883 user_group_name=None):
1884 try:
1884 try:
1885 _user_perms = set([perm_defs['repositories'][repo_name]])
1885 _user_perms = set([perm_defs['repositories'][repo_name]])
1886 except KeyError:
1886 except KeyError:
1887 log.warning(traceback.format_exc())
1887 log.warning(traceback.format_exc())
1888 return False
1888 return False
1889 if self.required_perms.intersection(_user_perms):
1889 if self.required_perms.intersection(_user_perms):
1890 return True
1890 return True
1891 return False
1891 return False
1892
1892
1893
1893
1894 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
1894 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
1895 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1895 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1896 user_group_name=None):
1896 user_group_name=None):
1897 try:
1897 try:
1898 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1898 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1899 except KeyError:
1899 except KeyError:
1900 log.warning(traceback.format_exc())
1900 log.warning(traceback.format_exc())
1901 return False
1901 return False
1902 if self.required_perms.intersection(_user_perms):
1902 if self.required_perms.intersection(_user_perms):
1903 return True
1903 return True
1904 return False
1904 return False
1905
1905
1906
1906
1907 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
1907 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
1908 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1908 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1909 user_group_name=None):
1909 user_group_name=None):
1910 try:
1910 try:
1911 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1911 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1912 except KeyError:
1912 except KeyError:
1913 log.warning(traceback.format_exc())
1913 log.warning(traceback.format_exc())
1914 return False
1914 return False
1915 if self.required_perms.issubset(_user_perms):
1915 if self.required_perms.issubset(_user_perms):
1916 return True
1916 return True
1917 return False
1917 return False
1918
1918
1919
1919
1920 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
1920 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
1921 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1921 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1922 user_group_name=None):
1922 user_group_name=None):
1923 try:
1923 try:
1924 _user_perms = set([perm_defs['user_groups'][user_group_name]])
1924 _user_perms = set([perm_defs['user_groups'][user_group_name]])
1925 except KeyError:
1925 except KeyError:
1926 log.warning(traceback.format_exc())
1926 log.warning(traceback.format_exc())
1927 return False
1927 return False
1928 if self.required_perms.intersection(_user_perms):
1928 if self.required_perms.intersection(_user_perms):
1929 return True
1929 return True
1930 return False
1930 return False
1931
1931
1932
1932
1933 def check_ip_access(source_ip, allowed_ips=None):
1933 def check_ip_access(source_ip, allowed_ips=None):
1934 """
1934 """
1935 Checks if source_ip is a subnet of any of allowed_ips.
1935 Checks if source_ip is a subnet of any of allowed_ips.
1936
1936
1937 :param source_ip:
1937 :param source_ip:
1938 :param allowed_ips: list of allowed ips together with mask
1938 :param allowed_ips: list of allowed ips together with mask
1939 """
1939 """
1940 log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips))
1940 log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips))
1941 source_ip_address = ipaddress.ip_address(source_ip)
1941 source_ip_address = ipaddress.ip_address(source_ip)
1942 if isinstance(allowed_ips, (tuple, list, set)):
1942 if isinstance(allowed_ips, (tuple, list, set)):
1943 for ip in allowed_ips:
1943 for ip in allowed_ips:
1944 try:
1944 try:
1945 network_address = ipaddress.ip_network(ip, strict=False)
1945 network_address = ipaddress.ip_network(ip, strict=False)
1946 if source_ip_address in network_address:
1946 if source_ip_address in network_address:
1947 log.debug('IP %s is network %s' %
1947 log.debug('IP %s is network %s' %
1948 (source_ip_address, network_address))
1948 (source_ip_address, network_address))
1949 return True
1949 return True
1950 # for any case we cannot determine the IP, don't crash just
1950 # for any case we cannot determine the IP, don't crash just
1951 # skip it and log as error, we want to say forbidden still when
1951 # skip it and log as error, we want to say forbidden still when
1952 # sending bad IP
1952 # sending bad IP
1953 except Exception:
1953 except Exception:
1954 log.error(traceback.format_exc())
1954 log.error(traceback.format_exc())
1955 continue
1955 continue
1956 return False
1956 return False
1957
1957
1958
1958
1959 def get_cython_compat_decorator(wrapper, func):
1959 def get_cython_compat_decorator(wrapper, func):
1960 """
1960 """
1961 Creates a cython compatible decorator. The previously used
1961 Creates a cython compatible decorator. The previously used
1962 decorator.decorator() function seems to be incompatible with cython.
1962 decorator.decorator() function seems to be incompatible with cython.
1963
1963
1964 :param wrapper: __wrapper method of the decorator class
1964 :param wrapper: __wrapper method of the decorator class
1965 :param func: decorated function
1965 :param func: decorated function
1966 """
1966 """
1967 @wraps(func)
1967 @wraps(func)
1968 def local_wrapper(*args, **kwds):
1968 def local_wrapper(*args, **kwds):
1969 return wrapper(func, *args, **kwds)
1969 return wrapper(func, *args, **kwds)
1970 local_wrapper.__wrapped__ = func
1970 local_wrapper.__wrapped__ = func
1971 return local_wrapper
1971 return local_wrapper
1972
1972
1973
1973
@@ -1,3986 +1,3986 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 Database Models for RhodeCode Enterprise
22 Database Models for RhodeCode Enterprise
23 """
23 """
24
24
25 import re
25 import re
26 import os
26 import os
27 import time
27 import time
28 import hashlib
28 import hashlib
29 import logging
29 import logging
30 import datetime
30 import datetime
31 import warnings
31 import warnings
32 import ipaddress
32 import ipaddress
33 import functools
33 import functools
34 import traceback
34 import traceback
35 import collections
35 import collections
36
36
37
37
38 from sqlalchemy import *
38 from sqlalchemy import *
39 from sqlalchemy.ext.declarative import declared_attr
39 from sqlalchemy.ext.declarative import declared_attr
40 from sqlalchemy.ext.hybrid import hybrid_property
40 from sqlalchemy.ext.hybrid import hybrid_property
41 from sqlalchemy.orm import (
41 from sqlalchemy.orm import (
42 relationship, joinedload, class_mapper, validates, aliased)
42 relationship, joinedload, class_mapper, validates, aliased)
43 from sqlalchemy.sql.expression import true
43 from sqlalchemy.sql.expression import true
44 from beaker.cache import cache_region
44 from beaker.cache import cache_region
45 from zope.cachedescriptors.property import Lazy as LazyProperty
45 from zope.cachedescriptors.property import Lazy as LazyProperty
46
46
47 from pylons import url
47 from pylons import url
48 from pylons.i18n.translation import lazy_ugettext as _
48 from pylons.i18n.translation import lazy_ugettext as _
49
49
50 from rhodecode.lib.vcs import get_vcs_instance
50 from rhodecode.lib.vcs import get_vcs_instance
51 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
51 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
52 from rhodecode.lib.utils2 import (
52 from rhodecode.lib.utils2 import (
53 str2bool, safe_str, get_commit_safe, safe_unicode, md5_safe,
53 str2bool, safe_str, get_commit_safe, safe_unicode, md5_safe,
54 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
54 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
55 glob2re, StrictAttributeDict, cleaned_uri)
55 glob2re, StrictAttributeDict, cleaned_uri)
56 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType
56 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType
57 from rhodecode.lib.ext_json import json
57 from rhodecode.lib.ext_json import json
58 from rhodecode.lib.caching_query import FromCache
58 from rhodecode.lib.caching_query import FromCache
59 from rhodecode.lib.encrypt import AESCipher
59 from rhodecode.lib.encrypt import AESCipher
60
60
61 from rhodecode.model.meta import Base, Session
61 from rhodecode.model.meta import Base, Session
62
62
63 URL_SEP = '/'
63 URL_SEP = '/'
64 log = logging.getLogger(__name__)
64 log = logging.getLogger(__name__)
65
65
66 # =============================================================================
66 # =============================================================================
67 # BASE CLASSES
67 # BASE CLASSES
68 # =============================================================================
68 # =============================================================================
69
69
70 # this is propagated from .ini file rhodecode.encrypted_values.secret or
70 # this is propagated from .ini file rhodecode.encrypted_values.secret or
71 # beaker.session.secret if first is not set.
71 # beaker.session.secret if first is not set.
72 # and initialized at environment.py
72 # and initialized at environment.py
73 ENCRYPTION_KEY = None
73 ENCRYPTION_KEY = None
74
74
75 # used to sort permissions by types, '#' used here is not allowed to be in
75 # used to sort permissions by types, '#' used here is not allowed to be in
76 # usernames, and it's very early in sorted string.printable table.
76 # usernames, and it's very early in sorted string.printable table.
77 PERMISSION_TYPE_SORT = {
77 PERMISSION_TYPE_SORT = {
78 'admin': '####',
78 'admin': '####',
79 'write': '###',
79 'write': '###',
80 'read': '##',
80 'read': '##',
81 'none': '#',
81 'none': '#',
82 }
82 }
83
83
84
84
85 def display_sort(obj):
85 def display_sort(obj):
86 """
86 """
87 Sort function used to sort permissions in .permissions() function of
87 Sort function used to sort permissions in .permissions() function of
88 Repository, RepoGroup, UserGroup. Also it put the default user in front
88 Repository, RepoGroup, UserGroup. Also it put the default user in front
89 of all other resources
89 of all other resources
90 """
90 """
91
91
92 if obj.username == User.DEFAULT_USER:
92 if obj.username == User.DEFAULT_USER:
93 return '#####'
93 return '#####'
94 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
94 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
95 return prefix + obj.username
95 return prefix + obj.username
96
96
97
97
98 def _hash_key(k):
98 def _hash_key(k):
99 return md5_safe(k)
99 return md5_safe(k)
100
100
101
101
102 class EncryptedTextValue(TypeDecorator):
102 class EncryptedTextValue(TypeDecorator):
103 """
103 """
104 Special column for encrypted long text data, use like::
104 Special column for encrypted long text data, use like::
105
105
106 value = Column("encrypted_value", EncryptedValue(), nullable=False)
106 value = Column("encrypted_value", EncryptedValue(), nullable=False)
107
107
108 This column is intelligent so if value is in unencrypted form it return
108 This column is intelligent so if value is in unencrypted form it return
109 unencrypted form, but on save it always encrypts
109 unencrypted form, but on save it always encrypts
110 """
110 """
111 impl = Text
111 impl = Text
112
112
113 def process_bind_param(self, value, dialect):
113 def process_bind_param(self, value, dialect):
114 if not value:
114 if not value:
115 return value
115 return value
116 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
116 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
117 # protect against double encrypting if someone manually starts
117 # protect against double encrypting if someone manually starts
118 # doing
118 # doing
119 raise ValueError('value needs to be in unencrypted format, ie. '
119 raise ValueError('value needs to be in unencrypted format, ie. '
120 'not starting with enc$aes')
120 'not starting with enc$aes')
121 return 'enc$aes_hmac$%s' % AESCipher(
121 return 'enc$aes_hmac$%s' % AESCipher(
122 ENCRYPTION_KEY, hmac=True).encrypt(value)
122 ENCRYPTION_KEY, hmac=True).encrypt(value)
123
123
124 def process_result_value(self, value, dialect):
124 def process_result_value(self, value, dialect):
125 import rhodecode
125 import rhodecode
126
126
127 if not value:
127 if not value:
128 return value
128 return value
129
129
130 parts = value.split('$', 3)
130 parts = value.split('$', 3)
131 if not len(parts) == 3:
131 if not len(parts) == 3:
132 # probably not encrypted values
132 # probably not encrypted values
133 return value
133 return value
134 else:
134 else:
135 if parts[0] != 'enc':
135 if parts[0] != 'enc':
136 # parts ok but without our header ?
136 # parts ok but without our header ?
137 return value
137 return value
138 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
138 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
139 'rhodecode.encrypted_values.strict') or True)
139 'rhodecode.encrypted_values.strict') or True)
140 # at that stage we know it's our encryption
140 # at that stage we know it's our encryption
141 if parts[1] == 'aes':
141 if parts[1] == 'aes':
142 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
142 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
143 elif parts[1] == 'aes_hmac':
143 elif parts[1] == 'aes_hmac':
144 decrypted_data = AESCipher(
144 decrypted_data = AESCipher(
145 ENCRYPTION_KEY, hmac=True,
145 ENCRYPTION_KEY, hmac=True,
146 strict_verification=enc_strict_mode).decrypt(parts[2])
146 strict_verification=enc_strict_mode).decrypt(parts[2])
147 else:
147 else:
148 raise ValueError(
148 raise ValueError(
149 'Encryption type part is wrong, must be `aes` '
149 'Encryption type part is wrong, must be `aes` '
150 'or `aes_hmac`, got `%s` instead' % (parts[1]))
150 'or `aes_hmac`, got `%s` instead' % (parts[1]))
151 return decrypted_data
151 return decrypted_data
152
152
153
153
154 class BaseModel(object):
154 class BaseModel(object):
155 """
155 """
156 Base Model for all classes
156 Base Model for all classes
157 """
157 """
158
158
159 @classmethod
159 @classmethod
160 def _get_keys(cls):
160 def _get_keys(cls):
161 """return column names for this model """
161 """return column names for this model """
162 return class_mapper(cls).c.keys()
162 return class_mapper(cls).c.keys()
163
163
164 def get_dict(self):
164 def get_dict(self):
165 """
165 """
166 return dict with keys and values corresponding
166 return dict with keys and values corresponding
167 to this model data """
167 to this model data """
168
168
169 d = {}
169 d = {}
170 for k in self._get_keys():
170 for k in self._get_keys():
171 d[k] = getattr(self, k)
171 d[k] = getattr(self, k)
172
172
173 # also use __json__() if present to get additional fields
173 # also use __json__() if present to get additional fields
174 _json_attr = getattr(self, '__json__', None)
174 _json_attr = getattr(self, '__json__', None)
175 if _json_attr:
175 if _json_attr:
176 # update with attributes from __json__
176 # update with attributes from __json__
177 if callable(_json_attr):
177 if callable(_json_attr):
178 _json_attr = _json_attr()
178 _json_attr = _json_attr()
179 for k, val in _json_attr.iteritems():
179 for k, val in _json_attr.iteritems():
180 d[k] = val
180 d[k] = val
181 return d
181 return d
182
182
183 def get_appstruct(self):
183 def get_appstruct(self):
184 """return list with keys and values tuples corresponding
184 """return list with keys and values tuples corresponding
185 to this model data """
185 to this model data """
186
186
187 l = []
187 l = []
188 for k in self._get_keys():
188 for k in self._get_keys():
189 l.append((k, getattr(self, k),))
189 l.append((k, getattr(self, k),))
190 return l
190 return l
191
191
192 def populate_obj(self, populate_dict):
192 def populate_obj(self, populate_dict):
193 """populate model with data from given populate_dict"""
193 """populate model with data from given populate_dict"""
194
194
195 for k in self._get_keys():
195 for k in self._get_keys():
196 if k in populate_dict:
196 if k in populate_dict:
197 setattr(self, k, populate_dict[k])
197 setattr(self, k, populate_dict[k])
198
198
199 @classmethod
199 @classmethod
200 def query(cls):
200 def query(cls):
201 return Session().query(cls)
201 return Session().query(cls)
202
202
203 @classmethod
203 @classmethod
204 def get(cls, id_):
204 def get(cls, id_):
205 if id_:
205 if id_:
206 return cls.query().get(id_)
206 return cls.query().get(id_)
207
207
208 @classmethod
208 @classmethod
209 def get_or_404(cls, id_, pyramid_exc=False):
209 def get_or_404(cls, id_, pyramid_exc=False):
210 if pyramid_exc:
210 if pyramid_exc:
211 # NOTE(marcink): backward compat, once migration to pyramid
211 # NOTE(marcink): backward compat, once migration to pyramid
212 # this should only use pyramid exceptions
212 # this should only use pyramid exceptions
213 from pyramid.httpexceptions import HTTPNotFound
213 from pyramid.httpexceptions import HTTPNotFound
214 else:
214 else:
215 from webob.exc import HTTPNotFound
215 from webob.exc import HTTPNotFound
216
216
217 try:
217 try:
218 id_ = int(id_)
218 id_ = int(id_)
219 except (TypeError, ValueError):
219 except (TypeError, ValueError):
220 raise HTTPNotFound
220 raise HTTPNotFound
221
221
222 res = cls.query().get(id_)
222 res = cls.query().get(id_)
223 if not res:
223 if not res:
224 raise HTTPNotFound
224 raise HTTPNotFound
225 return res
225 return res
226
226
227 @classmethod
227 @classmethod
228 def getAll(cls):
228 def getAll(cls):
229 # deprecated and left for backward compatibility
229 # deprecated and left for backward compatibility
230 return cls.get_all()
230 return cls.get_all()
231
231
232 @classmethod
232 @classmethod
233 def get_all(cls):
233 def get_all(cls):
234 return cls.query().all()
234 return cls.query().all()
235
235
236 @classmethod
236 @classmethod
237 def delete(cls, id_):
237 def delete(cls, id_):
238 obj = cls.query().get(id_)
238 obj = cls.query().get(id_)
239 Session().delete(obj)
239 Session().delete(obj)
240
240
241 @classmethod
241 @classmethod
242 def identity_cache(cls, session, attr_name, value):
242 def identity_cache(cls, session, attr_name, value):
243 exist_in_session = []
243 exist_in_session = []
244 for (item_cls, pkey), instance in session.identity_map.items():
244 for (item_cls, pkey), instance in session.identity_map.items():
245 if cls == item_cls and getattr(instance, attr_name) == value:
245 if cls == item_cls and getattr(instance, attr_name) == value:
246 exist_in_session.append(instance)
246 exist_in_session.append(instance)
247 if exist_in_session:
247 if exist_in_session:
248 if len(exist_in_session) == 1:
248 if len(exist_in_session) == 1:
249 return exist_in_session[0]
249 return exist_in_session[0]
250 log.exception(
250 log.exception(
251 'multiple objects with attr %s and '
251 'multiple objects with attr %s and '
252 'value %s found with same name: %r',
252 'value %s found with same name: %r',
253 attr_name, value, exist_in_session)
253 attr_name, value, exist_in_session)
254
254
255 def __repr__(self):
255 def __repr__(self):
256 if hasattr(self, '__unicode__'):
256 if hasattr(self, '__unicode__'):
257 # python repr needs to return str
257 # python repr needs to return str
258 try:
258 try:
259 return safe_str(self.__unicode__())
259 return safe_str(self.__unicode__())
260 except UnicodeDecodeError:
260 except UnicodeDecodeError:
261 pass
261 pass
262 return '<DB:%s>' % (self.__class__.__name__)
262 return '<DB:%s>' % (self.__class__.__name__)
263
263
264
264
265 class RhodeCodeSetting(Base, BaseModel):
265 class RhodeCodeSetting(Base, BaseModel):
266 __tablename__ = 'rhodecode_settings'
266 __tablename__ = 'rhodecode_settings'
267 __table_args__ = (
267 __table_args__ = (
268 UniqueConstraint('app_settings_name'),
268 UniqueConstraint('app_settings_name'),
269 {'extend_existing': True, 'mysql_engine': 'InnoDB',
269 {'extend_existing': True, 'mysql_engine': 'InnoDB',
270 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
270 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
271 )
271 )
272
272
273 SETTINGS_TYPES = {
273 SETTINGS_TYPES = {
274 'str': safe_str,
274 'str': safe_str,
275 'int': safe_int,
275 'int': safe_int,
276 'unicode': safe_unicode,
276 'unicode': safe_unicode,
277 'bool': str2bool,
277 'bool': str2bool,
278 'list': functools.partial(aslist, sep=',')
278 'list': functools.partial(aslist, sep=',')
279 }
279 }
280 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
280 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
281 GLOBAL_CONF_KEY = 'app_settings'
281 GLOBAL_CONF_KEY = 'app_settings'
282
282
283 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
283 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
284 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
284 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
285 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
285 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
286 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
286 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
287
287
288 def __init__(self, key='', val='', type='unicode'):
288 def __init__(self, key='', val='', type='unicode'):
289 self.app_settings_name = key
289 self.app_settings_name = key
290 self.app_settings_type = type
290 self.app_settings_type = type
291 self.app_settings_value = val
291 self.app_settings_value = val
292
292
293 @validates('_app_settings_value')
293 @validates('_app_settings_value')
294 def validate_settings_value(self, key, val):
294 def validate_settings_value(self, key, val):
295 assert type(val) == unicode
295 assert type(val) == unicode
296 return val
296 return val
297
297
298 @hybrid_property
298 @hybrid_property
299 def app_settings_value(self):
299 def app_settings_value(self):
300 v = self._app_settings_value
300 v = self._app_settings_value
301 _type = self.app_settings_type
301 _type = self.app_settings_type
302 if _type:
302 if _type:
303 _type = self.app_settings_type.split('.')[0]
303 _type = self.app_settings_type.split('.')[0]
304 # decode the encrypted value
304 # decode the encrypted value
305 if 'encrypted' in self.app_settings_type:
305 if 'encrypted' in self.app_settings_type:
306 cipher = EncryptedTextValue()
306 cipher = EncryptedTextValue()
307 v = safe_unicode(cipher.process_result_value(v, None))
307 v = safe_unicode(cipher.process_result_value(v, None))
308
308
309 converter = self.SETTINGS_TYPES.get(_type) or \
309 converter = self.SETTINGS_TYPES.get(_type) or \
310 self.SETTINGS_TYPES['unicode']
310 self.SETTINGS_TYPES['unicode']
311 return converter(v)
311 return converter(v)
312
312
313 @app_settings_value.setter
313 @app_settings_value.setter
314 def app_settings_value(self, val):
314 def app_settings_value(self, val):
315 """
315 """
316 Setter that will always make sure we use unicode in app_settings_value
316 Setter that will always make sure we use unicode in app_settings_value
317
317
318 :param val:
318 :param val:
319 """
319 """
320 val = safe_unicode(val)
320 val = safe_unicode(val)
321 # encode the encrypted value
321 # encode the encrypted value
322 if 'encrypted' in self.app_settings_type:
322 if 'encrypted' in self.app_settings_type:
323 cipher = EncryptedTextValue()
323 cipher = EncryptedTextValue()
324 val = safe_unicode(cipher.process_bind_param(val, None))
324 val = safe_unicode(cipher.process_bind_param(val, None))
325 self._app_settings_value = val
325 self._app_settings_value = val
326
326
327 @hybrid_property
327 @hybrid_property
328 def app_settings_type(self):
328 def app_settings_type(self):
329 return self._app_settings_type
329 return self._app_settings_type
330
330
331 @app_settings_type.setter
331 @app_settings_type.setter
332 def app_settings_type(self, val):
332 def app_settings_type(self, val):
333 if val.split('.')[0] not in self.SETTINGS_TYPES:
333 if val.split('.')[0] not in self.SETTINGS_TYPES:
334 raise Exception('type must be one of %s got %s'
334 raise Exception('type must be one of %s got %s'
335 % (self.SETTINGS_TYPES.keys(), val))
335 % (self.SETTINGS_TYPES.keys(), val))
336 self._app_settings_type = val
336 self._app_settings_type = val
337
337
338 def __unicode__(self):
338 def __unicode__(self):
339 return u"<%s('%s:%s[%s]')>" % (
339 return u"<%s('%s:%s[%s]')>" % (
340 self.__class__.__name__,
340 self.__class__.__name__,
341 self.app_settings_name, self.app_settings_value,
341 self.app_settings_name, self.app_settings_value,
342 self.app_settings_type
342 self.app_settings_type
343 )
343 )
344
344
345
345
346 class RhodeCodeUi(Base, BaseModel):
346 class RhodeCodeUi(Base, BaseModel):
347 __tablename__ = 'rhodecode_ui'
347 __tablename__ = 'rhodecode_ui'
348 __table_args__ = (
348 __table_args__ = (
349 UniqueConstraint('ui_key'),
349 UniqueConstraint('ui_key'),
350 {'extend_existing': True, 'mysql_engine': 'InnoDB',
350 {'extend_existing': True, 'mysql_engine': 'InnoDB',
351 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
351 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
352 )
352 )
353
353
354 HOOK_REPO_SIZE = 'changegroup.repo_size'
354 HOOK_REPO_SIZE = 'changegroup.repo_size'
355 # HG
355 # HG
356 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
356 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
357 HOOK_PULL = 'outgoing.pull_logger'
357 HOOK_PULL = 'outgoing.pull_logger'
358 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
358 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
359 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
359 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
360 HOOK_PUSH = 'changegroup.push_logger'
360 HOOK_PUSH = 'changegroup.push_logger'
361
361
362 # TODO: johbo: Unify way how hooks are configured for git and hg,
362 # TODO: johbo: Unify way how hooks are configured for git and hg,
363 # git part is currently hardcoded.
363 # git part is currently hardcoded.
364
364
365 # SVN PATTERNS
365 # SVN PATTERNS
366 SVN_BRANCH_ID = 'vcs_svn_branch'
366 SVN_BRANCH_ID = 'vcs_svn_branch'
367 SVN_TAG_ID = 'vcs_svn_tag'
367 SVN_TAG_ID = 'vcs_svn_tag'
368
368
369 ui_id = Column(
369 ui_id = Column(
370 "ui_id", Integer(), nullable=False, unique=True, default=None,
370 "ui_id", Integer(), nullable=False, unique=True, default=None,
371 primary_key=True)
371 primary_key=True)
372 ui_section = Column(
372 ui_section = Column(
373 "ui_section", String(255), nullable=True, unique=None, default=None)
373 "ui_section", String(255), nullable=True, unique=None, default=None)
374 ui_key = Column(
374 ui_key = Column(
375 "ui_key", String(255), nullable=True, unique=None, default=None)
375 "ui_key", String(255), nullable=True, unique=None, default=None)
376 ui_value = Column(
376 ui_value = Column(
377 "ui_value", String(255), nullable=True, unique=None, default=None)
377 "ui_value", String(255), nullable=True, unique=None, default=None)
378 ui_active = Column(
378 ui_active = Column(
379 "ui_active", Boolean(), nullable=True, unique=None, default=True)
379 "ui_active", Boolean(), nullable=True, unique=None, default=True)
380
380
381 def __repr__(self):
381 def __repr__(self):
382 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
382 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
383 self.ui_key, self.ui_value)
383 self.ui_key, self.ui_value)
384
384
385
385
386 class RepoRhodeCodeSetting(Base, BaseModel):
386 class RepoRhodeCodeSetting(Base, BaseModel):
387 __tablename__ = 'repo_rhodecode_settings'
387 __tablename__ = 'repo_rhodecode_settings'
388 __table_args__ = (
388 __table_args__ = (
389 UniqueConstraint(
389 UniqueConstraint(
390 'app_settings_name', 'repository_id',
390 'app_settings_name', 'repository_id',
391 name='uq_repo_rhodecode_setting_name_repo_id'),
391 name='uq_repo_rhodecode_setting_name_repo_id'),
392 {'extend_existing': True, 'mysql_engine': 'InnoDB',
392 {'extend_existing': True, 'mysql_engine': 'InnoDB',
393 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
393 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
394 )
394 )
395
395
396 repository_id = Column(
396 repository_id = Column(
397 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
397 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
398 nullable=False)
398 nullable=False)
399 app_settings_id = Column(
399 app_settings_id = Column(
400 "app_settings_id", Integer(), nullable=False, unique=True,
400 "app_settings_id", Integer(), nullable=False, unique=True,
401 default=None, primary_key=True)
401 default=None, primary_key=True)
402 app_settings_name = Column(
402 app_settings_name = Column(
403 "app_settings_name", String(255), nullable=True, unique=None,
403 "app_settings_name", String(255), nullable=True, unique=None,
404 default=None)
404 default=None)
405 _app_settings_value = Column(
405 _app_settings_value = Column(
406 "app_settings_value", String(4096), nullable=True, unique=None,
406 "app_settings_value", String(4096), nullable=True, unique=None,
407 default=None)
407 default=None)
408 _app_settings_type = Column(
408 _app_settings_type = Column(
409 "app_settings_type", String(255), nullable=True, unique=None,
409 "app_settings_type", String(255), nullable=True, unique=None,
410 default=None)
410 default=None)
411
411
412 repository = relationship('Repository')
412 repository = relationship('Repository')
413
413
414 def __init__(self, repository_id, key='', val='', type='unicode'):
414 def __init__(self, repository_id, key='', val='', type='unicode'):
415 self.repository_id = repository_id
415 self.repository_id = repository_id
416 self.app_settings_name = key
416 self.app_settings_name = key
417 self.app_settings_type = type
417 self.app_settings_type = type
418 self.app_settings_value = val
418 self.app_settings_value = val
419
419
420 @validates('_app_settings_value')
420 @validates('_app_settings_value')
421 def validate_settings_value(self, key, val):
421 def validate_settings_value(self, key, val):
422 assert type(val) == unicode
422 assert type(val) == unicode
423 return val
423 return val
424
424
425 @hybrid_property
425 @hybrid_property
426 def app_settings_value(self):
426 def app_settings_value(self):
427 v = self._app_settings_value
427 v = self._app_settings_value
428 type_ = self.app_settings_type
428 type_ = self.app_settings_type
429 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
429 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
430 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
430 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
431 return converter(v)
431 return converter(v)
432
432
433 @app_settings_value.setter
433 @app_settings_value.setter
434 def app_settings_value(self, val):
434 def app_settings_value(self, val):
435 """
435 """
436 Setter that will always make sure we use unicode in app_settings_value
436 Setter that will always make sure we use unicode in app_settings_value
437
437
438 :param val:
438 :param val:
439 """
439 """
440 self._app_settings_value = safe_unicode(val)
440 self._app_settings_value = safe_unicode(val)
441
441
442 @hybrid_property
442 @hybrid_property
443 def app_settings_type(self):
443 def app_settings_type(self):
444 return self._app_settings_type
444 return self._app_settings_type
445
445
446 @app_settings_type.setter
446 @app_settings_type.setter
447 def app_settings_type(self, val):
447 def app_settings_type(self, val):
448 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
448 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
449 if val not in SETTINGS_TYPES:
449 if val not in SETTINGS_TYPES:
450 raise Exception('type must be one of %s got %s'
450 raise Exception('type must be one of %s got %s'
451 % (SETTINGS_TYPES.keys(), val))
451 % (SETTINGS_TYPES.keys(), val))
452 self._app_settings_type = val
452 self._app_settings_type = val
453
453
454 def __unicode__(self):
454 def __unicode__(self):
455 return u"<%s('%s:%s:%s[%s]')>" % (
455 return u"<%s('%s:%s:%s[%s]')>" % (
456 self.__class__.__name__, self.repository.repo_name,
456 self.__class__.__name__, self.repository.repo_name,
457 self.app_settings_name, self.app_settings_value,
457 self.app_settings_name, self.app_settings_value,
458 self.app_settings_type
458 self.app_settings_type
459 )
459 )
460
460
461
461
462 class RepoRhodeCodeUi(Base, BaseModel):
462 class RepoRhodeCodeUi(Base, BaseModel):
463 __tablename__ = 'repo_rhodecode_ui'
463 __tablename__ = 'repo_rhodecode_ui'
464 __table_args__ = (
464 __table_args__ = (
465 UniqueConstraint(
465 UniqueConstraint(
466 'repository_id', 'ui_section', 'ui_key',
466 'repository_id', 'ui_section', 'ui_key',
467 name='uq_repo_rhodecode_ui_repository_id_section_key'),
467 name='uq_repo_rhodecode_ui_repository_id_section_key'),
468 {'extend_existing': True, 'mysql_engine': 'InnoDB',
468 {'extend_existing': True, 'mysql_engine': 'InnoDB',
469 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
469 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
470 )
470 )
471
471
472 repository_id = Column(
472 repository_id = Column(
473 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
473 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
474 nullable=False)
474 nullable=False)
475 ui_id = Column(
475 ui_id = Column(
476 "ui_id", Integer(), nullable=False, unique=True, default=None,
476 "ui_id", Integer(), nullable=False, unique=True, default=None,
477 primary_key=True)
477 primary_key=True)
478 ui_section = Column(
478 ui_section = Column(
479 "ui_section", String(255), nullable=True, unique=None, default=None)
479 "ui_section", String(255), nullable=True, unique=None, default=None)
480 ui_key = Column(
480 ui_key = Column(
481 "ui_key", String(255), nullable=True, unique=None, default=None)
481 "ui_key", String(255), nullable=True, unique=None, default=None)
482 ui_value = Column(
482 ui_value = Column(
483 "ui_value", String(255), nullable=True, unique=None, default=None)
483 "ui_value", String(255), nullable=True, unique=None, default=None)
484 ui_active = Column(
484 ui_active = Column(
485 "ui_active", Boolean(), nullable=True, unique=None, default=True)
485 "ui_active", Boolean(), nullable=True, unique=None, default=True)
486
486
487 repository = relationship('Repository')
487 repository = relationship('Repository')
488
488
489 def __repr__(self):
489 def __repr__(self):
490 return '<%s[%s:%s]%s=>%s]>' % (
490 return '<%s[%s:%s]%s=>%s]>' % (
491 self.__class__.__name__, self.repository.repo_name,
491 self.__class__.__name__, self.repository.repo_name,
492 self.ui_section, self.ui_key, self.ui_value)
492 self.ui_section, self.ui_key, self.ui_value)
493
493
494
494
495 class User(Base, BaseModel):
495 class User(Base, BaseModel):
496 __tablename__ = 'users'
496 __tablename__ = 'users'
497 __table_args__ = (
497 __table_args__ = (
498 UniqueConstraint('username'), UniqueConstraint('email'),
498 UniqueConstraint('username'), UniqueConstraint('email'),
499 Index('u_username_idx', 'username'),
499 Index('u_username_idx', 'username'),
500 Index('u_email_idx', 'email'),
500 Index('u_email_idx', 'email'),
501 {'extend_existing': True, 'mysql_engine': 'InnoDB',
501 {'extend_existing': True, 'mysql_engine': 'InnoDB',
502 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
502 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
503 )
503 )
504 DEFAULT_USER = 'default'
504 DEFAULT_USER = 'default'
505 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
505 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
506 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
506 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
507
507
508 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
508 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
509 username = Column("username", String(255), nullable=True, unique=None, default=None)
509 username = Column("username", String(255), nullable=True, unique=None, default=None)
510 password = Column("password", String(255), nullable=True, unique=None, default=None)
510 password = Column("password", String(255), nullable=True, unique=None, default=None)
511 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
511 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
512 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
512 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
513 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
513 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
514 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
514 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
515 _email = Column("email", String(255), nullable=True, unique=None, default=None)
515 _email = Column("email", String(255), nullable=True, unique=None, default=None)
516 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
516 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
517 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
517 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
518
518
519 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
519 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
520 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
520 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
521 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
521 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
522 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
522 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
523 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
523 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
524 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
524 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
525
525
526 user_log = relationship('UserLog')
526 user_log = relationship('UserLog')
527 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
527 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
528
528
529 repositories = relationship('Repository')
529 repositories = relationship('Repository')
530 repository_groups = relationship('RepoGroup')
530 repository_groups = relationship('RepoGroup')
531 user_groups = relationship('UserGroup')
531 user_groups = relationship('UserGroup')
532
532
533 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
533 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
534 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
534 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
535
535
536 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
536 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
537 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
537 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
538 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
538 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
539
539
540 group_member = relationship('UserGroupMember', cascade='all')
540 group_member = relationship('UserGroupMember', cascade='all')
541
541
542 notifications = relationship('UserNotification', cascade='all')
542 notifications = relationship('UserNotification', cascade='all')
543 # notifications assigned to this user
543 # notifications assigned to this user
544 user_created_notifications = relationship('Notification', cascade='all')
544 user_created_notifications = relationship('Notification', cascade='all')
545 # comments created by this user
545 # comments created by this user
546 user_comments = relationship('ChangesetComment', cascade='all')
546 user_comments = relationship('ChangesetComment', cascade='all')
547 # user profile extra info
547 # user profile extra info
548 user_emails = relationship('UserEmailMap', cascade='all')
548 user_emails = relationship('UserEmailMap', cascade='all')
549 user_ip_map = relationship('UserIpMap', cascade='all')
549 user_ip_map = relationship('UserIpMap', cascade='all')
550 user_auth_tokens = relationship('UserApiKeys', cascade='all')
550 user_auth_tokens = relationship('UserApiKeys', cascade='all')
551 # gists
551 # gists
552 user_gists = relationship('Gist', cascade='all')
552 user_gists = relationship('Gist', cascade='all')
553 # user pull requests
553 # user pull requests
554 user_pull_requests = relationship('PullRequest', cascade='all')
554 user_pull_requests = relationship('PullRequest', cascade='all')
555 # external identities
555 # external identities
556 extenal_identities = relationship(
556 extenal_identities = relationship(
557 'ExternalIdentity',
557 'ExternalIdentity',
558 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
558 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
559 cascade='all')
559 cascade='all')
560
560
561 def __unicode__(self):
561 def __unicode__(self):
562 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
562 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
563 self.user_id, self.username)
563 self.user_id, self.username)
564
564
565 @hybrid_property
565 @hybrid_property
566 def email(self):
566 def email(self):
567 return self._email
567 return self._email
568
568
569 @email.setter
569 @email.setter
570 def email(self, val):
570 def email(self, val):
571 self._email = val.lower() if val else None
571 self._email = val.lower() if val else None
572
572
573 @hybrid_property
573 @hybrid_property
574 def api_key(self):
574 def api_key(self):
575 """
575 """
576 Fetch if exist an auth-token with role ALL connected to this user
576 Fetch if exist an auth-token with role ALL connected to this user
577 """
577 """
578 user_auth_token = UserApiKeys.query()\
578 user_auth_token = UserApiKeys.query()\
579 .filter(UserApiKeys.user_id == self.user_id)\
579 .filter(UserApiKeys.user_id == self.user_id)\
580 .filter(or_(UserApiKeys.expires == -1,
580 .filter(or_(UserApiKeys.expires == -1,
581 UserApiKeys.expires >= time.time()))\
581 UserApiKeys.expires >= time.time()))\
582 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
582 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
583 if user_auth_token:
583 if user_auth_token:
584 user_auth_token = user_auth_token.api_key
584 user_auth_token = user_auth_token.api_key
585
585
586 return user_auth_token
586 return user_auth_token
587
587
588 @api_key.setter
588 @api_key.setter
589 def api_key(self, val):
589 def api_key(self, val):
590 # don't allow to set API key this is deprecated for now
590 # don't allow to set API key this is deprecated for now
591 self._api_key = None
591 self._api_key = None
592
592
593 @property
593 @property
594 def firstname(self):
594 def firstname(self):
595 # alias for future
595 # alias for future
596 return self.name
596 return self.name
597
597
598 @property
598 @property
599 def emails(self):
599 def emails(self):
600 other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
600 other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
601 return [self.email] + [x.email for x in other]
601 return [self.email] + [x.email for x in other]
602
602
603 @property
603 @property
604 def auth_tokens(self):
604 def auth_tokens(self):
605 return [x.api_key for x in self.extra_auth_tokens]
605 return [x.api_key for x in self.extra_auth_tokens]
606
606
607 @property
607 @property
608 def extra_auth_tokens(self):
608 def extra_auth_tokens(self):
609 return UserApiKeys.query().filter(UserApiKeys.user == self).all()
609 return UserApiKeys.query().filter(UserApiKeys.user == self).all()
610
610
611 @property
611 @property
612 def feed_token(self):
612 def feed_token(self):
613 return self.get_feed_token()
613 return self.get_feed_token()
614
614
615 def get_feed_token(self):
615 def get_feed_token(self):
616 feed_tokens = UserApiKeys.query()\
616 feed_tokens = UserApiKeys.query()\
617 .filter(UserApiKeys.user == self)\
617 .filter(UserApiKeys.user == self)\
618 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)\
618 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)\
619 .all()
619 .all()
620 if feed_tokens:
620 if feed_tokens:
621 return feed_tokens[0].api_key
621 return feed_tokens[0].api_key
622 return 'NO_FEED_TOKEN_AVAILABLE'
622 return 'NO_FEED_TOKEN_AVAILABLE'
623
623
624 @classmethod
624 @classmethod
625 def extra_valid_auth_tokens(cls, user, role=None):
625 def extra_valid_auth_tokens(cls, user, role=None):
626 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
626 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
627 .filter(or_(UserApiKeys.expires == -1,
627 .filter(or_(UserApiKeys.expires == -1,
628 UserApiKeys.expires >= time.time()))
628 UserApiKeys.expires >= time.time()))
629 if role:
629 if role:
630 tokens = tokens.filter(or_(UserApiKeys.role == role,
630 tokens = tokens.filter(or_(UserApiKeys.role == role,
631 UserApiKeys.role == UserApiKeys.ROLE_ALL))
631 UserApiKeys.role == UserApiKeys.ROLE_ALL))
632 return tokens.all()
632 return tokens.all()
633
633
634 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
634 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
635 from rhodecode.lib import auth
635 from rhodecode.lib import auth
636
636
637 log.debug('Trying to authenticate user: %s via auth-token, '
637 log.debug('Trying to authenticate user: %s via auth-token, '
638 'and roles: %s', self, roles)
638 'and roles: %s', self, roles)
639
639
640 if not auth_token:
640 if not auth_token:
641 return False
641 return False
642
642
643 crypto_backend = auth.crypto_backend()
643 crypto_backend = auth.crypto_backend()
644
644
645 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
645 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
646 tokens_q = UserApiKeys.query()\
646 tokens_q = UserApiKeys.query()\
647 .filter(UserApiKeys.user_id == self.user_id)\
647 .filter(UserApiKeys.user_id == self.user_id)\
648 .filter(or_(UserApiKeys.expires == -1,
648 .filter(or_(UserApiKeys.expires == -1,
649 UserApiKeys.expires >= time.time()))
649 UserApiKeys.expires >= time.time()))
650
650
651 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
651 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
652
652
653 plain_tokens = []
653 plain_tokens = []
654 hash_tokens = []
654 hash_tokens = []
655
655
656 for token in tokens_q.all():
656 for token in tokens_q.all():
657 # verify scope first
657 # verify scope first
658 if token.repo_id:
658 if token.repo_id:
659 # token has a scope, we need to verify it
659 # token has a scope, we need to verify it
660 if scope_repo_id != token.repo_id:
660 if scope_repo_id != token.repo_id:
661 log.debug(
661 log.debug(
662 'Scope mismatch: token has a set repo scope: %s, '
662 'Scope mismatch: token has a set repo scope: %s, '
663 'and calling scope is:%s, skipping further checks',
663 'and calling scope is:%s, skipping further checks',
664 token.repo, scope_repo_id)
664 token.repo, scope_repo_id)
665 # token has a scope, and it doesn't match, skip token
665 # token has a scope, and it doesn't match, skip token
666 continue
666 continue
667
667
668 if token.api_key.startswith(crypto_backend.ENC_PREF):
668 if token.api_key.startswith(crypto_backend.ENC_PREF):
669 hash_tokens.append(token.api_key)
669 hash_tokens.append(token.api_key)
670 else:
670 else:
671 plain_tokens.append(token.api_key)
671 plain_tokens.append(token.api_key)
672
672
673 is_plain_match = auth_token in plain_tokens
673 is_plain_match = auth_token in plain_tokens
674 if is_plain_match:
674 if is_plain_match:
675 return True
675 return True
676
676
677 for hashed in hash_tokens:
677 for hashed in hash_tokens:
678 # TODO(marcink): this is expensive to calculate, but most secure
678 # TODO(marcink): this is expensive to calculate, but most secure
679 match = crypto_backend.hash_check(auth_token, hashed)
679 match = crypto_backend.hash_check(auth_token, hashed)
680 if match:
680 if match:
681 return True
681 return True
682
682
683 return False
683 return False
684
684
685 @property
685 @property
686 def ip_addresses(self):
686 def ip_addresses(self):
687 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
687 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
688 return [x.ip_addr for x in ret]
688 return [x.ip_addr for x in ret]
689
689
690 @property
690 @property
691 def username_and_name(self):
691 def username_and_name(self):
692 return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
692 return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
693
693
694 @property
694 @property
695 def username_or_name_or_email(self):
695 def username_or_name_or_email(self):
696 full_name = self.full_name if self.full_name is not ' ' else None
696 full_name = self.full_name if self.full_name is not ' ' else None
697 return self.username or full_name or self.email
697 return self.username or full_name or self.email
698
698
699 @property
699 @property
700 def full_name(self):
700 def full_name(self):
701 return '%s %s' % (self.firstname, self.lastname)
701 return '%s %s' % (self.firstname, self.lastname)
702
702
703 @property
703 @property
704 def full_name_or_username(self):
704 def full_name_or_username(self):
705 return ('%s %s' % (self.firstname, self.lastname)
705 return ('%s %s' % (self.firstname, self.lastname)
706 if (self.firstname and self.lastname) else self.username)
706 if (self.firstname and self.lastname) else self.username)
707
707
708 @property
708 @property
709 def full_contact(self):
709 def full_contact(self):
710 return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
710 return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
711
711
712 @property
712 @property
713 def short_contact(self):
713 def short_contact(self):
714 return '%s %s' % (self.firstname, self.lastname)
714 return '%s %s' % (self.firstname, self.lastname)
715
715
716 @property
716 @property
717 def is_admin(self):
717 def is_admin(self):
718 return self.admin
718 return self.admin
719
719
720 @property
720 @property
721 def AuthUser(self):
721 def AuthUser(self):
722 """
722 """
723 Returns instance of AuthUser for this user
723 Returns instance of AuthUser for this user
724 """
724 """
725 from rhodecode.lib.auth import AuthUser
725 from rhodecode.lib.auth import AuthUser
726 return AuthUser(user_id=self.user_id, username=self.username)
726 return AuthUser(user_id=self.user_id, username=self.username)
727
727
728 @hybrid_property
728 @hybrid_property
729 def user_data(self):
729 def user_data(self):
730 if not self._user_data:
730 if not self._user_data:
731 return {}
731 return {}
732
732
733 try:
733 try:
734 return json.loads(self._user_data)
734 return json.loads(self._user_data)
735 except TypeError:
735 except TypeError:
736 return {}
736 return {}
737
737
738 @user_data.setter
738 @user_data.setter
739 def user_data(self, val):
739 def user_data(self, val):
740 if not isinstance(val, dict):
740 if not isinstance(val, dict):
741 raise Exception('user_data must be dict, got %s' % type(val))
741 raise Exception('user_data must be dict, got %s' % type(val))
742 try:
742 try:
743 self._user_data = json.dumps(val)
743 self._user_data = json.dumps(val)
744 except Exception:
744 except Exception:
745 log.error(traceback.format_exc())
745 log.error(traceback.format_exc())
746
746
747 @classmethod
747 @classmethod
748 def get_by_username(cls, username, case_insensitive=False,
748 def get_by_username(cls, username, case_insensitive=False,
749 cache=False, identity_cache=False):
749 cache=False, identity_cache=False):
750 session = Session()
750 session = Session()
751
751
752 if case_insensitive:
752 if case_insensitive:
753 q = cls.query().filter(
753 q = cls.query().filter(
754 func.lower(cls.username) == func.lower(username))
754 func.lower(cls.username) == func.lower(username))
755 else:
755 else:
756 q = cls.query().filter(cls.username == username)
756 q = cls.query().filter(cls.username == username)
757
757
758 if cache:
758 if cache:
759 if identity_cache:
759 if identity_cache:
760 val = cls.identity_cache(session, 'username', username)
760 val = cls.identity_cache(session, 'username', username)
761 if val:
761 if val:
762 return val
762 return val
763 else:
763 else:
764 cache_key = "get_user_by_name_%s" % _hash_key(username)
764 q = q.options(
765 q = q.options(
765 FromCache("sql_cache_short",
766 FromCache("sql_cache_short", cache_key))
766 "get_user_by_name_%s" % _hash_key(username)))
767
767
768 return q.scalar()
768 return q.scalar()
769
769
770 @classmethod
770 @classmethod
771 def get_by_auth_token(cls, auth_token, cache=False):
771 def get_by_auth_token(cls, auth_token, cache=False):
772 q = UserApiKeys.query()\
772 q = UserApiKeys.query()\
773 .filter(UserApiKeys.api_key == auth_token)\
773 .filter(UserApiKeys.api_key == auth_token)\
774 .filter(or_(UserApiKeys.expires == -1,
774 .filter(or_(UserApiKeys.expires == -1,
775 UserApiKeys.expires >= time.time()))
775 UserApiKeys.expires >= time.time()))
776 if cache:
776 if cache:
777 q = q.options(FromCache("sql_cache_short",
777 q = q.options(
778 "get_auth_token_%s" % auth_token))
778 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
779
779
780 match = q.first()
780 match = q.first()
781 if match:
781 if match:
782 return match.user
782 return match.user
783
783
784 @classmethod
784 @classmethod
785 def get_by_email(cls, email, case_insensitive=False, cache=False):
785 def get_by_email(cls, email, case_insensitive=False, cache=False):
786
786
787 if case_insensitive:
787 if case_insensitive:
788 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
788 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
789
789
790 else:
790 else:
791 q = cls.query().filter(cls.email == email)
791 q = cls.query().filter(cls.email == email)
792
792
793 email_key = _hash_key(email)
793 if cache:
794 if cache:
794 q = q.options(FromCache("sql_cache_short",
795 q = q.options(
795 "get_email_key_%s" % _hash_key(email)))
796 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
796
797
797 ret = q.scalar()
798 ret = q.scalar()
798 if ret is None:
799 if ret is None:
799 q = UserEmailMap.query()
800 q = UserEmailMap.query()
800 # try fetching in alternate email map
801 # try fetching in alternate email map
801 if case_insensitive:
802 if case_insensitive:
802 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
803 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
803 else:
804 else:
804 q = q.filter(UserEmailMap.email == email)
805 q = q.filter(UserEmailMap.email == email)
805 q = q.options(joinedload(UserEmailMap.user))
806 q = q.options(joinedload(UserEmailMap.user))
806 if cache:
807 if cache:
807 q = q.options(FromCache("sql_cache_short",
808 q = q.options(
808 "get_email_map_key_%s" % email))
809 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
809 ret = getattr(q.scalar(), 'user', None)
810 ret = getattr(q.scalar(), 'user', None)
810
811
811 return ret
812 return ret
812
813
813 @classmethod
814 @classmethod
814 def get_from_cs_author(cls, author):
815 def get_from_cs_author(cls, author):
815 """
816 """
816 Tries to get User objects out of commit author string
817 Tries to get User objects out of commit author string
817
818
818 :param author:
819 :param author:
819 """
820 """
820 from rhodecode.lib.helpers import email, author_name
821 from rhodecode.lib.helpers import email, author_name
821 # Valid email in the attribute passed, see if they're in the system
822 # Valid email in the attribute passed, see if they're in the system
822 _email = email(author)
823 _email = email(author)
823 if _email:
824 if _email:
824 user = cls.get_by_email(_email, case_insensitive=True)
825 user = cls.get_by_email(_email, case_insensitive=True)
825 if user:
826 if user:
826 return user
827 return user
827 # Maybe we can match by username?
828 # Maybe we can match by username?
828 _author = author_name(author)
829 _author = author_name(author)
829 user = cls.get_by_username(_author, case_insensitive=True)
830 user = cls.get_by_username(_author, case_insensitive=True)
830 if user:
831 if user:
831 return user
832 return user
832
833
833 def update_userdata(self, **kwargs):
834 def update_userdata(self, **kwargs):
834 usr = self
835 usr = self
835 old = usr.user_data
836 old = usr.user_data
836 old.update(**kwargs)
837 old.update(**kwargs)
837 usr.user_data = old
838 usr.user_data = old
838 Session().add(usr)
839 Session().add(usr)
839 log.debug('updated userdata with ', kwargs)
840 log.debug('updated userdata with ', kwargs)
840
841
841 def update_lastlogin(self):
842 def update_lastlogin(self):
842 """Update user lastlogin"""
843 """Update user lastlogin"""
843 self.last_login = datetime.datetime.now()
844 self.last_login = datetime.datetime.now()
844 Session().add(self)
845 Session().add(self)
845 log.debug('updated user %s lastlogin', self.username)
846 log.debug('updated user %s lastlogin', self.username)
846
847
847 def update_lastactivity(self):
848 def update_lastactivity(self):
848 """Update user lastactivity"""
849 """Update user lastactivity"""
849 self.last_activity = datetime.datetime.now()
850 self.last_activity = datetime.datetime.now()
850 Session().add(self)
851 Session().add(self)
851 log.debug('updated user %s lastactivity', self.username)
852 log.debug('updated user %s lastactivity', self.username)
852
853
853 def update_password(self, new_password):
854 def update_password(self, new_password):
854 from rhodecode.lib.auth import get_crypt_password
855 from rhodecode.lib.auth import get_crypt_password
855
856
856 self.password = get_crypt_password(new_password)
857 self.password = get_crypt_password(new_password)
857 Session().add(self)
858 Session().add(self)
858
859
859 @classmethod
860 @classmethod
860 def get_first_super_admin(cls):
861 def get_first_super_admin(cls):
861 user = User.query().filter(User.admin == true()).first()
862 user = User.query().filter(User.admin == true()).first()
862 if user is None:
863 if user is None:
863 raise Exception('FATAL: Missing administrative account!')
864 raise Exception('FATAL: Missing administrative account!')
864 return user
865 return user
865
866
866 @classmethod
867 @classmethod
867 def get_all_super_admins(cls):
868 def get_all_super_admins(cls):
868 """
869 """
869 Returns all admin accounts sorted by username
870 Returns all admin accounts sorted by username
870 """
871 """
871 return User.query().filter(User.admin == true())\
872 return User.query().filter(User.admin == true())\
872 .order_by(User.username.asc()).all()
873 .order_by(User.username.asc()).all()
873
874
874 @classmethod
875 @classmethod
875 def get_default_user(cls, cache=False):
876 def get_default_user(cls, cache=False):
876 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
877 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
877 if user is None:
878 if user is None:
878 raise Exception('FATAL: Missing default account!')
879 raise Exception('FATAL: Missing default account!')
879 return user
880 return user
880
881
881 def _get_default_perms(self, user, suffix=''):
882 def _get_default_perms(self, user, suffix=''):
882 from rhodecode.model.permission import PermissionModel
883 from rhodecode.model.permission import PermissionModel
883 return PermissionModel().get_default_perms(user.user_perms, suffix)
884 return PermissionModel().get_default_perms(user.user_perms, suffix)
884
885
885 def get_default_perms(self, suffix=''):
886 def get_default_perms(self, suffix=''):
886 return self._get_default_perms(self, suffix)
887 return self._get_default_perms(self, suffix)
887
888
888 def get_api_data(self, include_secrets=False, details='full'):
889 def get_api_data(self, include_secrets=False, details='full'):
889 """
890 """
890 Common function for generating user related data for API
891 Common function for generating user related data for API
891
892
892 :param include_secrets: By default secrets in the API data will be replaced
893 :param include_secrets: By default secrets in the API data will be replaced
893 by a placeholder value to prevent exposing this data by accident. In case
894 by a placeholder value to prevent exposing this data by accident. In case
894 this data shall be exposed, set this flag to ``True``.
895 this data shall be exposed, set this flag to ``True``.
895
896
896 :param details: details can be 'basic|full' basic gives only a subset of
897 :param details: details can be 'basic|full' basic gives only a subset of
897 the available user information that includes user_id, name and emails.
898 the available user information that includes user_id, name and emails.
898 """
899 """
899 user = self
900 user = self
900 user_data = self.user_data
901 user_data = self.user_data
901 data = {
902 data = {
902 'user_id': user.user_id,
903 'user_id': user.user_id,
903 'username': user.username,
904 'username': user.username,
904 'firstname': user.name,
905 'firstname': user.name,
905 'lastname': user.lastname,
906 'lastname': user.lastname,
906 'email': user.email,
907 'email': user.email,
907 'emails': user.emails,
908 'emails': user.emails,
908 }
909 }
909 if details == 'basic':
910 if details == 'basic':
910 return data
911 return data
911
912
912 api_key_length = 40
913 api_key_length = 40
913 api_key_replacement = '*' * api_key_length
914 api_key_replacement = '*' * api_key_length
914
915
915 extras = {
916 extras = {
916 'api_keys': [api_key_replacement],
917 'api_keys': [api_key_replacement],
917 'auth_tokens': [api_key_replacement],
918 'auth_tokens': [api_key_replacement],
918 'active': user.active,
919 'active': user.active,
919 'admin': user.admin,
920 'admin': user.admin,
920 'extern_type': user.extern_type,
921 'extern_type': user.extern_type,
921 'extern_name': user.extern_name,
922 'extern_name': user.extern_name,
922 'last_login': user.last_login,
923 'last_login': user.last_login,
923 'last_activity': user.last_activity,
924 'last_activity': user.last_activity,
924 'ip_addresses': user.ip_addresses,
925 'ip_addresses': user.ip_addresses,
925 'language': user_data.get('language')
926 'language': user_data.get('language')
926 }
927 }
927 data.update(extras)
928 data.update(extras)
928
929
929 if include_secrets:
930 if include_secrets:
930 data['api_keys'] = user.auth_tokens
931 data['api_keys'] = user.auth_tokens
931 data['auth_tokens'] = user.extra_auth_tokens
932 data['auth_tokens'] = user.extra_auth_tokens
932 return data
933 return data
933
934
934 def __json__(self):
935 def __json__(self):
935 data = {
936 data = {
936 'full_name': self.full_name,
937 'full_name': self.full_name,
937 'full_name_or_username': self.full_name_or_username,
938 'full_name_or_username': self.full_name_or_username,
938 'short_contact': self.short_contact,
939 'short_contact': self.short_contact,
939 'full_contact': self.full_contact,
940 'full_contact': self.full_contact,
940 }
941 }
941 data.update(self.get_api_data())
942 data.update(self.get_api_data())
942 return data
943 return data
943
944
944
945
945 class UserApiKeys(Base, BaseModel):
946 class UserApiKeys(Base, BaseModel):
946 __tablename__ = 'user_api_keys'
947 __tablename__ = 'user_api_keys'
947 __table_args__ = (
948 __table_args__ = (
948 Index('uak_api_key_idx', 'api_key'),
949 Index('uak_api_key_idx', 'api_key'),
949 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
950 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
950 UniqueConstraint('api_key'),
951 UniqueConstraint('api_key'),
951 {'extend_existing': True, 'mysql_engine': 'InnoDB',
952 {'extend_existing': True, 'mysql_engine': 'InnoDB',
952 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
953 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
953 )
954 )
954 __mapper_args__ = {}
955 __mapper_args__ = {}
955
956
956 # ApiKey role
957 # ApiKey role
957 ROLE_ALL = 'token_role_all'
958 ROLE_ALL = 'token_role_all'
958 ROLE_HTTP = 'token_role_http'
959 ROLE_HTTP = 'token_role_http'
959 ROLE_VCS = 'token_role_vcs'
960 ROLE_VCS = 'token_role_vcs'
960 ROLE_API = 'token_role_api'
961 ROLE_API = 'token_role_api'
961 ROLE_FEED = 'token_role_feed'
962 ROLE_FEED = 'token_role_feed'
962 ROLE_PASSWORD_RESET = 'token_password_reset'
963 ROLE_PASSWORD_RESET = 'token_password_reset'
963
964
964 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
965 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
965
966
966 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
967 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
967 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
968 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
968 api_key = Column("api_key", String(255), nullable=False, unique=True)
969 api_key = Column("api_key", String(255), nullable=False, unique=True)
969 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
970 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
970 expires = Column('expires', Float(53), nullable=False)
971 expires = Column('expires', Float(53), nullable=False)
971 role = Column('role', String(255), nullable=True)
972 role = Column('role', String(255), nullable=True)
972 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
973 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
973
974
974 # scope columns
975 # scope columns
975 repo_id = Column(
976 repo_id = Column(
976 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
977 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
977 nullable=True, unique=None, default=None)
978 nullable=True, unique=None, default=None)
978 repo = relationship('Repository', lazy='joined')
979 repo = relationship('Repository', lazy='joined')
979
980
980 repo_group_id = Column(
981 repo_group_id = Column(
981 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
982 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
982 nullable=True, unique=None, default=None)
983 nullable=True, unique=None, default=None)
983 repo_group = relationship('RepoGroup', lazy='joined')
984 repo_group = relationship('RepoGroup', lazy='joined')
984
985
985 user = relationship('User', lazy='joined')
986 user = relationship('User', lazy='joined')
986
987
987 def __unicode__(self):
988 def __unicode__(self):
988 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
989 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
989
990
990 def __json__(self):
991 def __json__(self):
991 data = {
992 data = {
992 'auth_token': self.api_key,
993 'auth_token': self.api_key,
993 'role': self.role,
994 'role': self.role,
994 'scope': self.scope_humanized,
995 'scope': self.scope_humanized,
995 'expired': self.expired
996 'expired': self.expired
996 }
997 }
997 return data
998 return data
998
999
999 @property
1000 @property
1000 def expired(self):
1001 def expired(self):
1001 if self.expires == -1:
1002 if self.expires == -1:
1002 return False
1003 return False
1003 return time.time() > self.expires
1004 return time.time() > self.expires
1004
1005
1005 @classmethod
1006 @classmethod
1006 def _get_role_name(cls, role):
1007 def _get_role_name(cls, role):
1007 return {
1008 return {
1008 cls.ROLE_ALL: _('all'),
1009 cls.ROLE_ALL: _('all'),
1009 cls.ROLE_HTTP: _('http/web interface'),
1010 cls.ROLE_HTTP: _('http/web interface'),
1010 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1011 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1011 cls.ROLE_API: _('api calls'),
1012 cls.ROLE_API: _('api calls'),
1012 cls.ROLE_FEED: _('feed access'),
1013 cls.ROLE_FEED: _('feed access'),
1013 }.get(role, role)
1014 }.get(role, role)
1014
1015
1015 @property
1016 @property
1016 def role_humanized(self):
1017 def role_humanized(self):
1017 return self._get_role_name(self.role)
1018 return self._get_role_name(self.role)
1018
1019
1019 def _get_scope(self):
1020 def _get_scope(self):
1020 if self.repo:
1021 if self.repo:
1021 return repr(self.repo)
1022 return repr(self.repo)
1022 if self.repo_group:
1023 if self.repo_group:
1023 return repr(self.repo_group) + ' (recursive)'
1024 return repr(self.repo_group) + ' (recursive)'
1024 return 'global'
1025 return 'global'
1025
1026
1026 @property
1027 @property
1027 def scope_humanized(self):
1028 def scope_humanized(self):
1028 return self._get_scope()
1029 return self._get_scope()
1029
1030
1030
1031
1031 class UserEmailMap(Base, BaseModel):
1032 class UserEmailMap(Base, BaseModel):
1032 __tablename__ = 'user_email_map'
1033 __tablename__ = 'user_email_map'
1033 __table_args__ = (
1034 __table_args__ = (
1034 Index('uem_email_idx', 'email'),
1035 Index('uem_email_idx', 'email'),
1035 UniqueConstraint('email'),
1036 UniqueConstraint('email'),
1036 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1037 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1037 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1038 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1038 )
1039 )
1039 __mapper_args__ = {}
1040 __mapper_args__ = {}
1040
1041
1041 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1042 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1042 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1043 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1043 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1044 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1044 user = relationship('User', lazy='joined')
1045 user = relationship('User', lazy='joined')
1045
1046
1046 @validates('_email')
1047 @validates('_email')
1047 def validate_email(self, key, email):
1048 def validate_email(self, key, email):
1048 # check if this email is not main one
1049 # check if this email is not main one
1049 main_email = Session().query(User).filter(User.email == email).scalar()
1050 main_email = Session().query(User).filter(User.email == email).scalar()
1050 if main_email is not None:
1051 if main_email is not None:
1051 raise AttributeError('email %s is present is user table' % email)
1052 raise AttributeError('email %s is present is user table' % email)
1052 return email
1053 return email
1053
1054
1054 @hybrid_property
1055 @hybrid_property
1055 def email(self):
1056 def email(self):
1056 return self._email
1057 return self._email
1057
1058
1058 @email.setter
1059 @email.setter
1059 def email(self, val):
1060 def email(self, val):
1060 self._email = val.lower() if val else None
1061 self._email = val.lower() if val else None
1061
1062
1062
1063
1063 class UserIpMap(Base, BaseModel):
1064 class UserIpMap(Base, BaseModel):
1064 __tablename__ = 'user_ip_map'
1065 __tablename__ = 'user_ip_map'
1065 __table_args__ = (
1066 __table_args__ = (
1066 UniqueConstraint('user_id', 'ip_addr'),
1067 UniqueConstraint('user_id', 'ip_addr'),
1067 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1068 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1068 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1069 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1069 )
1070 )
1070 __mapper_args__ = {}
1071 __mapper_args__ = {}
1071
1072
1072 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1073 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1073 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1074 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1074 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1075 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1075 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1076 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1076 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1077 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1077 user = relationship('User', lazy='joined')
1078 user = relationship('User', lazy='joined')
1078
1079
1079 @classmethod
1080 @classmethod
1080 def _get_ip_range(cls, ip_addr):
1081 def _get_ip_range(cls, ip_addr):
1081 net = ipaddress.ip_network(ip_addr, strict=False)
1082 net = ipaddress.ip_network(ip_addr, strict=False)
1082 return [str(net.network_address), str(net.broadcast_address)]
1083 return [str(net.network_address), str(net.broadcast_address)]
1083
1084
1084 def __json__(self):
1085 def __json__(self):
1085 return {
1086 return {
1086 'ip_addr': self.ip_addr,
1087 'ip_addr': self.ip_addr,
1087 'ip_range': self._get_ip_range(self.ip_addr),
1088 'ip_range': self._get_ip_range(self.ip_addr),
1088 }
1089 }
1089
1090
1090 def __unicode__(self):
1091 def __unicode__(self):
1091 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1092 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1092 self.user_id, self.ip_addr)
1093 self.user_id, self.ip_addr)
1093
1094
1094
1095
1095 class UserLog(Base, BaseModel):
1096 class UserLog(Base, BaseModel):
1096 __tablename__ = 'user_logs'
1097 __tablename__ = 'user_logs'
1097 __table_args__ = (
1098 __table_args__ = (
1098 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1099 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1099 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1100 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1100 )
1101 )
1101 VERSION_1 = 'v1'
1102 VERSION_1 = 'v1'
1102 VERSION_2 = 'v2'
1103 VERSION_2 = 'v2'
1103 VERSIONS = [VERSION_1, VERSION_2]
1104 VERSIONS = [VERSION_1, VERSION_2]
1104
1105
1105 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1106 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1106 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1107 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1107 username = Column("username", String(255), nullable=True, unique=None, default=None)
1108 username = Column("username", String(255), nullable=True, unique=None, default=None)
1108 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
1109 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
1109 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1110 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1110 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1111 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1111 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1112 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1112 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1113 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1113
1114
1114 version = Column("version", String(255), nullable=True, default=VERSION_1)
1115 version = Column("version", String(255), nullable=True, default=VERSION_1)
1115 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
1116 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
1116 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
1117 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
1117
1118
1118 def __unicode__(self):
1119 def __unicode__(self):
1119 return u"<%s('id:%s:%s')>" % (
1120 return u"<%s('id:%s:%s')>" % (
1120 self.__class__.__name__, self.repository_name, self.action)
1121 self.__class__.__name__, self.repository_name, self.action)
1121
1122
1122 def __json__(self):
1123 def __json__(self):
1123 return {
1124 return {
1124 'user_id': self.user_id,
1125 'user_id': self.user_id,
1125 'username': self.username,
1126 'username': self.username,
1126 'repository_id': self.repository_id,
1127 'repository_id': self.repository_id,
1127 'repository_name': self.repository_name,
1128 'repository_name': self.repository_name,
1128 'user_ip': self.user_ip,
1129 'user_ip': self.user_ip,
1129 'action_date': self.action_date,
1130 'action_date': self.action_date,
1130 'action': self.action,
1131 'action': self.action,
1131 }
1132 }
1132
1133
1133 @property
1134 @property
1134 def action_as_day(self):
1135 def action_as_day(self):
1135 return datetime.date(*self.action_date.timetuple()[:3])
1136 return datetime.date(*self.action_date.timetuple()[:3])
1136
1137
1137 user = relationship('User')
1138 user = relationship('User')
1138 repository = relationship('Repository', cascade='')
1139 repository = relationship('Repository', cascade='')
1139
1140
1140
1141
1141 class UserGroup(Base, BaseModel):
1142 class UserGroup(Base, BaseModel):
1142 __tablename__ = 'users_groups'
1143 __tablename__ = 'users_groups'
1143 __table_args__ = (
1144 __table_args__ = (
1144 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1145 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1145 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1146 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1146 )
1147 )
1147
1148
1148 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1149 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1149 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1150 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1150 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1151 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1151 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1152 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1152 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1153 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1153 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1154 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1154 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1155 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1155 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1156 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1156
1157
1157 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1158 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1158 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1159 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1159 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1160 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1160 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1161 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1161 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1162 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1162 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1163 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1163
1164
1164 user = relationship('User')
1165 user = relationship('User')
1165
1166
1166 @hybrid_property
1167 @hybrid_property
1167 def group_data(self):
1168 def group_data(self):
1168 if not self._group_data:
1169 if not self._group_data:
1169 return {}
1170 return {}
1170
1171
1171 try:
1172 try:
1172 return json.loads(self._group_data)
1173 return json.loads(self._group_data)
1173 except TypeError:
1174 except TypeError:
1174 return {}
1175 return {}
1175
1176
1176 @group_data.setter
1177 @group_data.setter
1177 def group_data(self, val):
1178 def group_data(self, val):
1178 try:
1179 try:
1179 self._group_data = json.dumps(val)
1180 self._group_data = json.dumps(val)
1180 except Exception:
1181 except Exception:
1181 log.error(traceback.format_exc())
1182 log.error(traceback.format_exc())
1182
1183
1183 def __unicode__(self):
1184 def __unicode__(self):
1184 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1185 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1185 self.users_group_id,
1186 self.users_group_id,
1186 self.users_group_name)
1187 self.users_group_name)
1187
1188
1188 @classmethod
1189 @classmethod
1189 def get_by_group_name(cls, group_name, cache=False,
1190 def get_by_group_name(cls, group_name, cache=False,
1190 case_insensitive=False):
1191 case_insensitive=False):
1191 if case_insensitive:
1192 if case_insensitive:
1192 q = cls.query().filter(func.lower(cls.users_group_name) ==
1193 q = cls.query().filter(func.lower(cls.users_group_name) ==
1193 func.lower(group_name))
1194 func.lower(group_name))
1194
1195
1195 else:
1196 else:
1196 q = cls.query().filter(cls.users_group_name == group_name)
1197 q = cls.query().filter(cls.users_group_name == group_name)
1197 if cache:
1198 if cache:
1198 q = q.options(FromCache(
1199 q = q.options(
1199 "sql_cache_short",
1200 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1200 "get_group_%s" % _hash_key(group_name)))
1201 return q.scalar()
1201 return q.scalar()
1202
1202
1203 @classmethod
1203 @classmethod
1204 def get(cls, user_group_id, cache=False):
1204 def get(cls, user_group_id, cache=False):
1205 user_group = cls.query()
1205 user_group = cls.query()
1206 if cache:
1206 if cache:
1207 user_group = user_group.options(FromCache("sql_cache_short",
1207 user_group = user_group.options(
1208 "get_users_group_%s" % user_group_id))
1208 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1209 return user_group.get(user_group_id)
1209 return user_group.get(user_group_id)
1210
1210
1211 def permissions(self, with_admins=True, with_owner=True):
1211 def permissions(self, with_admins=True, with_owner=True):
1212 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1212 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1213 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1213 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1214 joinedload(UserUserGroupToPerm.user),
1214 joinedload(UserUserGroupToPerm.user),
1215 joinedload(UserUserGroupToPerm.permission),)
1215 joinedload(UserUserGroupToPerm.permission),)
1216
1216
1217 # get owners and admins and permissions. We do a trick of re-writing
1217 # get owners and admins and permissions. We do a trick of re-writing
1218 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1218 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1219 # has a global reference and changing one object propagates to all
1219 # has a global reference and changing one object propagates to all
1220 # others. This means if admin is also an owner admin_row that change
1220 # others. This means if admin is also an owner admin_row that change
1221 # would propagate to both objects
1221 # would propagate to both objects
1222 perm_rows = []
1222 perm_rows = []
1223 for _usr in q.all():
1223 for _usr in q.all():
1224 usr = AttributeDict(_usr.user.get_dict())
1224 usr = AttributeDict(_usr.user.get_dict())
1225 usr.permission = _usr.permission.permission_name
1225 usr.permission = _usr.permission.permission_name
1226 perm_rows.append(usr)
1226 perm_rows.append(usr)
1227
1227
1228 # filter the perm rows by 'default' first and then sort them by
1228 # filter the perm rows by 'default' first and then sort them by
1229 # admin,write,read,none permissions sorted again alphabetically in
1229 # admin,write,read,none permissions sorted again alphabetically in
1230 # each group
1230 # each group
1231 perm_rows = sorted(perm_rows, key=display_sort)
1231 perm_rows = sorted(perm_rows, key=display_sort)
1232
1232
1233 _admin_perm = 'usergroup.admin'
1233 _admin_perm = 'usergroup.admin'
1234 owner_row = []
1234 owner_row = []
1235 if with_owner:
1235 if with_owner:
1236 usr = AttributeDict(self.user.get_dict())
1236 usr = AttributeDict(self.user.get_dict())
1237 usr.owner_row = True
1237 usr.owner_row = True
1238 usr.permission = _admin_perm
1238 usr.permission = _admin_perm
1239 owner_row.append(usr)
1239 owner_row.append(usr)
1240
1240
1241 super_admin_rows = []
1241 super_admin_rows = []
1242 if with_admins:
1242 if with_admins:
1243 for usr in User.get_all_super_admins():
1243 for usr in User.get_all_super_admins():
1244 # if this admin is also owner, don't double the record
1244 # if this admin is also owner, don't double the record
1245 if usr.user_id == owner_row[0].user_id:
1245 if usr.user_id == owner_row[0].user_id:
1246 owner_row[0].admin_row = True
1246 owner_row[0].admin_row = True
1247 else:
1247 else:
1248 usr = AttributeDict(usr.get_dict())
1248 usr = AttributeDict(usr.get_dict())
1249 usr.admin_row = True
1249 usr.admin_row = True
1250 usr.permission = _admin_perm
1250 usr.permission = _admin_perm
1251 super_admin_rows.append(usr)
1251 super_admin_rows.append(usr)
1252
1252
1253 return super_admin_rows + owner_row + perm_rows
1253 return super_admin_rows + owner_row + perm_rows
1254
1254
1255 def permission_user_groups(self):
1255 def permission_user_groups(self):
1256 q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self)
1256 q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self)
1257 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1257 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1258 joinedload(UserGroupUserGroupToPerm.target_user_group),
1258 joinedload(UserGroupUserGroupToPerm.target_user_group),
1259 joinedload(UserGroupUserGroupToPerm.permission),)
1259 joinedload(UserGroupUserGroupToPerm.permission),)
1260
1260
1261 perm_rows = []
1261 perm_rows = []
1262 for _user_group in q.all():
1262 for _user_group in q.all():
1263 usr = AttributeDict(_user_group.user_group.get_dict())
1263 usr = AttributeDict(_user_group.user_group.get_dict())
1264 usr.permission = _user_group.permission.permission_name
1264 usr.permission = _user_group.permission.permission_name
1265 perm_rows.append(usr)
1265 perm_rows.append(usr)
1266
1266
1267 return perm_rows
1267 return perm_rows
1268
1268
1269 def _get_default_perms(self, user_group, suffix=''):
1269 def _get_default_perms(self, user_group, suffix=''):
1270 from rhodecode.model.permission import PermissionModel
1270 from rhodecode.model.permission import PermissionModel
1271 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1271 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1272
1272
1273 def get_default_perms(self, suffix=''):
1273 def get_default_perms(self, suffix=''):
1274 return self._get_default_perms(self, suffix)
1274 return self._get_default_perms(self, suffix)
1275
1275
1276 def get_api_data(self, with_group_members=True, include_secrets=False):
1276 def get_api_data(self, with_group_members=True, include_secrets=False):
1277 """
1277 """
1278 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1278 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1279 basically forwarded.
1279 basically forwarded.
1280
1280
1281 """
1281 """
1282 user_group = self
1282 user_group = self
1283 data = {
1283 data = {
1284 'users_group_id': user_group.users_group_id,
1284 'users_group_id': user_group.users_group_id,
1285 'group_name': user_group.users_group_name,
1285 'group_name': user_group.users_group_name,
1286 'group_description': user_group.user_group_description,
1286 'group_description': user_group.user_group_description,
1287 'active': user_group.users_group_active,
1287 'active': user_group.users_group_active,
1288 'owner': user_group.user.username,
1288 'owner': user_group.user.username,
1289 'owner_email': user_group.user.email,
1289 'owner_email': user_group.user.email,
1290 }
1290 }
1291
1291
1292 if with_group_members:
1292 if with_group_members:
1293 users = []
1293 users = []
1294 for user in user_group.members:
1294 for user in user_group.members:
1295 user = user.user
1295 user = user.user
1296 users.append(user.get_api_data(include_secrets=include_secrets))
1296 users.append(user.get_api_data(include_secrets=include_secrets))
1297 data['users'] = users
1297 data['users'] = users
1298
1298
1299 return data
1299 return data
1300
1300
1301
1301
1302 class UserGroupMember(Base, BaseModel):
1302 class UserGroupMember(Base, BaseModel):
1303 __tablename__ = 'users_groups_members'
1303 __tablename__ = 'users_groups_members'
1304 __table_args__ = (
1304 __table_args__ = (
1305 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1305 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1306 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1306 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1307 )
1307 )
1308
1308
1309 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1309 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1310 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1310 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1311 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1311 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1312
1312
1313 user = relationship('User', lazy='joined')
1313 user = relationship('User', lazy='joined')
1314 users_group = relationship('UserGroup')
1314 users_group = relationship('UserGroup')
1315
1315
1316 def __init__(self, gr_id='', u_id=''):
1316 def __init__(self, gr_id='', u_id=''):
1317 self.users_group_id = gr_id
1317 self.users_group_id = gr_id
1318 self.user_id = u_id
1318 self.user_id = u_id
1319
1319
1320
1320
1321 class RepositoryField(Base, BaseModel):
1321 class RepositoryField(Base, BaseModel):
1322 __tablename__ = 'repositories_fields'
1322 __tablename__ = 'repositories_fields'
1323 __table_args__ = (
1323 __table_args__ = (
1324 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1324 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1325 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1325 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1326 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1326 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1327 )
1327 )
1328 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1328 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1329
1329
1330 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1330 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1331 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1331 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1332 field_key = Column("field_key", String(250))
1332 field_key = Column("field_key", String(250))
1333 field_label = Column("field_label", String(1024), nullable=False)
1333 field_label = Column("field_label", String(1024), nullable=False)
1334 field_value = Column("field_value", String(10000), nullable=False)
1334 field_value = Column("field_value", String(10000), nullable=False)
1335 field_desc = Column("field_desc", String(1024), nullable=False)
1335 field_desc = Column("field_desc", String(1024), nullable=False)
1336 field_type = Column("field_type", String(255), nullable=False, unique=None)
1336 field_type = Column("field_type", String(255), nullable=False, unique=None)
1337 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1337 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1338
1338
1339 repository = relationship('Repository')
1339 repository = relationship('Repository')
1340
1340
1341 @property
1341 @property
1342 def field_key_prefixed(self):
1342 def field_key_prefixed(self):
1343 return 'ex_%s' % self.field_key
1343 return 'ex_%s' % self.field_key
1344
1344
1345 @classmethod
1345 @classmethod
1346 def un_prefix_key(cls, key):
1346 def un_prefix_key(cls, key):
1347 if key.startswith(cls.PREFIX):
1347 if key.startswith(cls.PREFIX):
1348 return key[len(cls.PREFIX):]
1348 return key[len(cls.PREFIX):]
1349 return key
1349 return key
1350
1350
1351 @classmethod
1351 @classmethod
1352 def get_by_key_name(cls, key, repo):
1352 def get_by_key_name(cls, key, repo):
1353 row = cls.query()\
1353 row = cls.query()\
1354 .filter(cls.repository == repo)\
1354 .filter(cls.repository == repo)\
1355 .filter(cls.field_key == key).scalar()
1355 .filter(cls.field_key == key).scalar()
1356 return row
1356 return row
1357
1357
1358
1358
1359 class Repository(Base, BaseModel):
1359 class Repository(Base, BaseModel):
1360 __tablename__ = 'repositories'
1360 __tablename__ = 'repositories'
1361 __table_args__ = (
1361 __table_args__ = (
1362 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1362 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1363 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1363 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1364 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1364 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1365 )
1365 )
1366 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1366 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1367 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1367 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1368
1368
1369 STATE_CREATED = 'repo_state_created'
1369 STATE_CREATED = 'repo_state_created'
1370 STATE_PENDING = 'repo_state_pending'
1370 STATE_PENDING = 'repo_state_pending'
1371 STATE_ERROR = 'repo_state_error'
1371 STATE_ERROR = 'repo_state_error'
1372
1372
1373 LOCK_AUTOMATIC = 'lock_auto'
1373 LOCK_AUTOMATIC = 'lock_auto'
1374 LOCK_API = 'lock_api'
1374 LOCK_API = 'lock_api'
1375 LOCK_WEB = 'lock_web'
1375 LOCK_WEB = 'lock_web'
1376 LOCK_PULL = 'lock_pull'
1376 LOCK_PULL = 'lock_pull'
1377
1377
1378 NAME_SEP = URL_SEP
1378 NAME_SEP = URL_SEP
1379
1379
1380 repo_id = Column(
1380 repo_id = Column(
1381 "repo_id", Integer(), nullable=False, unique=True, default=None,
1381 "repo_id", Integer(), nullable=False, unique=True, default=None,
1382 primary_key=True)
1382 primary_key=True)
1383 _repo_name = Column(
1383 _repo_name = Column(
1384 "repo_name", Text(), nullable=False, default=None)
1384 "repo_name", Text(), nullable=False, default=None)
1385 _repo_name_hash = Column(
1385 _repo_name_hash = Column(
1386 "repo_name_hash", String(255), nullable=False, unique=True)
1386 "repo_name_hash", String(255), nullable=False, unique=True)
1387 repo_state = Column("repo_state", String(255), nullable=True)
1387 repo_state = Column("repo_state", String(255), nullable=True)
1388
1388
1389 clone_uri = Column(
1389 clone_uri = Column(
1390 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1390 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1391 default=None)
1391 default=None)
1392 repo_type = Column(
1392 repo_type = Column(
1393 "repo_type", String(255), nullable=False, unique=False, default=None)
1393 "repo_type", String(255), nullable=False, unique=False, default=None)
1394 user_id = Column(
1394 user_id = Column(
1395 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1395 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1396 unique=False, default=None)
1396 unique=False, default=None)
1397 private = Column(
1397 private = Column(
1398 "private", Boolean(), nullable=True, unique=None, default=None)
1398 "private", Boolean(), nullable=True, unique=None, default=None)
1399 enable_statistics = Column(
1399 enable_statistics = Column(
1400 "statistics", Boolean(), nullable=True, unique=None, default=True)
1400 "statistics", Boolean(), nullable=True, unique=None, default=True)
1401 enable_downloads = Column(
1401 enable_downloads = Column(
1402 "downloads", Boolean(), nullable=True, unique=None, default=True)
1402 "downloads", Boolean(), nullable=True, unique=None, default=True)
1403 description = Column(
1403 description = Column(
1404 "description", String(10000), nullable=True, unique=None, default=None)
1404 "description", String(10000), nullable=True, unique=None, default=None)
1405 created_on = Column(
1405 created_on = Column(
1406 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1406 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1407 default=datetime.datetime.now)
1407 default=datetime.datetime.now)
1408 updated_on = Column(
1408 updated_on = Column(
1409 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1409 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1410 default=datetime.datetime.now)
1410 default=datetime.datetime.now)
1411 _landing_revision = Column(
1411 _landing_revision = Column(
1412 "landing_revision", String(255), nullable=False, unique=False,
1412 "landing_revision", String(255), nullable=False, unique=False,
1413 default=None)
1413 default=None)
1414 enable_locking = Column(
1414 enable_locking = Column(
1415 "enable_locking", Boolean(), nullable=False, unique=None,
1415 "enable_locking", Boolean(), nullable=False, unique=None,
1416 default=False)
1416 default=False)
1417 _locked = Column(
1417 _locked = Column(
1418 "locked", String(255), nullable=True, unique=False, default=None)
1418 "locked", String(255), nullable=True, unique=False, default=None)
1419 _changeset_cache = Column(
1419 _changeset_cache = Column(
1420 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1420 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1421
1421
1422 fork_id = Column(
1422 fork_id = Column(
1423 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1423 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1424 nullable=True, unique=False, default=None)
1424 nullable=True, unique=False, default=None)
1425 group_id = Column(
1425 group_id = Column(
1426 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1426 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1427 unique=False, default=None)
1427 unique=False, default=None)
1428
1428
1429 user = relationship('User', lazy='joined')
1429 user = relationship('User', lazy='joined')
1430 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1430 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1431 group = relationship('RepoGroup', lazy='joined')
1431 group = relationship('RepoGroup', lazy='joined')
1432 repo_to_perm = relationship(
1432 repo_to_perm = relationship(
1433 'UserRepoToPerm', cascade='all',
1433 'UserRepoToPerm', cascade='all',
1434 order_by='UserRepoToPerm.repo_to_perm_id')
1434 order_by='UserRepoToPerm.repo_to_perm_id')
1435 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1435 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1436 stats = relationship('Statistics', cascade='all', uselist=False)
1436 stats = relationship('Statistics', cascade='all', uselist=False)
1437
1437
1438 followers = relationship(
1438 followers = relationship(
1439 'UserFollowing',
1439 'UserFollowing',
1440 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1440 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1441 cascade='all')
1441 cascade='all')
1442 extra_fields = relationship(
1442 extra_fields = relationship(
1443 'RepositoryField', cascade="all, delete, delete-orphan")
1443 'RepositoryField', cascade="all, delete, delete-orphan")
1444 logs = relationship('UserLog')
1444 logs = relationship('UserLog')
1445 comments = relationship(
1445 comments = relationship(
1446 'ChangesetComment', cascade="all, delete, delete-orphan")
1446 'ChangesetComment', cascade="all, delete, delete-orphan")
1447 pull_requests_source = relationship(
1447 pull_requests_source = relationship(
1448 'PullRequest',
1448 'PullRequest',
1449 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1449 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1450 cascade="all, delete, delete-orphan")
1450 cascade="all, delete, delete-orphan")
1451 pull_requests_target = relationship(
1451 pull_requests_target = relationship(
1452 'PullRequest',
1452 'PullRequest',
1453 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1453 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1454 cascade="all, delete, delete-orphan")
1454 cascade="all, delete, delete-orphan")
1455 ui = relationship('RepoRhodeCodeUi', cascade="all")
1455 ui = relationship('RepoRhodeCodeUi', cascade="all")
1456 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1456 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1457 integrations = relationship('Integration',
1457 integrations = relationship('Integration',
1458 cascade="all, delete, delete-orphan")
1458 cascade="all, delete, delete-orphan")
1459
1459
1460 def __unicode__(self):
1460 def __unicode__(self):
1461 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1461 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1462 safe_unicode(self.repo_name))
1462 safe_unicode(self.repo_name))
1463
1463
1464 @hybrid_property
1464 @hybrid_property
1465 def landing_rev(self):
1465 def landing_rev(self):
1466 # always should return [rev_type, rev]
1466 # always should return [rev_type, rev]
1467 if self._landing_revision:
1467 if self._landing_revision:
1468 _rev_info = self._landing_revision.split(':')
1468 _rev_info = self._landing_revision.split(':')
1469 if len(_rev_info) < 2:
1469 if len(_rev_info) < 2:
1470 _rev_info.insert(0, 'rev')
1470 _rev_info.insert(0, 'rev')
1471 return [_rev_info[0], _rev_info[1]]
1471 return [_rev_info[0], _rev_info[1]]
1472 return [None, None]
1472 return [None, None]
1473
1473
1474 @landing_rev.setter
1474 @landing_rev.setter
1475 def landing_rev(self, val):
1475 def landing_rev(self, val):
1476 if ':' not in val:
1476 if ':' not in val:
1477 raise ValueError('value must be delimited with `:` and consist '
1477 raise ValueError('value must be delimited with `:` and consist '
1478 'of <rev_type>:<rev>, got %s instead' % val)
1478 'of <rev_type>:<rev>, got %s instead' % val)
1479 self._landing_revision = val
1479 self._landing_revision = val
1480
1480
1481 @hybrid_property
1481 @hybrid_property
1482 def locked(self):
1482 def locked(self):
1483 if self._locked:
1483 if self._locked:
1484 user_id, timelocked, reason = self._locked.split(':')
1484 user_id, timelocked, reason = self._locked.split(':')
1485 lock_values = int(user_id), timelocked, reason
1485 lock_values = int(user_id), timelocked, reason
1486 else:
1486 else:
1487 lock_values = [None, None, None]
1487 lock_values = [None, None, None]
1488 return lock_values
1488 return lock_values
1489
1489
1490 @locked.setter
1490 @locked.setter
1491 def locked(self, val):
1491 def locked(self, val):
1492 if val and isinstance(val, (list, tuple)):
1492 if val and isinstance(val, (list, tuple)):
1493 self._locked = ':'.join(map(str, val))
1493 self._locked = ':'.join(map(str, val))
1494 else:
1494 else:
1495 self._locked = None
1495 self._locked = None
1496
1496
1497 @hybrid_property
1497 @hybrid_property
1498 def changeset_cache(self):
1498 def changeset_cache(self):
1499 from rhodecode.lib.vcs.backends.base import EmptyCommit
1499 from rhodecode.lib.vcs.backends.base import EmptyCommit
1500 dummy = EmptyCommit().__json__()
1500 dummy = EmptyCommit().__json__()
1501 if not self._changeset_cache:
1501 if not self._changeset_cache:
1502 return dummy
1502 return dummy
1503 try:
1503 try:
1504 return json.loads(self._changeset_cache)
1504 return json.loads(self._changeset_cache)
1505 except TypeError:
1505 except TypeError:
1506 return dummy
1506 return dummy
1507 except Exception:
1507 except Exception:
1508 log.error(traceback.format_exc())
1508 log.error(traceback.format_exc())
1509 return dummy
1509 return dummy
1510
1510
1511 @changeset_cache.setter
1511 @changeset_cache.setter
1512 def changeset_cache(self, val):
1512 def changeset_cache(self, val):
1513 try:
1513 try:
1514 self._changeset_cache = json.dumps(val)
1514 self._changeset_cache = json.dumps(val)
1515 except Exception:
1515 except Exception:
1516 log.error(traceback.format_exc())
1516 log.error(traceback.format_exc())
1517
1517
1518 @hybrid_property
1518 @hybrid_property
1519 def repo_name(self):
1519 def repo_name(self):
1520 return self._repo_name
1520 return self._repo_name
1521
1521
1522 @repo_name.setter
1522 @repo_name.setter
1523 def repo_name(self, value):
1523 def repo_name(self, value):
1524 self._repo_name = value
1524 self._repo_name = value
1525 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1525 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1526
1526
1527 @classmethod
1527 @classmethod
1528 def normalize_repo_name(cls, repo_name):
1528 def normalize_repo_name(cls, repo_name):
1529 """
1529 """
1530 Normalizes os specific repo_name to the format internally stored inside
1530 Normalizes os specific repo_name to the format internally stored inside
1531 database using URL_SEP
1531 database using URL_SEP
1532
1532
1533 :param cls:
1533 :param cls:
1534 :param repo_name:
1534 :param repo_name:
1535 """
1535 """
1536 return cls.NAME_SEP.join(repo_name.split(os.sep))
1536 return cls.NAME_SEP.join(repo_name.split(os.sep))
1537
1537
1538 @classmethod
1538 @classmethod
1539 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1539 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1540 session = Session()
1540 session = Session()
1541 q = session.query(cls).filter(cls.repo_name == repo_name)
1541 q = session.query(cls).filter(cls.repo_name == repo_name)
1542
1542
1543 if cache:
1543 if cache:
1544 if identity_cache:
1544 if identity_cache:
1545 val = cls.identity_cache(session, 'repo_name', repo_name)
1545 val = cls.identity_cache(session, 'repo_name', repo_name)
1546 if val:
1546 if val:
1547 return val
1547 return val
1548 else:
1548 else:
1549 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1549 q = q.options(
1550 q = q.options(
1550 FromCache("sql_cache_short",
1551 FromCache("sql_cache_short", cache_key))
1551 "get_repo_by_name_%s" % _hash_key(repo_name)))
1552
1552
1553 return q.scalar()
1553 return q.scalar()
1554
1554
1555 @classmethod
1555 @classmethod
1556 def get_by_full_path(cls, repo_full_path):
1556 def get_by_full_path(cls, repo_full_path):
1557 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1557 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1558 repo_name = cls.normalize_repo_name(repo_name)
1558 repo_name = cls.normalize_repo_name(repo_name)
1559 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1559 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1560
1560
1561 @classmethod
1561 @classmethod
1562 def get_repo_forks(cls, repo_id):
1562 def get_repo_forks(cls, repo_id):
1563 return cls.query().filter(Repository.fork_id == repo_id)
1563 return cls.query().filter(Repository.fork_id == repo_id)
1564
1564
1565 @classmethod
1565 @classmethod
1566 def base_path(cls):
1566 def base_path(cls):
1567 """
1567 """
1568 Returns base path when all repos are stored
1568 Returns base path when all repos are stored
1569
1569
1570 :param cls:
1570 :param cls:
1571 """
1571 """
1572 q = Session().query(RhodeCodeUi)\
1572 q = Session().query(RhodeCodeUi)\
1573 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1573 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1574 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1574 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1575 return q.one().ui_value
1575 return q.one().ui_value
1576
1576
1577 @classmethod
1577 @classmethod
1578 def is_valid(cls, repo_name):
1578 def is_valid(cls, repo_name):
1579 """
1579 """
1580 returns True if given repo name is a valid filesystem repository
1580 returns True if given repo name is a valid filesystem repository
1581
1581
1582 :param cls:
1582 :param cls:
1583 :param repo_name:
1583 :param repo_name:
1584 """
1584 """
1585 from rhodecode.lib.utils import is_valid_repo
1585 from rhodecode.lib.utils import is_valid_repo
1586
1586
1587 return is_valid_repo(repo_name, cls.base_path())
1587 return is_valid_repo(repo_name, cls.base_path())
1588
1588
1589 @classmethod
1589 @classmethod
1590 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1590 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1591 case_insensitive=True):
1591 case_insensitive=True):
1592 q = Repository.query()
1592 q = Repository.query()
1593
1593
1594 if not isinstance(user_id, Optional):
1594 if not isinstance(user_id, Optional):
1595 q = q.filter(Repository.user_id == user_id)
1595 q = q.filter(Repository.user_id == user_id)
1596
1596
1597 if not isinstance(group_id, Optional):
1597 if not isinstance(group_id, Optional):
1598 q = q.filter(Repository.group_id == group_id)
1598 q = q.filter(Repository.group_id == group_id)
1599
1599
1600 if case_insensitive:
1600 if case_insensitive:
1601 q = q.order_by(func.lower(Repository.repo_name))
1601 q = q.order_by(func.lower(Repository.repo_name))
1602 else:
1602 else:
1603 q = q.order_by(Repository.repo_name)
1603 q = q.order_by(Repository.repo_name)
1604 return q.all()
1604 return q.all()
1605
1605
1606 @property
1606 @property
1607 def forks(self):
1607 def forks(self):
1608 """
1608 """
1609 Return forks of this repo
1609 Return forks of this repo
1610 """
1610 """
1611 return Repository.get_repo_forks(self.repo_id)
1611 return Repository.get_repo_forks(self.repo_id)
1612
1612
1613 @property
1613 @property
1614 def parent(self):
1614 def parent(self):
1615 """
1615 """
1616 Returns fork parent
1616 Returns fork parent
1617 """
1617 """
1618 return self.fork
1618 return self.fork
1619
1619
1620 @property
1620 @property
1621 def just_name(self):
1621 def just_name(self):
1622 return self.repo_name.split(self.NAME_SEP)[-1]
1622 return self.repo_name.split(self.NAME_SEP)[-1]
1623
1623
1624 @property
1624 @property
1625 def groups_with_parents(self):
1625 def groups_with_parents(self):
1626 groups = []
1626 groups = []
1627 if self.group is None:
1627 if self.group is None:
1628 return groups
1628 return groups
1629
1629
1630 cur_gr = self.group
1630 cur_gr = self.group
1631 groups.insert(0, cur_gr)
1631 groups.insert(0, cur_gr)
1632 while 1:
1632 while 1:
1633 gr = getattr(cur_gr, 'parent_group', None)
1633 gr = getattr(cur_gr, 'parent_group', None)
1634 cur_gr = cur_gr.parent_group
1634 cur_gr = cur_gr.parent_group
1635 if gr is None:
1635 if gr is None:
1636 break
1636 break
1637 groups.insert(0, gr)
1637 groups.insert(0, gr)
1638
1638
1639 return groups
1639 return groups
1640
1640
1641 @property
1641 @property
1642 def groups_and_repo(self):
1642 def groups_and_repo(self):
1643 return self.groups_with_parents, self
1643 return self.groups_with_parents, self
1644
1644
1645 @LazyProperty
1645 @LazyProperty
1646 def repo_path(self):
1646 def repo_path(self):
1647 """
1647 """
1648 Returns base full path for that repository means where it actually
1648 Returns base full path for that repository means where it actually
1649 exists on a filesystem
1649 exists on a filesystem
1650 """
1650 """
1651 q = Session().query(RhodeCodeUi).filter(
1651 q = Session().query(RhodeCodeUi).filter(
1652 RhodeCodeUi.ui_key == self.NAME_SEP)
1652 RhodeCodeUi.ui_key == self.NAME_SEP)
1653 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1653 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1654 return q.one().ui_value
1654 return q.one().ui_value
1655
1655
1656 @property
1656 @property
1657 def repo_full_path(self):
1657 def repo_full_path(self):
1658 p = [self.repo_path]
1658 p = [self.repo_path]
1659 # we need to split the name by / since this is how we store the
1659 # we need to split the name by / since this is how we store the
1660 # names in the database, but that eventually needs to be converted
1660 # names in the database, but that eventually needs to be converted
1661 # into a valid system path
1661 # into a valid system path
1662 p += self.repo_name.split(self.NAME_SEP)
1662 p += self.repo_name.split(self.NAME_SEP)
1663 return os.path.join(*map(safe_unicode, p))
1663 return os.path.join(*map(safe_unicode, p))
1664
1664
1665 @property
1665 @property
1666 def cache_keys(self):
1666 def cache_keys(self):
1667 """
1667 """
1668 Returns associated cache keys for that repo
1668 Returns associated cache keys for that repo
1669 """
1669 """
1670 return CacheKey.query()\
1670 return CacheKey.query()\
1671 .filter(CacheKey.cache_args == self.repo_name)\
1671 .filter(CacheKey.cache_args == self.repo_name)\
1672 .order_by(CacheKey.cache_key)\
1672 .order_by(CacheKey.cache_key)\
1673 .all()
1673 .all()
1674
1674
1675 def get_new_name(self, repo_name):
1675 def get_new_name(self, repo_name):
1676 """
1676 """
1677 returns new full repository name based on assigned group and new new
1677 returns new full repository name based on assigned group and new new
1678
1678
1679 :param group_name:
1679 :param group_name:
1680 """
1680 """
1681 path_prefix = self.group.full_path_splitted if self.group else []
1681 path_prefix = self.group.full_path_splitted if self.group else []
1682 return self.NAME_SEP.join(path_prefix + [repo_name])
1682 return self.NAME_SEP.join(path_prefix + [repo_name])
1683
1683
1684 @property
1684 @property
1685 def _config(self):
1685 def _config(self):
1686 """
1686 """
1687 Returns db based config object.
1687 Returns db based config object.
1688 """
1688 """
1689 from rhodecode.lib.utils import make_db_config
1689 from rhodecode.lib.utils import make_db_config
1690 return make_db_config(clear_session=False, repo=self)
1690 return make_db_config(clear_session=False, repo=self)
1691
1691
1692 def permissions(self, with_admins=True, with_owner=True):
1692 def permissions(self, with_admins=True, with_owner=True):
1693 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1693 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1694 q = q.options(joinedload(UserRepoToPerm.repository),
1694 q = q.options(joinedload(UserRepoToPerm.repository),
1695 joinedload(UserRepoToPerm.user),
1695 joinedload(UserRepoToPerm.user),
1696 joinedload(UserRepoToPerm.permission),)
1696 joinedload(UserRepoToPerm.permission),)
1697
1697
1698 # get owners and admins and permissions. We do a trick of re-writing
1698 # get owners and admins and permissions. We do a trick of re-writing
1699 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1699 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1700 # has a global reference and changing one object propagates to all
1700 # has a global reference and changing one object propagates to all
1701 # others. This means if admin is also an owner admin_row that change
1701 # others. This means if admin is also an owner admin_row that change
1702 # would propagate to both objects
1702 # would propagate to both objects
1703 perm_rows = []
1703 perm_rows = []
1704 for _usr in q.all():
1704 for _usr in q.all():
1705 usr = AttributeDict(_usr.user.get_dict())
1705 usr = AttributeDict(_usr.user.get_dict())
1706 usr.permission = _usr.permission.permission_name
1706 usr.permission = _usr.permission.permission_name
1707 perm_rows.append(usr)
1707 perm_rows.append(usr)
1708
1708
1709 # filter the perm rows by 'default' first and then sort them by
1709 # filter the perm rows by 'default' first and then sort them by
1710 # admin,write,read,none permissions sorted again alphabetically in
1710 # admin,write,read,none permissions sorted again alphabetically in
1711 # each group
1711 # each group
1712 perm_rows = sorted(perm_rows, key=display_sort)
1712 perm_rows = sorted(perm_rows, key=display_sort)
1713
1713
1714 _admin_perm = 'repository.admin'
1714 _admin_perm = 'repository.admin'
1715 owner_row = []
1715 owner_row = []
1716 if with_owner:
1716 if with_owner:
1717 usr = AttributeDict(self.user.get_dict())
1717 usr = AttributeDict(self.user.get_dict())
1718 usr.owner_row = True
1718 usr.owner_row = True
1719 usr.permission = _admin_perm
1719 usr.permission = _admin_perm
1720 owner_row.append(usr)
1720 owner_row.append(usr)
1721
1721
1722 super_admin_rows = []
1722 super_admin_rows = []
1723 if with_admins:
1723 if with_admins:
1724 for usr in User.get_all_super_admins():
1724 for usr in User.get_all_super_admins():
1725 # if this admin is also owner, don't double the record
1725 # if this admin is also owner, don't double the record
1726 if usr.user_id == owner_row[0].user_id:
1726 if usr.user_id == owner_row[0].user_id:
1727 owner_row[0].admin_row = True
1727 owner_row[0].admin_row = True
1728 else:
1728 else:
1729 usr = AttributeDict(usr.get_dict())
1729 usr = AttributeDict(usr.get_dict())
1730 usr.admin_row = True
1730 usr.admin_row = True
1731 usr.permission = _admin_perm
1731 usr.permission = _admin_perm
1732 super_admin_rows.append(usr)
1732 super_admin_rows.append(usr)
1733
1733
1734 return super_admin_rows + owner_row + perm_rows
1734 return super_admin_rows + owner_row + perm_rows
1735
1735
1736 def permission_user_groups(self):
1736 def permission_user_groups(self):
1737 q = UserGroupRepoToPerm.query().filter(
1737 q = UserGroupRepoToPerm.query().filter(
1738 UserGroupRepoToPerm.repository == self)
1738 UserGroupRepoToPerm.repository == self)
1739 q = q.options(joinedload(UserGroupRepoToPerm.repository),
1739 q = q.options(joinedload(UserGroupRepoToPerm.repository),
1740 joinedload(UserGroupRepoToPerm.users_group),
1740 joinedload(UserGroupRepoToPerm.users_group),
1741 joinedload(UserGroupRepoToPerm.permission),)
1741 joinedload(UserGroupRepoToPerm.permission),)
1742
1742
1743 perm_rows = []
1743 perm_rows = []
1744 for _user_group in q.all():
1744 for _user_group in q.all():
1745 usr = AttributeDict(_user_group.users_group.get_dict())
1745 usr = AttributeDict(_user_group.users_group.get_dict())
1746 usr.permission = _user_group.permission.permission_name
1746 usr.permission = _user_group.permission.permission_name
1747 perm_rows.append(usr)
1747 perm_rows.append(usr)
1748
1748
1749 return perm_rows
1749 return perm_rows
1750
1750
1751 def get_api_data(self, include_secrets=False):
1751 def get_api_data(self, include_secrets=False):
1752 """
1752 """
1753 Common function for generating repo api data
1753 Common function for generating repo api data
1754
1754
1755 :param include_secrets: See :meth:`User.get_api_data`.
1755 :param include_secrets: See :meth:`User.get_api_data`.
1756
1756
1757 """
1757 """
1758 # TODO: mikhail: Here there is an anti-pattern, we probably need to
1758 # TODO: mikhail: Here there is an anti-pattern, we probably need to
1759 # move this methods on models level.
1759 # move this methods on models level.
1760 from rhodecode.model.settings import SettingsModel
1760 from rhodecode.model.settings import SettingsModel
1761
1761
1762 repo = self
1762 repo = self
1763 _user_id, _time, _reason = self.locked
1763 _user_id, _time, _reason = self.locked
1764
1764
1765 data = {
1765 data = {
1766 'repo_id': repo.repo_id,
1766 'repo_id': repo.repo_id,
1767 'repo_name': repo.repo_name,
1767 'repo_name': repo.repo_name,
1768 'repo_type': repo.repo_type,
1768 'repo_type': repo.repo_type,
1769 'clone_uri': repo.clone_uri or '',
1769 'clone_uri': repo.clone_uri or '',
1770 'url': url('summary_home', repo_name=self.repo_name, qualified=True),
1770 'url': url('summary_home', repo_name=self.repo_name, qualified=True),
1771 'private': repo.private,
1771 'private': repo.private,
1772 'created_on': repo.created_on,
1772 'created_on': repo.created_on,
1773 'description': repo.description,
1773 'description': repo.description,
1774 'landing_rev': repo.landing_rev,
1774 'landing_rev': repo.landing_rev,
1775 'owner': repo.user.username,
1775 'owner': repo.user.username,
1776 'fork_of': repo.fork.repo_name if repo.fork else None,
1776 'fork_of': repo.fork.repo_name if repo.fork else None,
1777 'enable_statistics': repo.enable_statistics,
1777 'enable_statistics': repo.enable_statistics,
1778 'enable_locking': repo.enable_locking,
1778 'enable_locking': repo.enable_locking,
1779 'enable_downloads': repo.enable_downloads,
1779 'enable_downloads': repo.enable_downloads,
1780 'last_changeset': repo.changeset_cache,
1780 'last_changeset': repo.changeset_cache,
1781 'locked_by': User.get(_user_id).get_api_data(
1781 'locked_by': User.get(_user_id).get_api_data(
1782 include_secrets=include_secrets) if _user_id else None,
1782 include_secrets=include_secrets) if _user_id else None,
1783 'locked_date': time_to_datetime(_time) if _time else None,
1783 'locked_date': time_to_datetime(_time) if _time else None,
1784 'lock_reason': _reason if _reason else None,
1784 'lock_reason': _reason if _reason else None,
1785 }
1785 }
1786
1786
1787 # TODO: mikhail: should be per-repo settings here
1787 # TODO: mikhail: should be per-repo settings here
1788 rc_config = SettingsModel().get_all_settings()
1788 rc_config = SettingsModel().get_all_settings()
1789 repository_fields = str2bool(
1789 repository_fields = str2bool(
1790 rc_config.get('rhodecode_repository_fields'))
1790 rc_config.get('rhodecode_repository_fields'))
1791 if repository_fields:
1791 if repository_fields:
1792 for f in self.extra_fields:
1792 for f in self.extra_fields:
1793 data[f.field_key_prefixed] = f.field_value
1793 data[f.field_key_prefixed] = f.field_value
1794
1794
1795 return data
1795 return data
1796
1796
1797 @classmethod
1797 @classmethod
1798 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
1798 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
1799 if not lock_time:
1799 if not lock_time:
1800 lock_time = time.time()
1800 lock_time = time.time()
1801 if not lock_reason:
1801 if not lock_reason:
1802 lock_reason = cls.LOCK_AUTOMATIC
1802 lock_reason = cls.LOCK_AUTOMATIC
1803 repo.locked = [user_id, lock_time, lock_reason]
1803 repo.locked = [user_id, lock_time, lock_reason]
1804 Session().add(repo)
1804 Session().add(repo)
1805 Session().commit()
1805 Session().commit()
1806
1806
1807 @classmethod
1807 @classmethod
1808 def unlock(cls, repo):
1808 def unlock(cls, repo):
1809 repo.locked = None
1809 repo.locked = None
1810 Session().add(repo)
1810 Session().add(repo)
1811 Session().commit()
1811 Session().commit()
1812
1812
1813 @classmethod
1813 @classmethod
1814 def getlock(cls, repo):
1814 def getlock(cls, repo):
1815 return repo.locked
1815 return repo.locked
1816
1816
1817 def is_user_lock(self, user_id):
1817 def is_user_lock(self, user_id):
1818 if self.lock[0]:
1818 if self.lock[0]:
1819 lock_user_id = safe_int(self.lock[0])
1819 lock_user_id = safe_int(self.lock[0])
1820 user_id = safe_int(user_id)
1820 user_id = safe_int(user_id)
1821 # both are ints, and they are equal
1821 # both are ints, and they are equal
1822 return all([lock_user_id, user_id]) and lock_user_id == user_id
1822 return all([lock_user_id, user_id]) and lock_user_id == user_id
1823
1823
1824 return False
1824 return False
1825
1825
1826 def get_locking_state(self, action, user_id, only_when_enabled=True):
1826 def get_locking_state(self, action, user_id, only_when_enabled=True):
1827 """
1827 """
1828 Checks locking on this repository, if locking is enabled and lock is
1828 Checks locking on this repository, if locking is enabled and lock is
1829 present returns a tuple of make_lock, locked, locked_by.
1829 present returns a tuple of make_lock, locked, locked_by.
1830 make_lock can have 3 states None (do nothing) True, make lock
1830 make_lock can have 3 states None (do nothing) True, make lock
1831 False release lock, This value is later propagated to hooks, which
1831 False release lock, This value is later propagated to hooks, which
1832 do the locking. Think about this as signals passed to hooks what to do.
1832 do the locking. Think about this as signals passed to hooks what to do.
1833
1833
1834 """
1834 """
1835 # TODO: johbo: This is part of the business logic and should be moved
1835 # TODO: johbo: This is part of the business logic and should be moved
1836 # into the RepositoryModel.
1836 # into the RepositoryModel.
1837
1837
1838 if action not in ('push', 'pull'):
1838 if action not in ('push', 'pull'):
1839 raise ValueError("Invalid action value: %s" % repr(action))
1839 raise ValueError("Invalid action value: %s" % repr(action))
1840
1840
1841 # defines if locked error should be thrown to user
1841 # defines if locked error should be thrown to user
1842 currently_locked = False
1842 currently_locked = False
1843 # defines if new lock should be made, tri-state
1843 # defines if new lock should be made, tri-state
1844 make_lock = None
1844 make_lock = None
1845 repo = self
1845 repo = self
1846 user = User.get(user_id)
1846 user = User.get(user_id)
1847
1847
1848 lock_info = repo.locked
1848 lock_info = repo.locked
1849
1849
1850 if repo and (repo.enable_locking or not only_when_enabled):
1850 if repo and (repo.enable_locking or not only_when_enabled):
1851 if action == 'push':
1851 if action == 'push':
1852 # check if it's already locked !, if it is compare users
1852 # check if it's already locked !, if it is compare users
1853 locked_by_user_id = lock_info[0]
1853 locked_by_user_id = lock_info[0]
1854 if user.user_id == locked_by_user_id:
1854 if user.user_id == locked_by_user_id:
1855 log.debug(
1855 log.debug(
1856 'Got `push` action from user %s, now unlocking', user)
1856 'Got `push` action from user %s, now unlocking', user)
1857 # unlock if we have push from user who locked
1857 # unlock if we have push from user who locked
1858 make_lock = False
1858 make_lock = False
1859 else:
1859 else:
1860 # we're not the same user who locked, ban with
1860 # we're not the same user who locked, ban with
1861 # code defined in settings (default is 423 HTTP Locked) !
1861 # code defined in settings (default is 423 HTTP Locked) !
1862 log.debug('Repo %s is currently locked by %s', repo, user)
1862 log.debug('Repo %s is currently locked by %s', repo, user)
1863 currently_locked = True
1863 currently_locked = True
1864 elif action == 'pull':
1864 elif action == 'pull':
1865 # [0] user [1] date
1865 # [0] user [1] date
1866 if lock_info[0] and lock_info[1]:
1866 if lock_info[0] and lock_info[1]:
1867 log.debug('Repo %s is currently locked by %s', repo, user)
1867 log.debug('Repo %s is currently locked by %s', repo, user)
1868 currently_locked = True
1868 currently_locked = True
1869 else:
1869 else:
1870 log.debug('Setting lock on repo %s by %s', repo, user)
1870 log.debug('Setting lock on repo %s by %s', repo, user)
1871 make_lock = True
1871 make_lock = True
1872
1872
1873 else:
1873 else:
1874 log.debug('Repository %s do not have locking enabled', repo)
1874 log.debug('Repository %s do not have locking enabled', repo)
1875
1875
1876 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
1876 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
1877 make_lock, currently_locked, lock_info)
1877 make_lock, currently_locked, lock_info)
1878
1878
1879 from rhodecode.lib.auth import HasRepoPermissionAny
1879 from rhodecode.lib.auth import HasRepoPermissionAny
1880 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
1880 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
1881 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
1881 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
1882 # if we don't have at least write permission we cannot make a lock
1882 # if we don't have at least write permission we cannot make a lock
1883 log.debug('lock state reset back to FALSE due to lack '
1883 log.debug('lock state reset back to FALSE due to lack '
1884 'of at least read permission')
1884 'of at least read permission')
1885 make_lock = False
1885 make_lock = False
1886
1886
1887 return make_lock, currently_locked, lock_info
1887 return make_lock, currently_locked, lock_info
1888
1888
1889 @property
1889 @property
1890 def last_db_change(self):
1890 def last_db_change(self):
1891 return self.updated_on
1891 return self.updated_on
1892
1892
1893 @property
1893 @property
1894 def clone_uri_hidden(self):
1894 def clone_uri_hidden(self):
1895 clone_uri = self.clone_uri
1895 clone_uri = self.clone_uri
1896 if clone_uri:
1896 if clone_uri:
1897 import urlobject
1897 import urlobject
1898 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
1898 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
1899 if url_obj.password:
1899 if url_obj.password:
1900 clone_uri = url_obj.with_password('*****')
1900 clone_uri = url_obj.with_password('*****')
1901 return clone_uri
1901 return clone_uri
1902
1902
1903 def clone_url(self, **override):
1903 def clone_url(self, **override):
1904 qualified_home_url = url('home', qualified=True)
1904 qualified_home_url = url('home', qualified=True)
1905
1905
1906 uri_tmpl = None
1906 uri_tmpl = None
1907 if 'with_id' in override:
1907 if 'with_id' in override:
1908 uri_tmpl = self.DEFAULT_CLONE_URI_ID
1908 uri_tmpl = self.DEFAULT_CLONE_URI_ID
1909 del override['with_id']
1909 del override['with_id']
1910
1910
1911 if 'uri_tmpl' in override:
1911 if 'uri_tmpl' in override:
1912 uri_tmpl = override['uri_tmpl']
1912 uri_tmpl = override['uri_tmpl']
1913 del override['uri_tmpl']
1913 del override['uri_tmpl']
1914
1914
1915 # we didn't override our tmpl from **overrides
1915 # we didn't override our tmpl from **overrides
1916 if not uri_tmpl:
1916 if not uri_tmpl:
1917 uri_tmpl = self.DEFAULT_CLONE_URI
1917 uri_tmpl = self.DEFAULT_CLONE_URI
1918 try:
1918 try:
1919 from pylons import tmpl_context as c
1919 from pylons import tmpl_context as c
1920 uri_tmpl = c.clone_uri_tmpl
1920 uri_tmpl = c.clone_uri_tmpl
1921 except Exception:
1921 except Exception:
1922 # in any case if we call this outside of request context,
1922 # in any case if we call this outside of request context,
1923 # ie, not having tmpl_context set up
1923 # ie, not having tmpl_context set up
1924 pass
1924 pass
1925
1925
1926 return get_clone_url(uri_tmpl=uri_tmpl,
1926 return get_clone_url(uri_tmpl=uri_tmpl,
1927 qualifed_home_url=qualified_home_url,
1927 qualifed_home_url=qualified_home_url,
1928 repo_name=self.repo_name,
1928 repo_name=self.repo_name,
1929 repo_id=self.repo_id, **override)
1929 repo_id=self.repo_id, **override)
1930
1930
1931 def set_state(self, state):
1931 def set_state(self, state):
1932 self.repo_state = state
1932 self.repo_state = state
1933 Session().add(self)
1933 Session().add(self)
1934 #==========================================================================
1934 #==========================================================================
1935 # SCM PROPERTIES
1935 # SCM PROPERTIES
1936 #==========================================================================
1936 #==========================================================================
1937
1937
1938 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
1938 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
1939 return get_commit_safe(
1939 return get_commit_safe(
1940 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
1940 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
1941
1941
1942 def get_changeset(self, rev=None, pre_load=None):
1942 def get_changeset(self, rev=None, pre_load=None):
1943 warnings.warn("Use get_commit", DeprecationWarning)
1943 warnings.warn("Use get_commit", DeprecationWarning)
1944 commit_id = None
1944 commit_id = None
1945 commit_idx = None
1945 commit_idx = None
1946 if isinstance(rev, basestring):
1946 if isinstance(rev, basestring):
1947 commit_id = rev
1947 commit_id = rev
1948 else:
1948 else:
1949 commit_idx = rev
1949 commit_idx = rev
1950 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
1950 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
1951 pre_load=pre_load)
1951 pre_load=pre_load)
1952
1952
1953 def get_landing_commit(self):
1953 def get_landing_commit(self):
1954 """
1954 """
1955 Returns landing commit, or if that doesn't exist returns the tip
1955 Returns landing commit, or if that doesn't exist returns the tip
1956 """
1956 """
1957 _rev_type, _rev = self.landing_rev
1957 _rev_type, _rev = self.landing_rev
1958 commit = self.get_commit(_rev)
1958 commit = self.get_commit(_rev)
1959 if isinstance(commit, EmptyCommit):
1959 if isinstance(commit, EmptyCommit):
1960 return self.get_commit()
1960 return self.get_commit()
1961 return commit
1961 return commit
1962
1962
1963 def update_commit_cache(self, cs_cache=None, config=None):
1963 def update_commit_cache(self, cs_cache=None, config=None):
1964 """
1964 """
1965 Update cache of last changeset for repository, keys should be::
1965 Update cache of last changeset for repository, keys should be::
1966
1966
1967 short_id
1967 short_id
1968 raw_id
1968 raw_id
1969 revision
1969 revision
1970 parents
1970 parents
1971 message
1971 message
1972 date
1972 date
1973 author
1973 author
1974
1974
1975 :param cs_cache:
1975 :param cs_cache:
1976 """
1976 """
1977 from rhodecode.lib.vcs.backends.base import BaseChangeset
1977 from rhodecode.lib.vcs.backends.base import BaseChangeset
1978 if cs_cache is None:
1978 if cs_cache is None:
1979 # use no-cache version here
1979 # use no-cache version here
1980 scm_repo = self.scm_instance(cache=False, config=config)
1980 scm_repo = self.scm_instance(cache=False, config=config)
1981 if scm_repo:
1981 if scm_repo:
1982 cs_cache = scm_repo.get_commit(
1982 cs_cache = scm_repo.get_commit(
1983 pre_load=["author", "date", "message", "parents"])
1983 pre_load=["author", "date", "message", "parents"])
1984 else:
1984 else:
1985 cs_cache = EmptyCommit()
1985 cs_cache = EmptyCommit()
1986
1986
1987 if isinstance(cs_cache, BaseChangeset):
1987 if isinstance(cs_cache, BaseChangeset):
1988 cs_cache = cs_cache.__json__()
1988 cs_cache = cs_cache.__json__()
1989
1989
1990 def is_outdated(new_cs_cache):
1990 def is_outdated(new_cs_cache):
1991 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
1991 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
1992 new_cs_cache['revision'] != self.changeset_cache['revision']):
1992 new_cs_cache['revision'] != self.changeset_cache['revision']):
1993 return True
1993 return True
1994 return False
1994 return False
1995
1995
1996 # check if we have maybe already latest cached revision
1996 # check if we have maybe already latest cached revision
1997 if is_outdated(cs_cache) or not self.changeset_cache:
1997 if is_outdated(cs_cache) or not self.changeset_cache:
1998 _default = datetime.datetime.fromtimestamp(0)
1998 _default = datetime.datetime.fromtimestamp(0)
1999 last_change = cs_cache.get('date') or _default
1999 last_change = cs_cache.get('date') or _default
2000 log.debug('updated repo %s with new cs cache %s',
2000 log.debug('updated repo %s with new cs cache %s',
2001 self.repo_name, cs_cache)
2001 self.repo_name, cs_cache)
2002 self.updated_on = last_change
2002 self.updated_on = last_change
2003 self.changeset_cache = cs_cache
2003 self.changeset_cache = cs_cache
2004 Session().add(self)
2004 Session().add(self)
2005 Session().commit()
2005 Session().commit()
2006 else:
2006 else:
2007 log.debug('Skipping update_commit_cache for repo:`%s` '
2007 log.debug('Skipping update_commit_cache for repo:`%s` '
2008 'commit already with latest changes', self.repo_name)
2008 'commit already with latest changes', self.repo_name)
2009
2009
2010 @property
2010 @property
2011 def tip(self):
2011 def tip(self):
2012 return self.get_commit('tip')
2012 return self.get_commit('tip')
2013
2013
2014 @property
2014 @property
2015 def author(self):
2015 def author(self):
2016 return self.tip.author
2016 return self.tip.author
2017
2017
2018 @property
2018 @property
2019 def last_change(self):
2019 def last_change(self):
2020 return self.scm_instance().last_change
2020 return self.scm_instance().last_change
2021
2021
2022 def get_comments(self, revisions=None):
2022 def get_comments(self, revisions=None):
2023 """
2023 """
2024 Returns comments for this repository grouped by revisions
2024 Returns comments for this repository grouped by revisions
2025
2025
2026 :param revisions: filter query by revisions only
2026 :param revisions: filter query by revisions only
2027 """
2027 """
2028 cmts = ChangesetComment.query()\
2028 cmts = ChangesetComment.query()\
2029 .filter(ChangesetComment.repo == self)
2029 .filter(ChangesetComment.repo == self)
2030 if revisions:
2030 if revisions:
2031 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2031 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2032 grouped = collections.defaultdict(list)
2032 grouped = collections.defaultdict(list)
2033 for cmt in cmts.all():
2033 for cmt in cmts.all():
2034 grouped[cmt.revision].append(cmt)
2034 grouped[cmt.revision].append(cmt)
2035 return grouped
2035 return grouped
2036
2036
2037 def statuses(self, revisions=None):
2037 def statuses(self, revisions=None):
2038 """
2038 """
2039 Returns statuses for this repository
2039 Returns statuses for this repository
2040
2040
2041 :param revisions: list of revisions to get statuses for
2041 :param revisions: list of revisions to get statuses for
2042 """
2042 """
2043 statuses = ChangesetStatus.query()\
2043 statuses = ChangesetStatus.query()\
2044 .filter(ChangesetStatus.repo == self)\
2044 .filter(ChangesetStatus.repo == self)\
2045 .filter(ChangesetStatus.version == 0)
2045 .filter(ChangesetStatus.version == 0)
2046
2046
2047 if revisions:
2047 if revisions:
2048 # Try doing the filtering in chunks to avoid hitting limits
2048 # Try doing the filtering in chunks to avoid hitting limits
2049 size = 500
2049 size = 500
2050 status_results = []
2050 status_results = []
2051 for chunk in xrange(0, len(revisions), size):
2051 for chunk in xrange(0, len(revisions), size):
2052 status_results += statuses.filter(
2052 status_results += statuses.filter(
2053 ChangesetStatus.revision.in_(
2053 ChangesetStatus.revision.in_(
2054 revisions[chunk: chunk+size])
2054 revisions[chunk: chunk+size])
2055 ).all()
2055 ).all()
2056 else:
2056 else:
2057 status_results = statuses.all()
2057 status_results = statuses.all()
2058
2058
2059 grouped = {}
2059 grouped = {}
2060
2060
2061 # maybe we have open new pullrequest without a status?
2061 # maybe we have open new pullrequest without a status?
2062 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2062 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2063 status_lbl = ChangesetStatus.get_status_lbl(stat)
2063 status_lbl = ChangesetStatus.get_status_lbl(stat)
2064 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2064 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2065 for rev in pr.revisions:
2065 for rev in pr.revisions:
2066 pr_id = pr.pull_request_id
2066 pr_id = pr.pull_request_id
2067 pr_repo = pr.target_repo.repo_name
2067 pr_repo = pr.target_repo.repo_name
2068 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2068 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2069
2069
2070 for stat in status_results:
2070 for stat in status_results:
2071 pr_id = pr_repo = None
2071 pr_id = pr_repo = None
2072 if stat.pull_request:
2072 if stat.pull_request:
2073 pr_id = stat.pull_request.pull_request_id
2073 pr_id = stat.pull_request.pull_request_id
2074 pr_repo = stat.pull_request.target_repo.repo_name
2074 pr_repo = stat.pull_request.target_repo.repo_name
2075 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2075 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2076 pr_id, pr_repo]
2076 pr_id, pr_repo]
2077 return grouped
2077 return grouped
2078
2078
2079 # ==========================================================================
2079 # ==========================================================================
2080 # SCM CACHE INSTANCE
2080 # SCM CACHE INSTANCE
2081 # ==========================================================================
2081 # ==========================================================================
2082
2082
2083 def scm_instance(self, **kwargs):
2083 def scm_instance(self, **kwargs):
2084 import rhodecode
2084 import rhodecode
2085
2085
2086 # Passing a config will not hit the cache currently only used
2086 # Passing a config will not hit the cache currently only used
2087 # for repo2dbmapper
2087 # for repo2dbmapper
2088 config = kwargs.pop('config', None)
2088 config = kwargs.pop('config', None)
2089 cache = kwargs.pop('cache', None)
2089 cache = kwargs.pop('cache', None)
2090 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2090 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2091 # if cache is NOT defined use default global, else we have a full
2091 # if cache is NOT defined use default global, else we have a full
2092 # control over cache behaviour
2092 # control over cache behaviour
2093 if cache is None and full_cache and not config:
2093 if cache is None and full_cache and not config:
2094 return self._get_instance_cached()
2094 return self._get_instance_cached()
2095 return self._get_instance(cache=bool(cache), config=config)
2095 return self._get_instance(cache=bool(cache), config=config)
2096
2096
2097 def _get_instance_cached(self):
2097 def _get_instance_cached(self):
2098 @cache_region('long_term')
2098 @cache_region('long_term')
2099 def _get_repo(cache_key):
2099 def _get_repo(cache_key):
2100 return self._get_instance()
2100 return self._get_instance()
2101
2101
2102 invalidator_context = CacheKey.repo_context_cache(
2102 invalidator_context = CacheKey.repo_context_cache(
2103 _get_repo, self.repo_name, None, thread_scoped=True)
2103 _get_repo, self.repo_name, None, thread_scoped=True)
2104
2104
2105 with invalidator_context as context:
2105 with invalidator_context as context:
2106 context.invalidate()
2106 context.invalidate()
2107 repo = context.compute()
2107 repo = context.compute()
2108
2108
2109 return repo
2109 return repo
2110
2110
2111 def _get_instance(self, cache=True, config=None):
2111 def _get_instance(self, cache=True, config=None):
2112 config = config or self._config
2112 config = config or self._config
2113 custom_wire = {
2113 custom_wire = {
2114 'cache': cache # controls the vcs.remote cache
2114 'cache': cache # controls the vcs.remote cache
2115 }
2115 }
2116 repo = get_vcs_instance(
2116 repo = get_vcs_instance(
2117 repo_path=safe_str(self.repo_full_path),
2117 repo_path=safe_str(self.repo_full_path),
2118 config=config,
2118 config=config,
2119 with_wire=custom_wire,
2119 with_wire=custom_wire,
2120 create=False,
2120 create=False,
2121 _vcs_alias=self.repo_type)
2121 _vcs_alias=self.repo_type)
2122
2122
2123 return repo
2123 return repo
2124
2124
2125 def __json__(self):
2125 def __json__(self):
2126 return {'landing_rev': self.landing_rev}
2126 return {'landing_rev': self.landing_rev}
2127
2127
2128 def get_dict(self):
2128 def get_dict(self):
2129
2129
2130 # Since we transformed `repo_name` to a hybrid property, we need to
2130 # Since we transformed `repo_name` to a hybrid property, we need to
2131 # keep compatibility with the code which uses `repo_name` field.
2131 # keep compatibility with the code which uses `repo_name` field.
2132
2132
2133 result = super(Repository, self).get_dict()
2133 result = super(Repository, self).get_dict()
2134 result['repo_name'] = result.pop('_repo_name', None)
2134 result['repo_name'] = result.pop('_repo_name', None)
2135 return result
2135 return result
2136
2136
2137
2137
2138 class RepoGroup(Base, BaseModel):
2138 class RepoGroup(Base, BaseModel):
2139 __tablename__ = 'groups'
2139 __tablename__ = 'groups'
2140 __table_args__ = (
2140 __table_args__ = (
2141 UniqueConstraint('group_name', 'group_parent_id'),
2141 UniqueConstraint('group_name', 'group_parent_id'),
2142 CheckConstraint('group_id != group_parent_id'),
2142 CheckConstraint('group_id != group_parent_id'),
2143 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2143 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2144 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2144 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2145 )
2145 )
2146 __mapper_args__ = {'order_by': 'group_name'}
2146 __mapper_args__ = {'order_by': 'group_name'}
2147
2147
2148 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2148 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2149
2149
2150 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2150 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2151 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2151 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2152 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2152 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2153 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2153 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2154 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2154 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2155 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2155 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2156 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2156 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2157 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2157 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2158
2158
2159 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2159 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2160 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2160 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2161 parent_group = relationship('RepoGroup', remote_side=group_id)
2161 parent_group = relationship('RepoGroup', remote_side=group_id)
2162 user = relationship('User')
2162 user = relationship('User')
2163 integrations = relationship('Integration',
2163 integrations = relationship('Integration',
2164 cascade="all, delete, delete-orphan")
2164 cascade="all, delete, delete-orphan")
2165
2165
2166 def __init__(self, group_name='', parent_group=None):
2166 def __init__(self, group_name='', parent_group=None):
2167 self.group_name = group_name
2167 self.group_name = group_name
2168 self.parent_group = parent_group
2168 self.parent_group = parent_group
2169
2169
2170 def __unicode__(self):
2170 def __unicode__(self):
2171 return u"<%s('id:%s:%s')>" % (self.__class__.__name__, self.group_id,
2171 return u"<%s('id:%s:%s')>" % (self.__class__.__name__, self.group_id,
2172 self.group_name)
2172 self.group_name)
2173
2173
2174 @classmethod
2174 @classmethod
2175 def _generate_choice(cls, repo_group):
2175 def _generate_choice(cls, repo_group):
2176 from webhelpers.html import literal as _literal
2176 from webhelpers.html import literal as _literal
2177 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2177 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2178 return repo_group.group_id, _name(repo_group.full_path_splitted)
2178 return repo_group.group_id, _name(repo_group.full_path_splitted)
2179
2179
2180 @classmethod
2180 @classmethod
2181 def groups_choices(cls, groups=None, show_empty_group=True):
2181 def groups_choices(cls, groups=None, show_empty_group=True):
2182 if not groups:
2182 if not groups:
2183 groups = cls.query().all()
2183 groups = cls.query().all()
2184
2184
2185 repo_groups = []
2185 repo_groups = []
2186 if show_empty_group:
2186 if show_empty_group:
2187 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2187 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2188
2188
2189 repo_groups.extend([cls._generate_choice(x) for x in groups])
2189 repo_groups.extend([cls._generate_choice(x) for x in groups])
2190
2190
2191 repo_groups = sorted(
2191 repo_groups = sorted(
2192 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2192 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2193 return repo_groups
2193 return repo_groups
2194
2194
2195 @classmethod
2195 @classmethod
2196 def url_sep(cls):
2196 def url_sep(cls):
2197 return URL_SEP
2197 return URL_SEP
2198
2198
2199 @classmethod
2199 @classmethod
2200 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2200 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2201 if case_insensitive:
2201 if case_insensitive:
2202 gr = cls.query().filter(func.lower(cls.group_name)
2202 gr = cls.query().filter(func.lower(cls.group_name)
2203 == func.lower(group_name))
2203 == func.lower(group_name))
2204 else:
2204 else:
2205 gr = cls.query().filter(cls.group_name == group_name)
2205 gr = cls.query().filter(cls.group_name == group_name)
2206 if cache:
2206 if cache:
2207 gr = gr.options(FromCache(
2207 name_key = _hash_key(group_name)
2208 "sql_cache_short",
2208 gr = gr.options(
2209 "get_group_%s" % _hash_key(group_name)))
2209 FromCache("sql_cache_short", "get_group_%s" % name_key))
2210 return gr.scalar()
2210 return gr.scalar()
2211
2211
2212 @classmethod
2212 @classmethod
2213 def get_user_personal_repo_group(cls, user_id):
2213 def get_user_personal_repo_group(cls, user_id):
2214 user = User.get(user_id)
2214 user = User.get(user_id)
2215 if user.username == User.DEFAULT_USER:
2215 if user.username == User.DEFAULT_USER:
2216 return None
2216 return None
2217
2217
2218 return cls.query()\
2218 return cls.query()\
2219 .filter(cls.personal == true()) \
2219 .filter(cls.personal == true()) \
2220 .filter(cls.user == user).scalar()
2220 .filter(cls.user == user).scalar()
2221
2221
2222 @classmethod
2222 @classmethod
2223 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2223 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2224 case_insensitive=True):
2224 case_insensitive=True):
2225 q = RepoGroup.query()
2225 q = RepoGroup.query()
2226
2226
2227 if not isinstance(user_id, Optional):
2227 if not isinstance(user_id, Optional):
2228 q = q.filter(RepoGroup.user_id == user_id)
2228 q = q.filter(RepoGroup.user_id == user_id)
2229
2229
2230 if not isinstance(group_id, Optional):
2230 if not isinstance(group_id, Optional):
2231 q = q.filter(RepoGroup.group_parent_id == group_id)
2231 q = q.filter(RepoGroup.group_parent_id == group_id)
2232
2232
2233 if case_insensitive:
2233 if case_insensitive:
2234 q = q.order_by(func.lower(RepoGroup.group_name))
2234 q = q.order_by(func.lower(RepoGroup.group_name))
2235 else:
2235 else:
2236 q = q.order_by(RepoGroup.group_name)
2236 q = q.order_by(RepoGroup.group_name)
2237 return q.all()
2237 return q.all()
2238
2238
2239 @property
2239 @property
2240 def parents(self):
2240 def parents(self):
2241 parents_recursion_limit = 10
2241 parents_recursion_limit = 10
2242 groups = []
2242 groups = []
2243 if self.parent_group is None:
2243 if self.parent_group is None:
2244 return groups
2244 return groups
2245 cur_gr = self.parent_group
2245 cur_gr = self.parent_group
2246 groups.insert(0, cur_gr)
2246 groups.insert(0, cur_gr)
2247 cnt = 0
2247 cnt = 0
2248 while 1:
2248 while 1:
2249 cnt += 1
2249 cnt += 1
2250 gr = getattr(cur_gr, 'parent_group', None)
2250 gr = getattr(cur_gr, 'parent_group', None)
2251 cur_gr = cur_gr.parent_group
2251 cur_gr = cur_gr.parent_group
2252 if gr is None:
2252 if gr is None:
2253 break
2253 break
2254 if cnt == parents_recursion_limit:
2254 if cnt == parents_recursion_limit:
2255 # this will prevent accidental infinit loops
2255 # this will prevent accidental infinit loops
2256 log.error(('more than %s parents found for group %s, stopping '
2256 log.error(('more than %s parents found for group %s, stopping '
2257 'recursive parent fetching' % (parents_recursion_limit, self)))
2257 'recursive parent fetching' % (parents_recursion_limit, self)))
2258 break
2258 break
2259
2259
2260 groups.insert(0, gr)
2260 groups.insert(0, gr)
2261 return groups
2261 return groups
2262
2262
2263 @property
2263 @property
2264 def children(self):
2264 def children(self):
2265 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2265 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2266
2266
2267 @property
2267 @property
2268 def name(self):
2268 def name(self):
2269 return self.group_name.split(RepoGroup.url_sep())[-1]
2269 return self.group_name.split(RepoGroup.url_sep())[-1]
2270
2270
2271 @property
2271 @property
2272 def full_path(self):
2272 def full_path(self):
2273 return self.group_name
2273 return self.group_name
2274
2274
2275 @property
2275 @property
2276 def full_path_splitted(self):
2276 def full_path_splitted(self):
2277 return self.group_name.split(RepoGroup.url_sep())
2277 return self.group_name.split(RepoGroup.url_sep())
2278
2278
2279 @property
2279 @property
2280 def repositories(self):
2280 def repositories(self):
2281 return Repository.query()\
2281 return Repository.query()\
2282 .filter(Repository.group == self)\
2282 .filter(Repository.group == self)\
2283 .order_by(Repository.repo_name)
2283 .order_by(Repository.repo_name)
2284
2284
2285 @property
2285 @property
2286 def repositories_recursive_count(self):
2286 def repositories_recursive_count(self):
2287 cnt = self.repositories.count()
2287 cnt = self.repositories.count()
2288
2288
2289 def children_count(group):
2289 def children_count(group):
2290 cnt = 0
2290 cnt = 0
2291 for child in group.children:
2291 for child in group.children:
2292 cnt += child.repositories.count()
2292 cnt += child.repositories.count()
2293 cnt += children_count(child)
2293 cnt += children_count(child)
2294 return cnt
2294 return cnt
2295
2295
2296 return cnt + children_count(self)
2296 return cnt + children_count(self)
2297
2297
2298 def _recursive_objects(self, include_repos=True):
2298 def _recursive_objects(self, include_repos=True):
2299 all_ = []
2299 all_ = []
2300
2300
2301 def _get_members(root_gr):
2301 def _get_members(root_gr):
2302 if include_repos:
2302 if include_repos:
2303 for r in root_gr.repositories:
2303 for r in root_gr.repositories:
2304 all_.append(r)
2304 all_.append(r)
2305 childs = root_gr.children.all()
2305 childs = root_gr.children.all()
2306 if childs:
2306 if childs:
2307 for gr in childs:
2307 for gr in childs:
2308 all_.append(gr)
2308 all_.append(gr)
2309 _get_members(gr)
2309 _get_members(gr)
2310
2310
2311 _get_members(self)
2311 _get_members(self)
2312 return [self] + all_
2312 return [self] + all_
2313
2313
2314 def recursive_groups_and_repos(self):
2314 def recursive_groups_and_repos(self):
2315 """
2315 """
2316 Recursive return all groups, with repositories in those groups
2316 Recursive return all groups, with repositories in those groups
2317 """
2317 """
2318 return self._recursive_objects()
2318 return self._recursive_objects()
2319
2319
2320 def recursive_groups(self):
2320 def recursive_groups(self):
2321 """
2321 """
2322 Returns all children groups for this group including children of children
2322 Returns all children groups for this group including children of children
2323 """
2323 """
2324 return self._recursive_objects(include_repos=False)
2324 return self._recursive_objects(include_repos=False)
2325
2325
2326 def get_new_name(self, group_name):
2326 def get_new_name(self, group_name):
2327 """
2327 """
2328 returns new full group name based on parent and new name
2328 returns new full group name based on parent and new name
2329
2329
2330 :param group_name:
2330 :param group_name:
2331 """
2331 """
2332 path_prefix = (self.parent_group.full_path_splitted if
2332 path_prefix = (self.parent_group.full_path_splitted if
2333 self.parent_group else [])
2333 self.parent_group else [])
2334 return RepoGroup.url_sep().join(path_prefix + [group_name])
2334 return RepoGroup.url_sep().join(path_prefix + [group_name])
2335
2335
2336 def permissions(self, with_admins=True, with_owner=True):
2336 def permissions(self, with_admins=True, with_owner=True):
2337 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2337 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2338 q = q.options(joinedload(UserRepoGroupToPerm.group),
2338 q = q.options(joinedload(UserRepoGroupToPerm.group),
2339 joinedload(UserRepoGroupToPerm.user),
2339 joinedload(UserRepoGroupToPerm.user),
2340 joinedload(UserRepoGroupToPerm.permission),)
2340 joinedload(UserRepoGroupToPerm.permission),)
2341
2341
2342 # get owners and admins and permissions. We do a trick of re-writing
2342 # get owners and admins and permissions. We do a trick of re-writing
2343 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2343 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2344 # has a global reference and changing one object propagates to all
2344 # has a global reference and changing one object propagates to all
2345 # others. This means if admin is also an owner admin_row that change
2345 # others. This means if admin is also an owner admin_row that change
2346 # would propagate to both objects
2346 # would propagate to both objects
2347 perm_rows = []
2347 perm_rows = []
2348 for _usr in q.all():
2348 for _usr in q.all():
2349 usr = AttributeDict(_usr.user.get_dict())
2349 usr = AttributeDict(_usr.user.get_dict())
2350 usr.permission = _usr.permission.permission_name
2350 usr.permission = _usr.permission.permission_name
2351 perm_rows.append(usr)
2351 perm_rows.append(usr)
2352
2352
2353 # filter the perm rows by 'default' first and then sort them by
2353 # filter the perm rows by 'default' first and then sort them by
2354 # admin,write,read,none permissions sorted again alphabetically in
2354 # admin,write,read,none permissions sorted again alphabetically in
2355 # each group
2355 # each group
2356 perm_rows = sorted(perm_rows, key=display_sort)
2356 perm_rows = sorted(perm_rows, key=display_sort)
2357
2357
2358 _admin_perm = 'group.admin'
2358 _admin_perm = 'group.admin'
2359 owner_row = []
2359 owner_row = []
2360 if with_owner:
2360 if with_owner:
2361 usr = AttributeDict(self.user.get_dict())
2361 usr = AttributeDict(self.user.get_dict())
2362 usr.owner_row = True
2362 usr.owner_row = True
2363 usr.permission = _admin_perm
2363 usr.permission = _admin_perm
2364 owner_row.append(usr)
2364 owner_row.append(usr)
2365
2365
2366 super_admin_rows = []
2366 super_admin_rows = []
2367 if with_admins:
2367 if with_admins:
2368 for usr in User.get_all_super_admins():
2368 for usr in User.get_all_super_admins():
2369 # if this admin is also owner, don't double the record
2369 # if this admin is also owner, don't double the record
2370 if usr.user_id == owner_row[0].user_id:
2370 if usr.user_id == owner_row[0].user_id:
2371 owner_row[0].admin_row = True
2371 owner_row[0].admin_row = True
2372 else:
2372 else:
2373 usr = AttributeDict(usr.get_dict())
2373 usr = AttributeDict(usr.get_dict())
2374 usr.admin_row = True
2374 usr.admin_row = True
2375 usr.permission = _admin_perm
2375 usr.permission = _admin_perm
2376 super_admin_rows.append(usr)
2376 super_admin_rows.append(usr)
2377
2377
2378 return super_admin_rows + owner_row + perm_rows
2378 return super_admin_rows + owner_row + perm_rows
2379
2379
2380 def permission_user_groups(self):
2380 def permission_user_groups(self):
2381 q = UserGroupRepoGroupToPerm.query().filter(UserGroupRepoGroupToPerm.group == self)
2381 q = UserGroupRepoGroupToPerm.query().filter(UserGroupRepoGroupToPerm.group == self)
2382 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2382 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2383 joinedload(UserGroupRepoGroupToPerm.users_group),
2383 joinedload(UserGroupRepoGroupToPerm.users_group),
2384 joinedload(UserGroupRepoGroupToPerm.permission),)
2384 joinedload(UserGroupRepoGroupToPerm.permission),)
2385
2385
2386 perm_rows = []
2386 perm_rows = []
2387 for _user_group in q.all():
2387 for _user_group in q.all():
2388 usr = AttributeDict(_user_group.users_group.get_dict())
2388 usr = AttributeDict(_user_group.users_group.get_dict())
2389 usr.permission = _user_group.permission.permission_name
2389 usr.permission = _user_group.permission.permission_name
2390 perm_rows.append(usr)
2390 perm_rows.append(usr)
2391
2391
2392 return perm_rows
2392 return perm_rows
2393
2393
2394 def get_api_data(self):
2394 def get_api_data(self):
2395 """
2395 """
2396 Common function for generating api data
2396 Common function for generating api data
2397
2397
2398 """
2398 """
2399 group = self
2399 group = self
2400 data = {
2400 data = {
2401 'group_id': group.group_id,
2401 'group_id': group.group_id,
2402 'group_name': group.group_name,
2402 'group_name': group.group_name,
2403 'group_description': group.group_description,
2403 'group_description': group.group_description,
2404 'parent_group': group.parent_group.group_name if group.parent_group else None,
2404 'parent_group': group.parent_group.group_name if group.parent_group else None,
2405 'repositories': [x.repo_name for x in group.repositories],
2405 'repositories': [x.repo_name for x in group.repositories],
2406 'owner': group.user.username,
2406 'owner': group.user.username,
2407 }
2407 }
2408 return data
2408 return data
2409
2409
2410
2410
2411 class Permission(Base, BaseModel):
2411 class Permission(Base, BaseModel):
2412 __tablename__ = 'permissions'
2412 __tablename__ = 'permissions'
2413 __table_args__ = (
2413 __table_args__ = (
2414 Index('p_perm_name_idx', 'permission_name'),
2414 Index('p_perm_name_idx', 'permission_name'),
2415 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2415 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2416 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2416 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2417 )
2417 )
2418 PERMS = [
2418 PERMS = [
2419 ('hg.admin', _('RhodeCode Super Administrator')),
2419 ('hg.admin', _('RhodeCode Super Administrator')),
2420
2420
2421 ('repository.none', _('Repository no access')),
2421 ('repository.none', _('Repository no access')),
2422 ('repository.read', _('Repository read access')),
2422 ('repository.read', _('Repository read access')),
2423 ('repository.write', _('Repository write access')),
2423 ('repository.write', _('Repository write access')),
2424 ('repository.admin', _('Repository admin access')),
2424 ('repository.admin', _('Repository admin access')),
2425
2425
2426 ('group.none', _('Repository group no access')),
2426 ('group.none', _('Repository group no access')),
2427 ('group.read', _('Repository group read access')),
2427 ('group.read', _('Repository group read access')),
2428 ('group.write', _('Repository group write access')),
2428 ('group.write', _('Repository group write access')),
2429 ('group.admin', _('Repository group admin access')),
2429 ('group.admin', _('Repository group admin access')),
2430
2430
2431 ('usergroup.none', _('User group no access')),
2431 ('usergroup.none', _('User group no access')),
2432 ('usergroup.read', _('User group read access')),
2432 ('usergroup.read', _('User group read access')),
2433 ('usergroup.write', _('User group write access')),
2433 ('usergroup.write', _('User group write access')),
2434 ('usergroup.admin', _('User group admin access')),
2434 ('usergroup.admin', _('User group admin access')),
2435
2435
2436 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2436 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2437 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2437 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2438
2438
2439 ('hg.usergroup.create.false', _('User Group creation disabled')),
2439 ('hg.usergroup.create.false', _('User Group creation disabled')),
2440 ('hg.usergroup.create.true', _('User Group creation enabled')),
2440 ('hg.usergroup.create.true', _('User Group creation enabled')),
2441
2441
2442 ('hg.create.none', _('Repository creation disabled')),
2442 ('hg.create.none', _('Repository creation disabled')),
2443 ('hg.create.repository', _('Repository creation enabled')),
2443 ('hg.create.repository', _('Repository creation enabled')),
2444 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2444 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2445 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2445 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2446
2446
2447 ('hg.fork.none', _('Repository forking disabled')),
2447 ('hg.fork.none', _('Repository forking disabled')),
2448 ('hg.fork.repository', _('Repository forking enabled')),
2448 ('hg.fork.repository', _('Repository forking enabled')),
2449
2449
2450 ('hg.register.none', _('Registration disabled')),
2450 ('hg.register.none', _('Registration disabled')),
2451 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2451 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2452 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2452 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2453
2453
2454 ('hg.password_reset.enabled', _('Password reset enabled')),
2454 ('hg.password_reset.enabled', _('Password reset enabled')),
2455 ('hg.password_reset.hidden', _('Password reset hidden')),
2455 ('hg.password_reset.hidden', _('Password reset hidden')),
2456 ('hg.password_reset.disabled', _('Password reset disabled')),
2456 ('hg.password_reset.disabled', _('Password reset disabled')),
2457
2457
2458 ('hg.extern_activate.manual', _('Manual activation of external account')),
2458 ('hg.extern_activate.manual', _('Manual activation of external account')),
2459 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2459 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2460
2460
2461 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2461 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2462 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2462 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2463 ]
2463 ]
2464
2464
2465 # definition of system default permissions for DEFAULT user
2465 # definition of system default permissions for DEFAULT user
2466 DEFAULT_USER_PERMISSIONS = [
2466 DEFAULT_USER_PERMISSIONS = [
2467 'repository.read',
2467 'repository.read',
2468 'group.read',
2468 'group.read',
2469 'usergroup.read',
2469 'usergroup.read',
2470 'hg.create.repository',
2470 'hg.create.repository',
2471 'hg.repogroup.create.false',
2471 'hg.repogroup.create.false',
2472 'hg.usergroup.create.false',
2472 'hg.usergroup.create.false',
2473 'hg.create.write_on_repogroup.true',
2473 'hg.create.write_on_repogroup.true',
2474 'hg.fork.repository',
2474 'hg.fork.repository',
2475 'hg.register.manual_activate',
2475 'hg.register.manual_activate',
2476 'hg.password_reset.enabled',
2476 'hg.password_reset.enabled',
2477 'hg.extern_activate.auto',
2477 'hg.extern_activate.auto',
2478 'hg.inherit_default_perms.true',
2478 'hg.inherit_default_perms.true',
2479 ]
2479 ]
2480
2480
2481 # defines which permissions are more important higher the more important
2481 # defines which permissions are more important higher the more important
2482 # Weight defines which permissions are more important.
2482 # Weight defines which permissions are more important.
2483 # The higher number the more important.
2483 # The higher number the more important.
2484 PERM_WEIGHTS = {
2484 PERM_WEIGHTS = {
2485 'repository.none': 0,
2485 'repository.none': 0,
2486 'repository.read': 1,
2486 'repository.read': 1,
2487 'repository.write': 3,
2487 'repository.write': 3,
2488 'repository.admin': 4,
2488 'repository.admin': 4,
2489
2489
2490 'group.none': 0,
2490 'group.none': 0,
2491 'group.read': 1,
2491 'group.read': 1,
2492 'group.write': 3,
2492 'group.write': 3,
2493 'group.admin': 4,
2493 'group.admin': 4,
2494
2494
2495 'usergroup.none': 0,
2495 'usergroup.none': 0,
2496 'usergroup.read': 1,
2496 'usergroup.read': 1,
2497 'usergroup.write': 3,
2497 'usergroup.write': 3,
2498 'usergroup.admin': 4,
2498 'usergroup.admin': 4,
2499
2499
2500 'hg.repogroup.create.false': 0,
2500 'hg.repogroup.create.false': 0,
2501 'hg.repogroup.create.true': 1,
2501 'hg.repogroup.create.true': 1,
2502
2502
2503 'hg.usergroup.create.false': 0,
2503 'hg.usergroup.create.false': 0,
2504 'hg.usergroup.create.true': 1,
2504 'hg.usergroup.create.true': 1,
2505
2505
2506 'hg.fork.none': 0,
2506 'hg.fork.none': 0,
2507 'hg.fork.repository': 1,
2507 'hg.fork.repository': 1,
2508 'hg.create.none': 0,
2508 'hg.create.none': 0,
2509 'hg.create.repository': 1
2509 'hg.create.repository': 1
2510 }
2510 }
2511
2511
2512 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2512 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2513 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2513 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2514 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2514 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2515
2515
2516 def __unicode__(self):
2516 def __unicode__(self):
2517 return u"<%s('%s:%s')>" % (
2517 return u"<%s('%s:%s')>" % (
2518 self.__class__.__name__, self.permission_id, self.permission_name
2518 self.__class__.__name__, self.permission_id, self.permission_name
2519 )
2519 )
2520
2520
2521 @classmethod
2521 @classmethod
2522 def get_by_key(cls, key):
2522 def get_by_key(cls, key):
2523 return cls.query().filter(cls.permission_name == key).scalar()
2523 return cls.query().filter(cls.permission_name == key).scalar()
2524
2524
2525 @classmethod
2525 @classmethod
2526 def get_default_repo_perms(cls, user_id, repo_id=None):
2526 def get_default_repo_perms(cls, user_id, repo_id=None):
2527 q = Session().query(UserRepoToPerm, Repository, Permission)\
2527 q = Session().query(UserRepoToPerm, Repository, Permission)\
2528 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2528 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2529 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2529 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2530 .filter(UserRepoToPerm.user_id == user_id)
2530 .filter(UserRepoToPerm.user_id == user_id)
2531 if repo_id:
2531 if repo_id:
2532 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2532 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2533 return q.all()
2533 return q.all()
2534
2534
2535 @classmethod
2535 @classmethod
2536 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2536 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2537 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2537 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2538 .join(
2538 .join(
2539 Permission,
2539 Permission,
2540 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2540 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2541 .join(
2541 .join(
2542 Repository,
2542 Repository,
2543 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2543 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2544 .join(
2544 .join(
2545 UserGroup,
2545 UserGroup,
2546 UserGroupRepoToPerm.users_group_id ==
2546 UserGroupRepoToPerm.users_group_id ==
2547 UserGroup.users_group_id)\
2547 UserGroup.users_group_id)\
2548 .join(
2548 .join(
2549 UserGroupMember,
2549 UserGroupMember,
2550 UserGroupRepoToPerm.users_group_id ==
2550 UserGroupRepoToPerm.users_group_id ==
2551 UserGroupMember.users_group_id)\
2551 UserGroupMember.users_group_id)\
2552 .filter(
2552 .filter(
2553 UserGroupMember.user_id == user_id,
2553 UserGroupMember.user_id == user_id,
2554 UserGroup.users_group_active == true())
2554 UserGroup.users_group_active == true())
2555 if repo_id:
2555 if repo_id:
2556 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2556 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2557 return q.all()
2557 return q.all()
2558
2558
2559 @classmethod
2559 @classmethod
2560 def get_default_group_perms(cls, user_id, repo_group_id=None):
2560 def get_default_group_perms(cls, user_id, repo_group_id=None):
2561 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2561 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2562 .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\
2562 .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\
2563 .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
2563 .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
2564 .filter(UserRepoGroupToPerm.user_id == user_id)
2564 .filter(UserRepoGroupToPerm.user_id == user_id)
2565 if repo_group_id:
2565 if repo_group_id:
2566 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2566 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2567 return q.all()
2567 return q.all()
2568
2568
2569 @classmethod
2569 @classmethod
2570 def get_default_group_perms_from_user_group(
2570 def get_default_group_perms_from_user_group(
2571 cls, user_id, repo_group_id=None):
2571 cls, user_id, repo_group_id=None):
2572 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2572 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2573 .join(
2573 .join(
2574 Permission,
2574 Permission,
2575 UserGroupRepoGroupToPerm.permission_id ==
2575 UserGroupRepoGroupToPerm.permission_id ==
2576 Permission.permission_id)\
2576 Permission.permission_id)\
2577 .join(
2577 .join(
2578 RepoGroup,
2578 RepoGroup,
2579 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2579 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2580 .join(
2580 .join(
2581 UserGroup,
2581 UserGroup,
2582 UserGroupRepoGroupToPerm.users_group_id ==
2582 UserGroupRepoGroupToPerm.users_group_id ==
2583 UserGroup.users_group_id)\
2583 UserGroup.users_group_id)\
2584 .join(
2584 .join(
2585 UserGroupMember,
2585 UserGroupMember,
2586 UserGroupRepoGroupToPerm.users_group_id ==
2586 UserGroupRepoGroupToPerm.users_group_id ==
2587 UserGroupMember.users_group_id)\
2587 UserGroupMember.users_group_id)\
2588 .filter(
2588 .filter(
2589 UserGroupMember.user_id == user_id,
2589 UserGroupMember.user_id == user_id,
2590 UserGroup.users_group_active == true())
2590 UserGroup.users_group_active == true())
2591 if repo_group_id:
2591 if repo_group_id:
2592 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
2592 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
2593 return q.all()
2593 return q.all()
2594
2594
2595 @classmethod
2595 @classmethod
2596 def get_default_user_group_perms(cls, user_id, user_group_id=None):
2596 def get_default_user_group_perms(cls, user_id, user_group_id=None):
2597 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
2597 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
2598 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
2598 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
2599 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
2599 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
2600 .filter(UserUserGroupToPerm.user_id == user_id)
2600 .filter(UserUserGroupToPerm.user_id == user_id)
2601 if user_group_id:
2601 if user_group_id:
2602 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
2602 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
2603 return q.all()
2603 return q.all()
2604
2604
2605 @classmethod
2605 @classmethod
2606 def get_default_user_group_perms_from_user_group(
2606 def get_default_user_group_perms_from_user_group(
2607 cls, user_id, user_group_id=None):
2607 cls, user_id, user_group_id=None):
2608 TargetUserGroup = aliased(UserGroup, name='target_user_group')
2608 TargetUserGroup = aliased(UserGroup, name='target_user_group')
2609 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
2609 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
2610 .join(
2610 .join(
2611 Permission,
2611 Permission,
2612 UserGroupUserGroupToPerm.permission_id ==
2612 UserGroupUserGroupToPerm.permission_id ==
2613 Permission.permission_id)\
2613 Permission.permission_id)\
2614 .join(
2614 .join(
2615 TargetUserGroup,
2615 TargetUserGroup,
2616 UserGroupUserGroupToPerm.target_user_group_id ==
2616 UserGroupUserGroupToPerm.target_user_group_id ==
2617 TargetUserGroup.users_group_id)\
2617 TargetUserGroup.users_group_id)\
2618 .join(
2618 .join(
2619 UserGroup,
2619 UserGroup,
2620 UserGroupUserGroupToPerm.user_group_id ==
2620 UserGroupUserGroupToPerm.user_group_id ==
2621 UserGroup.users_group_id)\
2621 UserGroup.users_group_id)\
2622 .join(
2622 .join(
2623 UserGroupMember,
2623 UserGroupMember,
2624 UserGroupUserGroupToPerm.user_group_id ==
2624 UserGroupUserGroupToPerm.user_group_id ==
2625 UserGroupMember.users_group_id)\
2625 UserGroupMember.users_group_id)\
2626 .filter(
2626 .filter(
2627 UserGroupMember.user_id == user_id,
2627 UserGroupMember.user_id == user_id,
2628 UserGroup.users_group_active == true())
2628 UserGroup.users_group_active == true())
2629 if user_group_id:
2629 if user_group_id:
2630 q = q.filter(
2630 q = q.filter(
2631 UserGroupUserGroupToPerm.user_group_id == user_group_id)
2631 UserGroupUserGroupToPerm.user_group_id == user_group_id)
2632
2632
2633 return q.all()
2633 return q.all()
2634
2634
2635
2635
2636 class UserRepoToPerm(Base, BaseModel):
2636 class UserRepoToPerm(Base, BaseModel):
2637 __tablename__ = 'repo_to_perm'
2637 __tablename__ = 'repo_to_perm'
2638 __table_args__ = (
2638 __table_args__ = (
2639 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
2639 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
2640 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2640 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2641 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2641 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2642 )
2642 )
2643 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2643 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2644 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2644 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2645 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2645 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2646 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2646 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2647
2647
2648 user = relationship('User')
2648 user = relationship('User')
2649 repository = relationship('Repository')
2649 repository = relationship('Repository')
2650 permission = relationship('Permission')
2650 permission = relationship('Permission')
2651
2651
2652 @classmethod
2652 @classmethod
2653 def create(cls, user, repository, permission):
2653 def create(cls, user, repository, permission):
2654 n = cls()
2654 n = cls()
2655 n.user = user
2655 n.user = user
2656 n.repository = repository
2656 n.repository = repository
2657 n.permission = permission
2657 n.permission = permission
2658 Session().add(n)
2658 Session().add(n)
2659 return n
2659 return n
2660
2660
2661 def __unicode__(self):
2661 def __unicode__(self):
2662 return u'<%s => %s >' % (self.user, self.repository)
2662 return u'<%s => %s >' % (self.user, self.repository)
2663
2663
2664
2664
2665 class UserUserGroupToPerm(Base, BaseModel):
2665 class UserUserGroupToPerm(Base, BaseModel):
2666 __tablename__ = 'user_user_group_to_perm'
2666 __tablename__ = 'user_user_group_to_perm'
2667 __table_args__ = (
2667 __table_args__ = (
2668 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
2668 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
2669 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2669 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2670 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2670 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2671 )
2671 )
2672 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2672 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2673 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2673 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2674 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2674 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2675 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2675 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2676
2676
2677 user = relationship('User')
2677 user = relationship('User')
2678 user_group = relationship('UserGroup')
2678 user_group = relationship('UserGroup')
2679 permission = relationship('Permission')
2679 permission = relationship('Permission')
2680
2680
2681 @classmethod
2681 @classmethod
2682 def create(cls, user, user_group, permission):
2682 def create(cls, user, user_group, permission):
2683 n = cls()
2683 n = cls()
2684 n.user = user
2684 n.user = user
2685 n.user_group = user_group
2685 n.user_group = user_group
2686 n.permission = permission
2686 n.permission = permission
2687 Session().add(n)
2687 Session().add(n)
2688 return n
2688 return n
2689
2689
2690 def __unicode__(self):
2690 def __unicode__(self):
2691 return u'<%s => %s >' % (self.user, self.user_group)
2691 return u'<%s => %s >' % (self.user, self.user_group)
2692
2692
2693
2693
2694 class UserToPerm(Base, BaseModel):
2694 class UserToPerm(Base, BaseModel):
2695 __tablename__ = 'user_to_perm'
2695 __tablename__ = 'user_to_perm'
2696 __table_args__ = (
2696 __table_args__ = (
2697 UniqueConstraint('user_id', 'permission_id'),
2697 UniqueConstraint('user_id', 'permission_id'),
2698 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2698 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2699 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2699 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2700 )
2700 )
2701 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2701 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2702 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2702 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2703 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2703 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2704
2704
2705 user = relationship('User')
2705 user = relationship('User')
2706 permission = relationship('Permission', lazy='joined')
2706 permission = relationship('Permission', lazy='joined')
2707
2707
2708 def __unicode__(self):
2708 def __unicode__(self):
2709 return u'<%s => %s >' % (self.user, self.permission)
2709 return u'<%s => %s >' % (self.user, self.permission)
2710
2710
2711
2711
2712 class UserGroupRepoToPerm(Base, BaseModel):
2712 class UserGroupRepoToPerm(Base, BaseModel):
2713 __tablename__ = 'users_group_repo_to_perm'
2713 __tablename__ = 'users_group_repo_to_perm'
2714 __table_args__ = (
2714 __table_args__ = (
2715 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
2715 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
2716 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2716 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2717 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2717 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2718 )
2718 )
2719 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2719 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2720 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2720 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2721 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2721 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2722 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2722 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2723
2723
2724 users_group = relationship('UserGroup')
2724 users_group = relationship('UserGroup')
2725 permission = relationship('Permission')
2725 permission = relationship('Permission')
2726 repository = relationship('Repository')
2726 repository = relationship('Repository')
2727
2727
2728 @classmethod
2728 @classmethod
2729 def create(cls, users_group, repository, permission):
2729 def create(cls, users_group, repository, permission):
2730 n = cls()
2730 n = cls()
2731 n.users_group = users_group
2731 n.users_group = users_group
2732 n.repository = repository
2732 n.repository = repository
2733 n.permission = permission
2733 n.permission = permission
2734 Session().add(n)
2734 Session().add(n)
2735 return n
2735 return n
2736
2736
2737 def __unicode__(self):
2737 def __unicode__(self):
2738 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
2738 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
2739
2739
2740
2740
2741 class UserGroupUserGroupToPerm(Base, BaseModel):
2741 class UserGroupUserGroupToPerm(Base, BaseModel):
2742 __tablename__ = 'user_group_user_group_to_perm'
2742 __tablename__ = 'user_group_user_group_to_perm'
2743 __table_args__ = (
2743 __table_args__ = (
2744 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
2744 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
2745 CheckConstraint('target_user_group_id != user_group_id'),
2745 CheckConstraint('target_user_group_id != user_group_id'),
2746 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2746 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2747 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2747 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2748 )
2748 )
2749 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)
2749 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)
2750 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2750 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2751 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2751 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2752 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2752 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2753
2753
2754 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
2754 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
2755 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
2755 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
2756 permission = relationship('Permission')
2756 permission = relationship('Permission')
2757
2757
2758 @classmethod
2758 @classmethod
2759 def create(cls, target_user_group, user_group, permission):
2759 def create(cls, target_user_group, user_group, permission):
2760 n = cls()
2760 n = cls()
2761 n.target_user_group = target_user_group
2761 n.target_user_group = target_user_group
2762 n.user_group = user_group
2762 n.user_group = user_group
2763 n.permission = permission
2763 n.permission = permission
2764 Session().add(n)
2764 Session().add(n)
2765 return n
2765 return n
2766
2766
2767 def __unicode__(self):
2767 def __unicode__(self):
2768 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
2768 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
2769
2769
2770
2770
2771 class UserGroupToPerm(Base, BaseModel):
2771 class UserGroupToPerm(Base, BaseModel):
2772 __tablename__ = 'users_group_to_perm'
2772 __tablename__ = 'users_group_to_perm'
2773 __table_args__ = (
2773 __table_args__ = (
2774 UniqueConstraint('users_group_id', 'permission_id',),
2774 UniqueConstraint('users_group_id', 'permission_id',),
2775 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2775 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2776 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2776 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2777 )
2777 )
2778 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2778 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2779 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2779 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2780 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2780 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2781
2781
2782 users_group = relationship('UserGroup')
2782 users_group = relationship('UserGroup')
2783 permission = relationship('Permission')
2783 permission = relationship('Permission')
2784
2784
2785
2785
2786 class UserRepoGroupToPerm(Base, BaseModel):
2786 class UserRepoGroupToPerm(Base, BaseModel):
2787 __tablename__ = 'user_repo_group_to_perm'
2787 __tablename__ = 'user_repo_group_to_perm'
2788 __table_args__ = (
2788 __table_args__ = (
2789 UniqueConstraint('user_id', 'group_id', 'permission_id'),
2789 UniqueConstraint('user_id', 'group_id', 'permission_id'),
2790 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2790 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2791 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2791 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2792 )
2792 )
2793
2793
2794 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2794 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2795 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2795 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2796 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2796 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2797 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2797 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2798
2798
2799 user = relationship('User')
2799 user = relationship('User')
2800 group = relationship('RepoGroup')
2800 group = relationship('RepoGroup')
2801 permission = relationship('Permission')
2801 permission = relationship('Permission')
2802
2802
2803 @classmethod
2803 @classmethod
2804 def create(cls, user, repository_group, permission):
2804 def create(cls, user, repository_group, permission):
2805 n = cls()
2805 n = cls()
2806 n.user = user
2806 n.user = user
2807 n.group = repository_group
2807 n.group = repository_group
2808 n.permission = permission
2808 n.permission = permission
2809 Session().add(n)
2809 Session().add(n)
2810 return n
2810 return n
2811
2811
2812
2812
2813 class UserGroupRepoGroupToPerm(Base, BaseModel):
2813 class UserGroupRepoGroupToPerm(Base, BaseModel):
2814 __tablename__ = 'users_group_repo_group_to_perm'
2814 __tablename__ = 'users_group_repo_group_to_perm'
2815 __table_args__ = (
2815 __table_args__ = (
2816 UniqueConstraint('users_group_id', 'group_id'),
2816 UniqueConstraint('users_group_id', 'group_id'),
2817 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2817 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2818 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2818 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2819 )
2819 )
2820
2820
2821 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)
2821 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)
2822 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2822 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2823 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2823 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2824 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2824 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2825
2825
2826 users_group = relationship('UserGroup')
2826 users_group = relationship('UserGroup')
2827 permission = relationship('Permission')
2827 permission = relationship('Permission')
2828 group = relationship('RepoGroup')
2828 group = relationship('RepoGroup')
2829
2829
2830 @classmethod
2830 @classmethod
2831 def create(cls, user_group, repository_group, permission):
2831 def create(cls, user_group, repository_group, permission):
2832 n = cls()
2832 n = cls()
2833 n.users_group = user_group
2833 n.users_group = user_group
2834 n.group = repository_group
2834 n.group = repository_group
2835 n.permission = permission
2835 n.permission = permission
2836 Session().add(n)
2836 Session().add(n)
2837 return n
2837 return n
2838
2838
2839 def __unicode__(self):
2839 def __unicode__(self):
2840 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
2840 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
2841
2841
2842
2842
2843 class Statistics(Base, BaseModel):
2843 class Statistics(Base, BaseModel):
2844 __tablename__ = 'statistics'
2844 __tablename__ = 'statistics'
2845 __table_args__ = (
2845 __table_args__ = (
2846 UniqueConstraint('repository_id'),
2846 UniqueConstraint('repository_id'),
2847 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2847 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2848 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2848 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2849 )
2849 )
2850 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2850 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2851 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
2851 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
2852 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
2852 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
2853 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
2853 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
2854 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
2854 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
2855 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
2855 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
2856
2856
2857 repository = relationship('Repository', single_parent=True)
2857 repository = relationship('Repository', single_parent=True)
2858
2858
2859
2859
2860 class UserFollowing(Base, BaseModel):
2860 class UserFollowing(Base, BaseModel):
2861 __tablename__ = 'user_followings'
2861 __tablename__ = 'user_followings'
2862 __table_args__ = (
2862 __table_args__ = (
2863 UniqueConstraint('user_id', 'follows_repository_id'),
2863 UniqueConstraint('user_id', 'follows_repository_id'),
2864 UniqueConstraint('user_id', 'follows_user_id'),
2864 UniqueConstraint('user_id', 'follows_user_id'),
2865 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2865 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2866 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2866 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2867 )
2867 )
2868
2868
2869 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2869 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2870 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2870 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2871 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
2871 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
2872 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
2872 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
2873 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2873 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2874
2874
2875 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
2875 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
2876
2876
2877 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
2877 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
2878 follows_repository = relationship('Repository', order_by='Repository.repo_name')
2878 follows_repository = relationship('Repository', order_by='Repository.repo_name')
2879
2879
2880 @classmethod
2880 @classmethod
2881 def get_repo_followers(cls, repo_id):
2881 def get_repo_followers(cls, repo_id):
2882 return cls.query().filter(cls.follows_repo_id == repo_id)
2882 return cls.query().filter(cls.follows_repo_id == repo_id)
2883
2883
2884
2884
2885 class CacheKey(Base, BaseModel):
2885 class CacheKey(Base, BaseModel):
2886 __tablename__ = 'cache_invalidation'
2886 __tablename__ = 'cache_invalidation'
2887 __table_args__ = (
2887 __table_args__ = (
2888 UniqueConstraint('cache_key'),
2888 UniqueConstraint('cache_key'),
2889 Index('key_idx', 'cache_key'),
2889 Index('key_idx', 'cache_key'),
2890 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2890 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2891 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2891 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2892 )
2892 )
2893 CACHE_TYPE_ATOM = 'ATOM'
2893 CACHE_TYPE_ATOM = 'ATOM'
2894 CACHE_TYPE_RSS = 'RSS'
2894 CACHE_TYPE_RSS = 'RSS'
2895 CACHE_TYPE_README = 'README'
2895 CACHE_TYPE_README = 'README'
2896
2896
2897 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2897 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2898 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
2898 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
2899 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
2899 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
2900 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
2900 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
2901
2901
2902 def __init__(self, cache_key, cache_args=''):
2902 def __init__(self, cache_key, cache_args=''):
2903 self.cache_key = cache_key
2903 self.cache_key = cache_key
2904 self.cache_args = cache_args
2904 self.cache_args = cache_args
2905 self.cache_active = False
2905 self.cache_active = False
2906
2906
2907 def __unicode__(self):
2907 def __unicode__(self):
2908 return u"<%s('%s:%s[%s]')>" % (
2908 return u"<%s('%s:%s[%s]')>" % (
2909 self.__class__.__name__,
2909 self.__class__.__name__,
2910 self.cache_id, self.cache_key, self.cache_active)
2910 self.cache_id, self.cache_key, self.cache_active)
2911
2911
2912 def _cache_key_partition(self):
2912 def _cache_key_partition(self):
2913 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
2913 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
2914 return prefix, repo_name, suffix
2914 return prefix, repo_name, suffix
2915
2915
2916 def get_prefix(self):
2916 def get_prefix(self):
2917 """
2917 """
2918 Try to extract prefix from existing cache key. The key could consist
2918 Try to extract prefix from existing cache key. The key could consist
2919 of prefix, repo_name, suffix
2919 of prefix, repo_name, suffix
2920 """
2920 """
2921 # this returns prefix, repo_name, suffix
2921 # this returns prefix, repo_name, suffix
2922 return self._cache_key_partition()[0]
2922 return self._cache_key_partition()[0]
2923
2923
2924 def get_suffix(self):
2924 def get_suffix(self):
2925 """
2925 """
2926 get suffix that might have been used in _get_cache_key to
2926 get suffix that might have been used in _get_cache_key to
2927 generate self.cache_key. Only used for informational purposes
2927 generate self.cache_key. Only used for informational purposes
2928 in repo_edit.mako.
2928 in repo_edit.mako.
2929 """
2929 """
2930 # prefix, repo_name, suffix
2930 # prefix, repo_name, suffix
2931 return self._cache_key_partition()[2]
2931 return self._cache_key_partition()[2]
2932
2932
2933 @classmethod
2933 @classmethod
2934 def delete_all_cache(cls):
2934 def delete_all_cache(cls):
2935 """
2935 """
2936 Delete all cache keys from database.
2936 Delete all cache keys from database.
2937 Should only be run when all instances are down and all entries
2937 Should only be run when all instances are down and all entries
2938 thus stale.
2938 thus stale.
2939 """
2939 """
2940 cls.query().delete()
2940 cls.query().delete()
2941 Session().commit()
2941 Session().commit()
2942
2942
2943 @classmethod
2943 @classmethod
2944 def get_cache_key(cls, repo_name, cache_type):
2944 def get_cache_key(cls, repo_name, cache_type):
2945 """
2945 """
2946
2946
2947 Generate a cache key for this process of RhodeCode instance.
2947 Generate a cache key for this process of RhodeCode instance.
2948 Prefix most likely will be process id or maybe explicitly set
2948 Prefix most likely will be process id or maybe explicitly set
2949 instance_id from .ini file.
2949 instance_id from .ini file.
2950 """
2950 """
2951 import rhodecode
2951 import rhodecode
2952 prefix = safe_unicode(rhodecode.CONFIG.get('instance_id') or '')
2952 prefix = safe_unicode(rhodecode.CONFIG.get('instance_id') or '')
2953
2953
2954 repo_as_unicode = safe_unicode(repo_name)
2954 repo_as_unicode = safe_unicode(repo_name)
2955 key = u'{}_{}'.format(repo_as_unicode, cache_type) \
2955 key = u'{}_{}'.format(repo_as_unicode, cache_type) \
2956 if cache_type else repo_as_unicode
2956 if cache_type else repo_as_unicode
2957
2957
2958 return u'{}{}'.format(prefix, key)
2958 return u'{}{}'.format(prefix, key)
2959
2959
2960 @classmethod
2960 @classmethod
2961 def set_invalidate(cls, repo_name, delete=False):
2961 def set_invalidate(cls, repo_name, delete=False):
2962 """
2962 """
2963 Mark all caches of a repo as invalid in the database.
2963 Mark all caches of a repo as invalid in the database.
2964 """
2964 """
2965
2965
2966 try:
2966 try:
2967 qry = Session().query(cls).filter(cls.cache_args == repo_name)
2967 qry = Session().query(cls).filter(cls.cache_args == repo_name)
2968 if delete:
2968 if delete:
2969 log.debug('cache objects deleted for repo %s',
2969 log.debug('cache objects deleted for repo %s',
2970 safe_str(repo_name))
2970 safe_str(repo_name))
2971 qry.delete()
2971 qry.delete()
2972 else:
2972 else:
2973 log.debug('cache objects marked as invalid for repo %s',
2973 log.debug('cache objects marked as invalid for repo %s',
2974 safe_str(repo_name))
2974 safe_str(repo_name))
2975 qry.update({"cache_active": False})
2975 qry.update({"cache_active": False})
2976
2976
2977 Session().commit()
2977 Session().commit()
2978 except Exception:
2978 except Exception:
2979 log.exception(
2979 log.exception(
2980 'Cache key invalidation failed for repository %s',
2980 'Cache key invalidation failed for repository %s',
2981 safe_str(repo_name))
2981 safe_str(repo_name))
2982 Session().rollback()
2982 Session().rollback()
2983
2983
2984 @classmethod
2984 @classmethod
2985 def get_active_cache(cls, cache_key):
2985 def get_active_cache(cls, cache_key):
2986 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
2986 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
2987 if inv_obj:
2987 if inv_obj:
2988 return inv_obj
2988 return inv_obj
2989 return None
2989 return None
2990
2990
2991 @classmethod
2991 @classmethod
2992 def repo_context_cache(cls, compute_func, repo_name, cache_type,
2992 def repo_context_cache(cls, compute_func, repo_name, cache_type,
2993 thread_scoped=False):
2993 thread_scoped=False):
2994 """
2994 """
2995 @cache_region('long_term')
2995 @cache_region('long_term')
2996 def _heavy_calculation(cache_key):
2996 def _heavy_calculation(cache_key):
2997 return 'result'
2997 return 'result'
2998
2998
2999 cache_context = CacheKey.repo_context_cache(
2999 cache_context = CacheKey.repo_context_cache(
3000 _heavy_calculation, repo_name, cache_type)
3000 _heavy_calculation, repo_name, cache_type)
3001
3001
3002 with cache_context as context:
3002 with cache_context as context:
3003 context.invalidate()
3003 context.invalidate()
3004 computed = context.compute()
3004 computed = context.compute()
3005
3005
3006 assert computed == 'result'
3006 assert computed == 'result'
3007 """
3007 """
3008 from rhodecode.lib import caches
3008 from rhodecode.lib import caches
3009 return caches.InvalidationContext(
3009 return caches.InvalidationContext(
3010 compute_func, repo_name, cache_type, thread_scoped=thread_scoped)
3010 compute_func, repo_name, cache_type, thread_scoped=thread_scoped)
3011
3011
3012
3012
3013 class ChangesetComment(Base, BaseModel):
3013 class ChangesetComment(Base, BaseModel):
3014 __tablename__ = 'changeset_comments'
3014 __tablename__ = 'changeset_comments'
3015 __table_args__ = (
3015 __table_args__ = (
3016 Index('cc_revision_idx', 'revision'),
3016 Index('cc_revision_idx', 'revision'),
3017 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3017 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3018 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3018 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3019 )
3019 )
3020
3020
3021 COMMENT_OUTDATED = u'comment_outdated'
3021 COMMENT_OUTDATED = u'comment_outdated'
3022 COMMENT_TYPE_NOTE = u'note'
3022 COMMENT_TYPE_NOTE = u'note'
3023 COMMENT_TYPE_TODO = u'todo'
3023 COMMENT_TYPE_TODO = u'todo'
3024 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3024 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3025
3025
3026 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3026 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3027 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3027 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3028 revision = Column('revision', String(40), nullable=True)
3028 revision = Column('revision', String(40), nullable=True)
3029 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3029 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3030 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3030 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3031 line_no = Column('line_no', Unicode(10), nullable=True)
3031 line_no = Column('line_no', Unicode(10), nullable=True)
3032 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3032 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3033 f_path = Column('f_path', Unicode(1000), nullable=True)
3033 f_path = Column('f_path', Unicode(1000), nullable=True)
3034 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3034 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3035 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3035 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3036 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3036 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3037 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3037 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3038 renderer = Column('renderer', Unicode(64), nullable=True)
3038 renderer = Column('renderer', Unicode(64), nullable=True)
3039 display_state = Column('display_state', Unicode(128), nullable=True)
3039 display_state = Column('display_state', Unicode(128), nullable=True)
3040
3040
3041 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3041 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3042 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3042 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3043 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, backref='resolved_by')
3043 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, backref='resolved_by')
3044 author = relationship('User', lazy='joined')
3044 author = relationship('User', lazy='joined')
3045 repo = relationship('Repository')
3045 repo = relationship('Repository')
3046 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3046 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3047 pull_request = relationship('PullRequest', lazy='joined')
3047 pull_request = relationship('PullRequest', lazy='joined')
3048 pull_request_version = relationship('PullRequestVersion')
3048 pull_request_version = relationship('PullRequestVersion')
3049
3049
3050 @classmethod
3050 @classmethod
3051 def get_users(cls, revision=None, pull_request_id=None):
3051 def get_users(cls, revision=None, pull_request_id=None):
3052 """
3052 """
3053 Returns user associated with this ChangesetComment. ie those
3053 Returns user associated with this ChangesetComment. ie those
3054 who actually commented
3054 who actually commented
3055
3055
3056 :param cls:
3056 :param cls:
3057 :param revision:
3057 :param revision:
3058 """
3058 """
3059 q = Session().query(User)\
3059 q = Session().query(User)\
3060 .join(ChangesetComment.author)
3060 .join(ChangesetComment.author)
3061 if revision:
3061 if revision:
3062 q = q.filter(cls.revision == revision)
3062 q = q.filter(cls.revision == revision)
3063 elif pull_request_id:
3063 elif pull_request_id:
3064 q = q.filter(cls.pull_request_id == pull_request_id)
3064 q = q.filter(cls.pull_request_id == pull_request_id)
3065 return q.all()
3065 return q.all()
3066
3066
3067 @classmethod
3067 @classmethod
3068 def get_index_from_version(cls, pr_version, versions):
3068 def get_index_from_version(cls, pr_version, versions):
3069 num_versions = [x.pull_request_version_id for x in versions]
3069 num_versions = [x.pull_request_version_id for x in versions]
3070 try:
3070 try:
3071 return num_versions.index(pr_version) +1
3071 return num_versions.index(pr_version) +1
3072 except (IndexError, ValueError):
3072 except (IndexError, ValueError):
3073 return
3073 return
3074
3074
3075 @property
3075 @property
3076 def outdated(self):
3076 def outdated(self):
3077 return self.display_state == self.COMMENT_OUTDATED
3077 return self.display_state == self.COMMENT_OUTDATED
3078
3078
3079 def outdated_at_version(self, version):
3079 def outdated_at_version(self, version):
3080 """
3080 """
3081 Checks if comment is outdated for given pull request version
3081 Checks if comment is outdated for given pull request version
3082 """
3082 """
3083 return self.outdated and self.pull_request_version_id != version
3083 return self.outdated and self.pull_request_version_id != version
3084
3084
3085 def older_than_version(self, version):
3085 def older_than_version(self, version):
3086 """
3086 """
3087 Checks if comment is made from previous version than given
3087 Checks if comment is made from previous version than given
3088 """
3088 """
3089 if version is None:
3089 if version is None:
3090 return self.pull_request_version_id is not None
3090 return self.pull_request_version_id is not None
3091
3091
3092 return self.pull_request_version_id < version
3092 return self.pull_request_version_id < version
3093
3093
3094 @property
3094 @property
3095 def resolved(self):
3095 def resolved(self):
3096 return self.resolved_by[0] if self.resolved_by else None
3096 return self.resolved_by[0] if self.resolved_by else None
3097
3097
3098 @property
3098 @property
3099 def is_todo(self):
3099 def is_todo(self):
3100 return self.comment_type == self.COMMENT_TYPE_TODO
3100 return self.comment_type == self.COMMENT_TYPE_TODO
3101
3101
3102 def get_index_version(self, versions):
3102 def get_index_version(self, versions):
3103 return self.get_index_from_version(
3103 return self.get_index_from_version(
3104 self.pull_request_version_id, versions)
3104 self.pull_request_version_id, versions)
3105
3105
3106 def __repr__(self):
3106 def __repr__(self):
3107 if self.comment_id:
3107 if self.comment_id:
3108 return '<DB:Comment #%s>' % self.comment_id
3108 return '<DB:Comment #%s>' % self.comment_id
3109 else:
3109 else:
3110 return '<DB:Comment at %#x>' % id(self)
3110 return '<DB:Comment at %#x>' % id(self)
3111
3111
3112
3112
3113 class ChangesetStatus(Base, BaseModel):
3113 class ChangesetStatus(Base, BaseModel):
3114 __tablename__ = 'changeset_statuses'
3114 __tablename__ = 'changeset_statuses'
3115 __table_args__ = (
3115 __table_args__ = (
3116 Index('cs_revision_idx', 'revision'),
3116 Index('cs_revision_idx', 'revision'),
3117 Index('cs_version_idx', 'version'),
3117 Index('cs_version_idx', 'version'),
3118 UniqueConstraint('repo_id', 'revision', 'version'),
3118 UniqueConstraint('repo_id', 'revision', 'version'),
3119 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3119 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3120 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3120 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3121 )
3121 )
3122 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3122 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3123 STATUS_APPROVED = 'approved'
3123 STATUS_APPROVED = 'approved'
3124 STATUS_REJECTED = 'rejected'
3124 STATUS_REJECTED = 'rejected'
3125 STATUS_UNDER_REVIEW = 'under_review'
3125 STATUS_UNDER_REVIEW = 'under_review'
3126
3126
3127 STATUSES = [
3127 STATUSES = [
3128 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3128 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3129 (STATUS_APPROVED, _("Approved")),
3129 (STATUS_APPROVED, _("Approved")),
3130 (STATUS_REJECTED, _("Rejected")),
3130 (STATUS_REJECTED, _("Rejected")),
3131 (STATUS_UNDER_REVIEW, _("Under Review")),
3131 (STATUS_UNDER_REVIEW, _("Under Review")),
3132 ]
3132 ]
3133
3133
3134 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3134 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3135 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3135 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3136 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3136 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3137 revision = Column('revision', String(40), nullable=False)
3137 revision = Column('revision', String(40), nullable=False)
3138 status = Column('status', String(128), nullable=False, default=DEFAULT)
3138 status = Column('status', String(128), nullable=False, default=DEFAULT)
3139 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3139 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3140 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3140 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3141 version = Column('version', Integer(), nullable=False, default=0)
3141 version = Column('version', Integer(), nullable=False, default=0)
3142 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3142 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3143
3143
3144 author = relationship('User', lazy='joined')
3144 author = relationship('User', lazy='joined')
3145 repo = relationship('Repository')
3145 repo = relationship('Repository')
3146 comment = relationship('ChangesetComment', lazy='joined')
3146 comment = relationship('ChangesetComment', lazy='joined')
3147 pull_request = relationship('PullRequest', lazy='joined')
3147 pull_request = relationship('PullRequest', lazy='joined')
3148
3148
3149 def __unicode__(self):
3149 def __unicode__(self):
3150 return u"<%s('%s[v%s]:%s')>" % (
3150 return u"<%s('%s[v%s]:%s')>" % (
3151 self.__class__.__name__,
3151 self.__class__.__name__,
3152 self.status, self.version, self.author
3152 self.status, self.version, self.author
3153 )
3153 )
3154
3154
3155 @classmethod
3155 @classmethod
3156 def get_status_lbl(cls, value):
3156 def get_status_lbl(cls, value):
3157 return dict(cls.STATUSES).get(value)
3157 return dict(cls.STATUSES).get(value)
3158
3158
3159 @property
3159 @property
3160 def status_lbl(self):
3160 def status_lbl(self):
3161 return ChangesetStatus.get_status_lbl(self.status)
3161 return ChangesetStatus.get_status_lbl(self.status)
3162
3162
3163
3163
3164 class _PullRequestBase(BaseModel):
3164 class _PullRequestBase(BaseModel):
3165 """
3165 """
3166 Common attributes of pull request and version entries.
3166 Common attributes of pull request and version entries.
3167 """
3167 """
3168
3168
3169 # .status values
3169 # .status values
3170 STATUS_NEW = u'new'
3170 STATUS_NEW = u'new'
3171 STATUS_OPEN = u'open'
3171 STATUS_OPEN = u'open'
3172 STATUS_CLOSED = u'closed'
3172 STATUS_CLOSED = u'closed'
3173
3173
3174 title = Column('title', Unicode(255), nullable=True)
3174 title = Column('title', Unicode(255), nullable=True)
3175 description = Column(
3175 description = Column(
3176 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3176 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3177 nullable=True)
3177 nullable=True)
3178 # new/open/closed status of pull request (not approve/reject/etc)
3178 # new/open/closed status of pull request (not approve/reject/etc)
3179 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3179 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3180 created_on = Column(
3180 created_on = Column(
3181 'created_on', DateTime(timezone=False), nullable=False,
3181 'created_on', DateTime(timezone=False), nullable=False,
3182 default=datetime.datetime.now)
3182 default=datetime.datetime.now)
3183 updated_on = Column(
3183 updated_on = Column(
3184 'updated_on', DateTime(timezone=False), nullable=False,
3184 'updated_on', DateTime(timezone=False), nullable=False,
3185 default=datetime.datetime.now)
3185 default=datetime.datetime.now)
3186
3186
3187 @declared_attr
3187 @declared_attr
3188 def user_id(cls):
3188 def user_id(cls):
3189 return Column(
3189 return Column(
3190 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3190 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3191 unique=None)
3191 unique=None)
3192
3192
3193 # 500 revisions max
3193 # 500 revisions max
3194 _revisions = Column(
3194 _revisions = Column(
3195 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3195 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3196
3196
3197 @declared_attr
3197 @declared_attr
3198 def source_repo_id(cls):
3198 def source_repo_id(cls):
3199 # TODO: dan: rename column to source_repo_id
3199 # TODO: dan: rename column to source_repo_id
3200 return Column(
3200 return Column(
3201 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3201 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3202 nullable=False)
3202 nullable=False)
3203
3203
3204 source_ref = Column('org_ref', Unicode(255), nullable=False)
3204 source_ref = Column('org_ref', Unicode(255), nullable=False)
3205
3205
3206 @declared_attr
3206 @declared_attr
3207 def target_repo_id(cls):
3207 def target_repo_id(cls):
3208 # TODO: dan: rename column to target_repo_id
3208 # TODO: dan: rename column to target_repo_id
3209 return Column(
3209 return Column(
3210 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3210 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3211 nullable=False)
3211 nullable=False)
3212
3212
3213 target_ref = Column('other_ref', Unicode(255), nullable=False)
3213 target_ref = Column('other_ref', Unicode(255), nullable=False)
3214 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3214 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3215
3215
3216 # TODO: dan: rename column to last_merge_source_rev
3216 # TODO: dan: rename column to last_merge_source_rev
3217 _last_merge_source_rev = Column(
3217 _last_merge_source_rev = Column(
3218 'last_merge_org_rev', String(40), nullable=True)
3218 'last_merge_org_rev', String(40), nullable=True)
3219 # TODO: dan: rename column to last_merge_target_rev
3219 # TODO: dan: rename column to last_merge_target_rev
3220 _last_merge_target_rev = Column(
3220 _last_merge_target_rev = Column(
3221 'last_merge_other_rev', String(40), nullable=True)
3221 'last_merge_other_rev', String(40), nullable=True)
3222 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3222 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3223 merge_rev = Column('merge_rev', String(40), nullable=True)
3223 merge_rev = Column('merge_rev', String(40), nullable=True)
3224
3224
3225 @hybrid_property
3225 @hybrid_property
3226 def revisions(self):
3226 def revisions(self):
3227 return self._revisions.split(':') if self._revisions else []
3227 return self._revisions.split(':') if self._revisions else []
3228
3228
3229 @revisions.setter
3229 @revisions.setter
3230 def revisions(self, val):
3230 def revisions(self, val):
3231 self._revisions = ':'.join(val)
3231 self._revisions = ':'.join(val)
3232
3232
3233 @declared_attr
3233 @declared_attr
3234 def author(cls):
3234 def author(cls):
3235 return relationship('User', lazy='joined')
3235 return relationship('User', lazy='joined')
3236
3236
3237 @declared_attr
3237 @declared_attr
3238 def source_repo(cls):
3238 def source_repo(cls):
3239 return relationship(
3239 return relationship(
3240 'Repository',
3240 'Repository',
3241 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3241 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3242
3242
3243 @property
3243 @property
3244 def source_ref_parts(self):
3244 def source_ref_parts(self):
3245 return self.unicode_to_reference(self.source_ref)
3245 return self.unicode_to_reference(self.source_ref)
3246
3246
3247 @declared_attr
3247 @declared_attr
3248 def target_repo(cls):
3248 def target_repo(cls):
3249 return relationship(
3249 return relationship(
3250 'Repository',
3250 'Repository',
3251 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3251 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3252
3252
3253 @property
3253 @property
3254 def target_ref_parts(self):
3254 def target_ref_parts(self):
3255 return self.unicode_to_reference(self.target_ref)
3255 return self.unicode_to_reference(self.target_ref)
3256
3256
3257 @property
3257 @property
3258 def shadow_merge_ref(self):
3258 def shadow_merge_ref(self):
3259 return self.unicode_to_reference(self._shadow_merge_ref)
3259 return self.unicode_to_reference(self._shadow_merge_ref)
3260
3260
3261 @shadow_merge_ref.setter
3261 @shadow_merge_ref.setter
3262 def shadow_merge_ref(self, ref):
3262 def shadow_merge_ref(self, ref):
3263 self._shadow_merge_ref = self.reference_to_unicode(ref)
3263 self._shadow_merge_ref = self.reference_to_unicode(ref)
3264
3264
3265 def unicode_to_reference(self, raw):
3265 def unicode_to_reference(self, raw):
3266 """
3266 """
3267 Convert a unicode (or string) to a reference object.
3267 Convert a unicode (or string) to a reference object.
3268 If unicode evaluates to False it returns None.
3268 If unicode evaluates to False it returns None.
3269 """
3269 """
3270 if raw:
3270 if raw:
3271 refs = raw.split(':')
3271 refs = raw.split(':')
3272 return Reference(*refs)
3272 return Reference(*refs)
3273 else:
3273 else:
3274 return None
3274 return None
3275
3275
3276 def reference_to_unicode(self, ref):
3276 def reference_to_unicode(self, ref):
3277 """
3277 """
3278 Convert a reference object to unicode.
3278 Convert a reference object to unicode.
3279 If reference is None it returns None.
3279 If reference is None it returns None.
3280 """
3280 """
3281 if ref:
3281 if ref:
3282 return u':'.join(ref)
3282 return u':'.join(ref)
3283 else:
3283 else:
3284 return None
3284 return None
3285
3285
3286 def get_api_data(self):
3286 def get_api_data(self):
3287 from rhodecode.model.pull_request import PullRequestModel
3287 from rhodecode.model.pull_request import PullRequestModel
3288 pull_request = self
3288 pull_request = self
3289 merge_status = PullRequestModel().merge_status(pull_request)
3289 merge_status = PullRequestModel().merge_status(pull_request)
3290
3290
3291 pull_request_url = url(
3291 pull_request_url = url(
3292 'pullrequest_show', repo_name=self.target_repo.repo_name,
3292 'pullrequest_show', repo_name=self.target_repo.repo_name,
3293 pull_request_id=self.pull_request_id, qualified=True)
3293 pull_request_id=self.pull_request_id, qualified=True)
3294
3294
3295 merge_data = {
3295 merge_data = {
3296 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3296 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3297 'reference': (
3297 'reference': (
3298 pull_request.shadow_merge_ref._asdict()
3298 pull_request.shadow_merge_ref._asdict()
3299 if pull_request.shadow_merge_ref else None),
3299 if pull_request.shadow_merge_ref else None),
3300 }
3300 }
3301
3301
3302 data = {
3302 data = {
3303 'pull_request_id': pull_request.pull_request_id,
3303 'pull_request_id': pull_request.pull_request_id,
3304 'url': pull_request_url,
3304 'url': pull_request_url,
3305 'title': pull_request.title,
3305 'title': pull_request.title,
3306 'description': pull_request.description,
3306 'description': pull_request.description,
3307 'status': pull_request.status,
3307 'status': pull_request.status,
3308 'created_on': pull_request.created_on,
3308 'created_on': pull_request.created_on,
3309 'updated_on': pull_request.updated_on,
3309 'updated_on': pull_request.updated_on,
3310 'commit_ids': pull_request.revisions,
3310 'commit_ids': pull_request.revisions,
3311 'review_status': pull_request.calculated_review_status(),
3311 'review_status': pull_request.calculated_review_status(),
3312 'mergeable': {
3312 'mergeable': {
3313 'status': merge_status[0],
3313 'status': merge_status[0],
3314 'message': unicode(merge_status[1]),
3314 'message': unicode(merge_status[1]),
3315 },
3315 },
3316 'source': {
3316 'source': {
3317 'clone_url': pull_request.source_repo.clone_url(),
3317 'clone_url': pull_request.source_repo.clone_url(),
3318 'repository': pull_request.source_repo.repo_name,
3318 'repository': pull_request.source_repo.repo_name,
3319 'reference': {
3319 'reference': {
3320 'name': pull_request.source_ref_parts.name,
3320 'name': pull_request.source_ref_parts.name,
3321 'type': pull_request.source_ref_parts.type,
3321 'type': pull_request.source_ref_parts.type,
3322 'commit_id': pull_request.source_ref_parts.commit_id,
3322 'commit_id': pull_request.source_ref_parts.commit_id,
3323 },
3323 },
3324 },
3324 },
3325 'target': {
3325 'target': {
3326 'clone_url': pull_request.target_repo.clone_url(),
3326 'clone_url': pull_request.target_repo.clone_url(),
3327 'repository': pull_request.target_repo.repo_name,
3327 'repository': pull_request.target_repo.repo_name,
3328 'reference': {
3328 'reference': {
3329 'name': pull_request.target_ref_parts.name,
3329 'name': pull_request.target_ref_parts.name,
3330 'type': pull_request.target_ref_parts.type,
3330 'type': pull_request.target_ref_parts.type,
3331 'commit_id': pull_request.target_ref_parts.commit_id,
3331 'commit_id': pull_request.target_ref_parts.commit_id,
3332 },
3332 },
3333 },
3333 },
3334 'merge': merge_data,
3334 'merge': merge_data,
3335 'author': pull_request.author.get_api_data(include_secrets=False,
3335 'author': pull_request.author.get_api_data(include_secrets=False,
3336 details='basic'),
3336 details='basic'),
3337 'reviewers': [
3337 'reviewers': [
3338 {
3338 {
3339 'user': reviewer.get_api_data(include_secrets=False,
3339 'user': reviewer.get_api_data(include_secrets=False,
3340 details='basic'),
3340 details='basic'),
3341 'reasons': reasons,
3341 'reasons': reasons,
3342 'review_status': st[0][1].status if st else 'not_reviewed',
3342 'review_status': st[0][1].status if st else 'not_reviewed',
3343 }
3343 }
3344 for reviewer, reasons, st in pull_request.reviewers_statuses()
3344 for reviewer, reasons, st in pull_request.reviewers_statuses()
3345 ]
3345 ]
3346 }
3346 }
3347
3347
3348 return data
3348 return data
3349
3349
3350
3350
3351 class PullRequest(Base, _PullRequestBase):
3351 class PullRequest(Base, _PullRequestBase):
3352 __tablename__ = 'pull_requests'
3352 __tablename__ = 'pull_requests'
3353 __table_args__ = (
3353 __table_args__ = (
3354 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3354 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3355 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3355 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3356 )
3356 )
3357
3357
3358 pull_request_id = Column(
3358 pull_request_id = Column(
3359 'pull_request_id', Integer(), nullable=False, primary_key=True)
3359 'pull_request_id', Integer(), nullable=False, primary_key=True)
3360
3360
3361 def __repr__(self):
3361 def __repr__(self):
3362 if self.pull_request_id:
3362 if self.pull_request_id:
3363 return '<DB:PullRequest #%s>' % self.pull_request_id
3363 return '<DB:PullRequest #%s>' % self.pull_request_id
3364 else:
3364 else:
3365 return '<DB:PullRequest at %#x>' % id(self)
3365 return '<DB:PullRequest at %#x>' % id(self)
3366
3366
3367 reviewers = relationship('PullRequestReviewers',
3367 reviewers = relationship('PullRequestReviewers',
3368 cascade="all, delete, delete-orphan")
3368 cascade="all, delete, delete-orphan")
3369 statuses = relationship('ChangesetStatus')
3369 statuses = relationship('ChangesetStatus')
3370 comments = relationship('ChangesetComment',
3370 comments = relationship('ChangesetComment',
3371 cascade="all, delete, delete-orphan")
3371 cascade="all, delete, delete-orphan")
3372 versions = relationship('PullRequestVersion',
3372 versions = relationship('PullRequestVersion',
3373 cascade="all, delete, delete-orphan",
3373 cascade="all, delete, delete-orphan",
3374 lazy='dynamic')
3374 lazy='dynamic')
3375
3375
3376 @classmethod
3376 @classmethod
3377 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3377 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3378 internal_methods=None):
3378 internal_methods=None):
3379
3379
3380 class PullRequestDisplay(object):
3380 class PullRequestDisplay(object):
3381 """
3381 """
3382 Special object wrapper for showing PullRequest data via Versions
3382 Special object wrapper for showing PullRequest data via Versions
3383 It mimics PR object as close as possible. This is read only object
3383 It mimics PR object as close as possible. This is read only object
3384 just for display
3384 just for display
3385 """
3385 """
3386
3386
3387 def __init__(self, attrs, internal=None):
3387 def __init__(self, attrs, internal=None):
3388 self.attrs = attrs
3388 self.attrs = attrs
3389 # internal have priority over the given ones via attrs
3389 # internal have priority over the given ones via attrs
3390 self.internal = internal or ['versions']
3390 self.internal = internal or ['versions']
3391
3391
3392 def __getattr__(self, item):
3392 def __getattr__(self, item):
3393 if item in self.internal:
3393 if item in self.internal:
3394 return getattr(self, item)
3394 return getattr(self, item)
3395 try:
3395 try:
3396 return self.attrs[item]
3396 return self.attrs[item]
3397 except KeyError:
3397 except KeyError:
3398 raise AttributeError(
3398 raise AttributeError(
3399 '%s object has no attribute %s' % (self, item))
3399 '%s object has no attribute %s' % (self, item))
3400
3400
3401 def __repr__(self):
3401 def __repr__(self):
3402 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3402 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3403
3403
3404 def versions(self):
3404 def versions(self):
3405 return pull_request_obj.versions.order_by(
3405 return pull_request_obj.versions.order_by(
3406 PullRequestVersion.pull_request_version_id).all()
3406 PullRequestVersion.pull_request_version_id).all()
3407
3407
3408 def is_closed(self):
3408 def is_closed(self):
3409 return pull_request_obj.is_closed()
3409 return pull_request_obj.is_closed()
3410
3410
3411 @property
3411 @property
3412 def pull_request_version_id(self):
3412 def pull_request_version_id(self):
3413 return getattr(pull_request_obj, 'pull_request_version_id', None)
3413 return getattr(pull_request_obj, 'pull_request_version_id', None)
3414
3414
3415 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3415 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3416
3416
3417 attrs.author = StrictAttributeDict(
3417 attrs.author = StrictAttributeDict(
3418 pull_request_obj.author.get_api_data())
3418 pull_request_obj.author.get_api_data())
3419 if pull_request_obj.target_repo:
3419 if pull_request_obj.target_repo:
3420 attrs.target_repo = StrictAttributeDict(
3420 attrs.target_repo = StrictAttributeDict(
3421 pull_request_obj.target_repo.get_api_data())
3421 pull_request_obj.target_repo.get_api_data())
3422 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3422 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3423
3423
3424 if pull_request_obj.source_repo:
3424 if pull_request_obj.source_repo:
3425 attrs.source_repo = StrictAttributeDict(
3425 attrs.source_repo = StrictAttributeDict(
3426 pull_request_obj.source_repo.get_api_data())
3426 pull_request_obj.source_repo.get_api_data())
3427 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3427 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3428
3428
3429 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3429 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3430 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3430 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3431 attrs.revisions = pull_request_obj.revisions
3431 attrs.revisions = pull_request_obj.revisions
3432
3432
3433 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3433 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3434
3434
3435 return PullRequestDisplay(attrs, internal=internal_methods)
3435 return PullRequestDisplay(attrs, internal=internal_methods)
3436
3436
3437 def is_closed(self):
3437 def is_closed(self):
3438 return self.status == self.STATUS_CLOSED
3438 return self.status == self.STATUS_CLOSED
3439
3439
3440 def __json__(self):
3440 def __json__(self):
3441 return {
3441 return {
3442 'revisions': self.revisions,
3442 'revisions': self.revisions,
3443 }
3443 }
3444
3444
3445 def calculated_review_status(self):
3445 def calculated_review_status(self):
3446 from rhodecode.model.changeset_status import ChangesetStatusModel
3446 from rhodecode.model.changeset_status import ChangesetStatusModel
3447 return ChangesetStatusModel().calculated_review_status(self)
3447 return ChangesetStatusModel().calculated_review_status(self)
3448
3448
3449 def reviewers_statuses(self):
3449 def reviewers_statuses(self):
3450 from rhodecode.model.changeset_status import ChangesetStatusModel
3450 from rhodecode.model.changeset_status import ChangesetStatusModel
3451 return ChangesetStatusModel().reviewers_statuses(self)
3451 return ChangesetStatusModel().reviewers_statuses(self)
3452
3452
3453 @property
3453 @property
3454 def workspace_id(self):
3454 def workspace_id(self):
3455 from rhodecode.model.pull_request import PullRequestModel
3455 from rhodecode.model.pull_request import PullRequestModel
3456 return PullRequestModel()._workspace_id(self)
3456 return PullRequestModel()._workspace_id(self)
3457
3457
3458 def get_shadow_repo(self):
3458 def get_shadow_repo(self):
3459 workspace_id = self.workspace_id
3459 workspace_id = self.workspace_id
3460 vcs_obj = self.target_repo.scm_instance()
3460 vcs_obj = self.target_repo.scm_instance()
3461 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3461 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3462 workspace_id)
3462 workspace_id)
3463 return vcs_obj._get_shadow_instance(shadow_repository_path)
3463 return vcs_obj._get_shadow_instance(shadow_repository_path)
3464
3464
3465
3465
3466 class PullRequestVersion(Base, _PullRequestBase):
3466 class PullRequestVersion(Base, _PullRequestBase):
3467 __tablename__ = 'pull_request_versions'
3467 __tablename__ = 'pull_request_versions'
3468 __table_args__ = (
3468 __table_args__ = (
3469 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3469 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3470 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3470 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3471 )
3471 )
3472
3472
3473 pull_request_version_id = Column(
3473 pull_request_version_id = Column(
3474 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3474 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3475 pull_request_id = Column(
3475 pull_request_id = Column(
3476 'pull_request_id', Integer(),
3476 'pull_request_id', Integer(),
3477 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3477 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3478 pull_request = relationship('PullRequest')
3478 pull_request = relationship('PullRequest')
3479
3479
3480 def __repr__(self):
3480 def __repr__(self):
3481 if self.pull_request_version_id:
3481 if self.pull_request_version_id:
3482 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3482 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3483 else:
3483 else:
3484 return '<DB:PullRequestVersion at %#x>' % id(self)
3484 return '<DB:PullRequestVersion at %#x>' % id(self)
3485
3485
3486 @property
3486 @property
3487 def reviewers(self):
3487 def reviewers(self):
3488 return self.pull_request.reviewers
3488 return self.pull_request.reviewers
3489
3489
3490 @property
3490 @property
3491 def versions(self):
3491 def versions(self):
3492 return self.pull_request.versions
3492 return self.pull_request.versions
3493
3493
3494 def is_closed(self):
3494 def is_closed(self):
3495 # calculate from original
3495 # calculate from original
3496 return self.pull_request.status == self.STATUS_CLOSED
3496 return self.pull_request.status == self.STATUS_CLOSED
3497
3497
3498 def calculated_review_status(self):
3498 def calculated_review_status(self):
3499 return self.pull_request.calculated_review_status()
3499 return self.pull_request.calculated_review_status()
3500
3500
3501 def reviewers_statuses(self):
3501 def reviewers_statuses(self):
3502 return self.pull_request.reviewers_statuses()
3502 return self.pull_request.reviewers_statuses()
3503
3503
3504
3504
3505 class PullRequestReviewers(Base, BaseModel):
3505 class PullRequestReviewers(Base, BaseModel):
3506 __tablename__ = 'pull_request_reviewers'
3506 __tablename__ = 'pull_request_reviewers'
3507 __table_args__ = (
3507 __table_args__ = (
3508 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3508 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3509 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3509 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3510 )
3510 )
3511
3511
3512 def __init__(self, user=None, pull_request=None, reasons=None):
3512 def __init__(self, user=None, pull_request=None, reasons=None):
3513 self.user = user
3513 self.user = user
3514 self.pull_request = pull_request
3514 self.pull_request = pull_request
3515 self.reasons = reasons or []
3515 self.reasons = reasons or []
3516
3516
3517 @hybrid_property
3517 @hybrid_property
3518 def reasons(self):
3518 def reasons(self):
3519 if not self._reasons:
3519 if not self._reasons:
3520 return []
3520 return []
3521 return self._reasons
3521 return self._reasons
3522
3522
3523 @reasons.setter
3523 @reasons.setter
3524 def reasons(self, val):
3524 def reasons(self, val):
3525 val = val or []
3525 val = val or []
3526 if any(not isinstance(x, basestring) for x in val):
3526 if any(not isinstance(x, basestring) for x in val):
3527 raise Exception('invalid reasons type, must be list of strings')
3527 raise Exception('invalid reasons type, must be list of strings')
3528 self._reasons = val
3528 self._reasons = val
3529
3529
3530 pull_requests_reviewers_id = Column(
3530 pull_requests_reviewers_id = Column(
3531 'pull_requests_reviewers_id', Integer(), nullable=False,
3531 'pull_requests_reviewers_id', Integer(), nullable=False,
3532 primary_key=True)
3532 primary_key=True)
3533 pull_request_id = Column(
3533 pull_request_id = Column(
3534 "pull_request_id", Integer(),
3534 "pull_request_id", Integer(),
3535 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3535 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3536 user_id = Column(
3536 user_id = Column(
3537 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3537 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3538 _reasons = Column(
3538 _reasons = Column(
3539 'reason', MutationList.as_mutable(
3539 'reason', MutationList.as_mutable(
3540 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
3540 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
3541
3541
3542 user = relationship('User')
3542 user = relationship('User')
3543 pull_request = relationship('PullRequest')
3543 pull_request = relationship('PullRequest')
3544
3544
3545
3545
3546 class Notification(Base, BaseModel):
3546 class Notification(Base, BaseModel):
3547 __tablename__ = 'notifications'
3547 __tablename__ = 'notifications'
3548 __table_args__ = (
3548 __table_args__ = (
3549 Index('notification_type_idx', 'type'),
3549 Index('notification_type_idx', 'type'),
3550 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3550 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3551 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3551 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3552 )
3552 )
3553
3553
3554 TYPE_CHANGESET_COMMENT = u'cs_comment'
3554 TYPE_CHANGESET_COMMENT = u'cs_comment'
3555 TYPE_MESSAGE = u'message'
3555 TYPE_MESSAGE = u'message'
3556 TYPE_MENTION = u'mention'
3556 TYPE_MENTION = u'mention'
3557 TYPE_REGISTRATION = u'registration'
3557 TYPE_REGISTRATION = u'registration'
3558 TYPE_PULL_REQUEST = u'pull_request'
3558 TYPE_PULL_REQUEST = u'pull_request'
3559 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
3559 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
3560
3560
3561 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
3561 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
3562 subject = Column('subject', Unicode(512), nullable=True)
3562 subject = Column('subject', Unicode(512), nullable=True)
3563 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
3563 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
3564 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
3564 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
3565 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3565 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3566 type_ = Column('type', Unicode(255))
3566 type_ = Column('type', Unicode(255))
3567
3567
3568 created_by_user = relationship('User')
3568 created_by_user = relationship('User')
3569 notifications_to_users = relationship('UserNotification', lazy='joined',
3569 notifications_to_users = relationship('UserNotification', lazy='joined',
3570 cascade="all, delete, delete-orphan")
3570 cascade="all, delete, delete-orphan")
3571
3571
3572 @property
3572 @property
3573 def recipients(self):
3573 def recipients(self):
3574 return [x.user for x in UserNotification.query()\
3574 return [x.user for x in UserNotification.query()\
3575 .filter(UserNotification.notification == self)\
3575 .filter(UserNotification.notification == self)\
3576 .order_by(UserNotification.user_id.asc()).all()]
3576 .order_by(UserNotification.user_id.asc()).all()]
3577
3577
3578 @classmethod
3578 @classmethod
3579 def create(cls, created_by, subject, body, recipients, type_=None):
3579 def create(cls, created_by, subject, body, recipients, type_=None):
3580 if type_ is None:
3580 if type_ is None:
3581 type_ = Notification.TYPE_MESSAGE
3581 type_ = Notification.TYPE_MESSAGE
3582
3582
3583 notification = cls()
3583 notification = cls()
3584 notification.created_by_user = created_by
3584 notification.created_by_user = created_by
3585 notification.subject = subject
3585 notification.subject = subject
3586 notification.body = body
3586 notification.body = body
3587 notification.type_ = type_
3587 notification.type_ = type_
3588 notification.created_on = datetime.datetime.now()
3588 notification.created_on = datetime.datetime.now()
3589
3589
3590 for u in recipients:
3590 for u in recipients:
3591 assoc = UserNotification()
3591 assoc = UserNotification()
3592 assoc.notification = notification
3592 assoc.notification = notification
3593
3593
3594 # if created_by is inside recipients mark his notification
3594 # if created_by is inside recipients mark his notification
3595 # as read
3595 # as read
3596 if u.user_id == created_by.user_id:
3596 if u.user_id == created_by.user_id:
3597 assoc.read = True
3597 assoc.read = True
3598
3598
3599 u.notifications.append(assoc)
3599 u.notifications.append(assoc)
3600 Session().add(notification)
3600 Session().add(notification)
3601
3601
3602 return notification
3602 return notification
3603
3603
3604 @property
3604 @property
3605 def description(self):
3605 def description(self):
3606 from rhodecode.model.notification import NotificationModel
3606 from rhodecode.model.notification import NotificationModel
3607 return NotificationModel().make_description(self)
3607 return NotificationModel().make_description(self)
3608
3608
3609
3609
3610 class UserNotification(Base, BaseModel):
3610 class UserNotification(Base, BaseModel):
3611 __tablename__ = 'user_to_notification'
3611 __tablename__ = 'user_to_notification'
3612 __table_args__ = (
3612 __table_args__ = (
3613 UniqueConstraint('user_id', 'notification_id'),
3613 UniqueConstraint('user_id', 'notification_id'),
3614 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3614 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3615 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3615 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3616 )
3616 )
3617 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
3617 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
3618 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
3618 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
3619 read = Column('read', Boolean, default=False)
3619 read = Column('read', Boolean, default=False)
3620 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
3620 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
3621
3621
3622 user = relationship('User', lazy="joined")
3622 user = relationship('User', lazy="joined")
3623 notification = relationship('Notification', lazy="joined",
3623 notification = relationship('Notification', lazy="joined",
3624 order_by=lambda: Notification.created_on.desc(),)
3624 order_by=lambda: Notification.created_on.desc(),)
3625
3625
3626 def mark_as_read(self):
3626 def mark_as_read(self):
3627 self.read = True
3627 self.read = True
3628 Session().add(self)
3628 Session().add(self)
3629
3629
3630
3630
3631 class Gist(Base, BaseModel):
3631 class Gist(Base, BaseModel):
3632 __tablename__ = 'gists'
3632 __tablename__ = 'gists'
3633 __table_args__ = (
3633 __table_args__ = (
3634 Index('g_gist_access_id_idx', 'gist_access_id'),
3634 Index('g_gist_access_id_idx', 'gist_access_id'),
3635 Index('g_created_on_idx', 'created_on'),
3635 Index('g_created_on_idx', 'created_on'),
3636 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3636 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3637 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3637 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3638 )
3638 )
3639 GIST_PUBLIC = u'public'
3639 GIST_PUBLIC = u'public'
3640 GIST_PRIVATE = u'private'
3640 GIST_PRIVATE = u'private'
3641 DEFAULT_FILENAME = u'gistfile1.txt'
3641 DEFAULT_FILENAME = u'gistfile1.txt'
3642
3642
3643 ACL_LEVEL_PUBLIC = u'acl_public'
3643 ACL_LEVEL_PUBLIC = u'acl_public'
3644 ACL_LEVEL_PRIVATE = u'acl_private'
3644 ACL_LEVEL_PRIVATE = u'acl_private'
3645
3645
3646 gist_id = Column('gist_id', Integer(), primary_key=True)
3646 gist_id = Column('gist_id', Integer(), primary_key=True)
3647 gist_access_id = Column('gist_access_id', Unicode(250))
3647 gist_access_id = Column('gist_access_id', Unicode(250))
3648 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
3648 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
3649 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
3649 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
3650 gist_expires = Column('gist_expires', Float(53), nullable=False)
3650 gist_expires = Column('gist_expires', Float(53), nullable=False)
3651 gist_type = Column('gist_type', Unicode(128), nullable=False)
3651 gist_type = Column('gist_type', Unicode(128), nullable=False)
3652 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3652 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3653 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3653 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3654 acl_level = Column('acl_level', Unicode(128), nullable=True)
3654 acl_level = Column('acl_level', Unicode(128), nullable=True)
3655
3655
3656 owner = relationship('User')
3656 owner = relationship('User')
3657
3657
3658 def __repr__(self):
3658 def __repr__(self):
3659 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
3659 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
3660
3660
3661 @classmethod
3661 @classmethod
3662 def get_or_404(cls, id_, pyramid_exc=False):
3662 def get_or_404(cls, id_, pyramid_exc=False):
3663
3663
3664 if pyramid_exc:
3664 if pyramid_exc:
3665 from pyramid.httpexceptions import HTTPNotFound
3665 from pyramid.httpexceptions import HTTPNotFound
3666 else:
3666 else:
3667 from webob.exc import HTTPNotFound
3667 from webob.exc import HTTPNotFound
3668
3668
3669 res = cls.query().filter(cls.gist_access_id == id_).scalar()
3669 res = cls.query().filter(cls.gist_access_id == id_).scalar()
3670 if not res:
3670 if not res:
3671 raise HTTPNotFound
3671 raise HTTPNotFound
3672 return res
3672 return res
3673
3673
3674 @classmethod
3674 @classmethod
3675 def get_by_access_id(cls, gist_access_id):
3675 def get_by_access_id(cls, gist_access_id):
3676 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
3676 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
3677
3677
3678 def gist_url(self):
3678 def gist_url(self):
3679 import rhodecode
3679 import rhodecode
3680 alias_url = rhodecode.CONFIG.get('gist_alias_url')
3680 alias_url = rhodecode.CONFIG.get('gist_alias_url')
3681 if alias_url:
3681 if alias_url:
3682 return alias_url.replace('{gistid}', self.gist_access_id)
3682 return alias_url.replace('{gistid}', self.gist_access_id)
3683
3683
3684 return url('gist', gist_id=self.gist_access_id, qualified=True)
3684 return url('gist', gist_id=self.gist_access_id, qualified=True)
3685
3685
3686 @classmethod
3686 @classmethod
3687 def base_path(cls):
3687 def base_path(cls):
3688 """
3688 """
3689 Returns base path when all gists are stored
3689 Returns base path when all gists are stored
3690
3690
3691 :param cls:
3691 :param cls:
3692 """
3692 """
3693 from rhodecode.model.gist import GIST_STORE_LOC
3693 from rhodecode.model.gist import GIST_STORE_LOC
3694 q = Session().query(RhodeCodeUi)\
3694 q = Session().query(RhodeCodeUi)\
3695 .filter(RhodeCodeUi.ui_key == URL_SEP)
3695 .filter(RhodeCodeUi.ui_key == URL_SEP)
3696 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
3696 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
3697 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
3697 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
3698
3698
3699 def get_api_data(self):
3699 def get_api_data(self):
3700 """
3700 """
3701 Common function for generating gist related data for API
3701 Common function for generating gist related data for API
3702 """
3702 """
3703 gist = self
3703 gist = self
3704 data = {
3704 data = {
3705 'gist_id': gist.gist_id,
3705 'gist_id': gist.gist_id,
3706 'type': gist.gist_type,
3706 'type': gist.gist_type,
3707 'access_id': gist.gist_access_id,
3707 'access_id': gist.gist_access_id,
3708 'description': gist.gist_description,
3708 'description': gist.gist_description,
3709 'url': gist.gist_url(),
3709 'url': gist.gist_url(),
3710 'expires': gist.gist_expires,
3710 'expires': gist.gist_expires,
3711 'created_on': gist.created_on,
3711 'created_on': gist.created_on,
3712 'modified_at': gist.modified_at,
3712 'modified_at': gist.modified_at,
3713 'content': None,
3713 'content': None,
3714 'acl_level': gist.acl_level,
3714 'acl_level': gist.acl_level,
3715 }
3715 }
3716 return data
3716 return data
3717
3717
3718 def __json__(self):
3718 def __json__(self):
3719 data = dict(
3719 data = dict(
3720 )
3720 )
3721 data.update(self.get_api_data())
3721 data.update(self.get_api_data())
3722 return data
3722 return data
3723 # SCM functions
3723 # SCM functions
3724
3724
3725 def scm_instance(self, **kwargs):
3725 def scm_instance(self, **kwargs):
3726 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
3726 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
3727 return get_vcs_instance(
3727 return get_vcs_instance(
3728 repo_path=safe_str(full_repo_path), create=False)
3728 repo_path=safe_str(full_repo_path), create=False)
3729
3729
3730
3730
3731 class ExternalIdentity(Base, BaseModel):
3731 class ExternalIdentity(Base, BaseModel):
3732 __tablename__ = 'external_identities'
3732 __tablename__ = 'external_identities'
3733 __table_args__ = (
3733 __table_args__ = (
3734 Index('local_user_id_idx', 'local_user_id'),
3734 Index('local_user_id_idx', 'local_user_id'),
3735 Index('external_id_idx', 'external_id'),
3735 Index('external_id_idx', 'external_id'),
3736 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3736 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3737 'mysql_charset': 'utf8'})
3737 'mysql_charset': 'utf8'})
3738
3738
3739 external_id = Column('external_id', Unicode(255), default=u'',
3739 external_id = Column('external_id', Unicode(255), default=u'',
3740 primary_key=True)
3740 primary_key=True)
3741 external_username = Column('external_username', Unicode(1024), default=u'')
3741 external_username = Column('external_username', Unicode(1024), default=u'')
3742 local_user_id = Column('local_user_id', Integer(),
3742 local_user_id = Column('local_user_id', Integer(),
3743 ForeignKey('users.user_id'), primary_key=True)
3743 ForeignKey('users.user_id'), primary_key=True)
3744 provider_name = Column('provider_name', Unicode(255), default=u'',
3744 provider_name = Column('provider_name', Unicode(255), default=u'',
3745 primary_key=True)
3745 primary_key=True)
3746 access_token = Column('access_token', String(1024), default=u'')
3746 access_token = Column('access_token', String(1024), default=u'')
3747 alt_token = Column('alt_token', String(1024), default=u'')
3747 alt_token = Column('alt_token', String(1024), default=u'')
3748 token_secret = Column('token_secret', String(1024), default=u'')
3748 token_secret = Column('token_secret', String(1024), default=u'')
3749
3749
3750 @classmethod
3750 @classmethod
3751 def by_external_id_and_provider(cls, external_id, provider_name,
3751 def by_external_id_and_provider(cls, external_id, provider_name,
3752 local_user_id=None):
3752 local_user_id=None):
3753 """
3753 """
3754 Returns ExternalIdentity instance based on search params
3754 Returns ExternalIdentity instance based on search params
3755
3755
3756 :param external_id:
3756 :param external_id:
3757 :param provider_name:
3757 :param provider_name:
3758 :return: ExternalIdentity
3758 :return: ExternalIdentity
3759 """
3759 """
3760 query = cls.query()
3760 query = cls.query()
3761 query = query.filter(cls.external_id == external_id)
3761 query = query.filter(cls.external_id == external_id)
3762 query = query.filter(cls.provider_name == provider_name)
3762 query = query.filter(cls.provider_name == provider_name)
3763 if local_user_id:
3763 if local_user_id:
3764 query = query.filter(cls.local_user_id == local_user_id)
3764 query = query.filter(cls.local_user_id == local_user_id)
3765 return query.first()
3765 return query.first()
3766
3766
3767 @classmethod
3767 @classmethod
3768 def user_by_external_id_and_provider(cls, external_id, provider_name):
3768 def user_by_external_id_and_provider(cls, external_id, provider_name):
3769 """
3769 """
3770 Returns User instance based on search params
3770 Returns User instance based on search params
3771
3771
3772 :param external_id:
3772 :param external_id:
3773 :param provider_name:
3773 :param provider_name:
3774 :return: User
3774 :return: User
3775 """
3775 """
3776 query = User.query()
3776 query = User.query()
3777 query = query.filter(cls.external_id == external_id)
3777 query = query.filter(cls.external_id == external_id)
3778 query = query.filter(cls.provider_name == provider_name)
3778 query = query.filter(cls.provider_name == provider_name)
3779 query = query.filter(User.user_id == cls.local_user_id)
3779 query = query.filter(User.user_id == cls.local_user_id)
3780 return query.first()
3780 return query.first()
3781
3781
3782 @classmethod
3782 @classmethod
3783 def by_local_user_id(cls, local_user_id):
3783 def by_local_user_id(cls, local_user_id):
3784 """
3784 """
3785 Returns all tokens for user
3785 Returns all tokens for user
3786
3786
3787 :param local_user_id:
3787 :param local_user_id:
3788 :return: ExternalIdentity
3788 :return: ExternalIdentity
3789 """
3789 """
3790 query = cls.query()
3790 query = cls.query()
3791 query = query.filter(cls.local_user_id == local_user_id)
3791 query = query.filter(cls.local_user_id == local_user_id)
3792 return query
3792 return query
3793
3793
3794
3794
3795 class Integration(Base, BaseModel):
3795 class Integration(Base, BaseModel):
3796 __tablename__ = 'integrations'
3796 __tablename__ = 'integrations'
3797 __table_args__ = (
3797 __table_args__ = (
3798 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3798 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3799 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3799 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3800 )
3800 )
3801
3801
3802 integration_id = Column('integration_id', Integer(), primary_key=True)
3802 integration_id = Column('integration_id', Integer(), primary_key=True)
3803 integration_type = Column('integration_type', String(255))
3803 integration_type = Column('integration_type', String(255))
3804 enabled = Column('enabled', Boolean(), nullable=False)
3804 enabled = Column('enabled', Boolean(), nullable=False)
3805 name = Column('name', String(255), nullable=False)
3805 name = Column('name', String(255), nullable=False)
3806 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
3806 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
3807 default=False)
3807 default=False)
3808
3808
3809 settings = Column(
3809 settings = Column(
3810 'settings_json', MutationObj.as_mutable(
3810 'settings_json', MutationObj.as_mutable(
3811 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3811 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3812 repo_id = Column(
3812 repo_id = Column(
3813 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
3813 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
3814 nullable=True, unique=None, default=None)
3814 nullable=True, unique=None, default=None)
3815 repo = relationship('Repository', lazy='joined')
3815 repo = relationship('Repository', lazy='joined')
3816
3816
3817 repo_group_id = Column(
3817 repo_group_id = Column(
3818 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
3818 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
3819 nullable=True, unique=None, default=None)
3819 nullable=True, unique=None, default=None)
3820 repo_group = relationship('RepoGroup', lazy='joined')
3820 repo_group = relationship('RepoGroup', lazy='joined')
3821
3821
3822 @property
3822 @property
3823 def scope(self):
3823 def scope(self):
3824 if self.repo:
3824 if self.repo:
3825 return repr(self.repo)
3825 return repr(self.repo)
3826 if self.repo_group:
3826 if self.repo_group:
3827 if self.child_repos_only:
3827 if self.child_repos_only:
3828 return repr(self.repo_group) + ' (child repos only)'
3828 return repr(self.repo_group) + ' (child repos only)'
3829 else:
3829 else:
3830 return repr(self.repo_group) + ' (recursive)'
3830 return repr(self.repo_group) + ' (recursive)'
3831 if self.child_repos_only:
3831 if self.child_repos_only:
3832 return 'root_repos'
3832 return 'root_repos'
3833 return 'global'
3833 return 'global'
3834
3834
3835 def __repr__(self):
3835 def __repr__(self):
3836 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
3836 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
3837
3837
3838
3838
3839 class RepoReviewRuleUser(Base, BaseModel):
3839 class RepoReviewRuleUser(Base, BaseModel):
3840 __tablename__ = 'repo_review_rules_users'
3840 __tablename__ = 'repo_review_rules_users'
3841 __table_args__ = (
3841 __table_args__ = (
3842 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3842 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3843 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3843 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3844 )
3844 )
3845 repo_review_rule_user_id = Column(
3845 repo_review_rule_user_id = Column(
3846 'repo_review_rule_user_id', Integer(), primary_key=True)
3846 'repo_review_rule_user_id', Integer(), primary_key=True)
3847 repo_review_rule_id = Column("repo_review_rule_id",
3847 repo_review_rule_id = Column("repo_review_rule_id",
3848 Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
3848 Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
3849 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'),
3849 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'),
3850 nullable=False)
3850 nullable=False)
3851 user = relationship('User')
3851 user = relationship('User')
3852
3852
3853
3853
3854 class RepoReviewRuleUserGroup(Base, BaseModel):
3854 class RepoReviewRuleUserGroup(Base, BaseModel):
3855 __tablename__ = 'repo_review_rules_users_groups'
3855 __tablename__ = 'repo_review_rules_users_groups'
3856 __table_args__ = (
3856 __table_args__ = (
3857 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3857 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3858 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3858 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3859 )
3859 )
3860 repo_review_rule_users_group_id = Column(
3860 repo_review_rule_users_group_id = Column(
3861 'repo_review_rule_users_group_id', Integer(), primary_key=True)
3861 'repo_review_rule_users_group_id', Integer(), primary_key=True)
3862 repo_review_rule_id = Column("repo_review_rule_id",
3862 repo_review_rule_id = Column("repo_review_rule_id",
3863 Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
3863 Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
3864 users_group_id = Column("users_group_id", Integer(),
3864 users_group_id = Column("users_group_id", Integer(),
3865 ForeignKey('users_groups.users_group_id'), nullable=False)
3865 ForeignKey('users_groups.users_group_id'), nullable=False)
3866 users_group = relationship('UserGroup')
3866 users_group = relationship('UserGroup')
3867
3867
3868
3868
3869 class RepoReviewRule(Base, BaseModel):
3869 class RepoReviewRule(Base, BaseModel):
3870 __tablename__ = 'repo_review_rules'
3870 __tablename__ = 'repo_review_rules'
3871 __table_args__ = (
3871 __table_args__ = (
3872 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3872 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3873 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3873 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3874 )
3874 )
3875
3875
3876 repo_review_rule_id = Column(
3876 repo_review_rule_id = Column(
3877 'repo_review_rule_id', Integer(), primary_key=True)
3877 'repo_review_rule_id', Integer(), primary_key=True)
3878 repo_id = Column(
3878 repo_id = Column(
3879 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
3879 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
3880 repo = relationship('Repository', backref='review_rules')
3880 repo = relationship('Repository', backref='review_rules')
3881
3881
3882 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'),
3882 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'),
3883 default=u'*') # glob
3883 default=u'*') # glob
3884 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'),
3884 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'),
3885 default=u'*') # glob
3885 default=u'*') # glob
3886
3886
3887 use_authors_for_review = Column("use_authors_for_review", Boolean(),
3887 use_authors_for_review = Column("use_authors_for_review", Boolean(),
3888 nullable=False, default=False)
3888 nullable=False, default=False)
3889 rule_users = relationship('RepoReviewRuleUser')
3889 rule_users = relationship('RepoReviewRuleUser')
3890 rule_user_groups = relationship('RepoReviewRuleUserGroup')
3890 rule_user_groups = relationship('RepoReviewRuleUserGroup')
3891
3891
3892 @hybrid_property
3892 @hybrid_property
3893 def branch_pattern(self):
3893 def branch_pattern(self):
3894 return self._branch_pattern or '*'
3894 return self._branch_pattern or '*'
3895
3895
3896 def _validate_glob(self, value):
3896 def _validate_glob(self, value):
3897 re.compile('^' + glob2re(value) + '$')
3897 re.compile('^' + glob2re(value) + '$')
3898
3898
3899 @branch_pattern.setter
3899 @branch_pattern.setter
3900 def branch_pattern(self, value):
3900 def branch_pattern(self, value):
3901 self._validate_glob(value)
3901 self._validate_glob(value)
3902 self._branch_pattern = value or '*'
3902 self._branch_pattern = value or '*'
3903
3903
3904 @hybrid_property
3904 @hybrid_property
3905 def file_pattern(self):
3905 def file_pattern(self):
3906 return self._file_pattern or '*'
3906 return self._file_pattern or '*'
3907
3907
3908 @file_pattern.setter
3908 @file_pattern.setter
3909 def file_pattern(self, value):
3909 def file_pattern(self, value):
3910 self._validate_glob(value)
3910 self._validate_glob(value)
3911 self._file_pattern = value or '*'
3911 self._file_pattern = value or '*'
3912
3912
3913 def matches(self, branch, files_changed):
3913 def matches(self, branch, files_changed):
3914 """
3914 """
3915 Check if this review rule matches a branch/files in a pull request
3915 Check if this review rule matches a branch/files in a pull request
3916
3916
3917 :param branch: branch name for the commit
3917 :param branch: branch name for the commit
3918 :param files_changed: list of file paths changed in the pull request
3918 :param files_changed: list of file paths changed in the pull request
3919 """
3919 """
3920
3920
3921 branch = branch or ''
3921 branch = branch or ''
3922 files_changed = files_changed or []
3922 files_changed = files_changed or []
3923
3923
3924 branch_matches = True
3924 branch_matches = True
3925 if branch:
3925 if branch:
3926 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
3926 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
3927 branch_matches = bool(branch_regex.search(branch))
3927 branch_matches = bool(branch_regex.search(branch))
3928
3928
3929 files_matches = True
3929 files_matches = True
3930 if self.file_pattern != '*':
3930 if self.file_pattern != '*':
3931 files_matches = False
3931 files_matches = False
3932 file_regex = re.compile(glob2re(self.file_pattern))
3932 file_regex = re.compile(glob2re(self.file_pattern))
3933 for filename in files_changed:
3933 for filename in files_changed:
3934 if file_regex.search(filename):
3934 if file_regex.search(filename):
3935 files_matches = True
3935 files_matches = True
3936 break
3936 break
3937
3937
3938 return branch_matches and files_matches
3938 return branch_matches and files_matches
3939
3939
3940 @property
3940 @property
3941 def review_users(self):
3941 def review_users(self):
3942 """ Returns the users which this rule applies to """
3942 """ Returns the users which this rule applies to """
3943
3943
3944 users = set()
3944 users = set()
3945 users |= set([
3945 users |= set([
3946 rule_user.user for rule_user in self.rule_users
3946 rule_user.user for rule_user in self.rule_users
3947 if rule_user.user.active])
3947 if rule_user.user.active])
3948 users |= set(
3948 users |= set(
3949 member.user
3949 member.user
3950 for rule_user_group in self.rule_user_groups
3950 for rule_user_group in self.rule_user_groups
3951 for member in rule_user_group.users_group.members
3951 for member in rule_user_group.users_group.members
3952 if member.user.active
3952 if member.user.active
3953 )
3953 )
3954 return users
3954 return users
3955
3955
3956 def __repr__(self):
3956 def __repr__(self):
3957 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
3957 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
3958 self.repo_review_rule_id, self.repo)
3958 self.repo_review_rule_id, self.repo)
3959
3959
3960
3960
3961 class DbMigrateVersion(Base, BaseModel):
3961 class DbMigrateVersion(Base, BaseModel):
3962 __tablename__ = 'db_migrate_version'
3962 __tablename__ = 'db_migrate_version'
3963 __table_args__ = (
3963 __table_args__ = (
3964 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3964 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3965 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3965 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3966 )
3966 )
3967 repository_id = Column('repository_id', String(250), primary_key=True)
3967 repository_id = Column('repository_id', String(250), primary_key=True)
3968 repository_path = Column('repository_path', Text)
3968 repository_path = Column('repository_path', Text)
3969 version = Column('version', Integer)
3969 version = Column('version', Integer)
3970
3970
3971
3971
3972 class DbSession(Base, BaseModel):
3972 class DbSession(Base, BaseModel):
3973 __tablename__ = 'db_session'
3973 __tablename__ = 'db_session'
3974 __table_args__ = (
3974 __table_args__ = (
3975 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3975 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3976 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3976 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3977 )
3977 )
3978
3978
3979 def __repr__(self):
3979 def __repr__(self):
3980 return '<DB:DbSession({})>'.format(self.id)
3980 return '<DB:DbSession({})>'.format(self.id)
3981
3981
3982 id = Column('id', Integer())
3982 id = Column('id', Integer())
3983 namespace = Column('namespace', String(255), primary_key=True)
3983 namespace = Column('namespace', String(255), primary_key=True)
3984 accessed = Column('accessed', DateTime, nullable=False)
3984 accessed = Column('accessed', DateTime, nullable=False)
3985 created = Column('created', DateTime, nullable=False)
3985 created = Column('created', DateTime, nullable=False)
3986 data = Column('data', PickleType, nullable=False)
3986 data = Column('data', PickleType, nullable=False)
@@ -1,213 +1,213 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2011-2017 RhodeCode GmbH
3 # Copyright (C) 2011-2017 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21
21
22 """
22 """
23 Model for integrations
23 Model for integrations
24 """
24 """
25
25
26
26
27 import logging
27 import logging
28
28
29 from sqlalchemy import or_, and_
29 from sqlalchemy import or_, and_
30
30
31 import rhodecode
31 import rhodecode
32 from rhodecode import events
32 from rhodecode import events
33 from rhodecode.lib.caching_query import FromCache
33 from rhodecode.lib.caching_query import FromCache
34 from rhodecode.model import BaseModel
34 from rhodecode.model import BaseModel
35 from rhodecode.model.db import Integration, Repository, RepoGroup
35 from rhodecode.model.db import Integration, Repository, RepoGroup
36 from rhodecode.integrations import integration_type_registry
36 from rhodecode.integrations import integration_type_registry
37
37
38 log = logging.getLogger(__name__)
38 log = logging.getLogger(__name__)
39
39
40
40
41 class IntegrationModel(BaseModel):
41 class IntegrationModel(BaseModel):
42
42
43 cls = Integration
43 cls = Integration
44
44
45 def __get_integration(self, integration):
45 def __get_integration(self, integration):
46 if isinstance(integration, Integration):
46 if isinstance(integration, Integration):
47 return integration
47 return integration
48 elif isinstance(integration, (int, long)):
48 elif isinstance(integration, (int, long)):
49 return self.sa.query(Integration).get(integration)
49 return self.sa.query(Integration).get(integration)
50 else:
50 else:
51 if integration:
51 if integration:
52 raise Exception('integration must be int, long or Instance'
52 raise Exception('integration must be int, long or Instance'
53 ' of Integration got %s' % type(integration))
53 ' of Integration got %s' % type(integration))
54
54
55 def create(self, IntegrationType, name, enabled, repo, repo_group,
55 def create(self, IntegrationType, name, enabled, repo, repo_group,
56 child_repos_only, settings):
56 child_repos_only, settings):
57 """ Create an IntegrationType integration """
57 """ Create an IntegrationType integration """
58 integration = Integration()
58 integration = Integration()
59 integration.integration_type = IntegrationType.key
59 integration.integration_type = IntegrationType.key
60 self.sa.add(integration)
60 self.sa.add(integration)
61 self.update_integration(integration, name, enabled, repo, repo_group,
61 self.update_integration(integration, name, enabled, repo, repo_group,
62 child_repos_only, settings)
62 child_repos_only, settings)
63 self.sa.commit()
63 self.sa.commit()
64 return integration
64 return integration
65
65
66 def update_integration(self, integration, name, enabled, repo, repo_group,
66 def update_integration(self, integration, name, enabled, repo, repo_group,
67 child_repos_only, settings):
67 child_repos_only, settings):
68 integration = self.__get_integration(integration)
68 integration = self.__get_integration(integration)
69
69
70 integration.repo = repo
70 integration.repo = repo
71 integration.repo_group = repo_group
71 integration.repo_group = repo_group
72 integration.child_repos_only = child_repos_only
72 integration.child_repos_only = child_repos_only
73 integration.name = name
73 integration.name = name
74 integration.enabled = enabled
74 integration.enabled = enabled
75 integration.settings = settings
75 integration.settings = settings
76
76
77 return integration
77 return integration
78
78
79 def delete(self, integration):
79 def delete(self, integration):
80 integration = self.__get_integration(integration)
80 integration = self.__get_integration(integration)
81 if integration:
81 if integration:
82 self.sa.delete(integration)
82 self.sa.delete(integration)
83 return True
83 return True
84 return False
84 return False
85
85
86 def get_integration_handler(self, integration):
86 def get_integration_handler(self, integration):
87 TypeClass = integration_type_registry.get(integration.integration_type)
87 TypeClass = integration_type_registry.get(integration.integration_type)
88 if not TypeClass:
88 if not TypeClass:
89 log.error('No class could be found for integration type: {}'.format(
89 log.error('No class could be found for integration type: {}'.format(
90 integration.integration_type))
90 integration.integration_type))
91 return None
91 return None
92
92
93 return TypeClass(integration.settings)
93 return TypeClass(integration.settings)
94
94
95 def send_event(self, integration, event):
95 def send_event(self, integration, event):
96 """ Send an event to an integration """
96 """ Send an event to an integration """
97 handler = self.get_integration_handler(integration)
97 handler = self.get_integration_handler(integration)
98 if handler:
98 if handler:
99 handler.send_event(event)
99 handler.send_event(event)
100
100
101 def get_integrations(self, scope, IntegrationType=None):
101 def get_integrations(self, scope, IntegrationType=None):
102 """
102 """
103 Return integrations for a scope, which must be one of:
103 Return integrations for a scope, which must be one of:
104
104
105 'all' - every integration, global/repogroup/repo
105 'all' - every integration, global/repogroup/repo
106 'global' - global integrations only
106 'global' - global integrations only
107 <Repository> instance - integrations for this repo only
107 <Repository> instance - integrations for this repo only
108 <RepoGroup> instance - integrations for this repogroup only
108 <RepoGroup> instance - integrations for this repogroup only
109 """
109 """
110
110
111 if isinstance(scope, Repository):
111 if isinstance(scope, Repository):
112 query = self.sa.query(Integration).filter(
112 query = self.sa.query(Integration).filter(
113 Integration.repo==scope)
113 Integration.repo==scope)
114 elif isinstance(scope, RepoGroup):
114 elif isinstance(scope, RepoGroup):
115 query = self.sa.query(Integration).filter(
115 query = self.sa.query(Integration).filter(
116 Integration.repo_group==scope)
116 Integration.repo_group==scope)
117 elif scope == 'global':
117 elif scope == 'global':
118 # global integrations
118 # global integrations
119 query = self.sa.query(Integration).filter(
119 query = self.sa.query(Integration).filter(
120 and_(Integration.repo_id==None, Integration.repo_group_id==None)
120 and_(Integration.repo_id==None, Integration.repo_group_id==None)
121 )
121 )
122 elif scope == 'root-repos':
122 elif scope == 'root-repos':
123 query = self.sa.query(Integration).filter(
123 query = self.sa.query(Integration).filter(
124 and_(Integration.repo_id==None,
124 and_(Integration.repo_id==None,
125 Integration.repo_group_id==None,
125 Integration.repo_group_id==None,
126 Integration.child_repos_only==True)
126 Integration.child_repos_only==True)
127 )
127 )
128 elif scope == 'all':
128 elif scope == 'all':
129 query = self.sa.query(Integration)
129 query = self.sa.query(Integration)
130 else:
130 else:
131 raise Exception(
131 raise Exception(
132 "invalid `scope`, must be one of: "
132 "invalid `scope`, must be one of: "
133 "['global', 'all', <Repository>, <RepoGroup>]")
133 "['global', 'all', <Repository>, <RepoGroup>]")
134
134
135 if IntegrationType is not None:
135 if IntegrationType is not None:
136 query = query.filter(
136 query = query.filter(
137 Integration.integration_type==IntegrationType.key)
137 Integration.integration_type==IntegrationType.key)
138
138
139 result = []
139 result = []
140 for integration in query.all():
140 for integration in query.all():
141 IntType = integration_type_registry.get(integration.integration_type)
141 IntType = integration_type_registry.get(integration.integration_type)
142 result.append((IntType, integration))
142 result.append((IntType, integration))
143 return result
143 return result
144
144
145 def get_for_event(self, event, cache=False):
145 def get_for_event(self, event, cache=False):
146 """
146 """
147 Get integrations that match an event
147 Get integrations that match an event
148 """
148 """
149 query = self.sa.query(
149 query = self.sa.query(
150 Integration
150 Integration
151 ).filter(
151 ).filter(
152 Integration.enabled==True
152 Integration.enabled==True
153 )
153 )
154
154
155 global_integrations_filter = and_(
155 global_integrations_filter = and_(
156 Integration.repo_id==None,
156 Integration.repo_id==None,
157 Integration.repo_group_id==None,
157 Integration.repo_group_id==None,
158 Integration.child_repos_only==False,
158 Integration.child_repos_only==False,
159 )
159 )
160
160
161 if isinstance(event, events.RepoEvent):
161 if isinstance(event, events.RepoEvent):
162 root_repos_integrations_filter = and_(
162 root_repos_integrations_filter = and_(
163 Integration.repo_id==None,
163 Integration.repo_id==None,
164 Integration.repo_group_id==None,
164 Integration.repo_group_id==None,
165 Integration.child_repos_only==True,
165 Integration.child_repos_only==True,
166 )
166 )
167
167
168 clauses = [
168 clauses = [
169 global_integrations_filter,
169 global_integrations_filter,
170 ]
170 ]
171
171
172 # repo integrations
172 # repo integrations
173 if event.repo.repo_id: # pre create events dont have a repo_id yet
173 if event.repo.repo_id: # pre create events dont have a repo_id yet
174 clauses.append(
174 clauses.append(
175 Integration.repo_id==event.repo.repo_id
175 Integration.repo_id==event.repo.repo_id
176 )
176 )
177
177
178 if event.repo.group:
178 if event.repo.group:
179 clauses.append(
179 clauses.append(
180 and_(
180 and_(
181 Integration.repo_group_id==event.repo.group.group_id,
181 Integration.repo_group_id==event.repo.group.group_id,
182 Integration.child_repos_only==True
182 Integration.child_repos_only==True
183 )
183 )
184 )
184 )
185 # repo group cascade to kids
185 # repo group cascade to kids
186 clauses.append(
186 clauses.append(
187 and_(
187 and_(
188 Integration.repo_group_id.in_(
188 Integration.repo_group_id.in_(
189 [group.group_id for group in
189 [group.group_id for group in
190 event.repo.groups_with_parents]
190 event.repo.groups_with_parents]
191 ),
191 ),
192 Integration.child_repos_only==False
192 Integration.child_repos_only==False
193 )
193 )
194 )
194 )
195
195
196
196
197 if not event.repo.group: # root repo
197 if not event.repo.group: # root repo
198 clauses.append(root_repos_integrations_filter)
198 clauses.append(root_repos_integrations_filter)
199
199
200 query = query.filter(or_(*clauses))
200 query = query.filter(or_(*clauses))
201
201
202 if cache:
202 if cache:
203 query = query.options(FromCache(
203 cache_key = "get_enabled_repo_integrations_%i" % event.repo.repo_id
204 "sql_cache_short",
204 query = query.options(
205 "get_enabled_repo_integrations_%i" % event.repo.repo_id))
205 FromCache("sql_cache_short", cache_key))
206 else: # only global integrations
206 else: # only global integrations
207 query = query.filter(global_integrations_filter)
207 query = query.filter(global_integrations_filter)
208 if cache:
208 if cache:
209 query = query.options(FromCache(
209 query = query.options(
210 "sql_cache_short", "get_enabled_global_integrations"))
210 FromCache("sql_cache_short", "get_enabled_global_integrations"))
211
211
212 result = query.all()
212 result = query.all()
213 return result No newline at end of file
213 return result
@@ -1,999 +1,1000 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 Repository model for rhodecode
22 Repository model for rhodecode
23 """
23 """
24
24
25 import logging
25 import logging
26 import os
26 import os
27 import re
27 import re
28 import shutil
28 import shutil
29 import time
29 import time
30 import traceback
30 import traceback
31 from datetime import datetime, timedelta
31 from datetime import datetime, timedelta
32
32
33 from zope.cachedescriptors.property import Lazy as LazyProperty
33 from zope.cachedescriptors.property import Lazy as LazyProperty
34
34
35 from rhodecode import events
35 from rhodecode import events
36 from rhodecode.lib import helpers as h
36 from rhodecode.lib import helpers as h
37 from rhodecode.lib.auth import HasUserGroupPermissionAny
37 from rhodecode.lib.auth import HasUserGroupPermissionAny
38 from rhodecode.lib.caching_query import FromCache
38 from rhodecode.lib.caching_query import FromCache
39 from rhodecode.lib.exceptions import AttachedForksError
39 from rhodecode.lib.exceptions import AttachedForksError
40 from rhodecode.lib.hooks_base import log_delete_repository
40 from rhodecode.lib.hooks_base import log_delete_repository
41 from rhodecode.lib.utils import make_db_config
41 from rhodecode.lib.utils import make_db_config
42 from rhodecode.lib.utils2 import (
42 from rhodecode.lib.utils2 import (
43 safe_str, safe_unicode, remove_prefix, obfuscate_url_pw,
43 safe_str, safe_unicode, remove_prefix, obfuscate_url_pw,
44 get_current_rhodecode_user, safe_int, datetime_to_time, action_logger_generic)
44 get_current_rhodecode_user, safe_int, datetime_to_time, action_logger_generic)
45 from rhodecode.lib.vcs.backends import get_backend
45 from rhodecode.lib.vcs.backends import get_backend
46 from rhodecode.model import BaseModel
46 from rhodecode.model import BaseModel
47 from rhodecode.model.db import (
47 from rhodecode.model.db import (_hash_key,
48 Repository, UserRepoToPerm, UserGroupRepoToPerm, UserRepoGroupToPerm,
48 Repository, UserRepoToPerm, UserGroupRepoToPerm, UserRepoGroupToPerm,
49 UserGroupRepoGroupToPerm, User, Permission, Statistics, UserGroup,
49 UserGroupRepoGroupToPerm, User, Permission, Statistics, UserGroup,
50 RepoGroup, RepositoryField)
50 RepoGroup, RepositoryField)
51
51
52 from rhodecode.model.settings import VcsSettingsModel
52 from rhodecode.model.settings import VcsSettingsModel
53
53
54
54
55 log = logging.getLogger(__name__)
55 log = logging.getLogger(__name__)
56
56
57
57
58 class RepoModel(BaseModel):
58 class RepoModel(BaseModel):
59
59
60 cls = Repository
60 cls = Repository
61
61
62 def _get_user_group(self, users_group):
62 def _get_user_group(self, users_group):
63 return self._get_instance(UserGroup, users_group,
63 return self._get_instance(UserGroup, users_group,
64 callback=UserGroup.get_by_group_name)
64 callback=UserGroup.get_by_group_name)
65
65
66 def _get_repo_group(self, repo_group):
66 def _get_repo_group(self, repo_group):
67 return self._get_instance(RepoGroup, repo_group,
67 return self._get_instance(RepoGroup, repo_group,
68 callback=RepoGroup.get_by_group_name)
68 callback=RepoGroup.get_by_group_name)
69
69
70 def _create_default_perms(self, repository, private):
70 def _create_default_perms(self, repository, private):
71 # create default permission
71 # create default permission
72 default = 'repository.read'
72 default = 'repository.read'
73 def_user = User.get_default_user()
73 def_user = User.get_default_user()
74 for p in def_user.user_perms:
74 for p in def_user.user_perms:
75 if p.permission.permission_name.startswith('repository.'):
75 if p.permission.permission_name.startswith('repository.'):
76 default = p.permission.permission_name
76 default = p.permission.permission_name
77 break
77 break
78
78
79 default_perm = 'repository.none' if private else default
79 default_perm = 'repository.none' if private else default
80
80
81 repo_to_perm = UserRepoToPerm()
81 repo_to_perm = UserRepoToPerm()
82 repo_to_perm.permission = Permission.get_by_key(default_perm)
82 repo_to_perm.permission = Permission.get_by_key(default_perm)
83
83
84 repo_to_perm.repository = repository
84 repo_to_perm.repository = repository
85 repo_to_perm.user_id = def_user.user_id
85 repo_to_perm.user_id = def_user.user_id
86
86
87 return repo_to_perm
87 return repo_to_perm
88
88
89 @LazyProperty
89 @LazyProperty
90 def repos_path(self):
90 def repos_path(self):
91 """
91 """
92 Gets the repositories root path from database
92 Gets the repositories root path from database
93 """
93 """
94 settings_model = VcsSettingsModel(sa=self.sa)
94 settings_model = VcsSettingsModel(sa=self.sa)
95 return settings_model.get_repos_location()
95 return settings_model.get_repos_location()
96
96
97 def get(self, repo_id, cache=False):
97 def get(self, repo_id, cache=False):
98 repo = self.sa.query(Repository) \
98 repo = self.sa.query(Repository) \
99 .filter(Repository.repo_id == repo_id)
99 .filter(Repository.repo_id == repo_id)
100
100
101 if cache:
101 if cache:
102 repo = repo.options(FromCache("sql_cache_short",
102 repo = repo.options(
103 "get_repo_%s" % repo_id))
103 FromCache("sql_cache_short", "get_repo_%s" % repo_id))
104 return repo.scalar()
104 return repo.scalar()
105
105
106 def get_repo(self, repository):
106 def get_repo(self, repository):
107 return self._get_repo(repository)
107 return self._get_repo(repository)
108
108
109 def get_by_repo_name(self, repo_name, cache=False):
109 def get_by_repo_name(self, repo_name, cache=False):
110 repo = self.sa.query(Repository) \
110 repo = self.sa.query(Repository) \
111 .filter(Repository.repo_name == repo_name)
111 .filter(Repository.repo_name == repo_name)
112
112
113 if cache:
113 if cache:
114 repo = repo.options(FromCache("sql_cache_short",
114 name_key = _hash_key(repo_name)
115 "get_repo_%s" % repo_name))
115 repo = repo.options(
116 FromCache("sql_cache_short", "get_repo_%s" % name_key))
116 return repo.scalar()
117 return repo.scalar()
117
118
118 def _extract_id_from_repo_name(self, repo_name):
119 def _extract_id_from_repo_name(self, repo_name):
119 if repo_name.startswith('/'):
120 if repo_name.startswith('/'):
120 repo_name = repo_name.lstrip('/')
121 repo_name = repo_name.lstrip('/')
121 by_id_match = re.match(r'^_(\d{1,})', repo_name)
122 by_id_match = re.match(r'^_(\d{1,})', repo_name)
122 if by_id_match:
123 if by_id_match:
123 return by_id_match.groups()[0]
124 return by_id_match.groups()[0]
124
125
125 def get_repo_by_id(self, repo_name):
126 def get_repo_by_id(self, repo_name):
126 """
127 """
127 Extracts repo_name by id from special urls.
128 Extracts repo_name by id from special urls.
128 Example url is _11/repo_name
129 Example url is _11/repo_name
129
130
130 :param repo_name:
131 :param repo_name:
131 :return: repo object if matched else None
132 :return: repo object if matched else None
132 """
133 """
133 try:
134 try:
134 _repo_id = self._extract_id_from_repo_name(repo_name)
135 _repo_id = self._extract_id_from_repo_name(repo_name)
135 if _repo_id:
136 if _repo_id:
136 return self.get(_repo_id)
137 return self.get(_repo_id)
137 except Exception:
138 except Exception:
138 log.exception('Failed to extract repo_name from URL')
139 log.exception('Failed to extract repo_name from URL')
139
140
140 return None
141 return None
141
142
142 def get_repos_for_root(self, root, traverse=False):
143 def get_repos_for_root(self, root, traverse=False):
143 if traverse:
144 if traverse:
144 like_expression = u'{}%'.format(safe_unicode(root))
145 like_expression = u'{}%'.format(safe_unicode(root))
145 repos = Repository.query().filter(
146 repos = Repository.query().filter(
146 Repository.repo_name.like(like_expression)).all()
147 Repository.repo_name.like(like_expression)).all()
147 else:
148 else:
148 if root and not isinstance(root, RepoGroup):
149 if root and not isinstance(root, RepoGroup):
149 raise ValueError(
150 raise ValueError(
150 'Root must be an instance '
151 'Root must be an instance '
151 'of RepoGroup, got:{} instead'.format(type(root)))
152 'of RepoGroup, got:{} instead'.format(type(root)))
152 repos = Repository.query().filter(Repository.group == root).all()
153 repos = Repository.query().filter(Repository.group == root).all()
153 return repos
154 return repos
154
155
155 def get_url(self, repo):
156 def get_url(self, repo):
156 return h.url('summary_home', repo_name=safe_str(repo.repo_name),
157 return h.url('summary_home', repo_name=safe_str(repo.repo_name),
157 qualified=True)
158 qualified=True)
158
159
159 @classmethod
160 @classmethod
160 def update_repoinfo(cls, repositories=None):
161 def update_repoinfo(cls, repositories=None):
161 if not repositories:
162 if not repositories:
162 repositories = Repository.getAll()
163 repositories = Repository.getAll()
163 for repo in repositories:
164 for repo in repositories:
164 repo.update_commit_cache()
165 repo.update_commit_cache()
165
166
166 def get_repos_as_dict(self, repo_list=None, admin=False,
167 def get_repos_as_dict(self, repo_list=None, admin=False,
167 super_user_actions=False):
168 super_user_actions=False):
168
169
169 from rhodecode.lib.utils import PartialRenderer
170 from rhodecode.lib.utils import PartialRenderer
170 _render = PartialRenderer('data_table/_dt_elements.mako')
171 _render = PartialRenderer('data_table/_dt_elements.mako')
171 c = _render.c
172 c = _render.c
172
173
173 def quick_menu(repo_name):
174 def quick_menu(repo_name):
174 return _render('quick_menu', repo_name)
175 return _render('quick_menu', repo_name)
175
176
176 def repo_lnk(name, rtype, rstate, private, fork_of):
177 def repo_lnk(name, rtype, rstate, private, fork_of):
177 return _render('repo_name', name, rtype, rstate, private, fork_of,
178 return _render('repo_name', name, rtype, rstate, private, fork_of,
178 short_name=not admin, admin=False)
179 short_name=not admin, admin=False)
179
180
180 def last_change(last_change):
181 def last_change(last_change):
181 if admin and isinstance(last_change, datetime) and not last_change.tzinfo:
182 if admin and isinstance(last_change, datetime) and not last_change.tzinfo:
182 last_change = last_change + timedelta(seconds=
183 last_change = last_change + timedelta(seconds=
183 (datetime.now() - datetime.utcnow()).seconds)
184 (datetime.now() - datetime.utcnow()).seconds)
184 return _render("last_change", last_change)
185 return _render("last_change", last_change)
185
186
186 def rss_lnk(repo_name):
187 def rss_lnk(repo_name):
187 return _render("rss", repo_name)
188 return _render("rss", repo_name)
188
189
189 def atom_lnk(repo_name):
190 def atom_lnk(repo_name):
190 return _render("atom", repo_name)
191 return _render("atom", repo_name)
191
192
192 def last_rev(repo_name, cs_cache):
193 def last_rev(repo_name, cs_cache):
193 return _render('revision', repo_name, cs_cache.get('revision'),
194 return _render('revision', repo_name, cs_cache.get('revision'),
194 cs_cache.get('raw_id'), cs_cache.get('author'),
195 cs_cache.get('raw_id'), cs_cache.get('author'),
195 cs_cache.get('message'))
196 cs_cache.get('message'))
196
197
197 def desc(desc):
198 def desc(desc):
198 if c.visual.stylify_metatags:
199 if c.visual.stylify_metatags:
199 desc = h.urlify_text(h.escaped_stylize(desc))
200 desc = h.urlify_text(h.escaped_stylize(desc))
200 else:
201 else:
201 desc = h.urlify_text(h.html_escape(desc))
202 desc = h.urlify_text(h.html_escape(desc))
202
203
203 return _render('repo_desc', desc)
204 return _render('repo_desc', desc)
204
205
205 def state(repo_state):
206 def state(repo_state):
206 return _render("repo_state", repo_state)
207 return _render("repo_state", repo_state)
207
208
208 def repo_actions(repo_name):
209 def repo_actions(repo_name):
209 return _render('repo_actions', repo_name, super_user_actions)
210 return _render('repo_actions', repo_name, super_user_actions)
210
211
211 def user_profile(username):
212 def user_profile(username):
212 return _render('user_profile', username)
213 return _render('user_profile', username)
213
214
214 repos_data = []
215 repos_data = []
215 for repo in repo_list:
216 for repo in repo_list:
216 cs_cache = repo.changeset_cache
217 cs_cache = repo.changeset_cache
217 row = {
218 row = {
218 "menu": quick_menu(repo.repo_name),
219 "menu": quick_menu(repo.repo_name),
219
220
220 "name": repo_lnk(repo.repo_name, repo.repo_type,
221 "name": repo_lnk(repo.repo_name, repo.repo_type,
221 repo.repo_state, repo.private, repo.fork),
222 repo.repo_state, repo.private, repo.fork),
222 "name_raw": repo.repo_name.lower(),
223 "name_raw": repo.repo_name.lower(),
223
224
224 "last_change": last_change(repo.last_db_change),
225 "last_change": last_change(repo.last_db_change),
225 "last_change_raw": datetime_to_time(repo.last_db_change),
226 "last_change_raw": datetime_to_time(repo.last_db_change),
226
227
227 "last_changeset": last_rev(repo.repo_name, cs_cache),
228 "last_changeset": last_rev(repo.repo_name, cs_cache),
228 "last_changeset_raw": cs_cache.get('revision'),
229 "last_changeset_raw": cs_cache.get('revision'),
229
230
230 "desc": desc(repo.description),
231 "desc": desc(repo.description),
231 "owner": user_profile(repo.user.username),
232 "owner": user_profile(repo.user.username),
232
233
233 "state": state(repo.repo_state),
234 "state": state(repo.repo_state),
234 "rss": rss_lnk(repo.repo_name),
235 "rss": rss_lnk(repo.repo_name),
235
236
236 "atom": atom_lnk(repo.repo_name),
237 "atom": atom_lnk(repo.repo_name),
237 }
238 }
238 if admin:
239 if admin:
239 row.update({
240 row.update({
240 "action": repo_actions(repo.repo_name),
241 "action": repo_actions(repo.repo_name),
241 })
242 })
242 repos_data.append(row)
243 repos_data.append(row)
243
244
244 return repos_data
245 return repos_data
245
246
246 def _get_defaults(self, repo_name):
247 def _get_defaults(self, repo_name):
247 """
248 """
248 Gets information about repository, and returns a dict for
249 Gets information about repository, and returns a dict for
249 usage in forms
250 usage in forms
250
251
251 :param repo_name:
252 :param repo_name:
252 """
253 """
253
254
254 repo_info = Repository.get_by_repo_name(repo_name)
255 repo_info = Repository.get_by_repo_name(repo_name)
255
256
256 if repo_info is None:
257 if repo_info is None:
257 return None
258 return None
258
259
259 defaults = repo_info.get_dict()
260 defaults = repo_info.get_dict()
260 defaults['repo_name'] = repo_info.just_name
261 defaults['repo_name'] = repo_info.just_name
261
262
262 groups = repo_info.groups_with_parents
263 groups = repo_info.groups_with_parents
263 parent_group = groups[-1] if groups else None
264 parent_group = groups[-1] if groups else None
264
265
265 # we use -1 as this is how in HTML, we mark an empty group
266 # we use -1 as this is how in HTML, we mark an empty group
266 defaults['repo_group'] = getattr(parent_group, 'group_id', -1)
267 defaults['repo_group'] = getattr(parent_group, 'group_id', -1)
267
268
268 keys_to_process = (
269 keys_to_process = (
269 {'k': 'repo_type', 'strip': False},
270 {'k': 'repo_type', 'strip': False},
270 {'k': 'repo_enable_downloads', 'strip': True},
271 {'k': 'repo_enable_downloads', 'strip': True},
271 {'k': 'repo_description', 'strip': True},
272 {'k': 'repo_description', 'strip': True},
272 {'k': 'repo_enable_locking', 'strip': True},
273 {'k': 'repo_enable_locking', 'strip': True},
273 {'k': 'repo_landing_rev', 'strip': True},
274 {'k': 'repo_landing_rev', 'strip': True},
274 {'k': 'clone_uri', 'strip': False},
275 {'k': 'clone_uri', 'strip': False},
275 {'k': 'repo_private', 'strip': True},
276 {'k': 'repo_private', 'strip': True},
276 {'k': 'repo_enable_statistics', 'strip': True}
277 {'k': 'repo_enable_statistics', 'strip': True}
277 )
278 )
278
279
279 for item in keys_to_process:
280 for item in keys_to_process:
280 attr = item['k']
281 attr = item['k']
281 if item['strip']:
282 if item['strip']:
282 attr = remove_prefix(item['k'], 'repo_')
283 attr = remove_prefix(item['k'], 'repo_')
283
284
284 val = defaults[attr]
285 val = defaults[attr]
285 if item['k'] == 'repo_landing_rev':
286 if item['k'] == 'repo_landing_rev':
286 val = ':'.join(defaults[attr])
287 val = ':'.join(defaults[attr])
287 defaults[item['k']] = val
288 defaults[item['k']] = val
288 if item['k'] == 'clone_uri':
289 if item['k'] == 'clone_uri':
289 defaults['clone_uri_hidden'] = repo_info.clone_uri_hidden
290 defaults['clone_uri_hidden'] = repo_info.clone_uri_hidden
290
291
291 # fill owner
292 # fill owner
292 if repo_info.user:
293 if repo_info.user:
293 defaults.update({'user': repo_info.user.username})
294 defaults.update({'user': repo_info.user.username})
294 else:
295 else:
295 replacement_user = User.get_first_super_admin().username
296 replacement_user = User.get_first_super_admin().username
296 defaults.update({'user': replacement_user})
297 defaults.update({'user': replacement_user})
297
298
298 return defaults
299 return defaults
299
300
300 def update(self, repo, **kwargs):
301 def update(self, repo, **kwargs):
301 try:
302 try:
302 cur_repo = self._get_repo(repo)
303 cur_repo = self._get_repo(repo)
303 source_repo_name = cur_repo.repo_name
304 source_repo_name = cur_repo.repo_name
304 if 'user' in kwargs:
305 if 'user' in kwargs:
305 cur_repo.user = User.get_by_username(kwargs['user'])
306 cur_repo.user = User.get_by_username(kwargs['user'])
306
307
307 if 'repo_group' in kwargs:
308 if 'repo_group' in kwargs:
308 cur_repo.group = RepoGroup.get(kwargs['repo_group'])
309 cur_repo.group = RepoGroup.get(kwargs['repo_group'])
309 log.debug('Updating repo %s with params:%s', cur_repo, kwargs)
310 log.debug('Updating repo %s with params:%s', cur_repo, kwargs)
310
311
311 update_keys = [
312 update_keys = [
312 (1, 'repo_description'),
313 (1, 'repo_description'),
313 (1, 'repo_landing_rev'),
314 (1, 'repo_landing_rev'),
314 (1, 'repo_private'),
315 (1, 'repo_private'),
315 (1, 'repo_enable_downloads'),
316 (1, 'repo_enable_downloads'),
316 (1, 'repo_enable_locking'),
317 (1, 'repo_enable_locking'),
317 (1, 'repo_enable_statistics'),
318 (1, 'repo_enable_statistics'),
318 (0, 'clone_uri'),
319 (0, 'clone_uri'),
319 (0, 'fork_id')
320 (0, 'fork_id')
320 ]
321 ]
321 for strip, k in update_keys:
322 for strip, k in update_keys:
322 if k in kwargs:
323 if k in kwargs:
323 val = kwargs[k]
324 val = kwargs[k]
324 if strip:
325 if strip:
325 k = remove_prefix(k, 'repo_')
326 k = remove_prefix(k, 'repo_')
326
327
327 setattr(cur_repo, k, val)
328 setattr(cur_repo, k, val)
328
329
329 new_name = cur_repo.get_new_name(kwargs['repo_name'])
330 new_name = cur_repo.get_new_name(kwargs['repo_name'])
330 cur_repo.repo_name = new_name
331 cur_repo.repo_name = new_name
331
332
332 # if private flag is set, reset default permission to NONE
333 # if private flag is set, reset default permission to NONE
333 if kwargs.get('repo_private'):
334 if kwargs.get('repo_private'):
334 EMPTY_PERM = 'repository.none'
335 EMPTY_PERM = 'repository.none'
335 RepoModel().grant_user_permission(
336 RepoModel().grant_user_permission(
336 repo=cur_repo, user=User.DEFAULT_USER, perm=EMPTY_PERM
337 repo=cur_repo, user=User.DEFAULT_USER, perm=EMPTY_PERM
337 )
338 )
338
339
339 # handle extra fields
340 # handle extra fields
340 for field in filter(lambda k: k.startswith(RepositoryField.PREFIX),
341 for field in filter(lambda k: k.startswith(RepositoryField.PREFIX),
341 kwargs):
342 kwargs):
342 k = RepositoryField.un_prefix_key(field)
343 k = RepositoryField.un_prefix_key(field)
343 ex_field = RepositoryField.get_by_key_name(
344 ex_field = RepositoryField.get_by_key_name(
344 key=k, repo=cur_repo)
345 key=k, repo=cur_repo)
345 if ex_field:
346 if ex_field:
346 ex_field.field_value = kwargs[field]
347 ex_field.field_value = kwargs[field]
347 self.sa.add(ex_field)
348 self.sa.add(ex_field)
348 self.sa.add(cur_repo)
349 self.sa.add(cur_repo)
349
350
350 if source_repo_name != new_name:
351 if source_repo_name != new_name:
351 # rename repository
352 # rename repository
352 self._rename_filesystem_repo(
353 self._rename_filesystem_repo(
353 old=source_repo_name, new=new_name)
354 old=source_repo_name, new=new_name)
354
355
355 return cur_repo
356 return cur_repo
356 except Exception:
357 except Exception:
357 log.error(traceback.format_exc())
358 log.error(traceback.format_exc())
358 raise
359 raise
359
360
360 def _create_repo(self, repo_name, repo_type, description, owner,
361 def _create_repo(self, repo_name, repo_type, description, owner,
361 private=False, clone_uri=None, repo_group=None,
362 private=False, clone_uri=None, repo_group=None,
362 landing_rev='rev:tip', fork_of=None,
363 landing_rev='rev:tip', fork_of=None,
363 copy_fork_permissions=False, enable_statistics=False,
364 copy_fork_permissions=False, enable_statistics=False,
364 enable_locking=False, enable_downloads=False,
365 enable_locking=False, enable_downloads=False,
365 copy_group_permissions=False,
366 copy_group_permissions=False,
366 state=Repository.STATE_PENDING):
367 state=Repository.STATE_PENDING):
367 """
368 """
368 Create repository inside database with PENDING state, this should be
369 Create repository inside database with PENDING state, this should be
369 only executed by create() repo. With exception of importing existing
370 only executed by create() repo. With exception of importing existing
370 repos
371 repos
371 """
372 """
372 from rhodecode.model.scm import ScmModel
373 from rhodecode.model.scm import ScmModel
373
374
374 owner = self._get_user(owner)
375 owner = self._get_user(owner)
375 fork_of = self._get_repo(fork_of)
376 fork_of = self._get_repo(fork_of)
376 repo_group = self._get_repo_group(safe_int(repo_group))
377 repo_group = self._get_repo_group(safe_int(repo_group))
377
378
378 try:
379 try:
379 repo_name = safe_unicode(repo_name)
380 repo_name = safe_unicode(repo_name)
380 description = safe_unicode(description)
381 description = safe_unicode(description)
381 # repo name is just a name of repository
382 # repo name is just a name of repository
382 # while repo_name_full is a full qualified name that is combined
383 # while repo_name_full is a full qualified name that is combined
383 # with name and path of group
384 # with name and path of group
384 repo_name_full = repo_name
385 repo_name_full = repo_name
385 repo_name = repo_name.split(Repository.NAME_SEP)[-1]
386 repo_name = repo_name.split(Repository.NAME_SEP)[-1]
386
387
387 new_repo = Repository()
388 new_repo = Repository()
388 new_repo.repo_state = state
389 new_repo.repo_state = state
389 new_repo.enable_statistics = False
390 new_repo.enable_statistics = False
390 new_repo.repo_name = repo_name_full
391 new_repo.repo_name = repo_name_full
391 new_repo.repo_type = repo_type
392 new_repo.repo_type = repo_type
392 new_repo.user = owner
393 new_repo.user = owner
393 new_repo.group = repo_group
394 new_repo.group = repo_group
394 new_repo.description = description or repo_name
395 new_repo.description = description or repo_name
395 new_repo.private = private
396 new_repo.private = private
396 new_repo.clone_uri = clone_uri
397 new_repo.clone_uri = clone_uri
397 new_repo.landing_rev = landing_rev
398 new_repo.landing_rev = landing_rev
398
399
399 new_repo.enable_statistics = enable_statistics
400 new_repo.enable_statistics = enable_statistics
400 new_repo.enable_locking = enable_locking
401 new_repo.enable_locking = enable_locking
401 new_repo.enable_downloads = enable_downloads
402 new_repo.enable_downloads = enable_downloads
402
403
403 if repo_group:
404 if repo_group:
404 new_repo.enable_locking = repo_group.enable_locking
405 new_repo.enable_locking = repo_group.enable_locking
405
406
406 if fork_of:
407 if fork_of:
407 parent_repo = fork_of
408 parent_repo = fork_of
408 new_repo.fork = parent_repo
409 new_repo.fork = parent_repo
409
410
410 events.trigger(events.RepoPreCreateEvent(new_repo))
411 events.trigger(events.RepoPreCreateEvent(new_repo))
411
412
412 self.sa.add(new_repo)
413 self.sa.add(new_repo)
413
414
414 EMPTY_PERM = 'repository.none'
415 EMPTY_PERM = 'repository.none'
415 if fork_of and copy_fork_permissions:
416 if fork_of and copy_fork_permissions:
416 repo = fork_of
417 repo = fork_of
417 user_perms = UserRepoToPerm.query() \
418 user_perms = UserRepoToPerm.query() \
418 .filter(UserRepoToPerm.repository == repo).all()
419 .filter(UserRepoToPerm.repository == repo).all()
419 group_perms = UserGroupRepoToPerm.query() \
420 group_perms = UserGroupRepoToPerm.query() \
420 .filter(UserGroupRepoToPerm.repository == repo).all()
421 .filter(UserGroupRepoToPerm.repository == repo).all()
421
422
422 for perm in user_perms:
423 for perm in user_perms:
423 UserRepoToPerm.create(
424 UserRepoToPerm.create(
424 perm.user, new_repo, perm.permission)
425 perm.user, new_repo, perm.permission)
425
426
426 for perm in group_perms:
427 for perm in group_perms:
427 UserGroupRepoToPerm.create(
428 UserGroupRepoToPerm.create(
428 perm.users_group, new_repo, perm.permission)
429 perm.users_group, new_repo, perm.permission)
429 # in case we copy permissions and also set this repo to private
430 # in case we copy permissions and also set this repo to private
430 # override the default user permission to make it a private
431 # override the default user permission to make it a private
431 # repo
432 # repo
432 if private:
433 if private:
433 RepoModel(self.sa).grant_user_permission(
434 RepoModel(self.sa).grant_user_permission(
434 repo=new_repo, user=User.DEFAULT_USER, perm=EMPTY_PERM)
435 repo=new_repo, user=User.DEFAULT_USER, perm=EMPTY_PERM)
435
436
436 elif repo_group and copy_group_permissions:
437 elif repo_group and copy_group_permissions:
437 user_perms = UserRepoGroupToPerm.query() \
438 user_perms = UserRepoGroupToPerm.query() \
438 .filter(UserRepoGroupToPerm.group == repo_group).all()
439 .filter(UserRepoGroupToPerm.group == repo_group).all()
439
440
440 group_perms = UserGroupRepoGroupToPerm.query() \
441 group_perms = UserGroupRepoGroupToPerm.query() \
441 .filter(UserGroupRepoGroupToPerm.group == repo_group).all()
442 .filter(UserGroupRepoGroupToPerm.group == repo_group).all()
442
443
443 for perm in user_perms:
444 for perm in user_perms:
444 perm_name = perm.permission.permission_name.replace(
445 perm_name = perm.permission.permission_name.replace(
445 'group.', 'repository.')
446 'group.', 'repository.')
446 perm_obj = Permission.get_by_key(perm_name)
447 perm_obj = Permission.get_by_key(perm_name)
447 UserRepoToPerm.create(perm.user, new_repo, perm_obj)
448 UserRepoToPerm.create(perm.user, new_repo, perm_obj)
448
449
449 for perm in group_perms:
450 for perm in group_perms:
450 perm_name = perm.permission.permission_name.replace(
451 perm_name = perm.permission.permission_name.replace(
451 'group.', 'repository.')
452 'group.', 'repository.')
452 perm_obj = Permission.get_by_key(perm_name)
453 perm_obj = Permission.get_by_key(perm_name)
453 UserGroupRepoToPerm.create(
454 UserGroupRepoToPerm.create(
454 perm.users_group, new_repo, perm_obj)
455 perm.users_group, new_repo, perm_obj)
455
456
456 if private:
457 if private:
457 RepoModel(self.sa).grant_user_permission(
458 RepoModel(self.sa).grant_user_permission(
458 repo=new_repo, user=User.DEFAULT_USER, perm=EMPTY_PERM)
459 repo=new_repo, user=User.DEFAULT_USER, perm=EMPTY_PERM)
459
460
460 else:
461 else:
461 perm_obj = self._create_default_perms(new_repo, private)
462 perm_obj = self._create_default_perms(new_repo, private)
462 self.sa.add(perm_obj)
463 self.sa.add(perm_obj)
463
464
464 # now automatically start following this repository as owner
465 # now automatically start following this repository as owner
465 ScmModel(self.sa).toggle_following_repo(new_repo.repo_id,
466 ScmModel(self.sa).toggle_following_repo(new_repo.repo_id,
466 owner.user_id)
467 owner.user_id)
467
468
468 # we need to flush here, in order to check if database won't
469 # we need to flush here, in order to check if database won't
469 # throw any exceptions, create filesystem dirs at the very end
470 # throw any exceptions, create filesystem dirs at the very end
470 self.sa.flush()
471 self.sa.flush()
471 events.trigger(events.RepoCreateEvent(new_repo))
472 events.trigger(events.RepoCreateEvent(new_repo))
472 return new_repo
473 return new_repo
473
474
474 except Exception:
475 except Exception:
475 log.error(traceback.format_exc())
476 log.error(traceback.format_exc())
476 raise
477 raise
477
478
478 def create(self, form_data, cur_user):
479 def create(self, form_data, cur_user):
479 """
480 """
480 Create repository using celery tasks
481 Create repository using celery tasks
481
482
482 :param form_data:
483 :param form_data:
483 :param cur_user:
484 :param cur_user:
484 """
485 """
485 from rhodecode.lib.celerylib import tasks, run_task
486 from rhodecode.lib.celerylib import tasks, run_task
486 return run_task(tasks.create_repo, form_data, cur_user)
487 return run_task(tasks.create_repo, form_data, cur_user)
487
488
488 def update_permissions(self, repo, perm_additions=None, perm_updates=None,
489 def update_permissions(self, repo, perm_additions=None, perm_updates=None,
489 perm_deletions=None, check_perms=True,
490 perm_deletions=None, check_perms=True,
490 cur_user=None):
491 cur_user=None):
491 if not perm_additions:
492 if not perm_additions:
492 perm_additions = []
493 perm_additions = []
493 if not perm_updates:
494 if not perm_updates:
494 perm_updates = []
495 perm_updates = []
495 if not perm_deletions:
496 if not perm_deletions:
496 perm_deletions = []
497 perm_deletions = []
497
498
498 req_perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin')
499 req_perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin')
499
500
500 changes = {
501 changes = {
501 'added': [],
502 'added': [],
502 'updated': [],
503 'updated': [],
503 'deleted': []
504 'deleted': []
504 }
505 }
505 # update permissions
506 # update permissions
506 for member_id, perm, member_type in perm_updates:
507 for member_id, perm, member_type in perm_updates:
507 member_id = int(member_id)
508 member_id = int(member_id)
508 if member_type == 'user':
509 if member_type == 'user':
509 member_name = User.get(member_id).username
510 member_name = User.get(member_id).username
510 # this updates also current one if found
511 # this updates also current one if found
511 self.grant_user_permission(
512 self.grant_user_permission(
512 repo=repo, user=member_id, perm=perm)
513 repo=repo, user=member_id, perm=perm)
513 else: # set for user group
514 else: # set for user group
514 # check if we have permissions to alter this usergroup
515 # check if we have permissions to alter this usergroup
515 member_name = UserGroup.get(member_id).users_group_name
516 member_name = UserGroup.get(member_id).users_group_name
516 if not check_perms or HasUserGroupPermissionAny(
517 if not check_perms or HasUserGroupPermissionAny(
517 *req_perms)(member_name, user=cur_user):
518 *req_perms)(member_name, user=cur_user):
518 self.grant_user_group_permission(
519 self.grant_user_group_permission(
519 repo=repo, group_name=member_id, perm=perm)
520 repo=repo, group_name=member_id, perm=perm)
520
521
521 changes['updated'].append({'type': member_type, 'id': member_id,
522 changes['updated'].append({'type': member_type, 'id': member_id,
522 'name': member_name, 'new_perm': perm})
523 'name': member_name, 'new_perm': perm})
523
524
524 # set new permissions
525 # set new permissions
525 for member_id, perm, member_type in perm_additions:
526 for member_id, perm, member_type in perm_additions:
526 member_id = int(member_id)
527 member_id = int(member_id)
527 if member_type == 'user':
528 if member_type == 'user':
528 member_name = User.get(member_id).username
529 member_name = User.get(member_id).username
529 self.grant_user_permission(
530 self.grant_user_permission(
530 repo=repo, user=member_id, perm=perm)
531 repo=repo, user=member_id, perm=perm)
531 else: # set for user group
532 else: # set for user group
532 # check if we have permissions to alter this usergroup
533 # check if we have permissions to alter this usergroup
533 member_name = UserGroup.get(member_id).users_group_name
534 member_name = UserGroup.get(member_id).users_group_name
534 if not check_perms or HasUserGroupPermissionAny(
535 if not check_perms or HasUserGroupPermissionAny(
535 *req_perms)(member_name, user=cur_user):
536 *req_perms)(member_name, user=cur_user):
536 self.grant_user_group_permission(
537 self.grant_user_group_permission(
537 repo=repo, group_name=member_id, perm=perm)
538 repo=repo, group_name=member_id, perm=perm)
538 changes['added'].append({'type': member_type, 'id': member_id,
539 changes['added'].append({'type': member_type, 'id': member_id,
539 'name': member_name, 'new_perm': perm})
540 'name': member_name, 'new_perm': perm})
540 # delete permissions
541 # delete permissions
541 for member_id, perm, member_type in perm_deletions:
542 for member_id, perm, member_type in perm_deletions:
542 member_id = int(member_id)
543 member_id = int(member_id)
543 if member_type == 'user':
544 if member_type == 'user':
544 member_name = User.get(member_id).username
545 member_name = User.get(member_id).username
545 self.revoke_user_permission(repo=repo, user=member_id)
546 self.revoke_user_permission(repo=repo, user=member_id)
546 else: # set for user group
547 else: # set for user group
547 # check if we have permissions to alter this usergroup
548 # check if we have permissions to alter this usergroup
548 member_name = UserGroup.get(member_id).users_group_name
549 member_name = UserGroup.get(member_id).users_group_name
549 if not check_perms or HasUserGroupPermissionAny(
550 if not check_perms or HasUserGroupPermissionAny(
550 *req_perms)(member_name, user=cur_user):
551 *req_perms)(member_name, user=cur_user):
551 self.revoke_user_group_permission(
552 self.revoke_user_group_permission(
552 repo=repo, group_name=member_id)
553 repo=repo, group_name=member_id)
553
554
554 changes['deleted'].append({'type': member_type, 'id': member_id,
555 changes['deleted'].append({'type': member_type, 'id': member_id,
555 'name': member_name, 'new_perm': perm})
556 'name': member_name, 'new_perm': perm})
556 return changes
557 return changes
557
558
558 def create_fork(self, form_data, cur_user):
559 def create_fork(self, form_data, cur_user):
559 """
560 """
560 Simple wrapper into executing celery task for fork creation
561 Simple wrapper into executing celery task for fork creation
561
562
562 :param form_data:
563 :param form_data:
563 :param cur_user:
564 :param cur_user:
564 """
565 """
565 from rhodecode.lib.celerylib import tasks, run_task
566 from rhodecode.lib.celerylib import tasks, run_task
566 return run_task(tasks.create_repo_fork, form_data, cur_user)
567 return run_task(tasks.create_repo_fork, form_data, cur_user)
567
568
568 def delete(self, repo, forks=None, fs_remove=True, cur_user=None):
569 def delete(self, repo, forks=None, fs_remove=True, cur_user=None):
569 """
570 """
570 Delete given repository, forks parameter defines what do do with
571 Delete given repository, forks parameter defines what do do with
571 attached forks. Throws AttachedForksError if deleted repo has attached
572 attached forks. Throws AttachedForksError if deleted repo has attached
572 forks
573 forks
573
574
574 :param repo:
575 :param repo:
575 :param forks: str 'delete' or 'detach'
576 :param forks: str 'delete' or 'detach'
576 :param fs_remove: remove(archive) repo from filesystem
577 :param fs_remove: remove(archive) repo from filesystem
577 """
578 """
578 if not cur_user:
579 if not cur_user:
579 cur_user = getattr(get_current_rhodecode_user(), 'username', None)
580 cur_user = getattr(get_current_rhodecode_user(), 'username', None)
580 repo = self._get_repo(repo)
581 repo = self._get_repo(repo)
581 if repo:
582 if repo:
582 if forks == 'detach':
583 if forks == 'detach':
583 for r in repo.forks:
584 for r in repo.forks:
584 r.fork = None
585 r.fork = None
585 self.sa.add(r)
586 self.sa.add(r)
586 elif forks == 'delete':
587 elif forks == 'delete':
587 for r in repo.forks:
588 for r in repo.forks:
588 self.delete(r, forks='delete')
589 self.delete(r, forks='delete')
589 elif [f for f in repo.forks]:
590 elif [f for f in repo.forks]:
590 raise AttachedForksError()
591 raise AttachedForksError()
591
592
592 old_repo_dict = repo.get_dict()
593 old_repo_dict = repo.get_dict()
593 events.trigger(events.RepoPreDeleteEvent(repo))
594 events.trigger(events.RepoPreDeleteEvent(repo))
594 try:
595 try:
595 self.sa.delete(repo)
596 self.sa.delete(repo)
596 if fs_remove:
597 if fs_remove:
597 self._delete_filesystem_repo(repo)
598 self._delete_filesystem_repo(repo)
598 else:
599 else:
599 log.debug('skipping removal from filesystem')
600 log.debug('skipping removal from filesystem')
600 old_repo_dict.update({
601 old_repo_dict.update({
601 'deleted_by': cur_user,
602 'deleted_by': cur_user,
602 'deleted_on': time.time(),
603 'deleted_on': time.time(),
603 })
604 })
604 log_delete_repository(**old_repo_dict)
605 log_delete_repository(**old_repo_dict)
605 events.trigger(events.RepoDeleteEvent(repo))
606 events.trigger(events.RepoDeleteEvent(repo))
606 except Exception:
607 except Exception:
607 log.error(traceback.format_exc())
608 log.error(traceback.format_exc())
608 raise
609 raise
609
610
610 def grant_user_permission(self, repo, user, perm):
611 def grant_user_permission(self, repo, user, perm):
611 """
612 """
612 Grant permission for user on given repository, or update existing one
613 Grant permission for user on given repository, or update existing one
613 if found
614 if found
614
615
615 :param repo: Instance of Repository, repository_id, or repository name
616 :param repo: Instance of Repository, repository_id, or repository name
616 :param user: Instance of User, user_id or username
617 :param user: Instance of User, user_id or username
617 :param perm: Instance of Permission, or permission_name
618 :param perm: Instance of Permission, or permission_name
618 """
619 """
619 user = self._get_user(user)
620 user = self._get_user(user)
620 repo = self._get_repo(repo)
621 repo = self._get_repo(repo)
621 permission = self._get_perm(perm)
622 permission = self._get_perm(perm)
622
623
623 # check if we have that permission already
624 # check if we have that permission already
624 obj = self.sa.query(UserRepoToPerm) \
625 obj = self.sa.query(UserRepoToPerm) \
625 .filter(UserRepoToPerm.user == user) \
626 .filter(UserRepoToPerm.user == user) \
626 .filter(UserRepoToPerm.repository == repo) \
627 .filter(UserRepoToPerm.repository == repo) \
627 .scalar()
628 .scalar()
628 if obj is None:
629 if obj is None:
629 # create new !
630 # create new !
630 obj = UserRepoToPerm()
631 obj = UserRepoToPerm()
631 obj.repository = repo
632 obj.repository = repo
632 obj.user = user
633 obj.user = user
633 obj.permission = permission
634 obj.permission = permission
634 self.sa.add(obj)
635 self.sa.add(obj)
635 log.debug('Granted perm %s to %s on %s', perm, user, repo)
636 log.debug('Granted perm %s to %s on %s', perm, user, repo)
636 action_logger_generic(
637 action_logger_generic(
637 'granted permission: {} to user: {} on repo: {}'.format(
638 'granted permission: {} to user: {} on repo: {}'.format(
638 perm, user, repo), namespace='security.repo')
639 perm, user, repo), namespace='security.repo')
639 return obj
640 return obj
640
641
641 def revoke_user_permission(self, repo, user):
642 def revoke_user_permission(self, repo, user):
642 """
643 """
643 Revoke permission for user on given repository
644 Revoke permission for user on given repository
644
645
645 :param repo: Instance of Repository, repository_id, or repository name
646 :param repo: Instance of Repository, repository_id, or repository name
646 :param user: Instance of User, user_id or username
647 :param user: Instance of User, user_id or username
647 """
648 """
648
649
649 user = self._get_user(user)
650 user = self._get_user(user)
650 repo = self._get_repo(repo)
651 repo = self._get_repo(repo)
651
652
652 obj = self.sa.query(UserRepoToPerm) \
653 obj = self.sa.query(UserRepoToPerm) \
653 .filter(UserRepoToPerm.repository == repo) \
654 .filter(UserRepoToPerm.repository == repo) \
654 .filter(UserRepoToPerm.user == user) \
655 .filter(UserRepoToPerm.user == user) \
655 .scalar()
656 .scalar()
656 if obj:
657 if obj:
657 self.sa.delete(obj)
658 self.sa.delete(obj)
658 log.debug('Revoked perm on %s on %s', repo, user)
659 log.debug('Revoked perm on %s on %s', repo, user)
659 action_logger_generic(
660 action_logger_generic(
660 'revoked permission from user: {} on repo: {}'.format(
661 'revoked permission from user: {} on repo: {}'.format(
661 user, repo), namespace='security.repo')
662 user, repo), namespace='security.repo')
662
663
663 def grant_user_group_permission(self, repo, group_name, perm):
664 def grant_user_group_permission(self, repo, group_name, perm):
664 """
665 """
665 Grant permission for user group on given repository, or update
666 Grant permission for user group on given repository, or update
666 existing one if found
667 existing one if found
667
668
668 :param repo: Instance of Repository, repository_id, or repository name
669 :param repo: Instance of Repository, repository_id, or repository name
669 :param group_name: Instance of UserGroup, users_group_id,
670 :param group_name: Instance of UserGroup, users_group_id,
670 or user group name
671 or user group name
671 :param perm: Instance of Permission, or permission_name
672 :param perm: Instance of Permission, or permission_name
672 """
673 """
673 repo = self._get_repo(repo)
674 repo = self._get_repo(repo)
674 group_name = self._get_user_group(group_name)
675 group_name = self._get_user_group(group_name)
675 permission = self._get_perm(perm)
676 permission = self._get_perm(perm)
676
677
677 # check if we have that permission already
678 # check if we have that permission already
678 obj = self.sa.query(UserGroupRepoToPerm) \
679 obj = self.sa.query(UserGroupRepoToPerm) \
679 .filter(UserGroupRepoToPerm.users_group == group_name) \
680 .filter(UserGroupRepoToPerm.users_group == group_name) \
680 .filter(UserGroupRepoToPerm.repository == repo) \
681 .filter(UserGroupRepoToPerm.repository == repo) \
681 .scalar()
682 .scalar()
682
683
683 if obj is None:
684 if obj is None:
684 # create new
685 # create new
685 obj = UserGroupRepoToPerm()
686 obj = UserGroupRepoToPerm()
686
687
687 obj.repository = repo
688 obj.repository = repo
688 obj.users_group = group_name
689 obj.users_group = group_name
689 obj.permission = permission
690 obj.permission = permission
690 self.sa.add(obj)
691 self.sa.add(obj)
691 log.debug('Granted perm %s to %s on %s', perm, group_name, repo)
692 log.debug('Granted perm %s to %s on %s', perm, group_name, repo)
692 action_logger_generic(
693 action_logger_generic(
693 'granted permission: {} to usergroup: {} on repo: {}'.format(
694 'granted permission: {} to usergroup: {} on repo: {}'.format(
694 perm, group_name, repo), namespace='security.repo')
695 perm, group_name, repo), namespace='security.repo')
695
696
696 return obj
697 return obj
697
698
698 def revoke_user_group_permission(self, repo, group_name):
699 def revoke_user_group_permission(self, repo, group_name):
699 """
700 """
700 Revoke permission for user group on given repository
701 Revoke permission for user group on given repository
701
702
702 :param repo: Instance of Repository, repository_id, or repository name
703 :param repo: Instance of Repository, repository_id, or repository name
703 :param group_name: Instance of UserGroup, users_group_id,
704 :param group_name: Instance of UserGroup, users_group_id,
704 or user group name
705 or user group name
705 """
706 """
706 repo = self._get_repo(repo)
707 repo = self._get_repo(repo)
707 group_name = self._get_user_group(group_name)
708 group_name = self._get_user_group(group_name)
708
709
709 obj = self.sa.query(UserGroupRepoToPerm) \
710 obj = self.sa.query(UserGroupRepoToPerm) \
710 .filter(UserGroupRepoToPerm.repository == repo) \
711 .filter(UserGroupRepoToPerm.repository == repo) \
711 .filter(UserGroupRepoToPerm.users_group == group_name) \
712 .filter(UserGroupRepoToPerm.users_group == group_name) \
712 .scalar()
713 .scalar()
713 if obj:
714 if obj:
714 self.sa.delete(obj)
715 self.sa.delete(obj)
715 log.debug('Revoked perm to %s on %s', repo, group_name)
716 log.debug('Revoked perm to %s on %s', repo, group_name)
716 action_logger_generic(
717 action_logger_generic(
717 'revoked permission from usergroup: {} on repo: {}'.format(
718 'revoked permission from usergroup: {} on repo: {}'.format(
718 group_name, repo), namespace='security.repo')
719 group_name, repo), namespace='security.repo')
719
720
720 def delete_stats(self, repo_name):
721 def delete_stats(self, repo_name):
721 """
722 """
722 removes stats for given repo
723 removes stats for given repo
723
724
724 :param repo_name:
725 :param repo_name:
725 """
726 """
726 repo = self._get_repo(repo_name)
727 repo = self._get_repo(repo_name)
727 try:
728 try:
728 obj = self.sa.query(Statistics) \
729 obj = self.sa.query(Statistics) \
729 .filter(Statistics.repository == repo).scalar()
730 .filter(Statistics.repository == repo).scalar()
730 if obj:
731 if obj:
731 self.sa.delete(obj)
732 self.sa.delete(obj)
732 except Exception:
733 except Exception:
733 log.error(traceback.format_exc())
734 log.error(traceback.format_exc())
734 raise
735 raise
735
736
736 def add_repo_field(self, repo_name, field_key, field_label, field_value='',
737 def add_repo_field(self, repo_name, field_key, field_label, field_value='',
737 field_type='str', field_desc=''):
738 field_type='str', field_desc=''):
738
739
739 repo = self._get_repo(repo_name)
740 repo = self._get_repo(repo_name)
740
741
741 new_field = RepositoryField()
742 new_field = RepositoryField()
742 new_field.repository = repo
743 new_field.repository = repo
743 new_field.field_key = field_key
744 new_field.field_key = field_key
744 new_field.field_type = field_type # python type
745 new_field.field_type = field_type # python type
745 new_field.field_value = field_value
746 new_field.field_value = field_value
746 new_field.field_desc = field_desc
747 new_field.field_desc = field_desc
747 new_field.field_label = field_label
748 new_field.field_label = field_label
748 self.sa.add(new_field)
749 self.sa.add(new_field)
749 return new_field
750 return new_field
750
751
751 def delete_repo_field(self, repo_name, field_key):
752 def delete_repo_field(self, repo_name, field_key):
752 repo = self._get_repo(repo_name)
753 repo = self._get_repo(repo_name)
753 field = RepositoryField.get_by_key_name(field_key, repo)
754 field = RepositoryField.get_by_key_name(field_key, repo)
754 if field:
755 if field:
755 self.sa.delete(field)
756 self.sa.delete(field)
756
757
757 def _create_filesystem_repo(self, repo_name, repo_type, repo_group,
758 def _create_filesystem_repo(self, repo_name, repo_type, repo_group,
758 clone_uri=None, repo_store_location=None,
759 clone_uri=None, repo_store_location=None,
759 use_global_config=False):
760 use_global_config=False):
760 """
761 """
761 makes repository on filesystem. It's group aware means it'll create
762 makes repository on filesystem. It's group aware means it'll create
762 a repository within a group, and alter the paths accordingly of
763 a repository within a group, and alter the paths accordingly of
763 group location
764 group location
764
765
765 :param repo_name:
766 :param repo_name:
766 :param alias:
767 :param alias:
767 :param parent:
768 :param parent:
768 :param clone_uri:
769 :param clone_uri:
769 :param repo_store_location:
770 :param repo_store_location:
770 """
771 """
771 from rhodecode.lib.utils import is_valid_repo, is_valid_repo_group
772 from rhodecode.lib.utils import is_valid_repo, is_valid_repo_group
772 from rhodecode.model.scm import ScmModel
773 from rhodecode.model.scm import ScmModel
773
774
774 if Repository.NAME_SEP in repo_name:
775 if Repository.NAME_SEP in repo_name:
775 raise ValueError(
776 raise ValueError(
776 'repo_name must not contain groups got `%s`' % repo_name)
777 'repo_name must not contain groups got `%s`' % repo_name)
777
778
778 if isinstance(repo_group, RepoGroup):
779 if isinstance(repo_group, RepoGroup):
779 new_parent_path = os.sep.join(repo_group.full_path_splitted)
780 new_parent_path = os.sep.join(repo_group.full_path_splitted)
780 else:
781 else:
781 new_parent_path = repo_group or ''
782 new_parent_path = repo_group or ''
782
783
783 if repo_store_location:
784 if repo_store_location:
784 _paths = [repo_store_location]
785 _paths = [repo_store_location]
785 else:
786 else:
786 _paths = [self.repos_path, new_parent_path, repo_name]
787 _paths = [self.repos_path, new_parent_path, repo_name]
787 # we need to make it str for mercurial
788 # we need to make it str for mercurial
788 repo_path = os.path.join(*map(lambda x: safe_str(x), _paths))
789 repo_path = os.path.join(*map(lambda x: safe_str(x), _paths))
789
790
790 # check if this path is not a repository
791 # check if this path is not a repository
791 if is_valid_repo(repo_path, self.repos_path):
792 if is_valid_repo(repo_path, self.repos_path):
792 raise Exception('This path %s is a valid repository' % repo_path)
793 raise Exception('This path %s is a valid repository' % repo_path)
793
794
794 # check if this path is a group
795 # check if this path is a group
795 if is_valid_repo_group(repo_path, self.repos_path):
796 if is_valid_repo_group(repo_path, self.repos_path):
796 raise Exception('This path %s is a valid group' % repo_path)
797 raise Exception('This path %s is a valid group' % repo_path)
797
798
798 log.info('creating repo %s in %s from url: `%s`',
799 log.info('creating repo %s in %s from url: `%s`',
799 repo_name, safe_unicode(repo_path),
800 repo_name, safe_unicode(repo_path),
800 obfuscate_url_pw(clone_uri))
801 obfuscate_url_pw(clone_uri))
801
802
802 backend = get_backend(repo_type)
803 backend = get_backend(repo_type)
803
804
804 config_repo = None if use_global_config else repo_name
805 config_repo = None if use_global_config else repo_name
805 if config_repo and new_parent_path:
806 if config_repo and new_parent_path:
806 config_repo = Repository.NAME_SEP.join(
807 config_repo = Repository.NAME_SEP.join(
807 (new_parent_path, config_repo))
808 (new_parent_path, config_repo))
808 config = make_db_config(clear_session=False, repo=config_repo)
809 config = make_db_config(clear_session=False, repo=config_repo)
809 config.set('extensions', 'largefiles', '')
810 config.set('extensions', 'largefiles', '')
810
811
811 # patch and reset hooks section of UI config to not run any
812 # patch and reset hooks section of UI config to not run any
812 # hooks on creating remote repo
813 # hooks on creating remote repo
813 config.clear_section('hooks')
814 config.clear_section('hooks')
814
815
815 # TODO: johbo: Unify this, hardcoded "bare=True" does not look nice
816 # TODO: johbo: Unify this, hardcoded "bare=True" does not look nice
816 if repo_type == 'git':
817 if repo_type == 'git':
817 repo = backend(
818 repo = backend(
818 repo_path, config=config, create=True, src_url=clone_uri,
819 repo_path, config=config, create=True, src_url=clone_uri,
819 bare=True)
820 bare=True)
820 else:
821 else:
821 repo = backend(
822 repo = backend(
822 repo_path, config=config, create=True, src_url=clone_uri)
823 repo_path, config=config, create=True, src_url=clone_uri)
823
824
824 ScmModel().install_hooks(repo, repo_type=repo_type)
825 ScmModel().install_hooks(repo, repo_type=repo_type)
825
826
826 log.debug('Created repo %s with %s backend',
827 log.debug('Created repo %s with %s backend',
827 safe_unicode(repo_name), safe_unicode(repo_type))
828 safe_unicode(repo_name), safe_unicode(repo_type))
828 return repo
829 return repo
829
830
830 def _rename_filesystem_repo(self, old, new):
831 def _rename_filesystem_repo(self, old, new):
831 """
832 """
832 renames repository on filesystem
833 renames repository on filesystem
833
834
834 :param old: old name
835 :param old: old name
835 :param new: new name
836 :param new: new name
836 """
837 """
837 log.info('renaming repo from %s to %s', old, new)
838 log.info('renaming repo from %s to %s', old, new)
838
839
839 old_path = os.path.join(self.repos_path, old)
840 old_path = os.path.join(self.repos_path, old)
840 new_path = os.path.join(self.repos_path, new)
841 new_path = os.path.join(self.repos_path, new)
841 if os.path.isdir(new_path):
842 if os.path.isdir(new_path):
842 raise Exception(
843 raise Exception(
843 'Was trying to rename to already existing dir %s' % new_path
844 'Was trying to rename to already existing dir %s' % new_path
844 )
845 )
845 shutil.move(old_path, new_path)
846 shutil.move(old_path, new_path)
846
847
847 def _delete_filesystem_repo(self, repo):
848 def _delete_filesystem_repo(self, repo):
848 """
849 """
849 removes repo from filesystem, the removal is acctually made by
850 removes repo from filesystem, the removal is acctually made by
850 added rm__ prefix into dir, and rename internat .hg/.git dirs so this
851 added rm__ prefix into dir, and rename internat .hg/.git dirs so this
851 repository is no longer valid for rhodecode, can be undeleted later on
852 repository is no longer valid for rhodecode, can be undeleted later on
852 by reverting the renames on this repository
853 by reverting the renames on this repository
853
854
854 :param repo: repo object
855 :param repo: repo object
855 """
856 """
856 rm_path = os.path.join(self.repos_path, repo.repo_name)
857 rm_path = os.path.join(self.repos_path, repo.repo_name)
857 repo_group = repo.group
858 repo_group = repo.group
858 log.info("Removing repository %s", rm_path)
859 log.info("Removing repository %s", rm_path)
859 # disable hg/git internal that it doesn't get detected as repo
860 # disable hg/git internal that it doesn't get detected as repo
860 alias = repo.repo_type
861 alias = repo.repo_type
861
862
862 config = make_db_config(clear_session=False)
863 config = make_db_config(clear_session=False)
863 config.set('extensions', 'largefiles', '')
864 config.set('extensions', 'largefiles', '')
864 bare = getattr(repo.scm_instance(config=config), 'bare', False)
865 bare = getattr(repo.scm_instance(config=config), 'bare', False)
865
866
866 # skip this for bare git repos
867 # skip this for bare git repos
867 if not bare:
868 if not bare:
868 # disable VCS repo
869 # disable VCS repo
869 vcs_path = os.path.join(rm_path, '.%s' % alias)
870 vcs_path = os.path.join(rm_path, '.%s' % alias)
870 if os.path.exists(vcs_path):
871 if os.path.exists(vcs_path):
871 shutil.move(vcs_path, os.path.join(rm_path, 'rm__.%s' % alias))
872 shutil.move(vcs_path, os.path.join(rm_path, 'rm__.%s' % alias))
872
873
873 _now = datetime.now()
874 _now = datetime.now()
874 _ms = str(_now.microsecond).rjust(6, '0')
875 _ms = str(_now.microsecond).rjust(6, '0')
875 _d = 'rm__%s__%s' % (_now.strftime('%Y%m%d_%H%M%S_' + _ms),
876 _d = 'rm__%s__%s' % (_now.strftime('%Y%m%d_%H%M%S_' + _ms),
876 repo.just_name)
877 repo.just_name)
877 if repo_group:
878 if repo_group:
878 # if repository is in group, prefix the removal path with the group
879 # if repository is in group, prefix the removal path with the group
879 args = repo_group.full_path_splitted + [_d]
880 args = repo_group.full_path_splitted + [_d]
880 _d = os.path.join(*args)
881 _d = os.path.join(*args)
881
882
882 if os.path.isdir(rm_path):
883 if os.path.isdir(rm_path):
883 shutil.move(rm_path, os.path.join(self.repos_path, _d))
884 shutil.move(rm_path, os.path.join(self.repos_path, _d))
884
885
885
886
886 class ReadmeFinder:
887 class ReadmeFinder:
887 """
888 """
888 Utility which knows how to find a readme for a specific commit.
889 Utility which knows how to find a readme for a specific commit.
889
890
890 The main idea is that this is a configurable algorithm. When creating an
891 The main idea is that this is a configurable algorithm. When creating an
891 instance you can define parameters, currently only the `default_renderer`.
892 instance you can define parameters, currently only the `default_renderer`.
892 Based on this configuration the method :meth:`search` behaves slightly
893 Based on this configuration the method :meth:`search` behaves slightly
893 different.
894 different.
894 """
895 """
895
896
896 readme_re = re.compile(r'^readme(\.[^\.]+)?$', re.IGNORECASE)
897 readme_re = re.compile(r'^readme(\.[^\.]+)?$', re.IGNORECASE)
897 path_re = re.compile(r'^docs?', re.IGNORECASE)
898 path_re = re.compile(r'^docs?', re.IGNORECASE)
898
899
899 default_priorities = {
900 default_priorities = {
900 None: 0,
901 None: 0,
901 '.text': 2,
902 '.text': 2,
902 '.txt': 3,
903 '.txt': 3,
903 '.rst': 1,
904 '.rst': 1,
904 '.rest': 2,
905 '.rest': 2,
905 '.md': 1,
906 '.md': 1,
906 '.mkdn': 2,
907 '.mkdn': 2,
907 '.mdown': 3,
908 '.mdown': 3,
908 '.markdown': 4,
909 '.markdown': 4,
909 }
910 }
910
911
911 path_priority = {
912 path_priority = {
912 'doc': 0,
913 'doc': 0,
913 'docs': 1,
914 'docs': 1,
914 }
915 }
915
916
916 FALLBACK_PRIORITY = 99
917 FALLBACK_PRIORITY = 99
917
918
918 RENDERER_TO_EXTENSION = {
919 RENDERER_TO_EXTENSION = {
919 'rst': ['.rst', '.rest'],
920 'rst': ['.rst', '.rest'],
920 'markdown': ['.md', 'mkdn', '.mdown', '.markdown'],
921 'markdown': ['.md', 'mkdn', '.mdown', '.markdown'],
921 }
922 }
922
923
923 def __init__(self, default_renderer=None):
924 def __init__(self, default_renderer=None):
924 self._default_renderer = default_renderer
925 self._default_renderer = default_renderer
925 self._renderer_extensions = self.RENDERER_TO_EXTENSION.get(
926 self._renderer_extensions = self.RENDERER_TO_EXTENSION.get(
926 default_renderer, [])
927 default_renderer, [])
927
928
928 def search(self, commit, path='/'):
929 def search(self, commit, path='/'):
929 """
930 """
930 Find a readme in the given `commit`.
931 Find a readme in the given `commit`.
931 """
932 """
932 nodes = commit.get_nodes(path)
933 nodes = commit.get_nodes(path)
933 matches = self._match_readmes(nodes)
934 matches = self._match_readmes(nodes)
934 matches = self._sort_according_to_priority(matches)
935 matches = self._sort_according_to_priority(matches)
935 if matches:
936 if matches:
936 return matches[0].node
937 return matches[0].node
937
938
938 paths = self._match_paths(nodes)
939 paths = self._match_paths(nodes)
939 paths = self._sort_paths_according_to_priority(paths)
940 paths = self._sort_paths_according_to_priority(paths)
940 for path in paths:
941 for path in paths:
941 match = self.search(commit, path=path)
942 match = self.search(commit, path=path)
942 if match:
943 if match:
943 return match
944 return match
944
945
945 return None
946 return None
946
947
947 def _match_readmes(self, nodes):
948 def _match_readmes(self, nodes):
948 for node in nodes:
949 for node in nodes:
949 if not node.is_file():
950 if not node.is_file():
950 continue
951 continue
951 path = node.path.rsplit('/', 1)[-1]
952 path = node.path.rsplit('/', 1)[-1]
952 match = self.readme_re.match(path)
953 match = self.readme_re.match(path)
953 if match:
954 if match:
954 extension = match.group(1)
955 extension = match.group(1)
955 yield ReadmeMatch(node, match, self._priority(extension))
956 yield ReadmeMatch(node, match, self._priority(extension))
956
957
957 def _match_paths(self, nodes):
958 def _match_paths(self, nodes):
958 for node in nodes:
959 for node in nodes:
959 if not node.is_dir():
960 if not node.is_dir():
960 continue
961 continue
961 match = self.path_re.match(node.path)
962 match = self.path_re.match(node.path)
962 if match:
963 if match:
963 yield node.path
964 yield node.path
964
965
965 def _priority(self, extension):
966 def _priority(self, extension):
966 renderer_priority = (
967 renderer_priority = (
967 0 if extension in self._renderer_extensions else 1)
968 0 if extension in self._renderer_extensions else 1)
968 extension_priority = self.default_priorities.get(
969 extension_priority = self.default_priorities.get(
969 extension, self.FALLBACK_PRIORITY)
970 extension, self.FALLBACK_PRIORITY)
970 return (renderer_priority, extension_priority)
971 return (renderer_priority, extension_priority)
971
972
972 def _sort_according_to_priority(self, matches):
973 def _sort_according_to_priority(self, matches):
973
974
974 def priority_and_path(match):
975 def priority_and_path(match):
975 return (match.priority, match.path)
976 return (match.priority, match.path)
976
977
977 return sorted(matches, key=priority_and_path)
978 return sorted(matches, key=priority_and_path)
978
979
979 def _sort_paths_according_to_priority(self, paths):
980 def _sort_paths_according_to_priority(self, paths):
980
981
981 def priority_and_path(path):
982 def priority_and_path(path):
982 return (self.path_priority.get(path, self.FALLBACK_PRIORITY), path)
983 return (self.path_priority.get(path, self.FALLBACK_PRIORITY), path)
983
984
984 return sorted(paths, key=priority_and_path)
985 return sorted(paths, key=priority_and_path)
985
986
986
987
987 class ReadmeMatch:
988 class ReadmeMatch:
988
989
989 def __init__(self, node, match, priority):
990 def __init__(self, node, match, priority):
990 self.node = node
991 self.node = node
991 self._match = match
992 self._match = match
992 self.priority = priority
993 self.priority = priority
993
994
994 @property
995 @property
995 def path(self):
996 def path(self):
996 return self.node.path
997 return self.node.path
997
998
998 def __repr__(self):
999 def __repr__(self):
999 return '<ReadmeMatch {} priority={}'.format(self.path, self.priority)
1000 return '<ReadmeMatch {} priority={}'.format(self.path, self.priority)
@@ -1,711 +1,712 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2011-2017 RhodeCode GmbH
3 # Copyright (C) 2011-2017 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21
21
22 """
22 """
23 repo group model for RhodeCode
23 repo group model for RhodeCode
24 """
24 """
25
25
26 import os
26 import os
27 import datetime
27 import datetime
28 import itertools
28 import itertools
29 import logging
29 import logging
30 import shutil
30 import shutil
31 import traceback
31 import traceback
32 import string
32 import string
33
33
34 from zope.cachedescriptors.property import Lazy as LazyProperty
34 from zope.cachedescriptors.property import Lazy as LazyProperty
35
35
36 from rhodecode import events
36 from rhodecode import events
37 from rhodecode.model import BaseModel
37 from rhodecode.model import BaseModel
38 from rhodecode.model.db import (
38 from rhodecode.model.db import (_hash_key,
39 RepoGroup, UserRepoGroupToPerm, User, Permission, UserGroupRepoGroupToPerm,
39 RepoGroup, UserRepoGroupToPerm, User, Permission, UserGroupRepoGroupToPerm,
40 UserGroup, Repository)
40 UserGroup, Repository)
41 from rhodecode.model.settings import VcsSettingsModel, SettingsModel
41 from rhodecode.model.settings import VcsSettingsModel, SettingsModel
42 from rhodecode.lib.caching_query import FromCache
42 from rhodecode.lib.caching_query import FromCache
43 from rhodecode.lib.utils2 import action_logger_generic
43 from rhodecode.lib.utils2 import action_logger_generic
44
44
45 log = logging.getLogger(__name__)
45 log = logging.getLogger(__name__)
46
46
47
47
48 class RepoGroupModel(BaseModel):
48 class RepoGroupModel(BaseModel):
49
49
50 cls = RepoGroup
50 cls = RepoGroup
51 PERSONAL_GROUP_DESC = 'personal repo group of user `%(username)s`'
51 PERSONAL_GROUP_DESC = 'personal repo group of user `%(username)s`'
52 PERSONAL_GROUP_PATTERN = '${username}' # default
52 PERSONAL_GROUP_PATTERN = '${username}' # default
53
53
54 def _get_user_group(self, users_group):
54 def _get_user_group(self, users_group):
55 return self._get_instance(UserGroup, users_group,
55 return self._get_instance(UserGroup, users_group,
56 callback=UserGroup.get_by_group_name)
56 callback=UserGroup.get_by_group_name)
57
57
58 def _get_repo_group(self, repo_group):
58 def _get_repo_group(self, repo_group):
59 return self._get_instance(RepoGroup, repo_group,
59 return self._get_instance(RepoGroup, repo_group,
60 callback=RepoGroup.get_by_group_name)
60 callback=RepoGroup.get_by_group_name)
61
61
62 @LazyProperty
62 @LazyProperty
63 def repos_path(self):
63 def repos_path(self):
64 """
64 """
65 Gets the repositories root path from database
65 Gets the repositories root path from database
66 """
66 """
67
67
68 settings_model = VcsSettingsModel(sa=self.sa)
68 settings_model = VcsSettingsModel(sa=self.sa)
69 return settings_model.get_repos_location()
69 return settings_model.get_repos_location()
70
70
71 def get_by_group_name(self, repo_group_name, cache=None):
71 def get_by_group_name(self, repo_group_name, cache=None):
72 repo = self.sa.query(RepoGroup) \
72 repo = self.sa.query(RepoGroup) \
73 .filter(RepoGroup.group_name == repo_group_name)
73 .filter(RepoGroup.group_name == repo_group_name)
74
74
75 if cache:
75 if cache:
76 repo = repo.options(FromCache(
76 name_key = _hash_key(repo_group_name)
77 "sql_cache_short", "get_repo_group_%s" % repo_group_name))
77 repo = repo.options(
78 FromCache("sql_cache_short", "get_repo_group_%s" % name_key))
78 return repo.scalar()
79 return repo.scalar()
79
80
80 def get_default_create_personal_repo_group(self):
81 def get_default_create_personal_repo_group(self):
81 value = SettingsModel().get_setting_by_name(
82 value = SettingsModel().get_setting_by_name(
82 'create_personal_repo_group')
83 'create_personal_repo_group')
83 return value.app_settings_value if value else None or False
84 return value.app_settings_value if value else None or False
84
85
85 def get_personal_group_name_pattern(self):
86 def get_personal_group_name_pattern(self):
86 value = SettingsModel().get_setting_by_name(
87 value = SettingsModel().get_setting_by_name(
87 'personal_repo_group_pattern')
88 'personal_repo_group_pattern')
88 val = value.app_settings_value if value else None
89 val = value.app_settings_value if value else None
89 group_template = val or self.PERSONAL_GROUP_PATTERN
90 group_template = val or self.PERSONAL_GROUP_PATTERN
90
91
91 group_template = group_template.lstrip('/')
92 group_template = group_template.lstrip('/')
92 return group_template
93 return group_template
93
94
94 def get_personal_group_name(self, user):
95 def get_personal_group_name(self, user):
95 template = self.get_personal_group_name_pattern()
96 template = self.get_personal_group_name_pattern()
96 return string.Template(template).safe_substitute(
97 return string.Template(template).safe_substitute(
97 username=user.username,
98 username=user.username,
98 user_id=user.user_id,
99 user_id=user.user_id,
99 )
100 )
100
101
101 def create_personal_repo_group(self, user, commit_early=True):
102 def create_personal_repo_group(self, user, commit_early=True):
102 desc = self.PERSONAL_GROUP_DESC % {'username': user.username}
103 desc = self.PERSONAL_GROUP_DESC % {'username': user.username}
103 personal_repo_group_name = self.get_personal_group_name(user)
104 personal_repo_group_name = self.get_personal_group_name(user)
104
105
105 # create a new one
106 # create a new one
106 RepoGroupModel().create(
107 RepoGroupModel().create(
107 group_name=personal_repo_group_name,
108 group_name=personal_repo_group_name,
108 group_description=desc,
109 group_description=desc,
109 owner=user.username,
110 owner=user.username,
110 personal=True,
111 personal=True,
111 commit_early=commit_early)
112 commit_early=commit_early)
112
113
113 def _create_default_perms(self, new_group):
114 def _create_default_perms(self, new_group):
114 # create default permission
115 # create default permission
115 default_perm = 'group.read'
116 default_perm = 'group.read'
116 def_user = User.get_default_user()
117 def_user = User.get_default_user()
117 for p in def_user.user_perms:
118 for p in def_user.user_perms:
118 if p.permission.permission_name.startswith('group.'):
119 if p.permission.permission_name.startswith('group.'):
119 default_perm = p.permission.permission_name
120 default_perm = p.permission.permission_name
120 break
121 break
121
122
122 repo_group_to_perm = UserRepoGroupToPerm()
123 repo_group_to_perm = UserRepoGroupToPerm()
123 repo_group_to_perm.permission = Permission.get_by_key(default_perm)
124 repo_group_to_perm.permission = Permission.get_by_key(default_perm)
124
125
125 repo_group_to_perm.group = new_group
126 repo_group_to_perm.group = new_group
126 repo_group_to_perm.user_id = def_user.user_id
127 repo_group_to_perm.user_id = def_user.user_id
127 return repo_group_to_perm
128 return repo_group_to_perm
128
129
129 def _get_group_name_and_parent(self, group_name_full, repo_in_path=False,
130 def _get_group_name_and_parent(self, group_name_full, repo_in_path=False,
130 get_object=False):
131 get_object=False):
131 """
132 """
132 Get's the group name and a parent group name from given group name.
133 Get's the group name and a parent group name from given group name.
133 If repo_in_path is set to truth, we asume the full path also includes
134 If repo_in_path is set to truth, we asume the full path also includes
134 repo name, in such case we clean the last element.
135 repo name, in such case we clean the last element.
135
136
136 :param group_name_full:
137 :param group_name_full:
137 """
138 """
138 split_paths = 1
139 split_paths = 1
139 if repo_in_path:
140 if repo_in_path:
140 split_paths = 2
141 split_paths = 2
141 _parts = group_name_full.rsplit(RepoGroup.url_sep(), split_paths)
142 _parts = group_name_full.rsplit(RepoGroup.url_sep(), split_paths)
142
143
143 if repo_in_path and len(_parts) > 1:
144 if repo_in_path and len(_parts) > 1:
144 # such case last element is the repo_name
145 # such case last element is the repo_name
145 _parts.pop(-1)
146 _parts.pop(-1)
146 group_name_cleaned = _parts[-1] # just the group name
147 group_name_cleaned = _parts[-1] # just the group name
147 parent_repo_group_name = None
148 parent_repo_group_name = None
148
149
149 if len(_parts) > 1:
150 if len(_parts) > 1:
150 parent_repo_group_name = _parts[0]
151 parent_repo_group_name = _parts[0]
151
152
152 parent_group = None
153 parent_group = None
153 if parent_repo_group_name:
154 if parent_repo_group_name:
154 parent_group = RepoGroup.get_by_group_name(parent_repo_group_name)
155 parent_group = RepoGroup.get_by_group_name(parent_repo_group_name)
155
156
156 if get_object:
157 if get_object:
157 return group_name_cleaned, parent_repo_group_name, parent_group
158 return group_name_cleaned, parent_repo_group_name, parent_group
158
159
159 return group_name_cleaned, parent_repo_group_name
160 return group_name_cleaned, parent_repo_group_name
160
161
161 def check_exist_filesystem(self, group_name, exc_on_failure=True):
162 def check_exist_filesystem(self, group_name, exc_on_failure=True):
162 create_path = os.path.join(self.repos_path, group_name)
163 create_path = os.path.join(self.repos_path, group_name)
163 log.debug('creating new group in %s', create_path)
164 log.debug('creating new group in %s', create_path)
164
165
165 if os.path.isdir(create_path):
166 if os.path.isdir(create_path):
166 if exc_on_failure:
167 if exc_on_failure:
167 abs_create_path = os.path.abspath(create_path)
168 abs_create_path = os.path.abspath(create_path)
168 raise Exception('Directory `{}` already exists !'.format(abs_create_path))
169 raise Exception('Directory `{}` already exists !'.format(abs_create_path))
169 return False
170 return False
170 return True
171 return True
171
172
172 def _create_group(self, group_name):
173 def _create_group(self, group_name):
173 """
174 """
174 makes repository group on filesystem
175 makes repository group on filesystem
175
176
176 :param repo_name:
177 :param repo_name:
177 :param parent_id:
178 :param parent_id:
178 """
179 """
179
180
180 self.check_exist_filesystem(group_name)
181 self.check_exist_filesystem(group_name)
181 create_path = os.path.join(self.repos_path, group_name)
182 create_path = os.path.join(self.repos_path, group_name)
182 log.debug('creating new group in %s', create_path)
183 log.debug('creating new group in %s', create_path)
183 os.makedirs(create_path, mode=0755)
184 os.makedirs(create_path, mode=0755)
184 log.debug('created group in %s', create_path)
185 log.debug('created group in %s', create_path)
185
186
186 def _rename_group(self, old, new):
187 def _rename_group(self, old, new):
187 """
188 """
188 Renames a group on filesystem
189 Renames a group on filesystem
189
190
190 :param group_name:
191 :param group_name:
191 """
192 """
192
193
193 if old == new:
194 if old == new:
194 log.debug('skipping group rename')
195 log.debug('skipping group rename')
195 return
196 return
196
197
197 log.debug('renaming repository group from %s to %s', old, new)
198 log.debug('renaming repository group from %s to %s', old, new)
198
199
199 old_path = os.path.join(self.repos_path, old)
200 old_path = os.path.join(self.repos_path, old)
200 new_path = os.path.join(self.repos_path, new)
201 new_path = os.path.join(self.repos_path, new)
201
202
202 log.debug('renaming repos paths from %s to %s', old_path, new_path)
203 log.debug('renaming repos paths from %s to %s', old_path, new_path)
203
204
204 if os.path.isdir(new_path):
205 if os.path.isdir(new_path):
205 raise Exception('Was trying to rename to already '
206 raise Exception('Was trying to rename to already '
206 'existing dir %s' % new_path)
207 'existing dir %s' % new_path)
207 shutil.move(old_path, new_path)
208 shutil.move(old_path, new_path)
208
209
209 def _delete_filesystem_group(self, group, force_delete=False):
210 def _delete_filesystem_group(self, group, force_delete=False):
210 """
211 """
211 Deletes a group from a filesystem
212 Deletes a group from a filesystem
212
213
213 :param group: instance of group from database
214 :param group: instance of group from database
214 :param force_delete: use shutil rmtree to remove all objects
215 :param force_delete: use shutil rmtree to remove all objects
215 """
216 """
216 paths = group.full_path.split(RepoGroup.url_sep())
217 paths = group.full_path.split(RepoGroup.url_sep())
217 paths = os.sep.join(paths)
218 paths = os.sep.join(paths)
218
219
219 rm_path = os.path.join(self.repos_path, paths)
220 rm_path = os.path.join(self.repos_path, paths)
220 log.info("Removing group %s", rm_path)
221 log.info("Removing group %s", rm_path)
221 # delete only if that path really exists
222 # delete only if that path really exists
222 if os.path.isdir(rm_path):
223 if os.path.isdir(rm_path):
223 if force_delete:
224 if force_delete:
224 shutil.rmtree(rm_path)
225 shutil.rmtree(rm_path)
225 else:
226 else:
226 # archive that group`
227 # archive that group`
227 _now = datetime.datetime.now()
228 _now = datetime.datetime.now()
228 _ms = str(_now.microsecond).rjust(6, '0')
229 _ms = str(_now.microsecond).rjust(6, '0')
229 _d = 'rm__%s_GROUP_%s' % (
230 _d = 'rm__%s_GROUP_%s' % (
230 _now.strftime('%Y%m%d_%H%M%S_' + _ms), group.name)
231 _now.strftime('%Y%m%d_%H%M%S_' + _ms), group.name)
231 shutil.move(rm_path, os.path.join(self.repos_path, _d))
232 shutil.move(rm_path, os.path.join(self.repos_path, _d))
232
233
233 def create(self, group_name, group_description, owner, just_db=False,
234 def create(self, group_name, group_description, owner, just_db=False,
234 copy_permissions=False, personal=None, commit_early=True):
235 copy_permissions=False, personal=None, commit_early=True):
235
236
236 (group_name_cleaned,
237 (group_name_cleaned,
237 parent_group_name) = RepoGroupModel()._get_group_name_and_parent(group_name)
238 parent_group_name) = RepoGroupModel()._get_group_name_and_parent(group_name)
238
239
239 parent_group = None
240 parent_group = None
240 if parent_group_name:
241 if parent_group_name:
241 parent_group = self._get_repo_group(parent_group_name)
242 parent_group = self._get_repo_group(parent_group_name)
242 if not parent_group:
243 if not parent_group:
243 # we tried to create a nested group, but the parent is not
244 # we tried to create a nested group, but the parent is not
244 # existing
245 # existing
245 raise ValueError(
246 raise ValueError(
246 'Parent group `%s` given in `%s` group name '
247 'Parent group `%s` given in `%s` group name '
247 'is not yet existing.' % (parent_group_name, group_name))
248 'is not yet existing.' % (parent_group_name, group_name))
248
249
249 # because we are doing a cleanup, we need to check if such directory
250 # because we are doing a cleanup, we need to check if such directory
250 # already exists. If we don't do that we can accidentally delete
251 # already exists. If we don't do that we can accidentally delete
251 # existing directory via cleanup that can cause data issues, since
252 # existing directory via cleanup that can cause data issues, since
252 # delete does a folder rename to special syntax later cleanup
253 # delete does a folder rename to special syntax later cleanup
253 # functions can delete this
254 # functions can delete this
254 cleanup_group = self.check_exist_filesystem(group_name,
255 cleanup_group = self.check_exist_filesystem(group_name,
255 exc_on_failure=False)
256 exc_on_failure=False)
256 try:
257 try:
257 user = self._get_user(owner)
258 user = self._get_user(owner)
258 new_repo_group = RepoGroup()
259 new_repo_group = RepoGroup()
259 new_repo_group.user = user
260 new_repo_group.user = user
260 new_repo_group.group_description = group_description or group_name
261 new_repo_group.group_description = group_description or group_name
261 new_repo_group.parent_group = parent_group
262 new_repo_group.parent_group = parent_group
262 new_repo_group.group_name = group_name
263 new_repo_group.group_name = group_name
263 new_repo_group.personal = personal
264 new_repo_group.personal = personal
264
265
265 self.sa.add(new_repo_group)
266 self.sa.add(new_repo_group)
266
267
267 # create an ADMIN permission for owner except if we're super admin,
268 # create an ADMIN permission for owner except if we're super admin,
268 # later owner should go into the owner field of groups
269 # later owner should go into the owner field of groups
269 if not user.is_admin:
270 if not user.is_admin:
270 self.grant_user_permission(repo_group=new_repo_group,
271 self.grant_user_permission(repo_group=new_repo_group,
271 user=owner, perm='group.admin')
272 user=owner, perm='group.admin')
272
273
273 if parent_group and copy_permissions:
274 if parent_group and copy_permissions:
274 # copy permissions from parent
275 # copy permissions from parent
275 user_perms = UserRepoGroupToPerm.query() \
276 user_perms = UserRepoGroupToPerm.query() \
276 .filter(UserRepoGroupToPerm.group == parent_group).all()
277 .filter(UserRepoGroupToPerm.group == parent_group).all()
277
278
278 group_perms = UserGroupRepoGroupToPerm.query() \
279 group_perms = UserGroupRepoGroupToPerm.query() \
279 .filter(UserGroupRepoGroupToPerm.group == parent_group).all()
280 .filter(UserGroupRepoGroupToPerm.group == parent_group).all()
280
281
281 for perm in user_perms:
282 for perm in user_perms:
282 # don't copy over the permission for user who is creating
283 # don't copy over the permission for user who is creating
283 # this group, if he is not super admin he get's admin
284 # this group, if he is not super admin he get's admin
284 # permission set above
285 # permission set above
285 if perm.user != user or user.is_admin:
286 if perm.user != user or user.is_admin:
286 UserRepoGroupToPerm.create(
287 UserRepoGroupToPerm.create(
287 perm.user, new_repo_group, perm.permission)
288 perm.user, new_repo_group, perm.permission)
288
289
289 for perm in group_perms:
290 for perm in group_perms:
290 UserGroupRepoGroupToPerm.create(
291 UserGroupRepoGroupToPerm.create(
291 perm.users_group, new_repo_group, perm.permission)
292 perm.users_group, new_repo_group, perm.permission)
292 else:
293 else:
293 perm_obj = self._create_default_perms(new_repo_group)
294 perm_obj = self._create_default_perms(new_repo_group)
294 self.sa.add(perm_obj)
295 self.sa.add(perm_obj)
295
296
296 # now commit the changes, earlier so we are sure everything is in
297 # now commit the changes, earlier so we are sure everything is in
297 # the database.
298 # the database.
298 if commit_early:
299 if commit_early:
299 self.sa.commit()
300 self.sa.commit()
300 if not just_db:
301 if not just_db:
301 self._create_group(new_repo_group.group_name)
302 self._create_group(new_repo_group.group_name)
302
303
303 # trigger the post hook
304 # trigger the post hook
304 from rhodecode.lib.hooks_base import log_create_repository_group
305 from rhodecode.lib.hooks_base import log_create_repository_group
305 repo_group = RepoGroup.get_by_group_name(group_name)
306 repo_group = RepoGroup.get_by_group_name(group_name)
306 log_create_repository_group(
307 log_create_repository_group(
307 created_by=user.username, **repo_group.get_dict())
308 created_by=user.username, **repo_group.get_dict())
308
309
309 # Trigger create event.
310 # Trigger create event.
310 events.trigger(events.RepoGroupCreateEvent(repo_group))
311 events.trigger(events.RepoGroupCreateEvent(repo_group))
311
312
312 return new_repo_group
313 return new_repo_group
313 except Exception:
314 except Exception:
314 self.sa.rollback()
315 self.sa.rollback()
315 log.exception('Exception occurred when creating repository group, '
316 log.exception('Exception occurred when creating repository group, '
316 'doing cleanup...')
317 'doing cleanup...')
317 # rollback things manually !
318 # rollback things manually !
318 repo_group = RepoGroup.get_by_group_name(group_name)
319 repo_group = RepoGroup.get_by_group_name(group_name)
319 if repo_group:
320 if repo_group:
320 RepoGroup.delete(repo_group.group_id)
321 RepoGroup.delete(repo_group.group_id)
321 self.sa.commit()
322 self.sa.commit()
322 if cleanup_group:
323 if cleanup_group:
323 RepoGroupModel()._delete_filesystem_group(repo_group)
324 RepoGroupModel()._delete_filesystem_group(repo_group)
324 raise
325 raise
325
326
326 def update_permissions(
327 def update_permissions(
327 self, repo_group, perm_additions=None, perm_updates=None,
328 self, repo_group, perm_additions=None, perm_updates=None,
328 perm_deletions=None, recursive=None, check_perms=True,
329 perm_deletions=None, recursive=None, check_perms=True,
329 cur_user=None):
330 cur_user=None):
330 from rhodecode.model.repo import RepoModel
331 from rhodecode.model.repo import RepoModel
331 from rhodecode.lib.auth import HasUserGroupPermissionAny
332 from rhodecode.lib.auth import HasUserGroupPermissionAny
332
333
333 if not perm_additions:
334 if not perm_additions:
334 perm_additions = []
335 perm_additions = []
335 if not perm_updates:
336 if not perm_updates:
336 perm_updates = []
337 perm_updates = []
337 if not perm_deletions:
338 if not perm_deletions:
338 perm_deletions = []
339 perm_deletions = []
339
340
340 req_perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin')
341 req_perms = ('usergroup.read', 'usergroup.write', 'usergroup.admin')
341
342
342 def _set_perm_user(obj, user, perm):
343 def _set_perm_user(obj, user, perm):
343 if isinstance(obj, RepoGroup):
344 if isinstance(obj, RepoGroup):
344 self.grant_user_permission(
345 self.grant_user_permission(
345 repo_group=obj, user=user, perm=perm)
346 repo_group=obj, user=user, perm=perm)
346 elif isinstance(obj, Repository):
347 elif isinstance(obj, Repository):
347 # private repos will not allow to change the default
348 # private repos will not allow to change the default
348 # permissions using recursive mode
349 # permissions using recursive mode
349 if obj.private and user == User.DEFAULT_USER:
350 if obj.private and user == User.DEFAULT_USER:
350 return
351 return
351
352
352 # we set group permission but we have to switch to repo
353 # we set group permission but we have to switch to repo
353 # permission
354 # permission
354 perm = perm.replace('group.', 'repository.')
355 perm = perm.replace('group.', 'repository.')
355 RepoModel().grant_user_permission(
356 RepoModel().grant_user_permission(
356 repo=obj, user=user, perm=perm)
357 repo=obj, user=user, perm=perm)
357
358
358 def _set_perm_group(obj, users_group, perm):
359 def _set_perm_group(obj, users_group, perm):
359 if isinstance(obj, RepoGroup):
360 if isinstance(obj, RepoGroup):
360 self.grant_user_group_permission(
361 self.grant_user_group_permission(
361 repo_group=obj, group_name=users_group, perm=perm)
362 repo_group=obj, group_name=users_group, perm=perm)
362 elif isinstance(obj, Repository):
363 elif isinstance(obj, Repository):
363 # we set group permission but we have to switch to repo
364 # we set group permission but we have to switch to repo
364 # permission
365 # permission
365 perm = perm.replace('group.', 'repository.')
366 perm = perm.replace('group.', 'repository.')
366 RepoModel().grant_user_group_permission(
367 RepoModel().grant_user_group_permission(
367 repo=obj, group_name=users_group, perm=perm)
368 repo=obj, group_name=users_group, perm=perm)
368
369
369 def _revoke_perm_user(obj, user):
370 def _revoke_perm_user(obj, user):
370 if isinstance(obj, RepoGroup):
371 if isinstance(obj, RepoGroup):
371 self.revoke_user_permission(repo_group=obj, user=user)
372 self.revoke_user_permission(repo_group=obj, user=user)
372 elif isinstance(obj, Repository):
373 elif isinstance(obj, Repository):
373 RepoModel().revoke_user_permission(repo=obj, user=user)
374 RepoModel().revoke_user_permission(repo=obj, user=user)
374
375
375 def _revoke_perm_group(obj, user_group):
376 def _revoke_perm_group(obj, user_group):
376 if isinstance(obj, RepoGroup):
377 if isinstance(obj, RepoGroup):
377 self.revoke_user_group_permission(
378 self.revoke_user_group_permission(
378 repo_group=obj, group_name=user_group)
379 repo_group=obj, group_name=user_group)
379 elif isinstance(obj, Repository):
380 elif isinstance(obj, Repository):
380 RepoModel().revoke_user_group_permission(
381 RepoModel().revoke_user_group_permission(
381 repo=obj, group_name=user_group)
382 repo=obj, group_name=user_group)
382
383
383 # start updates
384 # start updates
384 updates = []
385 updates = []
385 log.debug('Now updating permissions for %s in recursive mode:%s',
386 log.debug('Now updating permissions for %s in recursive mode:%s',
386 repo_group, recursive)
387 repo_group, recursive)
387
388
388 # initialize check function, we'll call that multiple times
389 # initialize check function, we'll call that multiple times
389 has_group_perm = HasUserGroupPermissionAny(*req_perms)
390 has_group_perm = HasUserGroupPermissionAny(*req_perms)
390
391
391 for obj in repo_group.recursive_groups_and_repos():
392 for obj in repo_group.recursive_groups_and_repos():
392 # iterated obj is an instance of a repos group or repository in
393 # iterated obj is an instance of a repos group or repository in
393 # that group, recursive option can be: none, repos, groups, all
394 # that group, recursive option can be: none, repos, groups, all
394 if recursive == 'all':
395 if recursive == 'all':
395 obj = obj
396 obj = obj
396 elif recursive == 'repos':
397 elif recursive == 'repos':
397 # skip groups, other than this one
398 # skip groups, other than this one
398 if isinstance(obj, RepoGroup) and not obj == repo_group:
399 if isinstance(obj, RepoGroup) and not obj == repo_group:
399 continue
400 continue
400 elif recursive == 'groups':
401 elif recursive == 'groups':
401 # skip repos
402 # skip repos
402 if isinstance(obj, Repository):
403 if isinstance(obj, Repository):
403 continue
404 continue
404 else: # recursive == 'none':
405 else: # recursive == 'none':
405 # DEFAULT option - don't apply to iterated objects
406 # DEFAULT option - don't apply to iterated objects
406 # also we do a break at the end of this loop. if we are not
407 # also we do a break at the end of this loop. if we are not
407 # in recursive mode
408 # in recursive mode
408 obj = repo_group
409 obj = repo_group
409
410
410 # update permissions
411 # update permissions
411 for member_id, perm, member_type in perm_updates:
412 for member_id, perm, member_type in perm_updates:
412 member_id = int(member_id)
413 member_id = int(member_id)
413 if member_type == 'user':
414 if member_type == 'user':
414 # this updates also current one if found
415 # this updates also current one if found
415 _set_perm_user(obj, user=member_id, perm=perm)
416 _set_perm_user(obj, user=member_id, perm=perm)
416 else: # set for user group
417 else: # set for user group
417 member_name = UserGroup.get(member_id).users_group_name
418 member_name = UserGroup.get(member_id).users_group_name
418 if not check_perms or has_group_perm(member_name,
419 if not check_perms or has_group_perm(member_name,
419 user=cur_user):
420 user=cur_user):
420 _set_perm_group(obj, users_group=member_id, perm=perm)
421 _set_perm_group(obj, users_group=member_id, perm=perm)
421
422
422 # set new permissions
423 # set new permissions
423 for member_id, perm, member_type in perm_additions:
424 for member_id, perm, member_type in perm_additions:
424 member_id = int(member_id)
425 member_id = int(member_id)
425 if member_type == 'user':
426 if member_type == 'user':
426 _set_perm_user(obj, user=member_id, perm=perm)
427 _set_perm_user(obj, user=member_id, perm=perm)
427 else: # set for user group
428 else: # set for user group
428 # check if we have permissions to alter this usergroup
429 # check if we have permissions to alter this usergroup
429 member_name = UserGroup.get(member_id).users_group_name
430 member_name = UserGroup.get(member_id).users_group_name
430 if not check_perms or has_group_perm(member_name,
431 if not check_perms or has_group_perm(member_name,
431 user=cur_user):
432 user=cur_user):
432 _set_perm_group(obj, users_group=member_id, perm=perm)
433 _set_perm_group(obj, users_group=member_id, perm=perm)
433
434
434 # delete permissions
435 # delete permissions
435 for member_id, perm, member_type in perm_deletions:
436 for member_id, perm, member_type in perm_deletions:
436 member_id = int(member_id)
437 member_id = int(member_id)
437 if member_type == 'user':
438 if member_type == 'user':
438 _revoke_perm_user(obj, user=member_id)
439 _revoke_perm_user(obj, user=member_id)
439 else: # set for user group
440 else: # set for user group
440 # check if we have permissions to alter this usergroup
441 # check if we have permissions to alter this usergroup
441 member_name = UserGroup.get(member_id).users_group_name
442 member_name = UserGroup.get(member_id).users_group_name
442 if not check_perms or has_group_perm(member_name,
443 if not check_perms or has_group_perm(member_name,
443 user=cur_user):
444 user=cur_user):
444 _revoke_perm_group(obj, user_group=member_id)
445 _revoke_perm_group(obj, user_group=member_id)
445
446
446 updates.append(obj)
447 updates.append(obj)
447 # if it's not recursive call for all,repos,groups
448 # if it's not recursive call for all,repos,groups
448 # break the loop and don't proceed with other changes
449 # break the loop and don't proceed with other changes
449 if recursive not in ['all', 'repos', 'groups']:
450 if recursive not in ['all', 'repos', 'groups']:
450 break
451 break
451
452
452 return updates
453 return updates
453
454
454 def update(self, repo_group, form_data):
455 def update(self, repo_group, form_data):
455 try:
456 try:
456 repo_group = self._get_repo_group(repo_group)
457 repo_group = self._get_repo_group(repo_group)
457 old_path = repo_group.full_path
458 old_path = repo_group.full_path
458
459
459 # change properties
460 # change properties
460 if 'group_description' in form_data:
461 if 'group_description' in form_data:
461 repo_group.group_description = form_data['group_description']
462 repo_group.group_description = form_data['group_description']
462
463
463 if 'enable_locking' in form_data:
464 if 'enable_locking' in form_data:
464 repo_group.enable_locking = form_data['enable_locking']
465 repo_group.enable_locking = form_data['enable_locking']
465
466
466 if 'group_parent_id' in form_data:
467 if 'group_parent_id' in form_data:
467 parent_group = (
468 parent_group = (
468 self._get_repo_group(form_data['group_parent_id']))
469 self._get_repo_group(form_data['group_parent_id']))
469 repo_group.group_parent_id = (
470 repo_group.group_parent_id = (
470 parent_group.group_id if parent_group else None)
471 parent_group.group_id if parent_group else None)
471 repo_group.parent_group = parent_group
472 repo_group.parent_group = parent_group
472
473
473 # mikhail: to update the full_path, we have to explicitly
474 # mikhail: to update the full_path, we have to explicitly
474 # update group_name
475 # update group_name
475 group_name = form_data.get('group_name', repo_group.name)
476 group_name = form_data.get('group_name', repo_group.name)
476 repo_group.group_name = repo_group.get_new_name(group_name)
477 repo_group.group_name = repo_group.get_new_name(group_name)
477
478
478 new_path = repo_group.full_path
479 new_path = repo_group.full_path
479
480
480 if 'user' in form_data:
481 if 'user' in form_data:
481 repo_group.user = User.get_by_username(form_data['user'])
482 repo_group.user = User.get_by_username(form_data['user'])
482
483
483 self.sa.add(repo_group)
484 self.sa.add(repo_group)
484
485
485 # iterate over all members of this groups and do fixes
486 # iterate over all members of this groups and do fixes
486 # set locking if given
487 # set locking if given
487 # if obj is a repoGroup also fix the name of the group according
488 # if obj is a repoGroup also fix the name of the group according
488 # to the parent
489 # to the parent
489 # if obj is a Repo fix it's name
490 # if obj is a Repo fix it's name
490 # this can be potentially heavy operation
491 # this can be potentially heavy operation
491 for obj in repo_group.recursive_groups_and_repos():
492 for obj in repo_group.recursive_groups_and_repos():
492 # set the value from it's parent
493 # set the value from it's parent
493 obj.enable_locking = repo_group.enable_locking
494 obj.enable_locking = repo_group.enable_locking
494 if isinstance(obj, RepoGroup):
495 if isinstance(obj, RepoGroup):
495 new_name = obj.get_new_name(obj.name)
496 new_name = obj.get_new_name(obj.name)
496 log.debug('Fixing group %s to new name %s',
497 log.debug('Fixing group %s to new name %s',
497 obj.group_name, new_name)
498 obj.group_name, new_name)
498 obj.group_name = new_name
499 obj.group_name = new_name
499 elif isinstance(obj, Repository):
500 elif isinstance(obj, Repository):
500 # we need to get all repositories from this new group and
501 # we need to get all repositories from this new group and
501 # rename them accordingly to new group path
502 # rename them accordingly to new group path
502 new_name = obj.get_new_name(obj.just_name)
503 new_name = obj.get_new_name(obj.just_name)
503 log.debug('Fixing repo %s to new name %s',
504 log.debug('Fixing repo %s to new name %s',
504 obj.repo_name, new_name)
505 obj.repo_name, new_name)
505 obj.repo_name = new_name
506 obj.repo_name = new_name
506 self.sa.add(obj)
507 self.sa.add(obj)
507
508
508 self._rename_group(old_path, new_path)
509 self._rename_group(old_path, new_path)
509
510
510 # Trigger update event.
511 # Trigger update event.
511 events.trigger(events.RepoGroupUpdateEvent(repo_group))
512 events.trigger(events.RepoGroupUpdateEvent(repo_group))
512
513
513 return repo_group
514 return repo_group
514 except Exception:
515 except Exception:
515 log.error(traceback.format_exc())
516 log.error(traceback.format_exc())
516 raise
517 raise
517
518
518 def delete(self, repo_group, force_delete=False, fs_remove=True):
519 def delete(self, repo_group, force_delete=False, fs_remove=True):
519 repo_group = self._get_repo_group(repo_group)
520 repo_group = self._get_repo_group(repo_group)
520 if not repo_group:
521 if not repo_group:
521 return False
522 return False
522 try:
523 try:
523 self.sa.delete(repo_group)
524 self.sa.delete(repo_group)
524 if fs_remove:
525 if fs_remove:
525 self._delete_filesystem_group(repo_group, force_delete)
526 self._delete_filesystem_group(repo_group, force_delete)
526 else:
527 else:
527 log.debug('skipping removal from filesystem')
528 log.debug('skipping removal from filesystem')
528
529
529 # Trigger delete event.
530 # Trigger delete event.
530 events.trigger(events.RepoGroupDeleteEvent(repo_group))
531 events.trigger(events.RepoGroupDeleteEvent(repo_group))
531 return True
532 return True
532
533
533 except Exception:
534 except Exception:
534 log.error('Error removing repo_group %s', repo_group)
535 log.error('Error removing repo_group %s', repo_group)
535 raise
536 raise
536
537
537 def grant_user_permission(self, repo_group, user, perm):
538 def grant_user_permission(self, repo_group, user, perm):
538 """
539 """
539 Grant permission for user on given repository group, or update
540 Grant permission for user on given repository group, or update
540 existing one if found
541 existing one if found
541
542
542 :param repo_group: Instance of RepoGroup, repositories_group_id,
543 :param repo_group: Instance of RepoGroup, repositories_group_id,
543 or repositories_group name
544 or repositories_group name
544 :param user: Instance of User, user_id or username
545 :param user: Instance of User, user_id or username
545 :param perm: Instance of Permission, or permission_name
546 :param perm: Instance of Permission, or permission_name
546 """
547 """
547
548
548 repo_group = self._get_repo_group(repo_group)
549 repo_group = self._get_repo_group(repo_group)
549 user = self._get_user(user)
550 user = self._get_user(user)
550 permission = self._get_perm(perm)
551 permission = self._get_perm(perm)
551
552
552 # check if we have that permission already
553 # check if we have that permission already
553 obj = self.sa.query(UserRepoGroupToPerm)\
554 obj = self.sa.query(UserRepoGroupToPerm)\
554 .filter(UserRepoGroupToPerm.user == user)\
555 .filter(UserRepoGroupToPerm.user == user)\
555 .filter(UserRepoGroupToPerm.group == repo_group)\
556 .filter(UserRepoGroupToPerm.group == repo_group)\
556 .scalar()
557 .scalar()
557 if obj is None:
558 if obj is None:
558 # create new !
559 # create new !
559 obj = UserRepoGroupToPerm()
560 obj = UserRepoGroupToPerm()
560 obj.group = repo_group
561 obj.group = repo_group
561 obj.user = user
562 obj.user = user
562 obj.permission = permission
563 obj.permission = permission
563 self.sa.add(obj)
564 self.sa.add(obj)
564 log.debug('Granted perm %s to %s on %s', perm, user, repo_group)
565 log.debug('Granted perm %s to %s on %s', perm, user, repo_group)
565 action_logger_generic(
566 action_logger_generic(
566 'granted permission: {} to user: {} on repogroup: {}'.format(
567 'granted permission: {} to user: {} on repogroup: {}'.format(
567 perm, user, repo_group), namespace='security.repogroup')
568 perm, user, repo_group), namespace='security.repogroup')
568 return obj
569 return obj
569
570
570 def revoke_user_permission(self, repo_group, user):
571 def revoke_user_permission(self, repo_group, user):
571 """
572 """
572 Revoke permission for user on given repository group
573 Revoke permission for user on given repository group
573
574
574 :param repo_group: Instance of RepoGroup, repositories_group_id,
575 :param repo_group: Instance of RepoGroup, repositories_group_id,
575 or repositories_group name
576 or repositories_group name
576 :param user: Instance of User, user_id or username
577 :param user: Instance of User, user_id or username
577 """
578 """
578
579
579 repo_group = self._get_repo_group(repo_group)
580 repo_group = self._get_repo_group(repo_group)
580 user = self._get_user(user)
581 user = self._get_user(user)
581
582
582 obj = self.sa.query(UserRepoGroupToPerm)\
583 obj = self.sa.query(UserRepoGroupToPerm)\
583 .filter(UserRepoGroupToPerm.user == user)\
584 .filter(UserRepoGroupToPerm.user == user)\
584 .filter(UserRepoGroupToPerm.group == repo_group)\
585 .filter(UserRepoGroupToPerm.group == repo_group)\
585 .scalar()
586 .scalar()
586 if obj:
587 if obj:
587 self.sa.delete(obj)
588 self.sa.delete(obj)
588 log.debug('Revoked perm on %s on %s', repo_group, user)
589 log.debug('Revoked perm on %s on %s', repo_group, user)
589 action_logger_generic(
590 action_logger_generic(
590 'revoked permission from user: {} on repogroup: {}'.format(
591 'revoked permission from user: {} on repogroup: {}'.format(
591 user, repo_group), namespace='security.repogroup')
592 user, repo_group), namespace='security.repogroup')
592
593
593 def grant_user_group_permission(self, repo_group, group_name, perm):
594 def grant_user_group_permission(self, repo_group, group_name, perm):
594 """
595 """
595 Grant permission for user group on given repository group, or update
596 Grant permission for user group on given repository group, or update
596 existing one if found
597 existing one if found
597
598
598 :param repo_group: Instance of RepoGroup, repositories_group_id,
599 :param repo_group: Instance of RepoGroup, repositories_group_id,
599 or repositories_group name
600 or repositories_group name
600 :param group_name: Instance of UserGroup, users_group_id,
601 :param group_name: Instance of UserGroup, users_group_id,
601 or user group name
602 or user group name
602 :param perm: Instance of Permission, or permission_name
603 :param perm: Instance of Permission, or permission_name
603 """
604 """
604 repo_group = self._get_repo_group(repo_group)
605 repo_group = self._get_repo_group(repo_group)
605 group_name = self._get_user_group(group_name)
606 group_name = self._get_user_group(group_name)
606 permission = self._get_perm(perm)
607 permission = self._get_perm(perm)
607
608
608 # check if we have that permission already
609 # check if we have that permission already
609 obj = self.sa.query(UserGroupRepoGroupToPerm)\
610 obj = self.sa.query(UserGroupRepoGroupToPerm)\
610 .filter(UserGroupRepoGroupToPerm.group == repo_group)\
611 .filter(UserGroupRepoGroupToPerm.group == repo_group)\
611 .filter(UserGroupRepoGroupToPerm.users_group == group_name)\
612 .filter(UserGroupRepoGroupToPerm.users_group == group_name)\
612 .scalar()
613 .scalar()
613
614
614 if obj is None:
615 if obj is None:
615 # create new
616 # create new
616 obj = UserGroupRepoGroupToPerm()
617 obj = UserGroupRepoGroupToPerm()
617
618
618 obj.group = repo_group
619 obj.group = repo_group
619 obj.users_group = group_name
620 obj.users_group = group_name
620 obj.permission = permission
621 obj.permission = permission
621 self.sa.add(obj)
622 self.sa.add(obj)
622 log.debug('Granted perm %s to %s on %s', perm, group_name, repo_group)
623 log.debug('Granted perm %s to %s on %s', perm, group_name, repo_group)
623 action_logger_generic(
624 action_logger_generic(
624 'granted permission: {} to usergroup: {} on repogroup: {}'.format(
625 'granted permission: {} to usergroup: {} on repogroup: {}'.format(
625 perm, group_name, repo_group), namespace='security.repogroup')
626 perm, group_name, repo_group), namespace='security.repogroup')
626 return obj
627 return obj
627
628
628 def revoke_user_group_permission(self, repo_group, group_name):
629 def revoke_user_group_permission(self, repo_group, group_name):
629 """
630 """
630 Revoke permission for user group on given repository group
631 Revoke permission for user group on given repository group
631
632
632 :param repo_group: Instance of RepoGroup, repositories_group_id,
633 :param repo_group: Instance of RepoGroup, repositories_group_id,
633 or repositories_group name
634 or repositories_group name
634 :param group_name: Instance of UserGroup, users_group_id,
635 :param group_name: Instance of UserGroup, users_group_id,
635 or user group name
636 or user group name
636 """
637 """
637 repo_group = self._get_repo_group(repo_group)
638 repo_group = self._get_repo_group(repo_group)
638 group_name = self._get_user_group(group_name)
639 group_name = self._get_user_group(group_name)
639
640
640 obj = self.sa.query(UserGroupRepoGroupToPerm)\
641 obj = self.sa.query(UserGroupRepoGroupToPerm)\
641 .filter(UserGroupRepoGroupToPerm.group == repo_group)\
642 .filter(UserGroupRepoGroupToPerm.group == repo_group)\
642 .filter(UserGroupRepoGroupToPerm.users_group == group_name)\
643 .filter(UserGroupRepoGroupToPerm.users_group == group_name)\
643 .scalar()
644 .scalar()
644 if obj:
645 if obj:
645 self.sa.delete(obj)
646 self.sa.delete(obj)
646 log.debug('Revoked perm to %s on %s', repo_group, group_name)
647 log.debug('Revoked perm to %s on %s', repo_group, group_name)
647 action_logger_generic(
648 action_logger_generic(
648 'revoked permission from usergroup: {} on repogroup: {}'.format(
649 'revoked permission from usergroup: {} on repogroup: {}'.format(
649 group_name, repo_group), namespace='security.repogroup')
650 group_name, repo_group), namespace='security.repogroup')
650
651
651 def get_repo_groups_as_dict(self, repo_group_list=None, admin=False,
652 def get_repo_groups_as_dict(self, repo_group_list=None, admin=False,
652 super_user_actions=False):
653 super_user_actions=False):
653
654
654 from rhodecode.lib.utils import PartialRenderer
655 from rhodecode.lib.utils import PartialRenderer
655 _render = PartialRenderer('data_table/_dt_elements.mako')
656 _render = PartialRenderer('data_table/_dt_elements.mako')
656 c = _render.c
657 c = _render.c
657 h = _render.h
658 h = _render.h
658
659
659 def quick_menu(repo_group_name):
660 def quick_menu(repo_group_name):
660 return _render('quick_repo_group_menu', repo_group_name)
661 return _render('quick_repo_group_menu', repo_group_name)
661
662
662 def repo_group_lnk(repo_group_name):
663 def repo_group_lnk(repo_group_name):
663 return _render('repo_group_name', repo_group_name)
664 return _render('repo_group_name', repo_group_name)
664
665
665 def desc(desc, personal):
666 def desc(desc, personal):
666 prefix = h.escaped_stylize(u'[personal] ') if personal else ''
667 prefix = h.escaped_stylize(u'[personal] ') if personal else ''
667
668
668 if c.visual.stylify_metatags:
669 if c.visual.stylify_metatags:
669 desc = h.urlify_text(prefix + h.escaped_stylize(desc))
670 desc = h.urlify_text(prefix + h.escaped_stylize(desc))
670 else:
671 else:
671 desc = h.urlify_text(prefix + h.html_escape(desc))
672 desc = h.urlify_text(prefix + h.html_escape(desc))
672
673
673 return _render('repo_group_desc', desc)
674 return _render('repo_group_desc', desc)
674
675
675 def repo_group_actions(repo_group_id, repo_group_name, gr_count):
676 def repo_group_actions(repo_group_id, repo_group_name, gr_count):
676 return _render(
677 return _render(
677 'repo_group_actions', repo_group_id, repo_group_name, gr_count)
678 'repo_group_actions', repo_group_id, repo_group_name, gr_count)
678
679
679 def repo_group_name(repo_group_name, children_groups):
680 def repo_group_name(repo_group_name, children_groups):
680 return _render("repo_group_name", repo_group_name, children_groups)
681 return _render("repo_group_name", repo_group_name, children_groups)
681
682
682 def user_profile(username):
683 def user_profile(username):
683 return _render('user_profile', username)
684 return _render('user_profile', username)
684
685
685 repo_group_data = []
686 repo_group_data = []
686 for group in repo_group_list:
687 for group in repo_group_list:
687
688
688 row = {
689 row = {
689 "menu": quick_menu(group.group_name),
690 "menu": quick_menu(group.group_name),
690 "name": repo_group_lnk(group.group_name),
691 "name": repo_group_lnk(group.group_name),
691 "name_raw": group.group_name,
692 "name_raw": group.group_name,
692 "desc": desc(group.group_description, group.personal),
693 "desc": desc(group.group_description, group.personal),
693 "top_level_repos": 0,
694 "top_level_repos": 0,
694 "owner": user_profile(group.user.username)
695 "owner": user_profile(group.user.username)
695 }
696 }
696 if admin:
697 if admin:
697 repo_count = group.repositories.count()
698 repo_count = group.repositories.count()
698 children_groups = map(
699 children_groups = map(
699 h.safe_unicode,
700 h.safe_unicode,
700 itertools.chain((g.name for g in group.parents),
701 itertools.chain((g.name for g in group.parents),
701 (x.name for x in [group])))
702 (x.name for x in [group])))
702 row.update({
703 row.update({
703 "action": repo_group_actions(
704 "action": repo_group_actions(
704 group.group_id, group.group_name, repo_count),
705 group.group_id, group.group_name, repo_count),
705 "top_level_repos": repo_count,
706 "top_level_repos": repo_count,
706 "name": repo_group_name(group.group_name, children_groups),
707 "name": repo_group_name(group.group_name, children_groups),
707
708
708 })
709 })
709 repo_group_data.append(row)
710 repo_group_data.append(row)
710
711
711 return repo_group_data
712 return repo_group_data
@@ -1,901 +1,902 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 users model for RhodeCode
22 users model for RhodeCode
23 """
23 """
24
24
25 import logging
25 import logging
26 import traceback
26 import traceback
27
27
28 import datetime
28 import datetime
29 from pylons.i18n.translation import _
29 from pylons.i18n.translation import _
30
30
31 import ipaddress
31 import ipaddress
32 from sqlalchemy.exc import DatabaseError
32 from sqlalchemy.exc import DatabaseError
33 from sqlalchemy.sql.expression import true, false
33 from sqlalchemy.sql.expression import true, false
34
34
35 from rhodecode import events
35 from rhodecode import events
36 from rhodecode.lib.user_log_filter import user_log_filter
36 from rhodecode.lib.user_log_filter import user_log_filter
37 from rhodecode.lib.utils2 import (
37 from rhodecode.lib.utils2 import (
38 safe_unicode, get_current_rhodecode_user, action_logger_generic,
38 safe_unicode, get_current_rhodecode_user, action_logger_generic,
39 AttributeDict, str2bool)
39 AttributeDict, str2bool)
40 from rhodecode.lib.caching_query import FromCache
40 from rhodecode.lib.caching_query import FromCache
41 from rhodecode.model import BaseModel
41 from rhodecode.model import BaseModel
42 from rhodecode.model.auth_token import AuthTokenModel
42 from rhodecode.model.auth_token import AuthTokenModel
43 from rhodecode.model.db import (
43 from rhodecode.model.db import (_hash_key,
44 or_, joinedload, User, UserToPerm, UserEmailMap, UserIpMap, UserLog)
44 or_, joinedload, User, UserToPerm, UserEmailMap, UserIpMap, UserLog)
45 from rhodecode.lib.exceptions import (
45 from rhodecode.lib.exceptions import (
46 DefaultUserException, UserOwnsReposException, UserOwnsRepoGroupsException,
46 DefaultUserException, UserOwnsReposException, UserOwnsRepoGroupsException,
47 UserOwnsUserGroupsException, NotAllowedToCreateUserError)
47 UserOwnsUserGroupsException, NotAllowedToCreateUserError)
48 from rhodecode.model.meta import Session
48 from rhodecode.model.meta import Session
49 from rhodecode.model.repo_group import RepoGroupModel
49 from rhodecode.model.repo_group import RepoGroupModel
50
50
51
51
52 log = logging.getLogger(__name__)
52 log = logging.getLogger(__name__)
53
53
54
54
55 class UserModel(BaseModel):
55 class UserModel(BaseModel):
56 cls = User
56 cls = User
57
57
58 def get(self, user_id, cache=False):
58 def get(self, user_id, cache=False):
59 user = self.sa.query(User)
59 user = self.sa.query(User)
60 if cache:
60 if cache:
61 user = user.options(FromCache("sql_cache_short",
61 user = user.options(
62 "get_user_%s" % user_id))
62 FromCache("sql_cache_short", "get_user_%s" % user_id))
63 return user.get(user_id)
63 return user.get(user_id)
64
64
65 def get_user(self, user):
65 def get_user(self, user):
66 return self._get_user(user)
66 return self._get_user(user)
67
67
68 def _serialize_user(self, user):
68 def _serialize_user(self, user):
69 import rhodecode.lib.helpers as h
69 import rhodecode.lib.helpers as h
70
70
71 return {
71 return {
72 'id': user.user_id,
72 'id': user.user_id,
73 'first_name': user.name,
73 'first_name': user.name,
74 'last_name': user.lastname,
74 'last_name': user.lastname,
75 'username': user.username,
75 'username': user.username,
76 'email': user.email,
76 'email': user.email,
77 'icon_link': h.gravatar_url(user.email, 30),
77 'icon_link': h.gravatar_url(user.email, 30),
78 'value_display': h.person(user),
78 'value_display': h.person(user),
79 'value': user.username,
79 'value': user.username,
80 'value_type': 'user',
80 'value_type': 'user',
81 'active': user.active,
81 'active': user.active,
82 }
82 }
83
83
84 def get_users(self, name_contains=None, limit=20, only_active=True):
84 def get_users(self, name_contains=None, limit=20, only_active=True):
85
85
86 query = self.sa.query(User)
86 query = self.sa.query(User)
87 if only_active:
87 if only_active:
88 query = query.filter(User.active == true())
88 query = query.filter(User.active == true())
89
89
90 if name_contains:
90 if name_contains:
91 ilike_expression = u'%{}%'.format(safe_unicode(name_contains))
91 ilike_expression = u'%{}%'.format(safe_unicode(name_contains))
92 query = query.filter(
92 query = query.filter(
93 or_(
93 or_(
94 User.name.ilike(ilike_expression),
94 User.name.ilike(ilike_expression),
95 User.lastname.ilike(ilike_expression),
95 User.lastname.ilike(ilike_expression),
96 User.username.ilike(ilike_expression)
96 User.username.ilike(ilike_expression)
97 )
97 )
98 )
98 )
99 query = query.limit(limit)
99 query = query.limit(limit)
100 users = query.all()
100 users = query.all()
101
101
102 _users = [
102 _users = [
103 self._serialize_user(user) for user in users
103 self._serialize_user(user) for user in users
104 ]
104 ]
105 return _users
105 return _users
106
106
107 def get_by_username(self, username, cache=False, case_insensitive=False):
107 def get_by_username(self, username, cache=False, case_insensitive=False):
108
108
109 if case_insensitive:
109 if case_insensitive:
110 user = self.sa.query(User).filter(User.username.ilike(username))
110 user = self.sa.query(User).filter(User.username.ilike(username))
111 else:
111 else:
112 user = self.sa.query(User)\
112 user = self.sa.query(User)\
113 .filter(User.username == username)
113 .filter(User.username == username)
114 if cache:
114 if cache:
115 user = user.options(FromCache("sql_cache_short",
115 name_key = _hash_key(username)
116 "get_user_%s" % username))
116 user = user.options(
117 FromCache("sql_cache_short", "get_user_%s" % name_key))
117 return user.scalar()
118 return user.scalar()
118
119
119 def get_by_email(self, email, cache=False, case_insensitive=False):
120 def get_by_email(self, email, cache=False, case_insensitive=False):
120 return User.get_by_email(email, case_insensitive, cache)
121 return User.get_by_email(email, case_insensitive, cache)
121
122
122 def get_by_auth_token(self, auth_token, cache=False):
123 def get_by_auth_token(self, auth_token, cache=False):
123 return User.get_by_auth_token(auth_token, cache)
124 return User.get_by_auth_token(auth_token, cache)
124
125
125 def get_active_user_count(self, cache=False):
126 def get_active_user_count(self, cache=False):
126 return User.query().filter(
127 return User.query().filter(
127 User.active == True).filter(
128 User.active == True).filter(
128 User.username != User.DEFAULT_USER).count()
129 User.username != User.DEFAULT_USER).count()
129
130
130 def create(self, form_data, cur_user=None):
131 def create(self, form_data, cur_user=None):
131 if not cur_user:
132 if not cur_user:
132 cur_user = getattr(get_current_rhodecode_user(), 'username', None)
133 cur_user = getattr(get_current_rhodecode_user(), 'username', None)
133
134
134 user_data = {
135 user_data = {
135 'username': form_data['username'],
136 'username': form_data['username'],
136 'password': form_data['password'],
137 'password': form_data['password'],
137 'email': form_data['email'],
138 'email': form_data['email'],
138 'firstname': form_data['firstname'],
139 'firstname': form_data['firstname'],
139 'lastname': form_data['lastname'],
140 'lastname': form_data['lastname'],
140 'active': form_data['active'],
141 'active': form_data['active'],
141 'extern_type': form_data['extern_type'],
142 'extern_type': form_data['extern_type'],
142 'extern_name': form_data['extern_name'],
143 'extern_name': form_data['extern_name'],
143 'admin': False,
144 'admin': False,
144 'cur_user': cur_user
145 'cur_user': cur_user
145 }
146 }
146
147
147 if 'create_repo_group' in form_data:
148 if 'create_repo_group' in form_data:
148 user_data['create_repo_group'] = str2bool(
149 user_data['create_repo_group'] = str2bool(
149 form_data.get('create_repo_group'))
150 form_data.get('create_repo_group'))
150
151
151 try:
152 try:
152 if form_data.get('password_change'):
153 if form_data.get('password_change'):
153 user_data['force_password_change'] = True
154 user_data['force_password_change'] = True
154 return UserModel().create_or_update(**user_data)
155 return UserModel().create_or_update(**user_data)
155 except Exception:
156 except Exception:
156 log.error(traceback.format_exc())
157 log.error(traceback.format_exc())
157 raise
158 raise
158
159
159 def update_user(self, user, skip_attrs=None, **kwargs):
160 def update_user(self, user, skip_attrs=None, **kwargs):
160 from rhodecode.lib.auth import get_crypt_password
161 from rhodecode.lib.auth import get_crypt_password
161
162
162 user = self._get_user(user)
163 user = self._get_user(user)
163 if user.username == User.DEFAULT_USER:
164 if user.username == User.DEFAULT_USER:
164 raise DefaultUserException(
165 raise DefaultUserException(
165 _("You can't Edit this user since it's"
166 _("You can't Edit this user since it's"
166 " crucial for entire application"))
167 " crucial for entire application"))
167
168
168 # first store only defaults
169 # first store only defaults
169 user_attrs = {
170 user_attrs = {
170 'updating_user_id': user.user_id,
171 'updating_user_id': user.user_id,
171 'username': user.username,
172 'username': user.username,
172 'password': user.password,
173 'password': user.password,
173 'email': user.email,
174 'email': user.email,
174 'firstname': user.name,
175 'firstname': user.name,
175 'lastname': user.lastname,
176 'lastname': user.lastname,
176 'active': user.active,
177 'active': user.active,
177 'admin': user.admin,
178 'admin': user.admin,
178 'extern_name': user.extern_name,
179 'extern_name': user.extern_name,
179 'extern_type': user.extern_type,
180 'extern_type': user.extern_type,
180 'language': user.user_data.get('language')
181 'language': user.user_data.get('language')
181 }
182 }
182
183
183 # in case there's new_password, that comes from form, use it to
184 # in case there's new_password, that comes from form, use it to
184 # store password
185 # store password
185 if kwargs.get('new_password'):
186 if kwargs.get('new_password'):
186 kwargs['password'] = kwargs['new_password']
187 kwargs['password'] = kwargs['new_password']
187
188
188 # cleanups, my_account password change form
189 # cleanups, my_account password change form
189 kwargs.pop('current_password', None)
190 kwargs.pop('current_password', None)
190 kwargs.pop('new_password', None)
191 kwargs.pop('new_password', None)
191
192
192 # cleanups, user edit password change form
193 # cleanups, user edit password change form
193 kwargs.pop('password_confirmation', None)
194 kwargs.pop('password_confirmation', None)
194 kwargs.pop('password_change', None)
195 kwargs.pop('password_change', None)
195
196
196 # create repo group on user creation
197 # create repo group on user creation
197 kwargs.pop('create_repo_group', None)
198 kwargs.pop('create_repo_group', None)
198
199
199 # legacy forms send name, which is the firstname
200 # legacy forms send name, which is the firstname
200 firstname = kwargs.pop('name', None)
201 firstname = kwargs.pop('name', None)
201 if firstname:
202 if firstname:
202 kwargs['firstname'] = firstname
203 kwargs['firstname'] = firstname
203
204
204 for k, v in kwargs.items():
205 for k, v in kwargs.items():
205 # skip if we don't want to update this
206 # skip if we don't want to update this
206 if skip_attrs and k in skip_attrs:
207 if skip_attrs and k in skip_attrs:
207 continue
208 continue
208
209
209 user_attrs[k] = v
210 user_attrs[k] = v
210
211
211 try:
212 try:
212 return self.create_or_update(**user_attrs)
213 return self.create_or_update(**user_attrs)
213 except Exception:
214 except Exception:
214 log.error(traceback.format_exc())
215 log.error(traceback.format_exc())
215 raise
216 raise
216
217
217 def create_or_update(
218 def create_or_update(
218 self, username, password, email, firstname='', lastname='',
219 self, username, password, email, firstname='', lastname='',
219 active=True, admin=False, extern_type=None, extern_name=None,
220 active=True, admin=False, extern_type=None, extern_name=None,
220 cur_user=None, plugin=None, force_password_change=False,
221 cur_user=None, plugin=None, force_password_change=False,
221 allow_to_create_user=True, create_repo_group=None,
222 allow_to_create_user=True, create_repo_group=None,
222 updating_user_id=None, language=None, strict_creation_check=True):
223 updating_user_id=None, language=None, strict_creation_check=True):
223 """
224 """
224 Creates a new instance if not found, or updates current one
225 Creates a new instance if not found, or updates current one
225
226
226 :param username:
227 :param username:
227 :param password:
228 :param password:
228 :param email:
229 :param email:
229 :param firstname:
230 :param firstname:
230 :param lastname:
231 :param lastname:
231 :param active:
232 :param active:
232 :param admin:
233 :param admin:
233 :param extern_type:
234 :param extern_type:
234 :param extern_name:
235 :param extern_name:
235 :param cur_user:
236 :param cur_user:
236 :param plugin: optional plugin this method was called from
237 :param plugin: optional plugin this method was called from
237 :param force_password_change: toggles new or existing user flag
238 :param force_password_change: toggles new or existing user flag
238 for password change
239 for password change
239 :param allow_to_create_user: Defines if the method can actually create
240 :param allow_to_create_user: Defines if the method can actually create
240 new users
241 new users
241 :param create_repo_group: Defines if the method should also
242 :param create_repo_group: Defines if the method should also
242 create an repo group with user name, and owner
243 create an repo group with user name, and owner
243 :param updating_user_id: if we set it up this is the user we want to
244 :param updating_user_id: if we set it up this is the user we want to
244 update this allows to editing username.
245 update this allows to editing username.
245 :param language: language of user from interface.
246 :param language: language of user from interface.
246
247
247 :returns: new User object with injected `is_new_user` attribute.
248 :returns: new User object with injected `is_new_user` attribute.
248 """
249 """
249 if not cur_user:
250 if not cur_user:
250 cur_user = getattr(get_current_rhodecode_user(), 'username', None)
251 cur_user = getattr(get_current_rhodecode_user(), 'username', None)
251
252
252 from rhodecode.lib.auth import (
253 from rhodecode.lib.auth import (
253 get_crypt_password, check_password, generate_auth_token)
254 get_crypt_password, check_password, generate_auth_token)
254 from rhodecode.lib.hooks_base import (
255 from rhodecode.lib.hooks_base import (
255 log_create_user, check_allowed_create_user)
256 log_create_user, check_allowed_create_user)
256
257
257 def _password_change(new_user, password):
258 def _password_change(new_user, password):
258 # empty password
259 # empty password
259 if not new_user.password:
260 if not new_user.password:
260 return False
261 return False
261
262
262 # password check is only needed for RhodeCode internal auth calls
263 # password check is only needed for RhodeCode internal auth calls
263 # in case it's a plugin we don't care
264 # in case it's a plugin we don't care
264 if not plugin:
265 if not plugin:
265
266
266 # first check if we gave crypted password back, and if it
267 # first check if we gave crypted password back, and if it
267 # matches it's not password change
268 # matches it's not password change
268 if new_user.password == password:
269 if new_user.password == password:
269 return False
270 return False
270
271
271 password_match = check_password(password, new_user.password)
272 password_match = check_password(password, new_user.password)
272 if not password_match:
273 if not password_match:
273 return True
274 return True
274
275
275 return False
276 return False
276
277
277 # read settings on default personal repo group creation
278 # read settings on default personal repo group creation
278 if create_repo_group is None:
279 if create_repo_group is None:
279 default_create_repo_group = RepoGroupModel()\
280 default_create_repo_group = RepoGroupModel()\
280 .get_default_create_personal_repo_group()
281 .get_default_create_personal_repo_group()
281 create_repo_group = default_create_repo_group
282 create_repo_group = default_create_repo_group
282
283
283 user_data = {
284 user_data = {
284 'username': username,
285 'username': username,
285 'password': password,
286 'password': password,
286 'email': email,
287 'email': email,
287 'firstname': firstname,
288 'firstname': firstname,
288 'lastname': lastname,
289 'lastname': lastname,
289 'active': active,
290 'active': active,
290 'admin': admin
291 'admin': admin
291 }
292 }
292
293
293 if updating_user_id:
294 if updating_user_id:
294 log.debug('Checking for existing account in RhodeCode '
295 log.debug('Checking for existing account in RhodeCode '
295 'database with user_id `%s` ' % (updating_user_id,))
296 'database with user_id `%s` ' % (updating_user_id,))
296 user = User.get(updating_user_id)
297 user = User.get(updating_user_id)
297 else:
298 else:
298 log.debug('Checking for existing account in RhodeCode '
299 log.debug('Checking for existing account in RhodeCode '
299 'database with username `%s` ' % (username,))
300 'database with username `%s` ' % (username,))
300 user = User.get_by_username(username, case_insensitive=True)
301 user = User.get_by_username(username, case_insensitive=True)
301
302
302 if user is None:
303 if user is None:
303 # we check internal flag if this method is actually allowed to
304 # we check internal flag if this method is actually allowed to
304 # create new user
305 # create new user
305 if not allow_to_create_user:
306 if not allow_to_create_user:
306 msg = ('Method wants to create new user, but it is not '
307 msg = ('Method wants to create new user, but it is not '
307 'allowed to do so')
308 'allowed to do so')
308 log.warning(msg)
309 log.warning(msg)
309 raise NotAllowedToCreateUserError(msg)
310 raise NotAllowedToCreateUserError(msg)
310
311
311 log.debug('Creating new user %s', username)
312 log.debug('Creating new user %s', username)
312
313
313 # only if we create user that is active
314 # only if we create user that is active
314 new_active_user = active
315 new_active_user = active
315 if new_active_user and strict_creation_check:
316 if new_active_user and strict_creation_check:
316 # raises UserCreationError if it's not allowed for any reason to
317 # raises UserCreationError if it's not allowed for any reason to
317 # create new active user, this also executes pre-create hooks
318 # create new active user, this also executes pre-create hooks
318 check_allowed_create_user(user_data, cur_user, strict_check=True)
319 check_allowed_create_user(user_data, cur_user, strict_check=True)
319 events.trigger(events.UserPreCreate(user_data))
320 events.trigger(events.UserPreCreate(user_data))
320 new_user = User()
321 new_user = User()
321 edit = False
322 edit = False
322 else:
323 else:
323 log.debug('updating user %s', username)
324 log.debug('updating user %s', username)
324 events.trigger(events.UserPreUpdate(user, user_data))
325 events.trigger(events.UserPreUpdate(user, user_data))
325 new_user = user
326 new_user = user
326 edit = True
327 edit = True
327
328
328 # we're not allowed to edit default user
329 # we're not allowed to edit default user
329 if user.username == User.DEFAULT_USER:
330 if user.username == User.DEFAULT_USER:
330 raise DefaultUserException(
331 raise DefaultUserException(
331 _("You can't edit this user (`%(username)s`) since it's "
332 _("You can't edit this user (`%(username)s`) since it's "
332 "crucial for entire application") % {'username': user.username})
333 "crucial for entire application") % {'username': user.username})
333
334
334 # inject special attribute that will tell us if User is new or old
335 # inject special attribute that will tell us if User is new or old
335 new_user.is_new_user = not edit
336 new_user.is_new_user = not edit
336 # for users that didn's specify auth type, we use RhodeCode built in
337 # for users that didn's specify auth type, we use RhodeCode built in
337 from rhodecode.authentication.plugins import auth_rhodecode
338 from rhodecode.authentication.plugins import auth_rhodecode
338 extern_name = extern_name or auth_rhodecode.RhodeCodeAuthPlugin.name
339 extern_name = extern_name or auth_rhodecode.RhodeCodeAuthPlugin.name
339 extern_type = extern_type or auth_rhodecode.RhodeCodeAuthPlugin.name
340 extern_type = extern_type or auth_rhodecode.RhodeCodeAuthPlugin.name
340
341
341 try:
342 try:
342 new_user.username = username
343 new_user.username = username
343 new_user.admin = admin
344 new_user.admin = admin
344 new_user.email = email
345 new_user.email = email
345 new_user.active = active
346 new_user.active = active
346 new_user.extern_name = safe_unicode(extern_name)
347 new_user.extern_name = safe_unicode(extern_name)
347 new_user.extern_type = safe_unicode(extern_type)
348 new_user.extern_type = safe_unicode(extern_type)
348 new_user.name = firstname
349 new_user.name = firstname
349 new_user.lastname = lastname
350 new_user.lastname = lastname
350
351
351 # set password only if creating an user or password is changed
352 # set password only if creating an user or password is changed
352 if not edit or _password_change(new_user, password):
353 if not edit or _password_change(new_user, password):
353 reason = 'new password' if edit else 'new user'
354 reason = 'new password' if edit else 'new user'
354 log.debug('Updating password reason=>%s', reason)
355 log.debug('Updating password reason=>%s', reason)
355 new_user.password = get_crypt_password(password) if password else None
356 new_user.password = get_crypt_password(password) if password else None
356
357
357 if force_password_change:
358 if force_password_change:
358 new_user.update_userdata(force_password_change=True)
359 new_user.update_userdata(force_password_change=True)
359 if language:
360 if language:
360 new_user.update_userdata(language=language)
361 new_user.update_userdata(language=language)
361 new_user.update_userdata(notification_status=True)
362 new_user.update_userdata(notification_status=True)
362
363
363 self.sa.add(new_user)
364 self.sa.add(new_user)
364
365
365 if not edit and create_repo_group:
366 if not edit and create_repo_group:
366 RepoGroupModel().create_personal_repo_group(
367 RepoGroupModel().create_personal_repo_group(
367 new_user, commit_early=False)
368 new_user, commit_early=False)
368
369
369 if not edit:
370 if not edit:
370 # add the RSS token
371 # add the RSS token
371 AuthTokenModel().create(username,
372 AuthTokenModel().create(username,
372 description='Generated feed token',
373 description='Generated feed token',
373 role=AuthTokenModel.cls.ROLE_FEED)
374 role=AuthTokenModel.cls.ROLE_FEED)
374 log_create_user(created_by=cur_user, **new_user.get_dict())
375 log_create_user(created_by=cur_user, **new_user.get_dict())
375 events.trigger(events.UserPostCreate(user_data))
376 events.trigger(events.UserPostCreate(user_data))
376 return new_user
377 return new_user
377 except (DatabaseError,):
378 except (DatabaseError,):
378 log.error(traceback.format_exc())
379 log.error(traceback.format_exc())
379 raise
380 raise
380
381
381 def create_registration(self, form_data):
382 def create_registration(self, form_data):
382 from rhodecode.model.notification import NotificationModel
383 from rhodecode.model.notification import NotificationModel
383 from rhodecode.model.notification import EmailNotificationModel
384 from rhodecode.model.notification import EmailNotificationModel
384
385
385 try:
386 try:
386 form_data['admin'] = False
387 form_data['admin'] = False
387 form_data['extern_name'] = 'rhodecode'
388 form_data['extern_name'] = 'rhodecode'
388 form_data['extern_type'] = 'rhodecode'
389 form_data['extern_type'] = 'rhodecode'
389 new_user = self.create(form_data)
390 new_user = self.create(form_data)
390
391
391 self.sa.add(new_user)
392 self.sa.add(new_user)
392 self.sa.flush()
393 self.sa.flush()
393
394
394 user_data = new_user.get_dict()
395 user_data = new_user.get_dict()
395 kwargs = {
396 kwargs = {
396 # use SQLALCHEMY safe dump of user data
397 # use SQLALCHEMY safe dump of user data
397 'user': AttributeDict(user_data),
398 'user': AttributeDict(user_data),
398 'date': datetime.datetime.now()
399 'date': datetime.datetime.now()
399 }
400 }
400 notification_type = EmailNotificationModel.TYPE_REGISTRATION
401 notification_type = EmailNotificationModel.TYPE_REGISTRATION
401 # pre-generate the subject for notification itself
402 # pre-generate the subject for notification itself
402 (subject,
403 (subject,
403 _h, _e, # we don't care about those
404 _h, _e, # we don't care about those
404 body_plaintext) = EmailNotificationModel().render_email(
405 body_plaintext) = EmailNotificationModel().render_email(
405 notification_type, **kwargs)
406 notification_type, **kwargs)
406
407
407 # create notification objects, and emails
408 # create notification objects, and emails
408 NotificationModel().create(
409 NotificationModel().create(
409 created_by=new_user,
410 created_by=new_user,
410 notification_subject=subject,
411 notification_subject=subject,
411 notification_body=body_plaintext,
412 notification_body=body_plaintext,
412 notification_type=notification_type,
413 notification_type=notification_type,
413 recipients=None, # all admins
414 recipients=None, # all admins
414 email_kwargs=kwargs,
415 email_kwargs=kwargs,
415 )
416 )
416
417
417 return new_user
418 return new_user
418 except Exception:
419 except Exception:
419 log.error(traceback.format_exc())
420 log.error(traceback.format_exc())
420 raise
421 raise
421
422
422 def _handle_user_repos(self, username, repositories, handle_mode=None):
423 def _handle_user_repos(self, username, repositories, handle_mode=None):
423 _superadmin = self.cls.get_first_super_admin()
424 _superadmin = self.cls.get_first_super_admin()
424 left_overs = True
425 left_overs = True
425
426
426 from rhodecode.model.repo import RepoModel
427 from rhodecode.model.repo import RepoModel
427
428
428 if handle_mode == 'detach':
429 if handle_mode == 'detach':
429 for obj in repositories:
430 for obj in repositories:
430 obj.user = _superadmin
431 obj.user = _superadmin
431 # set description we know why we super admin now owns
432 # set description we know why we super admin now owns
432 # additional repositories that were orphaned !
433 # additional repositories that were orphaned !
433 obj.description += ' \n::detached repository from deleted user: %s' % (username,)
434 obj.description += ' \n::detached repository from deleted user: %s' % (username,)
434 self.sa.add(obj)
435 self.sa.add(obj)
435 left_overs = False
436 left_overs = False
436 elif handle_mode == 'delete':
437 elif handle_mode == 'delete':
437 for obj in repositories:
438 for obj in repositories:
438 RepoModel().delete(obj, forks='detach')
439 RepoModel().delete(obj, forks='detach')
439 left_overs = False
440 left_overs = False
440
441
441 # if nothing is done we have left overs left
442 # if nothing is done we have left overs left
442 return left_overs
443 return left_overs
443
444
444 def _handle_user_repo_groups(self, username, repository_groups,
445 def _handle_user_repo_groups(self, username, repository_groups,
445 handle_mode=None):
446 handle_mode=None):
446 _superadmin = self.cls.get_first_super_admin()
447 _superadmin = self.cls.get_first_super_admin()
447 left_overs = True
448 left_overs = True
448
449
449 from rhodecode.model.repo_group import RepoGroupModel
450 from rhodecode.model.repo_group import RepoGroupModel
450
451
451 if handle_mode == 'detach':
452 if handle_mode == 'detach':
452 for r in repository_groups:
453 for r in repository_groups:
453 r.user = _superadmin
454 r.user = _superadmin
454 # set description we know why we super admin now owns
455 # set description we know why we super admin now owns
455 # additional repositories that were orphaned !
456 # additional repositories that were orphaned !
456 r.group_description += ' \n::detached repository group from deleted user: %s' % (username,)
457 r.group_description += ' \n::detached repository group from deleted user: %s' % (username,)
457 self.sa.add(r)
458 self.sa.add(r)
458 left_overs = False
459 left_overs = False
459 elif handle_mode == 'delete':
460 elif handle_mode == 'delete':
460 for r in repository_groups:
461 for r in repository_groups:
461 RepoGroupModel().delete(r)
462 RepoGroupModel().delete(r)
462 left_overs = False
463 left_overs = False
463
464
464 # if nothing is done we have left overs left
465 # if nothing is done we have left overs left
465 return left_overs
466 return left_overs
466
467
467 def _handle_user_user_groups(self, username, user_groups, handle_mode=None):
468 def _handle_user_user_groups(self, username, user_groups, handle_mode=None):
468 _superadmin = self.cls.get_first_super_admin()
469 _superadmin = self.cls.get_first_super_admin()
469 left_overs = True
470 left_overs = True
470
471
471 from rhodecode.model.user_group import UserGroupModel
472 from rhodecode.model.user_group import UserGroupModel
472
473
473 if handle_mode == 'detach':
474 if handle_mode == 'detach':
474 for r in user_groups:
475 for r in user_groups:
475 for user_user_group_to_perm in r.user_user_group_to_perm:
476 for user_user_group_to_perm in r.user_user_group_to_perm:
476 if user_user_group_to_perm.user.username == username:
477 if user_user_group_to_perm.user.username == username:
477 user_user_group_to_perm.user = _superadmin
478 user_user_group_to_perm.user = _superadmin
478 r.user = _superadmin
479 r.user = _superadmin
479 # set description we know why we super admin now owns
480 # set description we know why we super admin now owns
480 # additional repositories that were orphaned !
481 # additional repositories that were orphaned !
481 r.user_group_description += ' \n::detached user group from deleted user: %s' % (username,)
482 r.user_group_description += ' \n::detached user group from deleted user: %s' % (username,)
482 self.sa.add(r)
483 self.sa.add(r)
483 left_overs = False
484 left_overs = False
484 elif handle_mode == 'delete':
485 elif handle_mode == 'delete':
485 for r in user_groups:
486 for r in user_groups:
486 UserGroupModel().delete(r)
487 UserGroupModel().delete(r)
487 left_overs = False
488 left_overs = False
488
489
489 # if nothing is done we have left overs left
490 # if nothing is done we have left overs left
490 return left_overs
491 return left_overs
491
492
492 def delete(self, user, cur_user=None, handle_repos=None,
493 def delete(self, user, cur_user=None, handle_repos=None,
493 handle_repo_groups=None, handle_user_groups=None):
494 handle_repo_groups=None, handle_user_groups=None):
494 if not cur_user:
495 if not cur_user:
495 cur_user = getattr(get_current_rhodecode_user(), 'username', None)
496 cur_user = getattr(get_current_rhodecode_user(), 'username', None)
496 user = self._get_user(user)
497 user = self._get_user(user)
497
498
498 try:
499 try:
499 if user.username == User.DEFAULT_USER:
500 if user.username == User.DEFAULT_USER:
500 raise DefaultUserException(
501 raise DefaultUserException(
501 _(u"You can't remove this user since it's"
502 _(u"You can't remove this user since it's"
502 u" crucial for entire application"))
503 u" crucial for entire application"))
503
504
504 left_overs = self._handle_user_repos(
505 left_overs = self._handle_user_repos(
505 user.username, user.repositories, handle_repos)
506 user.username, user.repositories, handle_repos)
506 if left_overs and user.repositories:
507 if left_overs and user.repositories:
507 repos = [x.repo_name for x in user.repositories]
508 repos = [x.repo_name for x in user.repositories]
508 raise UserOwnsReposException(
509 raise UserOwnsReposException(
509 _(u'user "%s" still owns %s repositories and cannot be '
510 _(u'user "%s" still owns %s repositories and cannot be '
510 u'removed. Switch owners or remove those repositories:%s')
511 u'removed. Switch owners or remove those repositories:%s')
511 % (user.username, len(repos), ', '.join(repos)))
512 % (user.username, len(repos), ', '.join(repos)))
512
513
513 left_overs = self._handle_user_repo_groups(
514 left_overs = self._handle_user_repo_groups(
514 user.username, user.repository_groups, handle_repo_groups)
515 user.username, user.repository_groups, handle_repo_groups)
515 if left_overs and user.repository_groups:
516 if left_overs and user.repository_groups:
516 repo_groups = [x.group_name for x in user.repository_groups]
517 repo_groups = [x.group_name for x in user.repository_groups]
517 raise UserOwnsRepoGroupsException(
518 raise UserOwnsRepoGroupsException(
518 _(u'user "%s" still owns %s repository groups and cannot be '
519 _(u'user "%s" still owns %s repository groups and cannot be '
519 u'removed. Switch owners or remove those repository groups:%s')
520 u'removed. Switch owners or remove those repository groups:%s')
520 % (user.username, len(repo_groups), ', '.join(repo_groups)))
521 % (user.username, len(repo_groups), ', '.join(repo_groups)))
521
522
522 left_overs = self._handle_user_user_groups(
523 left_overs = self._handle_user_user_groups(
523 user.username, user.user_groups, handle_user_groups)
524 user.username, user.user_groups, handle_user_groups)
524 if left_overs and user.user_groups:
525 if left_overs and user.user_groups:
525 user_groups = [x.users_group_name for x in user.user_groups]
526 user_groups = [x.users_group_name for x in user.user_groups]
526 raise UserOwnsUserGroupsException(
527 raise UserOwnsUserGroupsException(
527 _(u'user "%s" still owns %s user groups and cannot be '
528 _(u'user "%s" still owns %s user groups and cannot be '
528 u'removed. Switch owners or remove those user groups:%s')
529 u'removed. Switch owners or remove those user groups:%s')
529 % (user.username, len(user_groups), ', '.join(user_groups)))
530 % (user.username, len(user_groups), ', '.join(user_groups)))
530
531
531 # we might change the user data with detach/delete, make sure
532 # we might change the user data with detach/delete, make sure
532 # the object is marked as expired before actually deleting !
533 # the object is marked as expired before actually deleting !
533 self.sa.expire(user)
534 self.sa.expire(user)
534 self.sa.delete(user)
535 self.sa.delete(user)
535 from rhodecode.lib.hooks_base import log_delete_user
536 from rhodecode.lib.hooks_base import log_delete_user
536 log_delete_user(deleted_by=cur_user, **user.get_dict())
537 log_delete_user(deleted_by=cur_user, **user.get_dict())
537 except Exception:
538 except Exception:
538 log.error(traceback.format_exc())
539 log.error(traceback.format_exc())
539 raise
540 raise
540
541
541 def reset_password_link(self, data, pwd_reset_url):
542 def reset_password_link(self, data, pwd_reset_url):
542 from rhodecode.lib.celerylib import tasks, run_task
543 from rhodecode.lib.celerylib import tasks, run_task
543 from rhodecode.model.notification import EmailNotificationModel
544 from rhodecode.model.notification import EmailNotificationModel
544 user_email = data['email']
545 user_email = data['email']
545 try:
546 try:
546 user = User.get_by_email(user_email)
547 user = User.get_by_email(user_email)
547 if user:
548 if user:
548 log.debug('password reset user found %s', user)
549 log.debug('password reset user found %s', user)
549
550
550 email_kwargs = {
551 email_kwargs = {
551 'password_reset_url': pwd_reset_url,
552 'password_reset_url': pwd_reset_url,
552 'user': user,
553 'user': user,
553 'email': user_email,
554 'email': user_email,
554 'date': datetime.datetime.now()
555 'date': datetime.datetime.now()
555 }
556 }
556
557
557 (subject, headers, email_body,
558 (subject, headers, email_body,
558 email_body_plaintext) = EmailNotificationModel().render_email(
559 email_body_plaintext) = EmailNotificationModel().render_email(
559 EmailNotificationModel.TYPE_PASSWORD_RESET, **email_kwargs)
560 EmailNotificationModel.TYPE_PASSWORD_RESET, **email_kwargs)
560
561
561 recipients = [user_email]
562 recipients = [user_email]
562
563
563 action_logger_generic(
564 action_logger_generic(
564 'sending password reset email to user: {}'.format(
565 'sending password reset email to user: {}'.format(
565 user), namespace='security.password_reset')
566 user), namespace='security.password_reset')
566
567
567 run_task(tasks.send_email, recipients, subject,
568 run_task(tasks.send_email, recipients, subject,
568 email_body_plaintext, email_body)
569 email_body_plaintext, email_body)
569
570
570 else:
571 else:
571 log.debug("password reset email %s not found", user_email)
572 log.debug("password reset email %s not found", user_email)
572 except Exception:
573 except Exception:
573 log.error(traceback.format_exc())
574 log.error(traceback.format_exc())
574 return False
575 return False
575
576
576 return True
577 return True
577
578
578 def reset_password(self, data):
579 def reset_password(self, data):
579 from rhodecode.lib.celerylib import tasks, run_task
580 from rhodecode.lib.celerylib import tasks, run_task
580 from rhodecode.model.notification import EmailNotificationModel
581 from rhodecode.model.notification import EmailNotificationModel
581 from rhodecode.lib import auth
582 from rhodecode.lib import auth
582 user_email = data['email']
583 user_email = data['email']
583 pre_db = True
584 pre_db = True
584 try:
585 try:
585 user = User.get_by_email(user_email)
586 user = User.get_by_email(user_email)
586 new_passwd = auth.PasswordGenerator().gen_password(
587 new_passwd = auth.PasswordGenerator().gen_password(
587 12, auth.PasswordGenerator.ALPHABETS_BIG_SMALL)
588 12, auth.PasswordGenerator.ALPHABETS_BIG_SMALL)
588 if user:
589 if user:
589 user.password = auth.get_crypt_password(new_passwd)
590 user.password = auth.get_crypt_password(new_passwd)
590 # also force this user to reset his password !
591 # also force this user to reset his password !
591 user.update_userdata(force_password_change=True)
592 user.update_userdata(force_password_change=True)
592
593
593 Session().add(user)
594 Session().add(user)
594
595
595 # now delete the token in question
596 # now delete the token in question
596 UserApiKeys = AuthTokenModel.cls
597 UserApiKeys = AuthTokenModel.cls
597 UserApiKeys().query().filter(
598 UserApiKeys().query().filter(
598 UserApiKeys.api_key == data['token']).delete()
599 UserApiKeys.api_key == data['token']).delete()
599
600
600 Session().commit()
601 Session().commit()
601 log.info('successfully reset password for `%s`', user_email)
602 log.info('successfully reset password for `%s`', user_email)
602
603
603 if new_passwd is None:
604 if new_passwd is None:
604 raise Exception('unable to generate new password')
605 raise Exception('unable to generate new password')
605
606
606 pre_db = False
607 pre_db = False
607
608
608 email_kwargs = {
609 email_kwargs = {
609 'new_password': new_passwd,
610 'new_password': new_passwd,
610 'user': user,
611 'user': user,
611 'email': user_email,
612 'email': user_email,
612 'date': datetime.datetime.now()
613 'date': datetime.datetime.now()
613 }
614 }
614
615
615 (subject, headers, email_body,
616 (subject, headers, email_body,
616 email_body_plaintext) = EmailNotificationModel().render_email(
617 email_body_plaintext) = EmailNotificationModel().render_email(
617 EmailNotificationModel.TYPE_PASSWORD_RESET_CONFIRMATION,
618 EmailNotificationModel.TYPE_PASSWORD_RESET_CONFIRMATION,
618 **email_kwargs)
619 **email_kwargs)
619
620
620 recipients = [user_email]
621 recipients = [user_email]
621
622
622 action_logger_generic(
623 action_logger_generic(
623 'sent new password to user: {} with email: {}'.format(
624 'sent new password to user: {} with email: {}'.format(
624 user, user_email), namespace='security.password_reset')
625 user, user_email), namespace='security.password_reset')
625
626
626 run_task(tasks.send_email, recipients, subject,
627 run_task(tasks.send_email, recipients, subject,
627 email_body_plaintext, email_body)
628 email_body_plaintext, email_body)
628
629
629 except Exception:
630 except Exception:
630 log.error('Failed to update user password')
631 log.error('Failed to update user password')
631 log.error(traceback.format_exc())
632 log.error(traceback.format_exc())
632 if pre_db:
633 if pre_db:
633 # we rollback only if local db stuff fails. If it goes into
634 # we rollback only if local db stuff fails. If it goes into
634 # run_task, we're pass rollback state this wouldn't work then
635 # run_task, we're pass rollback state this wouldn't work then
635 Session().rollback()
636 Session().rollback()
636
637
637 return True
638 return True
638
639
639 def fill_data(self, auth_user, user_id=None, api_key=None, username=None):
640 def fill_data(self, auth_user, user_id=None, api_key=None, username=None):
640 """
641 """
641 Fetches auth_user by user_id,or api_key if present.
642 Fetches auth_user by user_id,or api_key if present.
642 Fills auth_user attributes with those taken from database.
643 Fills auth_user attributes with those taken from database.
643 Additionally set's is_authenitated if lookup fails
644 Additionally set's is_authenitated if lookup fails
644 present in database
645 present in database
645
646
646 :param auth_user: instance of user to set attributes
647 :param auth_user: instance of user to set attributes
647 :param user_id: user id to fetch by
648 :param user_id: user id to fetch by
648 :param api_key: api key to fetch by
649 :param api_key: api key to fetch by
649 :param username: username to fetch by
650 :param username: username to fetch by
650 """
651 """
651 if user_id is None and api_key is None and username is None:
652 if user_id is None and api_key is None and username is None:
652 raise Exception('You need to pass user_id, api_key or username')
653 raise Exception('You need to pass user_id, api_key or username')
653
654
654 log.debug(
655 log.debug(
655 'doing fill data based on: user_id:%s api_key:%s username:%s',
656 'doing fill data based on: user_id:%s api_key:%s username:%s',
656 user_id, api_key, username)
657 user_id, api_key, username)
657 try:
658 try:
658 dbuser = None
659 dbuser = None
659 if user_id:
660 if user_id:
660 dbuser = self.get(user_id)
661 dbuser = self.get(user_id)
661 elif api_key:
662 elif api_key:
662 dbuser = self.get_by_auth_token(api_key)
663 dbuser = self.get_by_auth_token(api_key)
663 elif username:
664 elif username:
664 dbuser = self.get_by_username(username)
665 dbuser = self.get_by_username(username)
665
666
666 if not dbuser:
667 if not dbuser:
667 log.warning(
668 log.warning(
668 'Unable to lookup user by id:%s api_key:%s username:%s',
669 'Unable to lookup user by id:%s api_key:%s username:%s',
669 user_id, api_key, username)
670 user_id, api_key, username)
670 return False
671 return False
671 if not dbuser.active:
672 if not dbuser.active:
672 log.debug('User `%s:%s` is inactive, skipping fill data',
673 log.debug('User `%s:%s` is inactive, skipping fill data',
673 username, user_id)
674 username, user_id)
674 return False
675 return False
675
676
676 log.debug('filling user:%s data', dbuser)
677 log.debug('filling user:%s data', dbuser)
677
678
678 # TODO: johbo: Think about this and find a clean solution
679 # TODO: johbo: Think about this and find a clean solution
679 user_data = dbuser.get_dict()
680 user_data = dbuser.get_dict()
680 user_data.update(dbuser.get_api_data(include_secrets=True))
681 user_data.update(dbuser.get_api_data(include_secrets=True))
681
682
682 for k, v in user_data.iteritems():
683 for k, v in user_data.iteritems():
683 # properties of auth user we dont update
684 # properties of auth user we dont update
684 if k not in ['auth_tokens', 'permissions']:
685 if k not in ['auth_tokens', 'permissions']:
685 setattr(auth_user, k, v)
686 setattr(auth_user, k, v)
686
687
687 # few extras
688 # few extras
688 setattr(auth_user, 'feed_token', dbuser.feed_token)
689 setattr(auth_user, 'feed_token', dbuser.feed_token)
689 except Exception:
690 except Exception:
690 log.error(traceback.format_exc())
691 log.error(traceback.format_exc())
691 auth_user.is_authenticated = False
692 auth_user.is_authenticated = False
692 return False
693 return False
693
694
694 return True
695 return True
695
696
696 def has_perm(self, user, perm):
697 def has_perm(self, user, perm):
697 perm = self._get_perm(perm)
698 perm = self._get_perm(perm)
698 user = self._get_user(user)
699 user = self._get_user(user)
699
700
700 return UserToPerm.query().filter(UserToPerm.user == user)\
701 return UserToPerm.query().filter(UserToPerm.user == user)\
701 .filter(UserToPerm.permission == perm).scalar() is not None
702 .filter(UserToPerm.permission == perm).scalar() is not None
702
703
703 def grant_perm(self, user, perm):
704 def grant_perm(self, user, perm):
704 """
705 """
705 Grant user global permissions
706 Grant user global permissions
706
707
707 :param user:
708 :param user:
708 :param perm:
709 :param perm:
709 """
710 """
710 user = self._get_user(user)
711 user = self._get_user(user)
711 perm = self._get_perm(perm)
712 perm = self._get_perm(perm)
712 # if this permission is already granted skip it
713 # if this permission is already granted skip it
713 _perm = UserToPerm.query()\
714 _perm = UserToPerm.query()\
714 .filter(UserToPerm.user == user)\
715 .filter(UserToPerm.user == user)\
715 .filter(UserToPerm.permission == perm)\
716 .filter(UserToPerm.permission == perm)\
716 .scalar()
717 .scalar()
717 if _perm:
718 if _perm:
718 return
719 return
719 new = UserToPerm()
720 new = UserToPerm()
720 new.user = user
721 new.user = user
721 new.permission = perm
722 new.permission = perm
722 self.sa.add(new)
723 self.sa.add(new)
723 return new
724 return new
724
725
725 def revoke_perm(self, user, perm):
726 def revoke_perm(self, user, perm):
726 """
727 """
727 Revoke users global permissions
728 Revoke users global permissions
728
729
729 :param user:
730 :param user:
730 :param perm:
731 :param perm:
731 """
732 """
732 user = self._get_user(user)
733 user = self._get_user(user)
733 perm = self._get_perm(perm)
734 perm = self._get_perm(perm)
734
735
735 obj = UserToPerm.query()\
736 obj = UserToPerm.query()\
736 .filter(UserToPerm.user == user)\
737 .filter(UserToPerm.user == user)\
737 .filter(UserToPerm.permission == perm)\
738 .filter(UserToPerm.permission == perm)\
738 .scalar()
739 .scalar()
739 if obj:
740 if obj:
740 self.sa.delete(obj)
741 self.sa.delete(obj)
741
742
742 def add_extra_email(self, user, email):
743 def add_extra_email(self, user, email):
743 """
744 """
744 Adds email address to UserEmailMap
745 Adds email address to UserEmailMap
745
746
746 :param user:
747 :param user:
747 :param email:
748 :param email:
748 """
749 """
749 from rhodecode.model import forms
750 from rhodecode.model import forms
750 form = forms.UserExtraEmailForm()()
751 form = forms.UserExtraEmailForm()()
751 data = form.to_python({'email': email})
752 data = form.to_python({'email': email})
752 user = self._get_user(user)
753 user = self._get_user(user)
753
754
754 obj = UserEmailMap()
755 obj = UserEmailMap()
755 obj.user = user
756 obj.user = user
756 obj.email = data['email']
757 obj.email = data['email']
757 self.sa.add(obj)
758 self.sa.add(obj)
758 return obj
759 return obj
759
760
760 def delete_extra_email(self, user, email_id):
761 def delete_extra_email(self, user, email_id):
761 """
762 """
762 Removes email address from UserEmailMap
763 Removes email address from UserEmailMap
763
764
764 :param user:
765 :param user:
765 :param email_id:
766 :param email_id:
766 """
767 """
767 user = self._get_user(user)
768 user = self._get_user(user)
768 obj = UserEmailMap.query().get(email_id)
769 obj = UserEmailMap.query().get(email_id)
769 if obj:
770 if obj:
770 self.sa.delete(obj)
771 self.sa.delete(obj)
771
772
772 def parse_ip_range(self, ip_range):
773 def parse_ip_range(self, ip_range):
773 ip_list = []
774 ip_list = []
774 def make_unique(value):
775 def make_unique(value):
775 seen = []
776 seen = []
776 return [c for c in value if not (c in seen or seen.append(c))]
777 return [c for c in value if not (c in seen or seen.append(c))]
777
778
778 # firsts split by commas
779 # firsts split by commas
779 for ip_range in ip_range.split(','):
780 for ip_range in ip_range.split(','):
780 if not ip_range:
781 if not ip_range:
781 continue
782 continue
782 ip_range = ip_range.strip()
783 ip_range = ip_range.strip()
783 if '-' in ip_range:
784 if '-' in ip_range:
784 start_ip, end_ip = ip_range.split('-', 1)
785 start_ip, end_ip = ip_range.split('-', 1)
785 start_ip = ipaddress.ip_address(start_ip.strip())
786 start_ip = ipaddress.ip_address(start_ip.strip())
786 end_ip = ipaddress.ip_address(end_ip.strip())
787 end_ip = ipaddress.ip_address(end_ip.strip())
787 parsed_ip_range = []
788 parsed_ip_range = []
788
789
789 for index in xrange(int(start_ip), int(end_ip) + 1):
790 for index in xrange(int(start_ip), int(end_ip) + 1):
790 new_ip = ipaddress.ip_address(index)
791 new_ip = ipaddress.ip_address(index)
791 parsed_ip_range.append(str(new_ip))
792 parsed_ip_range.append(str(new_ip))
792 ip_list.extend(parsed_ip_range)
793 ip_list.extend(parsed_ip_range)
793 else:
794 else:
794 ip_list.append(ip_range)
795 ip_list.append(ip_range)
795
796
796 return make_unique(ip_list)
797 return make_unique(ip_list)
797
798
798 def add_extra_ip(self, user, ip, description=None):
799 def add_extra_ip(self, user, ip, description=None):
799 """
800 """
800 Adds ip address to UserIpMap
801 Adds ip address to UserIpMap
801
802
802 :param user:
803 :param user:
803 :param ip:
804 :param ip:
804 """
805 """
805 from rhodecode.model import forms
806 from rhodecode.model import forms
806 form = forms.UserExtraIpForm()()
807 form = forms.UserExtraIpForm()()
807 data = form.to_python({'ip': ip})
808 data = form.to_python({'ip': ip})
808 user = self._get_user(user)
809 user = self._get_user(user)
809
810
810 obj = UserIpMap()
811 obj = UserIpMap()
811 obj.user = user
812 obj.user = user
812 obj.ip_addr = data['ip']
813 obj.ip_addr = data['ip']
813 obj.description = description
814 obj.description = description
814 self.sa.add(obj)
815 self.sa.add(obj)
815 return obj
816 return obj
816
817
817 def delete_extra_ip(self, user, ip_id):
818 def delete_extra_ip(self, user, ip_id):
818 """
819 """
819 Removes ip address from UserIpMap
820 Removes ip address from UserIpMap
820
821
821 :param user:
822 :param user:
822 :param ip_id:
823 :param ip_id:
823 """
824 """
824 user = self._get_user(user)
825 user = self._get_user(user)
825 obj = UserIpMap.query().get(ip_id)
826 obj = UserIpMap.query().get(ip_id)
826 if obj:
827 if obj:
827 self.sa.delete(obj)
828 self.sa.delete(obj)
828
829
829 def get_accounts_in_creation_order(self, current_user=None):
830 def get_accounts_in_creation_order(self, current_user=None):
830 """
831 """
831 Get accounts in order of creation for deactivation for license limits
832 Get accounts in order of creation for deactivation for license limits
832
833
833 pick currently logged in user, and append to the list in position 0
834 pick currently logged in user, and append to the list in position 0
834 pick all super-admins in order of creation date and add it to the list
835 pick all super-admins in order of creation date and add it to the list
835 pick all other accounts in order of creation and add it to the list.
836 pick all other accounts in order of creation and add it to the list.
836
837
837 Based on that list, the last accounts can be disabled as they are
838 Based on that list, the last accounts can be disabled as they are
838 created at the end and don't include any of the super admins as well
839 created at the end and don't include any of the super admins as well
839 as the current user.
840 as the current user.
840
841
841 :param current_user: optionally current user running this operation
842 :param current_user: optionally current user running this operation
842 """
843 """
843
844
844 if not current_user:
845 if not current_user:
845 current_user = get_current_rhodecode_user()
846 current_user = get_current_rhodecode_user()
846 active_super_admins = [
847 active_super_admins = [
847 x.user_id for x in User.query()
848 x.user_id for x in User.query()
848 .filter(User.user_id != current_user.user_id)
849 .filter(User.user_id != current_user.user_id)
849 .filter(User.active == true())
850 .filter(User.active == true())
850 .filter(User.admin == true())
851 .filter(User.admin == true())
851 .order_by(User.created_on.asc())]
852 .order_by(User.created_on.asc())]
852
853
853 active_regular_users = [
854 active_regular_users = [
854 x.user_id for x in User.query()
855 x.user_id for x in User.query()
855 .filter(User.user_id != current_user.user_id)
856 .filter(User.user_id != current_user.user_id)
856 .filter(User.active == true())
857 .filter(User.active == true())
857 .filter(User.admin == false())
858 .filter(User.admin == false())
858 .order_by(User.created_on.asc())]
859 .order_by(User.created_on.asc())]
859
860
860 list_of_accounts = [current_user.user_id]
861 list_of_accounts = [current_user.user_id]
861 list_of_accounts += active_super_admins
862 list_of_accounts += active_super_admins
862 list_of_accounts += active_regular_users
863 list_of_accounts += active_regular_users
863
864
864 return list_of_accounts
865 return list_of_accounts
865
866
866 def deactivate_last_users(self, expected_users):
867 def deactivate_last_users(self, expected_users):
867 """
868 """
868 Deactivate accounts that are over the license limits.
869 Deactivate accounts that are over the license limits.
869 Algorithm of which accounts to disabled is based on the formula:
870 Algorithm of which accounts to disabled is based on the formula:
870
871
871 Get current user, then super admins in creation order, then regular
872 Get current user, then super admins in creation order, then regular
872 active users in creation order.
873 active users in creation order.
873
874
874 Using that list we mark all accounts from the end of it as inactive.
875 Using that list we mark all accounts from the end of it as inactive.
875 This way we block only latest created accounts.
876 This way we block only latest created accounts.
876
877
877 :param expected_users: list of users in special order, we deactivate
878 :param expected_users: list of users in special order, we deactivate
878 the end N ammoun of users from that list
879 the end N ammoun of users from that list
879 """
880 """
880
881
881 list_of_accounts = self.get_accounts_in_creation_order()
882 list_of_accounts = self.get_accounts_in_creation_order()
882
883
883 for acc_id in list_of_accounts[expected_users + 1:]:
884 for acc_id in list_of_accounts[expected_users + 1:]:
884 user = User.get(acc_id)
885 user = User.get(acc_id)
885 log.info('Deactivating account %s for license unlock', user)
886 log.info('Deactivating account %s for license unlock', user)
886 user.active = False
887 user.active = False
887 Session().add(user)
888 Session().add(user)
888 Session().commit()
889 Session().commit()
889
890
890 return
891 return
891
892
892 def get_user_log(self, user, filter_term):
893 def get_user_log(self, user, filter_term):
893 user_log = UserLog.query()\
894 user_log = UserLog.query()\
894 .filter(or_(UserLog.user_id == user.user_id,
895 .filter(or_(UserLog.user_id == user.user_id,
895 UserLog.username == user.username))\
896 UserLog.username == user.username))\
896 .options(joinedload(UserLog.user))\
897 .options(joinedload(UserLog.user))\
897 .options(joinedload(UserLog.repository))\
898 .options(joinedload(UserLog.repository))\
898 .order_by(UserLog.action_date.desc())
899 .order_by(UserLog.action_date.desc())
899
900
900 user_log = user_log_filter(user_log, filter_term)
901 user_log = user_log_filter(user_log, filter_term)
901 return user_log
902 return user_log
@@ -1,460 +1,460 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import base64
21 import base64
22
22
23 import mock
23 import mock
24 import pytest
24 import pytest
25
25
26 from rhodecode.tests.utils import CustomTestApp
26 from rhodecode.tests.utils import CustomTestApp
27
27
28 from rhodecode.lib.caching_query import FromCache
28 from rhodecode.lib.caching_query import FromCache
29 from rhodecode.lib.hooks_daemon import DummyHooksCallbackDaemon
29 from rhodecode.lib.hooks_daemon import DummyHooksCallbackDaemon
30 from rhodecode.lib.middleware import simplevcs
30 from rhodecode.lib.middleware import simplevcs
31 from rhodecode.lib.middleware.https_fixup import HttpsFixup
31 from rhodecode.lib.middleware.https_fixup import HttpsFixup
32 from rhodecode.lib.middleware.utils import scm_app_http
32 from rhodecode.lib.middleware.utils import scm_app_http
33 from rhodecode.model.db import User, _hash_key
33 from rhodecode.model.db import User, _hash_key
34 from rhodecode.model.meta import Session
34 from rhodecode.model.meta import Session
35 from rhodecode.tests import (
35 from rhodecode.tests import (
36 HG_REPO, TEST_USER_ADMIN_LOGIN, TEST_USER_ADMIN_PASS)
36 HG_REPO, TEST_USER_ADMIN_LOGIN, TEST_USER_ADMIN_PASS)
37 from rhodecode.tests.lib.middleware import mock_scm_app
37 from rhodecode.tests.lib.middleware import mock_scm_app
38 from rhodecode.tests.utils import set_anonymous_access
38 from rhodecode.tests.utils import set_anonymous_access
39
39
40
40
41 class StubVCSController(simplevcs.SimpleVCS):
41 class StubVCSController(simplevcs.SimpleVCS):
42
42
43 SCM = 'hg'
43 SCM = 'hg'
44 stub_response_body = tuple()
44 stub_response_body = tuple()
45
45
46 def __init__(self, *args, **kwargs):
46 def __init__(self, *args, **kwargs):
47 super(StubVCSController, self).__init__(*args, **kwargs)
47 super(StubVCSController, self).__init__(*args, **kwargs)
48 self._action = 'pull'
48 self._action = 'pull'
49 self._name = HG_REPO
49 self._name = HG_REPO
50 self.set_repo_names(None)
50 self.set_repo_names(None)
51
51
52 def _get_repository_name(self, environ):
52 def _get_repository_name(self, environ):
53 return self._name
53 return self._name
54
54
55 def _get_action(self, environ):
55 def _get_action(self, environ):
56 return self._action
56 return self._action
57
57
58 def _create_wsgi_app(self, repo_path, repo_name, config):
58 def _create_wsgi_app(self, repo_path, repo_name, config):
59 def fake_app(environ, start_response):
59 def fake_app(environ, start_response):
60 start_response('200 OK', [])
60 start_response('200 OK', [])
61 return self.stub_response_body
61 return self.stub_response_body
62 return fake_app
62 return fake_app
63
63
64 def _create_config(self, extras, repo_name):
64 def _create_config(self, extras, repo_name):
65 return None
65 return None
66
66
67
67
68 @pytest.fixture
68 @pytest.fixture
69 def vcscontroller(pylonsapp, config_stub):
69 def vcscontroller(pylonsapp, config_stub):
70 config_stub.testing_securitypolicy()
70 config_stub.testing_securitypolicy()
71 config_stub.include('rhodecode.authentication')
71 config_stub.include('rhodecode.authentication')
72
72
73 set_anonymous_access(True)
73 set_anonymous_access(True)
74 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
74 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
75 app = HttpsFixup(controller, pylonsapp.config)
75 app = HttpsFixup(controller, pylonsapp.config)
76 app = CustomTestApp(app)
76 app = CustomTestApp(app)
77
77
78 _remove_default_user_from_query_cache()
78 _remove_default_user_from_query_cache()
79
79
80 # Sanity checks that things are set up correctly
80 # Sanity checks that things are set up correctly
81 app.get('/' + HG_REPO, status=200)
81 app.get('/' + HG_REPO, status=200)
82
82
83 app.controller = controller
83 app.controller = controller
84 return app
84 return app
85
85
86
86
87 def _remove_default_user_from_query_cache():
87 def _remove_default_user_from_query_cache():
88 user = User.get_default_user(cache=True)
88 user = User.get_default_user(cache=True)
89 query = Session().query(User).filter(User.username == user.username)
89 query = Session().query(User).filter(User.username == user.username)
90 query = query.options(FromCache(
90 query = query.options(
91 "sql_cache_short", "get_user_%s" % _hash_key(user.username)))
91 FromCache("sql_cache_short", "get_user_%s" % _hash_key(user.username)))
92 query.invalidate()
92 query.invalidate()
93 Session().expire(user)
93 Session().expire(user)
94
94
95
95
96 @pytest.fixture
96 @pytest.fixture
97 def disable_anonymous_user(request, pylonsapp):
97 def disable_anonymous_user(request, pylonsapp):
98 set_anonymous_access(False)
98 set_anonymous_access(False)
99
99
100 @request.addfinalizer
100 @request.addfinalizer
101 def cleanup():
101 def cleanup():
102 set_anonymous_access(True)
102 set_anonymous_access(True)
103
103
104
104
105 def test_handles_exceptions_during_permissions_checks(
105 def test_handles_exceptions_during_permissions_checks(
106 vcscontroller, disable_anonymous_user):
106 vcscontroller, disable_anonymous_user):
107 user_and_pass = '%s:%s' % (TEST_USER_ADMIN_LOGIN, TEST_USER_ADMIN_PASS)
107 user_and_pass = '%s:%s' % (TEST_USER_ADMIN_LOGIN, TEST_USER_ADMIN_PASS)
108 auth_password = base64.encodestring(user_and_pass).strip()
108 auth_password = base64.encodestring(user_and_pass).strip()
109 extra_environ = {
109 extra_environ = {
110 'AUTH_TYPE': 'Basic',
110 'AUTH_TYPE': 'Basic',
111 'HTTP_AUTHORIZATION': 'Basic %s' % auth_password,
111 'HTTP_AUTHORIZATION': 'Basic %s' % auth_password,
112 'REMOTE_USER': TEST_USER_ADMIN_LOGIN,
112 'REMOTE_USER': TEST_USER_ADMIN_LOGIN,
113 }
113 }
114
114
115 # Verify that things are hooked up correctly
115 # Verify that things are hooked up correctly
116 vcscontroller.get('/', status=200, extra_environ=extra_environ)
116 vcscontroller.get('/', status=200, extra_environ=extra_environ)
117
117
118 # Simulate trouble during permission checks
118 # Simulate trouble during permission checks
119 with mock.patch('rhodecode.model.db.User.get_by_username',
119 with mock.patch('rhodecode.model.db.User.get_by_username',
120 side_effect=Exception) as get_user:
120 side_effect=Exception) as get_user:
121 # Verify that a correct 500 is returned and check that the expected
121 # Verify that a correct 500 is returned and check that the expected
122 # code path was hit.
122 # code path was hit.
123 vcscontroller.get('/', status=500, extra_environ=extra_environ)
123 vcscontroller.get('/', status=500, extra_environ=extra_environ)
124 assert get_user.called
124 assert get_user.called
125
125
126
126
127 def test_returns_forbidden_if_no_anonymous_access(
127 def test_returns_forbidden_if_no_anonymous_access(
128 vcscontroller, disable_anonymous_user):
128 vcscontroller, disable_anonymous_user):
129 vcscontroller.get('/', status=401)
129 vcscontroller.get('/', status=401)
130
130
131
131
132 class StubFailVCSController(simplevcs.SimpleVCS):
132 class StubFailVCSController(simplevcs.SimpleVCS):
133 def _handle_request(self, environ, start_response):
133 def _handle_request(self, environ, start_response):
134 raise Exception("BOOM")
134 raise Exception("BOOM")
135
135
136
136
137 @pytest.fixture(scope='module')
137 @pytest.fixture(scope='module')
138 def fail_controller(pylonsapp):
138 def fail_controller(pylonsapp):
139 controller = StubFailVCSController(pylonsapp, pylonsapp.config, None)
139 controller = StubFailVCSController(pylonsapp, pylonsapp.config, None)
140 controller = HttpsFixup(controller, pylonsapp.config)
140 controller = HttpsFixup(controller, pylonsapp.config)
141 controller = CustomTestApp(controller)
141 controller = CustomTestApp(controller)
142 return controller
142 return controller
143
143
144
144
145 def test_handles_exceptions_as_internal_server_error(fail_controller):
145 def test_handles_exceptions_as_internal_server_error(fail_controller):
146 fail_controller.get('/', status=500)
146 fail_controller.get('/', status=500)
147
147
148
148
149 def test_provides_traceback_for_appenlight(fail_controller):
149 def test_provides_traceback_for_appenlight(fail_controller):
150 response = fail_controller.get(
150 response = fail_controller.get(
151 '/', status=500, extra_environ={'appenlight.client': 'fake'})
151 '/', status=500, extra_environ={'appenlight.client': 'fake'})
152 assert 'appenlight.__traceback' in response.request.environ
152 assert 'appenlight.__traceback' in response.request.environ
153
153
154
154
155 def test_provides_utils_scm_app_as_scm_app_by_default(pylonsapp):
155 def test_provides_utils_scm_app_as_scm_app_by_default(pylonsapp):
156 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
156 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
157 assert controller.scm_app is scm_app_http
157 assert controller.scm_app is scm_app_http
158
158
159
159
160 def test_allows_to_override_scm_app_via_config(pylonsapp):
160 def test_allows_to_override_scm_app_via_config(pylonsapp):
161 config = pylonsapp.config.copy()
161 config = pylonsapp.config.copy()
162 config['vcs.scm_app_implementation'] = (
162 config['vcs.scm_app_implementation'] = (
163 'rhodecode.tests.lib.middleware.mock_scm_app')
163 'rhodecode.tests.lib.middleware.mock_scm_app')
164 controller = StubVCSController(pylonsapp, config, None)
164 controller = StubVCSController(pylonsapp, config, None)
165 assert controller.scm_app is mock_scm_app
165 assert controller.scm_app is mock_scm_app
166
166
167
167
168 @pytest.mark.parametrize('query_string, expected', [
168 @pytest.mark.parametrize('query_string, expected', [
169 ('cmd=stub_command', True),
169 ('cmd=stub_command', True),
170 ('cmd=listkeys', False),
170 ('cmd=listkeys', False),
171 ])
171 ])
172 def test_should_check_locking(query_string, expected):
172 def test_should_check_locking(query_string, expected):
173 result = simplevcs._should_check_locking(query_string)
173 result = simplevcs._should_check_locking(query_string)
174 assert result == expected
174 assert result == expected
175
175
176
176
177 class TestShadowRepoRegularExpression(object):
177 class TestShadowRepoRegularExpression(object):
178 pr_segment = 'pull-request'
178 pr_segment = 'pull-request'
179 shadow_segment = 'repository'
179 shadow_segment = 'repository'
180
180
181 @pytest.mark.parametrize('url, expected', [
181 @pytest.mark.parametrize('url, expected', [
182 # repo with/without groups
182 # repo with/without groups
183 ('My-Repo/{pr_segment}/1/{shadow_segment}', True),
183 ('My-Repo/{pr_segment}/1/{shadow_segment}', True),
184 ('Group/My-Repo/{pr_segment}/2/{shadow_segment}', True),
184 ('Group/My-Repo/{pr_segment}/2/{shadow_segment}', True),
185 ('Group/Sub-Group/My-Repo/{pr_segment}/3/{shadow_segment}', True),
185 ('Group/Sub-Group/My-Repo/{pr_segment}/3/{shadow_segment}', True),
186 ('Group/Sub-Group1/Sub-Group2/My-Repo/{pr_segment}/3/{shadow_segment}', True),
186 ('Group/Sub-Group1/Sub-Group2/My-Repo/{pr_segment}/3/{shadow_segment}', True),
187
187
188 # pull request ID
188 # pull request ID
189 ('MyRepo/{pr_segment}/1/{shadow_segment}', True),
189 ('MyRepo/{pr_segment}/1/{shadow_segment}', True),
190 ('MyRepo/{pr_segment}/1234567890/{shadow_segment}', True),
190 ('MyRepo/{pr_segment}/1234567890/{shadow_segment}', True),
191 ('MyRepo/{pr_segment}/-1/{shadow_segment}', False),
191 ('MyRepo/{pr_segment}/-1/{shadow_segment}', False),
192 ('MyRepo/{pr_segment}/invalid/{shadow_segment}', False),
192 ('MyRepo/{pr_segment}/invalid/{shadow_segment}', False),
193
193
194 # unicode
194 # unicode
195 (u'Sp€çîál-Repö/{pr_segment}/1/{shadow_segment}', True),
195 (u'Sp€çîál-Repö/{pr_segment}/1/{shadow_segment}', True),
196 (u'Sp€çîál-Gröüp/Sp€çîál-Repö/{pr_segment}/1/{shadow_segment}', True),
196 (u'Sp€çîál-Gröüp/Sp€çîál-Repö/{pr_segment}/1/{shadow_segment}', True),
197
197
198 # trailing/leading slash
198 # trailing/leading slash
199 ('/My-Repo/{pr_segment}/1/{shadow_segment}', False),
199 ('/My-Repo/{pr_segment}/1/{shadow_segment}', False),
200 ('My-Repo/{pr_segment}/1/{shadow_segment}/', False),
200 ('My-Repo/{pr_segment}/1/{shadow_segment}/', False),
201 ('/My-Repo/{pr_segment}/1/{shadow_segment}/', False),
201 ('/My-Repo/{pr_segment}/1/{shadow_segment}/', False),
202
202
203 # misc
203 # misc
204 ('My-Repo/{pr_segment}/1/{shadow_segment}/extra', False),
204 ('My-Repo/{pr_segment}/1/{shadow_segment}/extra', False),
205 ('My-Repo/{pr_segment}/1/{shadow_segment}extra', False),
205 ('My-Repo/{pr_segment}/1/{shadow_segment}extra', False),
206 ])
206 ])
207 def test_shadow_repo_regular_expression(self, url, expected):
207 def test_shadow_repo_regular_expression(self, url, expected):
208 from rhodecode.lib.middleware.simplevcs import SimpleVCS
208 from rhodecode.lib.middleware.simplevcs import SimpleVCS
209 url = url.format(
209 url = url.format(
210 pr_segment=self.pr_segment,
210 pr_segment=self.pr_segment,
211 shadow_segment=self.shadow_segment)
211 shadow_segment=self.shadow_segment)
212 match_obj = SimpleVCS.shadow_repo_re.match(url)
212 match_obj = SimpleVCS.shadow_repo_re.match(url)
213 assert (match_obj is not None) == expected
213 assert (match_obj is not None) == expected
214
214
215
215
216 @pytest.mark.backends('git', 'hg')
216 @pytest.mark.backends('git', 'hg')
217 class TestShadowRepoExposure(object):
217 class TestShadowRepoExposure(object):
218
218
219 def test_pull_on_shadow_repo_propagates_to_wsgi_app(self, pylonsapp):
219 def test_pull_on_shadow_repo_propagates_to_wsgi_app(self, pylonsapp):
220 """
220 """
221 Check that a pull action to a shadow repo is propagated to the
221 Check that a pull action to a shadow repo is propagated to the
222 underlying wsgi app.
222 underlying wsgi app.
223 """
223 """
224 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
224 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
225 controller._check_ssl = mock.Mock()
225 controller._check_ssl = mock.Mock()
226 controller.is_shadow_repo = True
226 controller.is_shadow_repo = True
227 controller._action = 'pull'
227 controller._action = 'pull'
228 controller.stub_response_body = 'dummy body value'
228 controller.stub_response_body = 'dummy body value'
229 environ_stub = {
229 environ_stub = {
230 'HTTP_HOST': 'test.example.com',
230 'HTTP_HOST': 'test.example.com',
231 'REQUEST_METHOD': 'GET',
231 'REQUEST_METHOD': 'GET',
232 'wsgi.url_scheme': 'http',
232 'wsgi.url_scheme': 'http',
233 }
233 }
234
234
235 response = controller(environ_stub, mock.Mock())
235 response = controller(environ_stub, mock.Mock())
236 response_body = ''.join(response)
236 response_body = ''.join(response)
237
237
238 # Assert that we got the response from the wsgi app.
238 # Assert that we got the response from the wsgi app.
239 assert response_body == controller.stub_response_body
239 assert response_body == controller.stub_response_body
240
240
241 def test_push_on_shadow_repo_raises(self, pylonsapp):
241 def test_push_on_shadow_repo_raises(self, pylonsapp):
242 """
242 """
243 Check that a push action to a shadow repo is aborted.
243 Check that a push action to a shadow repo is aborted.
244 """
244 """
245 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
245 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
246 controller._check_ssl = mock.Mock()
246 controller._check_ssl = mock.Mock()
247 controller.is_shadow_repo = True
247 controller.is_shadow_repo = True
248 controller._action = 'push'
248 controller._action = 'push'
249 controller.stub_response_body = 'dummy body value'
249 controller.stub_response_body = 'dummy body value'
250 environ_stub = {
250 environ_stub = {
251 'HTTP_HOST': 'test.example.com',
251 'HTTP_HOST': 'test.example.com',
252 'REQUEST_METHOD': 'GET',
252 'REQUEST_METHOD': 'GET',
253 'wsgi.url_scheme': 'http',
253 'wsgi.url_scheme': 'http',
254 }
254 }
255
255
256 response = controller(environ_stub, mock.Mock())
256 response = controller(environ_stub, mock.Mock())
257 response_body = ''.join(response)
257 response_body = ''.join(response)
258
258
259 assert response_body != controller.stub_response_body
259 assert response_body != controller.stub_response_body
260 # Assert that a 406 error is returned.
260 # Assert that a 406 error is returned.
261 assert '406 Not Acceptable' in response_body
261 assert '406 Not Acceptable' in response_body
262
262
263 def test_set_repo_names_no_shadow(self, pylonsapp):
263 def test_set_repo_names_no_shadow(self, pylonsapp):
264 """
264 """
265 Check that the set_repo_names method sets all names to the one returned
265 Check that the set_repo_names method sets all names to the one returned
266 by the _get_repository_name method on a request to a non shadow repo.
266 by the _get_repository_name method on a request to a non shadow repo.
267 """
267 """
268 environ_stub = {}
268 environ_stub = {}
269 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
269 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
270 controller._name = 'RepoGroup/MyRepo'
270 controller._name = 'RepoGroup/MyRepo'
271 controller.set_repo_names(environ_stub)
271 controller.set_repo_names(environ_stub)
272 assert not controller.is_shadow_repo
272 assert not controller.is_shadow_repo
273 assert (controller.url_repo_name ==
273 assert (controller.url_repo_name ==
274 controller.acl_repo_name ==
274 controller.acl_repo_name ==
275 controller.vcs_repo_name ==
275 controller.vcs_repo_name ==
276 controller._get_repository_name(environ_stub))
276 controller._get_repository_name(environ_stub))
277
277
278 def test_set_repo_names_with_shadow(self, pylonsapp, pr_util):
278 def test_set_repo_names_with_shadow(self, pylonsapp, pr_util):
279 """
279 """
280 Check that the set_repo_names method sets correct names on a request
280 Check that the set_repo_names method sets correct names on a request
281 to a shadow repo.
281 to a shadow repo.
282 """
282 """
283 from rhodecode.model.pull_request import PullRequestModel
283 from rhodecode.model.pull_request import PullRequestModel
284
284
285 pull_request = pr_util.create_pull_request()
285 pull_request = pr_util.create_pull_request()
286 shadow_url = '{target}/{pr_segment}/{pr_id}/{shadow_segment}'.format(
286 shadow_url = '{target}/{pr_segment}/{pr_id}/{shadow_segment}'.format(
287 target=pull_request.target_repo.repo_name,
287 target=pull_request.target_repo.repo_name,
288 pr_id=pull_request.pull_request_id,
288 pr_id=pull_request.pull_request_id,
289 pr_segment=TestShadowRepoRegularExpression.pr_segment,
289 pr_segment=TestShadowRepoRegularExpression.pr_segment,
290 shadow_segment=TestShadowRepoRegularExpression.shadow_segment)
290 shadow_segment=TestShadowRepoRegularExpression.shadow_segment)
291 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
291 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
292 controller._name = shadow_url
292 controller._name = shadow_url
293 controller.set_repo_names({})
293 controller.set_repo_names({})
294
294
295 # Get file system path to shadow repo for assertions.
295 # Get file system path to shadow repo for assertions.
296 workspace_id = PullRequestModel()._workspace_id(pull_request)
296 workspace_id = PullRequestModel()._workspace_id(pull_request)
297 target_vcs = pull_request.target_repo.scm_instance()
297 target_vcs = pull_request.target_repo.scm_instance()
298 vcs_repo_name = target_vcs._get_shadow_repository_path(
298 vcs_repo_name = target_vcs._get_shadow_repository_path(
299 workspace_id)
299 workspace_id)
300
300
301 assert controller.vcs_repo_name == vcs_repo_name
301 assert controller.vcs_repo_name == vcs_repo_name
302 assert controller.url_repo_name == shadow_url
302 assert controller.url_repo_name == shadow_url
303 assert controller.acl_repo_name == pull_request.target_repo.repo_name
303 assert controller.acl_repo_name == pull_request.target_repo.repo_name
304 assert controller.is_shadow_repo
304 assert controller.is_shadow_repo
305
305
306 def test_set_repo_names_with_shadow_but_missing_pr(
306 def test_set_repo_names_with_shadow_but_missing_pr(
307 self, pylonsapp, pr_util):
307 self, pylonsapp, pr_util):
308 """
308 """
309 Checks that the set_repo_names method enforces matching target repos
309 Checks that the set_repo_names method enforces matching target repos
310 and pull request IDs.
310 and pull request IDs.
311 """
311 """
312 pull_request = pr_util.create_pull_request()
312 pull_request = pr_util.create_pull_request()
313 shadow_url = '{target}/{pr_segment}/{pr_id}/{shadow_segment}'.format(
313 shadow_url = '{target}/{pr_segment}/{pr_id}/{shadow_segment}'.format(
314 target=pull_request.target_repo.repo_name,
314 target=pull_request.target_repo.repo_name,
315 pr_id=999999999,
315 pr_id=999999999,
316 pr_segment=TestShadowRepoRegularExpression.pr_segment,
316 pr_segment=TestShadowRepoRegularExpression.pr_segment,
317 shadow_segment=TestShadowRepoRegularExpression.shadow_segment)
317 shadow_segment=TestShadowRepoRegularExpression.shadow_segment)
318 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
318 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
319 controller._name = shadow_url
319 controller._name = shadow_url
320 controller.set_repo_names({})
320 controller.set_repo_names({})
321
321
322 assert not controller.is_shadow_repo
322 assert not controller.is_shadow_repo
323 assert (controller.url_repo_name ==
323 assert (controller.url_repo_name ==
324 controller.acl_repo_name ==
324 controller.acl_repo_name ==
325 controller.vcs_repo_name)
325 controller.vcs_repo_name)
326
326
327
327
328 @pytest.mark.usefixtures('db')
328 @pytest.mark.usefixtures('db')
329 class TestGenerateVcsResponse:
329 class TestGenerateVcsResponse:
330
330
331 def test_ensures_that_start_response_is_called_early_enough(self):
331 def test_ensures_that_start_response_is_called_early_enough(self):
332 self.call_controller_with_response_body(iter(['a', 'b']))
332 self.call_controller_with_response_body(iter(['a', 'b']))
333 assert self.start_response.called
333 assert self.start_response.called
334
334
335 def test_invalidates_cache_after_body_is_consumed(self):
335 def test_invalidates_cache_after_body_is_consumed(self):
336 result = self.call_controller_with_response_body(iter(['a', 'b']))
336 result = self.call_controller_with_response_body(iter(['a', 'b']))
337 assert not self.was_cache_invalidated()
337 assert not self.was_cache_invalidated()
338 # Consume the result
338 # Consume the result
339 list(result)
339 list(result)
340 assert self.was_cache_invalidated()
340 assert self.was_cache_invalidated()
341
341
342 @mock.patch('rhodecode.lib.middleware.simplevcs.HTTPLockedRC')
342 @mock.patch('rhodecode.lib.middleware.simplevcs.HTTPLockedRC')
343 def test_handles_locking_exception(self, http_locked_rc):
343 def test_handles_locking_exception(self, http_locked_rc):
344 result = self.call_controller_with_response_body(
344 result = self.call_controller_with_response_body(
345 self.raise_result_iter(vcs_kind='repo_locked'))
345 self.raise_result_iter(vcs_kind='repo_locked'))
346 assert not http_locked_rc.called
346 assert not http_locked_rc.called
347 # Consume the result
347 # Consume the result
348 list(result)
348 list(result)
349 assert http_locked_rc.called
349 assert http_locked_rc.called
350
350
351 @mock.patch('rhodecode.lib.middleware.simplevcs.HTTPRequirementError')
351 @mock.patch('rhodecode.lib.middleware.simplevcs.HTTPRequirementError')
352 def test_handles_requirement_exception(self, http_requirement):
352 def test_handles_requirement_exception(self, http_requirement):
353 result = self.call_controller_with_response_body(
353 result = self.call_controller_with_response_body(
354 self.raise_result_iter(vcs_kind='requirement'))
354 self.raise_result_iter(vcs_kind='requirement'))
355 assert not http_requirement.called
355 assert not http_requirement.called
356 # Consume the result
356 # Consume the result
357 list(result)
357 list(result)
358 assert http_requirement.called
358 assert http_requirement.called
359
359
360 @mock.patch('rhodecode.lib.middleware.simplevcs.HTTPLockedRC')
360 @mock.patch('rhodecode.lib.middleware.simplevcs.HTTPLockedRC')
361 def test_handles_locking_exception_in_app_call(self, http_locked_rc):
361 def test_handles_locking_exception_in_app_call(self, http_locked_rc):
362 app_factory_patcher = mock.patch.object(
362 app_factory_patcher = mock.patch.object(
363 StubVCSController, '_create_wsgi_app')
363 StubVCSController, '_create_wsgi_app')
364 with app_factory_patcher as app_factory:
364 with app_factory_patcher as app_factory:
365 app_factory().side_effect = self.vcs_exception()
365 app_factory().side_effect = self.vcs_exception()
366 result = self.call_controller_with_response_body(['a'])
366 result = self.call_controller_with_response_body(['a'])
367 list(result)
367 list(result)
368 assert http_locked_rc.called
368 assert http_locked_rc.called
369
369
370 def test_raises_unknown_exceptions(self):
370 def test_raises_unknown_exceptions(self):
371 result = self.call_controller_with_response_body(
371 result = self.call_controller_with_response_body(
372 self.raise_result_iter(vcs_kind='unknown'))
372 self.raise_result_iter(vcs_kind='unknown'))
373 with pytest.raises(Exception):
373 with pytest.raises(Exception):
374 list(result)
374 list(result)
375
375
376 def test_prepare_callback_daemon_is_called(self):
376 def test_prepare_callback_daemon_is_called(self):
377 def side_effect(extras):
377 def side_effect(extras):
378 return DummyHooksCallbackDaemon(), extras
378 return DummyHooksCallbackDaemon(), extras
379
379
380 prepare_patcher = mock.patch.object(
380 prepare_patcher = mock.patch.object(
381 StubVCSController, '_prepare_callback_daemon')
381 StubVCSController, '_prepare_callback_daemon')
382 with prepare_patcher as prepare_mock:
382 with prepare_patcher as prepare_mock:
383 prepare_mock.side_effect = side_effect
383 prepare_mock.side_effect = side_effect
384 self.call_controller_with_response_body(iter(['a', 'b']))
384 self.call_controller_with_response_body(iter(['a', 'b']))
385 assert prepare_mock.called
385 assert prepare_mock.called
386 assert prepare_mock.call_count == 1
386 assert prepare_mock.call_count == 1
387
387
388 def call_controller_with_response_body(self, response_body):
388 def call_controller_with_response_body(self, response_body):
389 settings = {
389 settings = {
390 'base_path': 'fake_base_path',
390 'base_path': 'fake_base_path',
391 'vcs.hooks.protocol': 'http',
391 'vcs.hooks.protocol': 'http',
392 'vcs.hooks.direct_calls': False,
392 'vcs.hooks.direct_calls': False,
393 }
393 }
394 controller = StubVCSController(None, settings, None)
394 controller = StubVCSController(None, settings, None)
395 controller._invalidate_cache = mock.Mock()
395 controller._invalidate_cache = mock.Mock()
396 controller.stub_response_body = response_body
396 controller.stub_response_body = response_body
397 self.start_response = mock.Mock()
397 self.start_response = mock.Mock()
398 result = controller._generate_vcs_response(
398 result = controller._generate_vcs_response(
399 environ={}, start_response=self.start_response,
399 environ={}, start_response=self.start_response,
400 repo_path='fake_repo_path',
400 repo_path='fake_repo_path',
401 extras={}, action='push')
401 extras={}, action='push')
402 self.controller = controller
402 self.controller = controller
403 return result
403 return result
404
404
405 def raise_result_iter(self, vcs_kind='repo_locked'):
405 def raise_result_iter(self, vcs_kind='repo_locked'):
406 """
406 """
407 Simulates an exception due to a vcs raised exception if kind vcs_kind
407 Simulates an exception due to a vcs raised exception if kind vcs_kind
408 """
408 """
409 raise self.vcs_exception(vcs_kind=vcs_kind)
409 raise self.vcs_exception(vcs_kind=vcs_kind)
410 yield "never_reached"
410 yield "never_reached"
411
411
412 def vcs_exception(self, vcs_kind='repo_locked'):
412 def vcs_exception(self, vcs_kind='repo_locked'):
413 locked_exception = Exception('TEST_MESSAGE')
413 locked_exception = Exception('TEST_MESSAGE')
414 locked_exception._vcs_kind = vcs_kind
414 locked_exception._vcs_kind = vcs_kind
415 return locked_exception
415 return locked_exception
416
416
417 def was_cache_invalidated(self):
417 def was_cache_invalidated(self):
418 return self.controller._invalidate_cache.called
418 return self.controller._invalidate_cache.called
419
419
420
420
421 class TestInitializeGenerator:
421 class TestInitializeGenerator:
422
422
423 def test_drains_first_element(self):
423 def test_drains_first_element(self):
424 gen = self.factory(['__init__', 1, 2])
424 gen = self.factory(['__init__', 1, 2])
425 result = list(gen)
425 result = list(gen)
426 assert result == [1, 2]
426 assert result == [1, 2]
427
427
428 @pytest.mark.parametrize('values', [
428 @pytest.mark.parametrize('values', [
429 [],
429 [],
430 [1, 2],
430 [1, 2],
431 ])
431 ])
432 def test_raises_value_error(self, values):
432 def test_raises_value_error(self, values):
433 with pytest.raises(ValueError):
433 with pytest.raises(ValueError):
434 self.factory(values)
434 self.factory(values)
435
435
436 @simplevcs.initialize_generator
436 @simplevcs.initialize_generator
437 def factory(self, iterable):
437 def factory(self, iterable):
438 for elem in iterable:
438 for elem in iterable:
439 yield elem
439 yield elem
440
440
441
441
442 class TestPrepareHooksDaemon(object):
442 class TestPrepareHooksDaemon(object):
443 def test_calls_imported_prepare_callback_daemon(self, app_settings):
443 def test_calls_imported_prepare_callback_daemon(self, app_settings):
444 expected_extras = {'extra1': 'value1'}
444 expected_extras = {'extra1': 'value1'}
445 daemon = DummyHooksCallbackDaemon()
445 daemon = DummyHooksCallbackDaemon()
446
446
447 controller = StubVCSController(None, app_settings, None)
447 controller = StubVCSController(None, app_settings, None)
448 prepare_patcher = mock.patch.object(
448 prepare_patcher = mock.patch.object(
449 simplevcs, 'prepare_callback_daemon',
449 simplevcs, 'prepare_callback_daemon',
450 return_value=(daemon, expected_extras))
450 return_value=(daemon, expected_extras))
451 with prepare_patcher as prepare_mock:
451 with prepare_patcher as prepare_mock:
452 callback_daemon, extras = controller._prepare_callback_daemon(
452 callback_daemon, extras = controller._prepare_callback_daemon(
453 expected_extras.copy())
453 expected_extras.copy())
454 prepare_mock.assert_called_once_with(
454 prepare_mock.assert_called_once_with(
455 expected_extras,
455 expected_extras,
456 protocol=app_settings['vcs.hooks.protocol'],
456 protocol=app_settings['vcs.hooks.protocol'],
457 use_direct_calls=app_settings['vcs.hooks.direct_calls'])
457 use_direct_calls=app_settings['vcs.hooks.direct_calls'])
458
458
459 assert callback_daemon == daemon
459 assert callback_daemon == daemon
460 assert extras == extras
460 assert extras == extras
General Comments 0
You need to be logged in to leave comments. Login now