Show More
@@ -1,1929 +1,1972 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 inspect |
|
26 | import inspect | |
26 | import collections |
|
27 | import collections | |
27 | import fnmatch |
|
28 | import fnmatch | |
28 | import hashlib |
|
29 | import hashlib | |
29 | import itertools |
|
30 | import itertools | |
30 | import logging |
|
31 | import logging | |
31 | import os |
|
|||
32 | import random |
|
32 | import random | |
33 | import time |
|
|||
34 | import traceback |
|
33 | import traceback | |
35 | from functools import wraps |
|
34 | from functools import wraps | |
36 |
|
35 | |||
37 | import ipaddress |
|
36 | import ipaddress | |
38 | from pyramid.httpexceptions import HTTPForbidden |
|
37 | from pyramid.httpexceptions import HTTPForbidden, HTTPFound | |
39 | from pylons import url, request |
|
38 | from pylons import url, request | |
40 | from pylons.controllers.util import abort, redirect |
|
39 | from pylons.controllers.util import abort, redirect | |
41 | from pylons.i18n.translation import _ |
|
40 | from pylons.i18n.translation import _ | |
42 | from sqlalchemy import or_ |
|
|||
43 | from sqlalchemy.orm.exc import ObjectDeletedError |
|
41 | from sqlalchemy.orm.exc import ObjectDeletedError | |
44 | from sqlalchemy.orm import joinedload |
|
42 | from sqlalchemy.orm import joinedload | |
45 | from zope.cachedescriptors.property import Lazy as LazyProperty |
|
43 | from zope.cachedescriptors.property import Lazy as LazyProperty | |
46 |
|
44 | |||
47 | import rhodecode |
|
45 | import rhodecode | |
48 | from rhodecode.model import meta |
|
46 | from rhodecode.model import meta | |
49 | from rhodecode.model.meta import Session |
|
47 | from rhodecode.model.meta import Session | |
50 | from rhodecode.model.user import UserModel |
|
48 | from rhodecode.model.user import UserModel | |
51 | from rhodecode.model.db import ( |
|
49 | from rhodecode.model.db import ( | |
52 | User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember, |
|
50 | User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember, | |
53 | UserIpMap, UserApiKeys, RepoGroup) |
|
51 | UserIpMap, UserApiKeys, RepoGroup) | |
54 | from rhodecode.lib import caches |
|
52 | from rhodecode.lib import caches | |
55 | from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5 |
|
53 | from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5 | |
56 | from rhodecode.lib.utils import ( |
|
54 | from rhodecode.lib.utils import ( | |
57 | get_repo_slug, get_repo_group_slug, get_user_group_slug) |
|
55 | get_repo_slug, get_repo_group_slug, get_user_group_slug) | |
58 | from rhodecode.lib.caching_query import FromCache |
|
56 | from rhodecode.lib.caching_query import FromCache | |
59 |
|
57 | |||
60 |
|
58 | |||
61 | if rhodecode.is_unix: |
|
59 | if rhodecode.is_unix: | |
62 | import bcrypt |
|
60 | import bcrypt | |
63 |
|
61 | |||
64 | log = logging.getLogger(__name__) |
|
62 | log = logging.getLogger(__name__) | |
65 |
|
63 | |||
66 | csrf_token_key = "csrf_token" |
|
64 | csrf_token_key = "csrf_token" | |
67 |
|
65 | |||
68 |
|
66 | |||
69 | class PasswordGenerator(object): |
|
67 | class PasswordGenerator(object): | |
70 | """ |
|
68 | """ | |
71 | 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 | |
72 | characters |
|
70 | characters | |
73 | usage:: |
|
71 | usage:: | |
74 |
|
72 | |||
75 | passwd_gen = PasswordGenerator() |
|
73 | passwd_gen = PasswordGenerator() | |
76 | #print 8-letter password containing only big and small letters |
|
74 | #print 8-letter password containing only big and small letters | |
77 | of alphabet |
|
75 | of alphabet | |
78 | passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL) |
|
76 | passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL) | |
79 | """ |
|
77 | """ | |
80 | ALPHABETS_NUM = r'''1234567890''' |
|
78 | ALPHABETS_NUM = r'''1234567890''' | |
81 | ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm''' |
|
79 | ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm''' | |
82 | ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM''' |
|
80 | ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM''' | |
83 | ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?''' |
|
81 | ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?''' | |
84 | ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \ |
|
82 | ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \ | |
85 | + ALPHABETS_NUM + ALPHABETS_SPECIAL |
|
83 | + ALPHABETS_NUM + ALPHABETS_SPECIAL | |
86 | ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM |
|
84 | ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM | |
87 | ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL |
|
85 | ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL | |
88 | ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM |
|
86 | ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM | |
89 | ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM |
|
87 | ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM | |
90 |
|
88 | |||
91 | def __init__(self, passwd=''): |
|
89 | def __init__(self, passwd=''): | |
92 | self.passwd = passwd |
|
90 | self.passwd = passwd | |
93 |
|
91 | |||
94 | def gen_password(self, length, type_=None): |
|
92 | def gen_password(self, length, type_=None): | |
95 | if type_ is None: |
|
93 | if type_ is None: | |
96 | type_ = self.ALPHABETS_FULL |
|
94 | type_ = self.ALPHABETS_FULL | |
97 | self.passwd = ''.join([random.choice(type_) for _ in xrange(length)]) |
|
95 | self.passwd = ''.join([random.choice(type_) for _ in xrange(length)]) | |
98 | return self.passwd |
|
96 | return self.passwd | |
99 |
|
97 | |||
100 |
|
98 | |||
101 | class _RhodeCodeCryptoBase(object): |
|
99 | class _RhodeCodeCryptoBase(object): | |
102 | ENC_PREF = None |
|
100 | ENC_PREF = None | |
103 |
|
101 | |||
104 | def hash_create(self, str_): |
|
102 | def hash_create(self, str_): | |
105 | """ |
|
103 | """ | |
106 | hash the string using |
|
104 | hash the string using | |
107 |
|
105 | |||
108 | :param str_: password to hash |
|
106 | :param str_: password to hash | |
109 | """ |
|
107 | """ | |
110 | raise NotImplementedError |
|
108 | raise NotImplementedError | |
111 |
|
109 | |||
112 | def hash_check_with_upgrade(self, password, hashed): |
|
110 | def hash_check_with_upgrade(self, password, hashed): | |
113 | """ |
|
111 | """ | |
114 | Returns tuple in which first element is boolean that states that |
|
112 | Returns tuple in which first element is boolean that states that | |
115 | 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 | |
116 | 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 | |
117 | cipher. |
|
115 | cipher. | |
118 | """ |
|
116 | """ | |
119 | checked_hash = self.hash_check(password, hashed) |
|
117 | checked_hash = self.hash_check(password, hashed) | |
120 | return checked_hash, None |
|
118 | return checked_hash, None | |
121 |
|
119 | |||
122 | def hash_check(self, password, hashed): |
|
120 | def hash_check(self, password, hashed): | |
123 | """ |
|
121 | """ | |
124 | Checks matching password with it's hashed value. |
|
122 | Checks matching password with it's hashed value. | |
125 |
|
123 | |||
126 | :param password: password |
|
124 | :param password: password | |
127 | :param hashed: password in hashed form |
|
125 | :param hashed: password in hashed form | |
128 | """ |
|
126 | """ | |
129 | raise NotImplementedError |
|
127 | raise NotImplementedError | |
130 |
|
128 | |||
131 | def _assert_bytes(self, value): |
|
129 | def _assert_bytes(self, value): | |
132 | """ |
|
130 | """ | |
133 | 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 | |
134 | if passwords contain non-ascii characters. Doing a type check |
|
132 | if passwords contain non-ascii characters. Doing a type check | |
135 | during runtime, so that such mistakes are detected early on. |
|
133 | during runtime, so that such mistakes are detected early on. | |
136 | """ |
|
134 | """ | |
137 | if not isinstance(value, str): |
|
135 | if not isinstance(value, str): | |
138 | raise TypeError( |
|
136 | raise TypeError( | |
139 | "Bytestring required as input, got %r." % (value, )) |
|
137 | "Bytestring required as input, got %r." % (value, )) | |
140 |
|
138 | |||
141 |
|
139 | |||
142 | class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase): |
|
140 | class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase): | |
143 | ENC_PREF = '$2a$10' |
|
141 | ENC_PREF = '$2a$10' | |
144 |
|
142 | |||
145 | def hash_create(self, str_): |
|
143 | def hash_create(self, str_): | |
146 | self._assert_bytes(str_) |
|
144 | self._assert_bytes(str_) | |
147 | return bcrypt.hashpw(str_, bcrypt.gensalt(10)) |
|
145 | return bcrypt.hashpw(str_, bcrypt.gensalt(10)) | |
148 |
|
146 | |||
149 | def hash_check_with_upgrade(self, password, hashed): |
|
147 | def hash_check_with_upgrade(self, password, hashed): | |
150 | """ |
|
148 | """ | |
151 | Returns tuple in which first element is boolean that states that |
|
149 | Returns tuple in which first element is boolean that states that | |
152 | 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 | |
153 | 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 | |
154 | cipher. |
|
152 | cipher. | |
155 |
|
153 | |||
156 | This implements special upgrade logic which works like that: |
|
154 | This implements special upgrade logic which works like that: | |
157 | - check if the given password == bcrypted hash, if yes then we |
|
155 | - check if the given password == bcrypted hash, if yes then we | |
158 | properly used password and it was already in bcrypt. Proceed |
|
156 | properly used password and it was already in bcrypt. Proceed | |
159 | without any changes |
|
157 | without any changes | |
160 | - 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 | |
161 | 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 | |
162 | hash change and proceed |
|
160 | hash change and proceed | |
163 | """ |
|
161 | """ | |
164 |
|
162 | |||
165 | new_hash = None |
|
163 | new_hash = None | |
166 |
|
164 | |||
167 | # regular pw check |
|
165 | # regular pw check | |
168 | password_match_bcrypt = self.hash_check(password, hashed) |
|
166 | password_match_bcrypt = self.hash_check(password, hashed) | |
169 |
|
167 | |||
170 | # 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 | |
171 | # basically calling _RhodeCodeCryptoSha256().hash_check() |
|
169 | # basically calling _RhodeCodeCryptoSha256().hash_check() | |
172 | if not password_match_bcrypt: |
|
170 | if not password_match_bcrypt: | |
173 | if _RhodeCodeCryptoSha256().hash_check(password, hashed): |
|
171 | if _RhodeCodeCryptoSha256().hash_check(password, hashed): | |
174 | new_hash = self.hash_create(password) # make new bcrypt hash |
|
172 | new_hash = self.hash_create(password) # make new bcrypt hash | |
175 | password_match_bcrypt = True |
|
173 | password_match_bcrypt = True | |
176 |
|
174 | |||
177 | return password_match_bcrypt, new_hash |
|
175 | return password_match_bcrypt, new_hash | |
178 |
|
176 | |||
179 | def hash_check(self, password, hashed): |
|
177 | def hash_check(self, password, hashed): | |
180 | """ |
|
178 | """ | |
181 | Checks matching password with it's hashed value. |
|
179 | Checks matching password with it's hashed value. | |
182 |
|
180 | |||
183 | :param password: password |
|
181 | :param password: password | |
184 | :param hashed: password in hashed form |
|
182 | :param hashed: password in hashed form | |
185 | """ |
|
183 | """ | |
186 | self._assert_bytes(password) |
|
184 | self._assert_bytes(password) | |
187 | try: |
|
185 | try: | |
188 | return bcrypt.hashpw(password, hashed) == hashed |
|
186 | return bcrypt.hashpw(password, hashed) == hashed | |
189 | except ValueError as e: |
|
187 | except ValueError as e: | |
190 | # 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 | |
191 | # just return with False as it would be a wrong password. |
|
189 | # just return with False as it would be a wrong password. | |
192 | log.debug('Failed to check password hash using bcrypt %s', |
|
190 | log.debug('Failed to check password hash using bcrypt %s', | |
193 | safe_str(e)) |
|
191 | safe_str(e)) | |
194 |
|
192 | |||
195 | return False |
|
193 | return False | |
196 |
|
194 | |||
197 |
|
195 | |||
198 | class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase): |
|
196 | class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase): | |
199 | ENC_PREF = '_' |
|
197 | ENC_PREF = '_' | |
200 |
|
198 | |||
201 | def hash_create(self, str_): |
|
199 | def hash_create(self, str_): | |
202 | self._assert_bytes(str_) |
|
200 | self._assert_bytes(str_) | |
203 | return hashlib.sha256(str_).hexdigest() |
|
201 | return hashlib.sha256(str_).hexdigest() | |
204 |
|
202 | |||
205 | def hash_check(self, password, hashed): |
|
203 | def hash_check(self, password, hashed): | |
206 | """ |
|
204 | """ | |
207 | Checks matching password with it's hashed value. |
|
205 | Checks matching password with it's hashed value. | |
208 |
|
206 | |||
209 | :param password: password |
|
207 | :param password: password | |
210 | :param hashed: password in hashed form |
|
208 | :param hashed: password in hashed form | |
211 | """ |
|
209 | """ | |
212 | self._assert_bytes(password) |
|
210 | self._assert_bytes(password) | |
213 | return hashlib.sha256(password).hexdigest() == hashed |
|
211 | return hashlib.sha256(password).hexdigest() == hashed | |
214 |
|
212 | |||
215 |
|
213 | |||
216 | class _RhodeCodeCryptoMd5(_RhodeCodeCryptoBase): |
|
214 | class _RhodeCodeCryptoMd5(_RhodeCodeCryptoBase): | |
217 | ENC_PREF = '_' |
|
215 | ENC_PREF = '_' | |
218 |
|
216 | |||
219 | def hash_create(self, str_): |
|
217 | def hash_create(self, str_): | |
220 | self._assert_bytes(str_) |
|
218 | self._assert_bytes(str_) | |
221 | return hashlib.md5(str_).hexdigest() |
|
219 | return hashlib.md5(str_).hexdigest() | |
222 |
|
220 | |||
223 | def hash_check(self, password, hashed): |
|
221 | def hash_check(self, password, hashed): | |
224 | """ |
|
222 | """ | |
225 | Checks matching password with it's hashed value. |
|
223 | Checks matching password with it's hashed value. | |
226 |
|
224 | |||
227 | :param password: password |
|
225 | :param password: password | |
228 | :param hashed: password in hashed form |
|
226 | :param hashed: password in hashed form | |
229 | """ |
|
227 | """ | |
230 | self._assert_bytes(password) |
|
228 | self._assert_bytes(password) | |
231 | return hashlib.md5(password).hexdigest() == hashed |
|
229 | return hashlib.md5(password).hexdigest() == hashed | |
232 |
|
230 | |||
233 |
|
231 | |||
234 | def crypto_backend(): |
|
232 | def crypto_backend(): | |
235 | """ |
|
233 | """ | |
236 | Return the matching crypto backend. |
|
234 | Return the matching crypto backend. | |
237 |
|
235 | |||
238 | 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 | |
239 | tests faster since BCRYPT is expensive to calculate |
|
237 | tests faster since BCRYPT is expensive to calculate | |
240 | """ |
|
238 | """ | |
241 | if rhodecode.is_test: |
|
239 | if rhodecode.is_test: | |
242 | RhodeCodeCrypto = _RhodeCodeCryptoMd5() |
|
240 | RhodeCodeCrypto = _RhodeCodeCryptoMd5() | |
243 | else: |
|
241 | else: | |
244 | RhodeCodeCrypto = _RhodeCodeCryptoBCrypt() |
|
242 | RhodeCodeCrypto = _RhodeCodeCryptoBCrypt() | |
245 |
|
243 | |||
246 | return RhodeCodeCrypto |
|
244 | return RhodeCodeCrypto | |
247 |
|
245 | |||
248 |
|
246 | |||
249 | def get_crypt_password(password): |
|
247 | def get_crypt_password(password): | |
250 | """ |
|
248 | """ | |
251 | Create the hash of `password` with the active crypto backend. |
|
249 | Create the hash of `password` with the active crypto backend. | |
252 |
|
250 | |||
253 | :param password: The cleartext password. |
|
251 | :param password: The cleartext password. | |
254 | :type password: unicode |
|
252 | :type password: unicode | |
255 | """ |
|
253 | """ | |
256 | password = safe_str(password) |
|
254 | password = safe_str(password) | |
257 | return crypto_backend().hash_create(password) |
|
255 | return crypto_backend().hash_create(password) | |
258 |
|
256 | |||
259 |
|
257 | |||
260 | def check_password(password, hashed): |
|
258 | def check_password(password, hashed): | |
261 | """ |
|
259 | """ | |
262 | Check if the value in `password` matches the hash in `hashed`. |
|
260 | Check if the value in `password` matches the hash in `hashed`. | |
263 |
|
261 | |||
264 | :param password: The cleartext password. |
|
262 | :param password: The cleartext password. | |
265 | :type password: unicode |
|
263 | :type password: unicode | |
266 |
|
264 | |||
267 | :param hashed: The expected hashed version of the password. |
|
265 | :param hashed: The expected hashed version of the password. | |
268 | :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. | |
269 | """ |
|
267 | """ | |
270 | password = safe_str(password) |
|
268 | password = safe_str(password) | |
271 | return crypto_backend().hash_check(password, hashed) |
|
269 | return crypto_backend().hash_check(password, hashed) | |
272 |
|
270 | |||
273 |
|
271 | |||
274 | def generate_auth_token(data, salt=None): |
|
272 | def generate_auth_token(data, salt=None): | |
275 | """ |
|
273 | """ | |
276 | Generates API KEY from given string |
|
274 | Generates API KEY from given string | |
277 | """ |
|
275 | """ | |
278 |
|
276 | |||
279 | if salt is None: |
|
277 | if salt is None: | |
280 | salt = os.urandom(16) |
|
278 | salt = os.urandom(16) | |
281 | return hashlib.sha1(safe_str(data) + salt).hexdigest() |
|
279 | return hashlib.sha1(safe_str(data) + salt).hexdigest() | |
282 |
|
280 | |||
283 |
|
281 | |||
284 | class CookieStoreWrapper(object): |
|
282 | class CookieStoreWrapper(object): | |
285 |
|
283 | |||
286 | def __init__(self, cookie_store): |
|
284 | def __init__(self, cookie_store): | |
287 | self.cookie_store = cookie_store |
|
285 | self.cookie_store = cookie_store | |
288 |
|
286 | |||
289 | def __repr__(self): |
|
287 | def __repr__(self): | |
290 | return 'CookieStore<%s>' % (self.cookie_store) |
|
288 | return 'CookieStore<%s>' % (self.cookie_store) | |
291 |
|
289 | |||
292 | def get(self, key, other=None): |
|
290 | def get(self, key, other=None): | |
293 | if isinstance(self.cookie_store, dict): |
|
291 | if isinstance(self.cookie_store, dict): | |
294 | return self.cookie_store.get(key, other) |
|
292 | return self.cookie_store.get(key, other) | |
295 | elif isinstance(self.cookie_store, AuthUser): |
|
293 | elif isinstance(self.cookie_store, AuthUser): | |
296 | return self.cookie_store.__dict__.get(key, other) |
|
294 | return self.cookie_store.__dict__.get(key, other) | |
297 |
|
295 | |||
298 |
|
296 | |||
299 | def _cached_perms_data(user_id, scope, user_is_admin, |
|
297 | def _cached_perms_data(user_id, scope, user_is_admin, | |
300 | user_inherit_default_permissions, explicit, algo): |
|
298 | user_inherit_default_permissions, explicit, algo): | |
301 |
|
299 | |||
302 | permissions = PermissionCalculator( |
|
300 | permissions = PermissionCalculator( | |
303 | user_id, scope, user_is_admin, user_inherit_default_permissions, |
|
301 | user_id, scope, user_is_admin, user_inherit_default_permissions, | |
304 | explicit, algo) |
|
302 | explicit, algo) | |
305 | return permissions.calculate() |
|
303 | return permissions.calculate() | |
306 |
|
304 | |||
307 | class PermOrigin: |
|
305 | class PermOrigin: | |
308 | ADMIN = 'superadmin' |
|
306 | ADMIN = 'superadmin' | |
309 |
|
307 | |||
310 | REPO_USER = 'user:%s' |
|
308 | REPO_USER = 'user:%s' | |
311 | REPO_USERGROUP = 'usergroup:%s' |
|
309 | REPO_USERGROUP = 'usergroup:%s' | |
312 | REPO_OWNER = 'repo.owner' |
|
310 | REPO_OWNER = 'repo.owner' | |
313 | REPO_DEFAULT = 'repo.default' |
|
311 | REPO_DEFAULT = 'repo.default' | |
314 | REPO_PRIVATE = 'repo.private' |
|
312 | REPO_PRIVATE = 'repo.private' | |
315 |
|
313 | |||
316 | REPOGROUP_USER = 'user:%s' |
|
314 | REPOGROUP_USER = 'user:%s' | |
317 | REPOGROUP_USERGROUP = 'usergroup:%s' |
|
315 | REPOGROUP_USERGROUP = 'usergroup:%s' | |
318 | REPOGROUP_OWNER = 'group.owner' |
|
316 | REPOGROUP_OWNER = 'group.owner' | |
319 | REPOGROUP_DEFAULT = 'group.default' |
|
317 | REPOGROUP_DEFAULT = 'group.default' | |
320 |
|
318 | |||
321 | USERGROUP_USER = 'user:%s' |
|
319 | USERGROUP_USER = 'user:%s' | |
322 | USERGROUP_USERGROUP = 'usergroup:%s' |
|
320 | USERGROUP_USERGROUP = 'usergroup:%s' | |
323 | USERGROUP_OWNER = 'usergroup.owner' |
|
321 | USERGROUP_OWNER = 'usergroup.owner' | |
324 | USERGROUP_DEFAULT = 'usergroup.default' |
|
322 | USERGROUP_DEFAULT = 'usergroup.default' | |
325 |
|
323 | |||
326 |
|
324 | |||
327 | class PermOriginDict(dict): |
|
325 | class PermOriginDict(dict): | |
328 | """ |
|
326 | """ | |
329 | A special dict used for tracking permissions along with their origins. |
|
327 | A special dict used for tracking permissions along with their origins. | |
330 |
|
328 | |||
331 | `__setitem__` has been overridden to expect a tuple(perm, origin) |
|
329 | `__setitem__` has been overridden to expect a tuple(perm, origin) | |
332 | `__getitem__` will return only the perm |
|
330 | `__getitem__` will return only the perm | |
333 | `.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 | |
334 |
|
332 | |||
335 | >>> perms = PermOriginDict() |
|
333 | >>> perms = PermOriginDict() | |
336 | >>> perms['resource'] = 'read', 'default' |
|
334 | >>> perms['resource'] = 'read', 'default' | |
337 | >>> perms['resource'] |
|
335 | >>> perms['resource'] | |
338 | 'read' |
|
336 | 'read' | |
339 | >>> perms['resource'] = 'write', 'admin' |
|
337 | >>> perms['resource'] = 'write', 'admin' | |
340 | >>> perms['resource'] |
|
338 | >>> perms['resource'] | |
341 | 'write' |
|
339 | 'write' | |
342 | >>> perms.perm_origin_stack |
|
340 | >>> perms.perm_origin_stack | |
343 | {'resource': [('read', 'default'), ('write', 'admin')]} |
|
341 | {'resource': [('read', 'default'), ('write', 'admin')]} | |
344 | """ |
|
342 | """ | |
345 |
|
343 | |||
346 |
|
344 | |||
347 | def __init__(self, *args, **kw): |
|
345 | def __init__(self, *args, **kw): | |
348 | dict.__init__(self, *args, **kw) |
|
346 | dict.__init__(self, *args, **kw) | |
349 | self.perm_origin_stack = {} |
|
347 | self.perm_origin_stack = {} | |
350 |
|
348 | |||
351 | def __setitem__(self, key, (perm, origin)): |
|
349 | def __setitem__(self, key, (perm, origin)): | |
352 | self.perm_origin_stack.setdefault(key, []).append((perm, origin)) |
|
350 | self.perm_origin_stack.setdefault(key, []).append((perm, origin)) | |
353 | dict.__setitem__(self, key, perm) |
|
351 | dict.__setitem__(self, key, perm) | |
354 |
|
352 | |||
355 |
|
353 | |||
356 | class PermissionCalculator(object): |
|
354 | class PermissionCalculator(object): | |
357 |
|
355 | |||
358 | def __init__( |
|
356 | def __init__( | |
359 | self, user_id, scope, user_is_admin, |
|
357 | self, user_id, scope, user_is_admin, | |
360 | user_inherit_default_permissions, explicit, algo): |
|
358 | user_inherit_default_permissions, explicit, algo): | |
361 | self.user_id = user_id |
|
359 | self.user_id = user_id | |
362 | self.user_is_admin = user_is_admin |
|
360 | self.user_is_admin = user_is_admin | |
363 | self.inherit_default_permissions = user_inherit_default_permissions |
|
361 | self.inherit_default_permissions = user_inherit_default_permissions | |
364 | self.explicit = explicit |
|
362 | self.explicit = explicit | |
365 | self.algo = algo |
|
363 | self.algo = algo | |
366 |
|
364 | |||
367 | scope = scope or {} |
|
365 | scope = scope or {} | |
368 | self.scope_repo_id = scope.get('repo_id') |
|
366 | self.scope_repo_id = scope.get('repo_id') | |
369 | self.scope_repo_group_id = scope.get('repo_group_id') |
|
367 | self.scope_repo_group_id = scope.get('repo_group_id') | |
370 | self.scope_user_group_id = scope.get('user_group_id') |
|
368 | self.scope_user_group_id = scope.get('user_group_id') | |
371 |
|
369 | |||
372 | 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 | |
373 |
|
371 | |||
374 | self.permissions_repositories = PermOriginDict() |
|
372 | self.permissions_repositories = PermOriginDict() | |
375 | self.permissions_repository_groups = PermOriginDict() |
|
373 | self.permissions_repository_groups = PermOriginDict() | |
376 | self.permissions_user_groups = PermOriginDict() |
|
374 | self.permissions_user_groups = PermOriginDict() | |
377 | self.permissions_global = set() |
|
375 | self.permissions_global = set() | |
378 |
|
376 | |||
379 | self.default_repo_perms = Permission.get_default_repo_perms( |
|
377 | self.default_repo_perms = Permission.get_default_repo_perms( | |
380 | self.default_user_id, self.scope_repo_id) |
|
378 | self.default_user_id, self.scope_repo_id) | |
381 | self.default_repo_groups_perms = Permission.get_default_group_perms( |
|
379 | self.default_repo_groups_perms = Permission.get_default_group_perms( | |
382 | self.default_user_id, self.scope_repo_group_id) |
|
380 | self.default_user_id, self.scope_repo_group_id) | |
383 | self.default_user_group_perms = \ |
|
381 | self.default_user_group_perms = \ | |
384 | Permission.get_default_user_group_perms( |
|
382 | Permission.get_default_user_group_perms( | |
385 | self.default_user_id, self.scope_user_group_id) |
|
383 | self.default_user_id, self.scope_user_group_id) | |
386 |
|
384 | |||
387 | def calculate(self): |
|
385 | def calculate(self): | |
388 | if self.user_is_admin: |
|
386 | if self.user_is_admin: | |
389 | return self._admin_permissions() |
|
387 | return self._admin_permissions() | |
390 |
|
388 | |||
391 | self._calculate_global_default_permissions() |
|
389 | self._calculate_global_default_permissions() | |
392 | self._calculate_global_permissions() |
|
390 | self._calculate_global_permissions() | |
393 | self._calculate_default_permissions() |
|
391 | self._calculate_default_permissions() | |
394 | self._calculate_repository_permissions() |
|
392 | self._calculate_repository_permissions() | |
395 | self._calculate_repository_group_permissions() |
|
393 | self._calculate_repository_group_permissions() | |
396 | self._calculate_user_group_permissions() |
|
394 | self._calculate_user_group_permissions() | |
397 | return self._permission_structure() |
|
395 | return self._permission_structure() | |
398 |
|
396 | |||
399 | def _admin_permissions(self): |
|
397 | def _admin_permissions(self): | |
400 | """ |
|
398 | """ | |
401 | admin user have all default rights for repositories |
|
399 | admin user have all default rights for repositories | |
402 | and groups set to admin |
|
400 | and groups set to admin | |
403 | """ |
|
401 | """ | |
404 | self.permissions_global.add('hg.admin') |
|
402 | self.permissions_global.add('hg.admin') | |
405 | self.permissions_global.add('hg.create.write_on_repogroup.true') |
|
403 | self.permissions_global.add('hg.create.write_on_repogroup.true') | |
406 |
|
404 | |||
407 | # repositories |
|
405 | # repositories | |
408 | for perm in self.default_repo_perms: |
|
406 | for perm in self.default_repo_perms: | |
409 | r_k = perm.UserRepoToPerm.repository.repo_name |
|
407 | r_k = perm.UserRepoToPerm.repository.repo_name | |
410 | p = 'repository.admin' |
|
408 | p = 'repository.admin' | |
411 | self.permissions_repositories[r_k] = p, PermOrigin.ADMIN |
|
409 | self.permissions_repositories[r_k] = p, PermOrigin.ADMIN | |
412 |
|
410 | |||
413 | # repository groups |
|
411 | # repository groups | |
414 | for perm in self.default_repo_groups_perms: |
|
412 | for perm in self.default_repo_groups_perms: | |
415 | rg_k = perm.UserRepoGroupToPerm.group.group_name |
|
413 | rg_k = perm.UserRepoGroupToPerm.group.group_name | |
416 | p = 'group.admin' |
|
414 | p = 'group.admin' | |
417 | self.permissions_repository_groups[rg_k] = p, PermOrigin.ADMIN |
|
415 | self.permissions_repository_groups[rg_k] = p, PermOrigin.ADMIN | |
418 |
|
416 | |||
419 | # user groups |
|
417 | # user groups | |
420 | for perm in self.default_user_group_perms: |
|
418 | for perm in self.default_user_group_perms: | |
421 | u_k = perm.UserUserGroupToPerm.user_group.users_group_name |
|
419 | u_k = perm.UserUserGroupToPerm.user_group.users_group_name | |
422 | p = 'usergroup.admin' |
|
420 | p = 'usergroup.admin' | |
423 | self.permissions_user_groups[u_k] = p, PermOrigin.ADMIN |
|
421 | self.permissions_user_groups[u_k] = p, PermOrigin.ADMIN | |
424 |
|
422 | |||
425 | return self._permission_structure() |
|
423 | return self._permission_structure() | |
426 |
|
424 | |||
427 | def _calculate_global_default_permissions(self): |
|
425 | def _calculate_global_default_permissions(self): | |
428 | """ |
|
426 | """ | |
429 | global permissions taken from the default user |
|
427 | global permissions taken from the default user | |
430 | """ |
|
428 | """ | |
431 | default_global_perms = UserToPerm.query()\ |
|
429 | default_global_perms = UserToPerm.query()\ | |
432 | .filter(UserToPerm.user_id == self.default_user_id)\ |
|
430 | .filter(UserToPerm.user_id == self.default_user_id)\ | |
433 | .options(joinedload(UserToPerm.permission)) |
|
431 | .options(joinedload(UserToPerm.permission)) | |
434 |
|
432 | |||
435 | for perm in default_global_perms: |
|
433 | for perm in default_global_perms: | |
436 | self.permissions_global.add(perm.permission.permission_name) |
|
434 | self.permissions_global.add(perm.permission.permission_name) | |
437 |
|
435 | |||
438 | def _calculate_global_permissions(self): |
|
436 | def _calculate_global_permissions(self): | |
439 | """ |
|
437 | """ | |
440 | Set global system permissions with user permissions or permissions |
|
438 | Set global system permissions with user permissions or permissions | |
441 | taken from the user groups of the current user. |
|
439 | taken from the user groups of the current user. | |
442 |
|
440 | |||
443 | The permissions include repo creating, repo group creating, forking |
|
441 | The permissions include repo creating, repo group creating, forking | |
444 | etc. |
|
442 | etc. | |
445 | """ |
|
443 | """ | |
446 |
|
444 | |||
447 | # 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 | |
448 | # before those can be configured from groups or users explicitly. |
|
446 | # before those can be configured from groups or users explicitly. | |
449 |
|
447 | |||
450 | # 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 | |
451 | # for the comment below and update it. |
|
449 | # for the comment below and update it. | |
452 |
|
450 | |||
453 | # 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 | |
454 | # User.DEFAULT_USER_PERMISSIONS definitions |
|
452 | # User.DEFAULT_USER_PERMISSIONS definitions | |
455 | _configurable = frozenset([ |
|
453 | _configurable = frozenset([ | |
456 | 'hg.fork.none', 'hg.fork.repository', |
|
454 | 'hg.fork.none', 'hg.fork.repository', | |
457 | 'hg.create.none', 'hg.create.repository', |
|
455 | 'hg.create.none', 'hg.create.repository', | |
458 | 'hg.usergroup.create.false', 'hg.usergroup.create.true', |
|
456 | 'hg.usergroup.create.false', 'hg.usergroup.create.true', | |
459 | 'hg.repogroup.create.false', 'hg.repogroup.create.true', |
|
457 | 'hg.repogroup.create.false', 'hg.repogroup.create.true', | |
460 | 'hg.create.write_on_repogroup.false', |
|
458 | 'hg.create.write_on_repogroup.false', | |
461 | 'hg.create.write_on_repogroup.true', |
|
459 | 'hg.create.write_on_repogroup.true', | |
462 | 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true' |
|
460 | 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true' | |
463 | ]) |
|
461 | ]) | |
464 |
|
462 | |||
465 | # USER GROUPS comes first user group global permissions |
|
463 | # USER GROUPS comes first user group global permissions | |
466 | user_perms_from_users_groups = Session().query(UserGroupToPerm)\ |
|
464 | user_perms_from_users_groups = Session().query(UserGroupToPerm)\ | |
467 | .options(joinedload(UserGroupToPerm.permission))\ |
|
465 | .options(joinedload(UserGroupToPerm.permission))\ | |
468 | .join((UserGroupMember, UserGroupToPerm.users_group_id == |
|
466 | .join((UserGroupMember, UserGroupToPerm.users_group_id == | |
469 | UserGroupMember.users_group_id))\ |
|
467 | UserGroupMember.users_group_id))\ | |
470 | .filter(UserGroupMember.user_id == self.user_id)\ |
|
468 | .filter(UserGroupMember.user_id == self.user_id)\ | |
471 | .order_by(UserGroupToPerm.users_group_id)\ |
|
469 | .order_by(UserGroupToPerm.users_group_id)\ | |
472 | .all() |
|
470 | .all() | |
473 |
|
471 | |||
474 | # 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 | |
475 | # one group, so we get all groups |
|
473 | # one group, so we get all groups | |
476 | _explicit_grouped_perms = [ |
|
474 | _explicit_grouped_perms = [ | |
477 | [x, list(y)] for x, y in |
|
475 | [x, list(y)] for x, y in | |
478 | itertools.groupby(user_perms_from_users_groups, |
|
476 | itertools.groupby(user_perms_from_users_groups, | |
479 | lambda _x: _x.users_group)] |
|
477 | lambda _x: _x.users_group)] | |
480 |
|
478 | |||
481 | for gr, perms in _explicit_grouped_perms: |
|
479 | for gr, perms in _explicit_grouped_perms: | |
482 | # since user can be in multiple groups iterate over them and |
|
480 | # since user can be in multiple groups iterate over them and | |
483 | # select the lowest permissions first (more explicit) |
|
481 | # select the lowest permissions first (more explicit) | |
484 | # TODO: marcink: do this^^ |
|
482 | # TODO: marcink: do this^^ | |
485 |
|
483 | |||
486 | # group doesn't inherit default permissions so we actually set them |
|
484 | # group doesn't inherit default permissions so we actually set them | |
487 | if not gr.inherit_default_permissions: |
|
485 | if not gr.inherit_default_permissions: | |
488 | # NEED TO IGNORE all previously set configurable permissions |
|
486 | # NEED TO IGNORE all previously set configurable permissions | |
489 | # and replace them with explicitly set from this user |
|
487 | # and replace them with explicitly set from this user | |
490 | # group permissions |
|
488 | # group permissions | |
491 | self.permissions_global = self.permissions_global.difference( |
|
489 | self.permissions_global = self.permissions_global.difference( | |
492 | _configurable) |
|
490 | _configurable) | |
493 | for perm in perms: |
|
491 | for perm in perms: | |
494 | self.permissions_global.add(perm.permission.permission_name) |
|
492 | self.permissions_global.add(perm.permission.permission_name) | |
495 |
|
493 | |||
496 | # user explicit global permissions |
|
494 | # user explicit global permissions | |
497 | user_perms = Session().query(UserToPerm)\ |
|
495 | user_perms = Session().query(UserToPerm)\ | |
498 | .options(joinedload(UserToPerm.permission))\ |
|
496 | .options(joinedload(UserToPerm.permission))\ | |
499 | .filter(UserToPerm.user_id == self.user_id).all() |
|
497 | .filter(UserToPerm.user_id == self.user_id).all() | |
500 |
|
498 | |||
501 | if not self.inherit_default_permissions: |
|
499 | if not self.inherit_default_permissions: | |
502 | # NEED TO IGNORE all configurable permissions and |
|
500 | # NEED TO IGNORE all configurable permissions and | |
503 | # replace them with explicitly set from this user permissions |
|
501 | # replace them with explicitly set from this user permissions | |
504 | self.permissions_global = self.permissions_global.difference( |
|
502 | self.permissions_global = self.permissions_global.difference( | |
505 | _configurable) |
|
503 | _configurable) | |
506 | for perm in user_perms: |
|
504 | for perm in user_perms: | |
507 | self.permissions_global.add(perm.permission.permission_name) |
|
505 | self.permissions_global.add(perm.permission.permission_name) | |
508 |
|
506 | |||
509 | def _calculate_default_permissions(self): |
|
507 | def _calculate_default_permissions(self): | |
510 | """ |
|
508 | """ | |
511 | Set default user permissions for repositories, repository groups |
|
509 | Set default user permissions for repositories, repository groups | |
512 | taken from the default user. |
|
510 | taken from the default user. | |
513 |
|
511 | |||
514 | Calculate inheritance of object permissions based on what we have now |
|
512 | Calculate inheritance of object permissions based on what we have now | |
515 | 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 | |
516 | explicitly set. Inherit is the opposite of .false being there. |
|
514 | explicitly set. Inherit is the opposite of .false being there. | |
517 |
|
515 | |||
518 | .. note:: |
|
516 | .. note:: | |
519 |
|
517 | |||
520 | 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 | |
521 | 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 | |
522 | inconsistent state when both .true/.false is there |
|
520 | inconsistent state when both .true/.false is there | |
523 | .false is more important |
|
521 | .false is more important | |
524 |
|
522 | |||
525 | """ |
|
523 | """ | |
526 | user_inherit_object_permissions = not ('hg.inherit_default_perms.false' |
|
524 | user_inherit_object_permissions = not ('hg.inherit_default_perms.false' | |
527 | in self.permissions_global) |
|
525 | in self.permissions_global) | |
528 |
|
526 | |||
529 | # defaults for repositories, taken from `default` user permissions |
|
527 | # defaults for repositories, taken from `default` user permissions | |
530 | # on given repo |
|
528 | # on given repo | |
531 | for perm in self.default_repo_perms: |
|
529 | for perm in self.default_repo_perms: | |
532 | r_k = perm.UserRepoToPerm.repository.repo_name |
|
530 | r_k = perm.UserRepoToPerm.repository.repo_name | |
533 | o = PermOrigin.REPO_DEFAULT |
|
531 | o = PermOrigin.REPO_DEFAULT | |
534 | if perm.Repository.private and not ( |
|
532 | if perm.Repository.private and not ( | |
535 | perm.Repository.user_id == self.user_id): |
|
533 | perm.Repository.user_id == self.user_id): | |
536 | # disable defaults for private repos, |
|
534 | # disable defaults for private repos, | |
537 | p = 'repository.none' |
|
535 | p = 'repository.none' | |
538 | o = PermOrigin.REPO_PRIVATE |
|
536 | o = PermOrigin.REPO_PRIVATE | |
539 | elif perm.Repository.user_id == self.user_id: |
|
537 | elif perm.Repository.user_id == self.user_id: | |
540 | # set admin if owner |
|
538 | # set admin if owner | |
541 | p = 'repository.admin' |
|
539 | p = 'repository.admin' | |
542 | o = PermOrigin.REPO_OWNER |
|
540 | o = PermOrigin.REPO_OWNER | |
543 | else: |
|
541 | else: | |
544 | p = perm.Permission.permission_name |
|
542 | p = perm.Permission.permission_name | |
545 | # if we decide this user isn't inheriting permissions from |
|
543 | # if we decide this user isn't inheriting permissions from | |
546 | # default user we set him to .none so only explicit |
|
544 | # default user we set him to .none so only explicit | |
547 | # permissions work |
|
545 | # permissions work | |
548 | if not user_inherit_object_permissions: |
|
546 | if not user_inherit_object_permissions: | |
549 | p = 'repository.none' |
|
547 | p = 'repository.none' | |
550 | self.permissions_repositories[r_k] = p, o |
|
548 | self.permissions_repositories[r_k] = p, o | |
551 |
|
549 | |||
552 | # defaults for repository groups taken from `default` user permission |
|
550 | # defaults for repository groups taken from `default` user permission | |
553 | # on given group |
|
551 | # on given group | |
554 | for perm in self.default_repo_groups_perms: |
|
552 | for perm in self.default_repo_groups_perms: | |
555 | rg_k = perm.UserRepoGroupToPerm.group.group_name |
|
553 | rg_k = perm.UserRepoGroupToPerm.group.group_name | |
556 | o = PermOrigin.REPOGROUP_DEFAULT |
|
554 | o = PermOrigin.REPOGROUP_DEFAULT | |
557 | if perm.RepoGroup.user_id == self.user_id: |
|
555 | if perm.RepoGroup.user_id == self.user_id: | |
558 | # set admin if owner |
|
556 | # set admin if owner | |
559 | p = 'group.admin' |
|
557 | p = 'group.admin' | |
560 | o = PermOrigin.REPOGROUP_OWNER |
|
558 | o = PermOrigin.REPOGROUP_OWNER | |
561 | else: |
|
559 | else: | |
562 | p = perm.Permission.permission_name |
|
560 | p = perm.Permission.permission_name | |
563 |
|
561 | |||
564 | # if we decide this user isn't inheriting permissions from default |
|
562 | # if we decide this user isn't inheriting permissions from default | |
565 | # user we set him to .none so only explicit permissions work |
|
563 | # user we set him to .none so only explicit permissions work | |
566 | if not user_inherit_object_permissions: |
|
564 | if not user_inherit_object_permissions: | |
567 | p = 'group.none' |
|
565 | p = 'group.none' | |
568 | self.permissions_repository_groups[rg_k] = p, o |
|
566 | self.permissions_repository_groups[rg_k] = p, o | |
569 |
|
567 | |||
570 | # defaults for user groups taken from `default` user permission |
|
568 | # defaults for user groups taken from `default` user permission | |
571 | # on given user group |
|
569 | # on given user group | |
572 | for perm in self.default_user_group_perms: |
|
570 | for perm in self.default_user_group_perms: | |
573 | u_k = perm.UserUserGroupToPerm.user_group.users_group_name |
|
571 | u_k = perm.UserUserGroupToPerm.user_group.users_group_name | |
574 | o = PermOrigin.USERGROUP_DEFAULT |
|
572 | o = PermOrigin.USERGROUP_DEFAULT | |
575 | if perm.UserGroup.user_id == self.user_id: |
|
573 | if perm.UserGroup.user_id == self.user_id: | |
576 | # set admin if owner |
|
574 | # set admin if owner | |
577 | p = 'usergroup.admin' |
|
575 | p = 'usergroup.admin' | |
578 | o = PermOrigin.USERGROUP_OWNER |
|
576 | o = PermOrigin.USERGROUP_OWNER | |
579 | else: |
|
577 | else: | |
580 | p = perm.Permission.permission_name |
|
578 | p = perm.Permission.permission_name | |
581 |
|
579 | |||
582 | # if we decide this user isn't inheriting permissions from default |
|
580 | # if we decide this user isn't inheriting permissions from default | |
583 | # user we set him to .none so only explicit permissions work |
|
581 | # user we set him to .none so only explicit permissions work | |
584 | if not user_inherit_object_permissions: |
|
582 | if not user_inherit_object_permissions: | |
585 | p = 'usergroup.none' |
|
583 | p = 'usergroup.none' | |
586 | self.permissions_user_groups[u_k] = p, o |
|
584 | self.permissions_user_groups[u_k] = p, o | |
587 |
|
585 | |||
588 | def _calculate_repository_permissions(self): |
|
586 | def _calculate_repository_permissions(self): | |
589 | """ |
|
587 | """ | |
590 | Repository permissions for the current user. |
|
588 | Repository permissions for the current user. | |
591 |
|
589 | |||
592 | 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 | |
593 | fill in the permission from it. `_choose_permission` decides of which |
|
591 | fill in the permission from it. `_choose_permission` decides of which | |
594 | permission should be selected based on selected method. |
|
592 | permission should be selected based on selected method. | |
595 | """ |
|
593 | """ | |
596 |
|
594 | |||
597 | # user group for repositories permissions |
|
595 | # user group for repositories permissions | |
598 | user_repo_perms_from_user_group = Permission\ |
|
596 | user_repo_perms_from_user_group = Permission\ | |
599 | .get_default_repo_perms_from_user_group( |
|
597 | .get_default_repo_perms_from_user_group( | |
600 | self.user_id, self.scope_repo_id) |
|
598 | self.user_id, self.scope_repo_id) | |
601 |
|
599 | |||
602 | multiple_counter = collections.defaultdict(int) |
|
600 | multiple_counter = collections.defaultdict(int) | |
603 | for perm in user_repo_perms_from_user_group: |
|
601 | for perm in user_repo_perms_from_user_group: | |
604 | r_k = perm.UserGroupRepoToPerm.repository.repo_name |
|
602 | r_k = perm.UserGroupRepoToPerm.repository.repo_name | |
605 | ug_k = perm.UserGroupRepoToPerm.users_group.users_group_name |
|
603 | ug_k = perm.UserGroupRepoToPerm.users_group.users_group_name | |
606 | multiple_counter[r_k] += 1 |
|
604 | multiple_counter[r_k] += 1 | |
607 | p = perm.Permission.permission_name |
|
605 | p = perm.Permission.permission_name | |
608 | o = PermOrigin.REPO_USERGROUP % ug_k |
|
606 | o = PermOrigin.REPO_USERGROUP % ug_k | |
609 |
|
607 | |||
610 | if perm.Repository.user_id == self.user_id: |
|
608 | if perm.Repository.user_id == self.user_id: | |
611 | # set admin if owner |
|
609 | # set admin if owner | |
612 | p = 'repository.admin' |
|
610 | p = 'repository.admin' | |
613 | o = PermOrigin.REPO_OWNER |
|
611 | o = PermOrigin.REPO_OWNER | |
614 | else: |
|
612 | else: | |
615 | if multiple_counter[r_k] > 1: |
|
613 | if multiple_counter[r_k] > 1: | |
616 | cur_perm = self.permissions_repositories[r_k] |
|
614 | cur_perm = self.permissions_repositories[r_k] | |
617 | p = self._choose_permission(p, cur_perm) |
|
615 | p = self._choose_permission(p, cur_perm) | |
618 | self.permissions_repositories[r_k] = p, o |
|
616 | self.permissions_repositories[r_k] = p, o | |
619 |
|
617 | |||
620 | # user explicit permissions for repositories, overrides any specified |
|
618 | # user explicit permissions for repositories, overrides any specified | |
621 | # by the group permission |
|
619 | # by the group permission | |
622 | user_repo_perms = Permission.get_default_repo_perms( |
|
620 | user_repo_perms = Permission.get_default_repo_perms( | |
623 | self.user_id, self.scope_repo_id) |
|
621 | self.user_id, self.scope_repo_id) | |
624 | for perm in user_repo_perms: |
|
622 | for perm in user_repo_perms: | |
625 | r_k = perm.UserRepoToPerm.repository.repo_name |
|
623 | r_k = perm.UserRepoToPerm.repository.repo_name | |
626 | o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username |
|
624 | o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username | |
627 | # set admin if owner |
|
625 | # set admin if owner | |
628 | if perm.Repository.user_id == self.user_id: |
|
626 | if perm.Repository.user_id == self.user_id: | |
629 | p = 'repository.admin' |
|
627 | p = 'repository.admin' | |
630 | o = PermOrigin.REPO_OWNER |
|
628 | o = PermOrigin.REPO_OWNER | |
631 | else: |
|
629 | else: | |
632 | p = perm.Permission.permission_name |
|
630 | p = perm.Permission.permission_name | |
633 | if not self.explicit: |
|
631 | if not self.explicit: | |
634 | cur_perm = self.permissions_repositories.get( |
|
632 | cur_perm = self.permissions_repositories.get( | |
635 | r_k, 'repository.none') |
|
633 | r_k, 'repository.none') | |
636 | p = self._choose_permission(p, cur_perm) |
|
634 | p = self._choose_permission(p, cur_perm) | |
637 | self.permissions_repositories[r_k] = p, o |
|
635 | self.permissions_repositories[r_k] = p, o | |
638 |
|
636 | |||
639 | def _calculate_repository_group_permissions(self): |
|
637 | def _calculate_repository_group_permissions(self): | |
640 | """ |
|
638 | """ | |
641 | Repository group permissions for the current user. |
|
639 | Repository group permissions for the current user. | |
642 |
|
640 | |||
643 | 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 | |
644 | fill in the permissions from it. `_choose_permmission` decides of which |
|
642 | fill in the permissions from it. `_choose_permmission` decides of which | |
645 | permission should be selected based on selected method. |
|
643 | permission should be selected based on selected method. | |
646 | """ |
|
644 | """ | |
647 | # user group for repo groups permissions |
|
645 | # user group for repo groups permissions | |
648 | user_repo_group_perms_from_user_group = Permission\ |
|
646 | user_repo_group_perms_from_user_group = Permission\ | |
649 | .get_default_group_perms_from_user_group( |
|
647 | .get_default_group_perms_from_user_group( | |
650 | self.user_id, self.scope_repo_group_id) |
|
648 | self.user_id, self.scope_repo_group_id) | |
651 |
|
649 | |||
652 | multiple_counter = collections.defaultdict(int) |
|
650 | multiple_counter = collections.defaultdict(int) | |
653 | for perm in user_repo_group_perms_from_user_group: |
|
651 | for perm in user_repo_group_perms_from_user_group: | |
654 | g_k = perm.UserGroupRepoGroupToPerm.group.group_name |
|
652 | g_k = perm.UserGroupRepoGroupToPerm.group.group_name | |
655 | ug_k = perm.UserGroupRepoGroupToPerm.users_group.users_group_name |
|
653 | ug_k = perm.UserGroupRepoGroupToPerm.users_group.users_group_name | |
656 | o = PermOrigin.REPOGROUP_USERGROUP % ug_k |
|
654 | o = PermOrigin.REPOGROUP_USERGROUP % ug_k | |
657 | multiple_counter[g_k] += 1 |
|
655 | multiple_counter[g_k] += 1 | |
658 | p = perm.Permission.permission_name |
|
656 | p = perm.Permission.permission_name | |
659 | if perm.RepoGroup.user_id == self.user_id: |
|
657 | if perm.RepoGroup.user_id == self.user_id: | |
660 | # set admin if owner, even for member of other user group |
|
658 | # set admin if owner, even for member of other user group | |
661 | p = 'group.admin' |
|
659 | p = 'group.admin' | |
662 | o = PermOrigin.REPOGROUP_OWNER |
|
660 | o = PermOrigin.REPOGROUP_OWNER | |
663 | else: |
|
661 | else: | |
664 | if multiple_counter[g_k] > 1: |
|
662 | if multiple_counter[g_k] > 1: | |
665 | cur_perm = self.permissions_repository_groups[g_k] |
|
663 | cur_perm = self.permissions_repository_groups[g_k] | |
666 | p = self._choose_permission(p, cur_perm) |
|
664 | p = self._choose_permission(p, cur_perm) | |
667 | self.permissions_repository_groups[g_k] = p, o |
|
665 | self.permissions_repository_groups[g_k] = p, o | |
668 |
|
666 | |||
669 | # user explicit permissions for repository groups |
|
667 | # user explicit permissions for repository groups | |
670 | user_repo_groups_perms = Permission.get_default_group_perms( |
|
668 | user_repo_groups_perms = Permission.get_default_group_perms( | |
671 | self.user_id, self.scope_repo_group_id) |
|
669 | self.user_id, self.scope_repo_group_id) | |
672 | for perm in user_repo_groups_perms: |
|
670 | for perm in user_repo_groups_perms: | |
673 | rg_k = perm.UserRepoGroupToPerm.group.group_name |
|
671 | rg_k = perm.UserRepoGroupToPerm.group.group_name | |
674 | u_k = perm.UserRepoGroupToPerm.user.username |
|
672 | u_k = perm.UserRepoGroupToPerm.user.username | |
675 | o = PermOrigin.REPOGROUP_USER % u_k |
|
673 | o = PermOrigin.REPOGROUP_USER % u_k | |
676 |
|
674 | |||
677 | if perm.RepoGroup.user_id == self.user_id: |
|
675 | if perm.RepoGroup.user_id == self.user_id: | |
678 | # set admin if owner |
|
676 | # set admin if owner | |
679 | p = 'group.admin' |
|
677 | p = 'group.admin' | |
680 | o = PermOrigin.REPOGROUP_OWNER |
|
678 | o = PermOrigin.REPOGROUP_OWNER | |
681 | else: |
|
679 | else: | |
682 | p = perm.Permission.permission_name |
|
680 | p = perm.Permission.permission_name | |
683 | if not self.explicit: |
|
681 | if not self.explicit: | |
684 | cur_perm = self.permissions_repository_groups.get( |
|
682 | cur_perm = self.permissions_repository_groups.get( | |
685 | rg_k, 'group.none') |
|
683 | rg_k, 'group.none') | |
686 | p = self._choose_permission(p, cur_perm) |
|
684 | p = self._choose_permission(p, cur_perm) | |
687 | self.permissions_repository_groups[rg_k] = p, o |
|
685 | self.permissions_repository_groups[rg_k] = p, o | |
688 |
|
686 | |||
689 | def _calculate_user_group_permissions(self): |
|
687 | def _calculate_user_group_permissions(self): | |
690 | """ |
|
688 | """ | |
691 | User group permissions for the current user. |
|
689 | User group permissions for the current user. | |
692 | """ |
|
690 | """ | |
693 | # user group for user group permissions |
|
691 | # user group for user group permissions | |
694 | user_group_from_user_group = Permission\ |
|
692 | user_group_from_user_group = Permission\ | |
695 | .get_default_user_group_perms_from_user_group( |
|
693 | .get_default_user_group_perms_from_user_group( | |
696 | self.user_id, self.scope_user_group_id) |
|
694 | self.user_id, self.scope_user_group_id) | |
697 |
|
695 | |||
698 | multiple_counter = collections.defaultdict(int) |
|
696 | multiple_counter = collections.defaultdict(int) | |
699 | for perm in user_group_from_user_group: |
|
697 | for perm in user_group_from_user_group: | |
700 | g_k = perm.UserGroupUserGroupToPerm\ |
|
698 | g_k = perm.UserGroupUserGroupToPerm\ | |
701 | .target_user_group.users_group_name |
|
699 | .target_user_group.users_group_name | |
702 | u_k = perm.UserGroupUserGroupToPerm\ |
|
700 | u_k = perm.UserGroupUserGroupToPerm\ | |
703 | .user_group.users_group_name |
|
701 | .user_group.users_group_name | |
704 | o = PermOrigin.USERGROUP_USERGROUP % u_k |
|
702 | o = PermOrigin.USERGROUP_USERGROUP % u_k | |
705 | multiple_counter[g_k] += 1 |
|
703 | multiple_counter[g_k] += 1 | |
706 | p = perm.Permission.permission_name |
|
704 | p = perm.Permission.permission_name | |
707 |
|
705 | |||
708 | if perm.UserGroup.user_id == self.user_id: |
|
706 | if perm.UserGroup.user_id == self.user_id: | |
709 | # set admin if owner, even for member of other user group |
|
707 | # set admin if owner, even for member of other user group | |
710 | p = 'usergroup.admin' |
|
708 | p = 'usergroup.admin' | |
711 | o = PermOrigin.USERGROUP_OWNER |
|
709 | o = PermOrigin.USERGROUP_OWNER | |
712 | else: |
|
710 | else: | |
713 | if multiple_counter[g_k] > 1: |
|
711 | if multiple_counter[g_k] > 1: | |
714 | cur_perm = self.permissions_user_groups[g_k] |
|
712 | cur_perm = self.permissions_user_groups[g_k] | |
715 | p = self._choose_permission(p, cur_perm) |
|
713 | p = self._choose_permission(p, cur_perm) | |
716 | self.permissions_user_groups[g_k] = p, o |
|
714 | self.permissions_user_groups[g_k] = p, o | |
717 |
|
715 | |||
718 | # user explicit permission for user groups |
|
716 | # user explicit permission for user groups | |
719 | user_user_groups_perms = Permission.get_default_user_group_perms( |
|
717 | user_user_groups_perms = Permission.get_default_user_group_perms( | |
720 | self.user_id, self.scope_user_group_id) |
|
718 | self.user_id, self.scope_user_group_id) | |
721 | for perm in user_user_groups_perms: |
|
719 | for perm in user_user_groups_perms: | |
722 | ug_k = perm.UserUserGroupToPerm.user_group.users_group_name |
|
720 | ug_k = perm.UserUserGroupToPerm.user_group.users_group_name | |
723 | u_k = perm.UserUserGroupToPerm.user.username |
|
721 | u_k = perm.UserUserGroupToPerm.user.username | |
724 | o = PermOrigin.USERGROUP_USER % u_k |
|
722 | o = PermOrigin.USERGROUP_USER % u_k | |
725 |
|
723 | |||
726 | if perm.UserGroup.user_id == self.user_id: |
|
724 | if perm.UserGroup.user_id == self.user_id: | |
727 | # set admin if owner |
|
725 | # set admin if owner | |
728 | p = 'usergroup.admin' |
|
726 | p = 'usergroup.admin' | |
729 | o = PermOrigin.USERGROUP_OWNER |
|
727 | o = PermOrigin.USERGROUP_OWNER | |
730 | else: |
|
728 | else: | |
731 | p = perm.Permission.permission_name |
|
729 | p = perm.Permission.permission_name | |
732 | if not self.explicit: |
|
730 | if not self.explicit: | |
733 | cur_perm = self.permissions_user_groups.get( |
|
731 | cur_perm = self.permissions_user_groups.get( | |
734 | ug_k, 'usergroup.none') |
|
732 | ug_k, 'usergroup.none') | |
735 | p = self._choose_permission(p, cur_perm) |
|
733 | p = self._choose_permission(p, cur_perm) | |
736 | self.permissions_user_groups[ug_k] = p, o |
|
734 | self.permissions_user_groups[ug_k] = p, o | |
737 |
|
735 | |||
738 | def _choose_permission(self, new_perm, cur_perm): |
|
736 | def _choose_permission(self, new_perm, cur_perm): | |
739 | new_perm_val = Permission.PERM_WEIGHTS[new_perm] |
|
737 | new_perm_val = Permission.PERM_WEIGHTS[new_perm] | |
740 | cur_perm_val = Permission.PERM_WEIGHTS[cur_perm] |
|
738 | cur_perm_val = Permission.PERM_WEIGHTS[cur_perm] | |
741 | if self.algo == 'higherwin': |
|
739 | if self.algo == 'higherwin': | |
742 | if new_perm_val > cur_perm_val: |
|
740 | if new_perm_val > cur_perm_val: | |
743 | return new_perm |
|
741 | return new_perm | |
744 | return cur_perm |
|
742 | return cur_perm | |
745 | elif self.algo == 'lowerwin': |
|
743 | elif self.algo == 'lowerwin': | |
746 | if new_perm_val < cur_perm_val: |
|
744 | if new_perm_val < cur_perm_val: | |
747 | return new_perm |
|
745 | return new_perm | |
748 | return cur_perm |
|
746 | return cur_perm | |
749 |
|
747 | |||
750 | def _permission_structure(self): |
|
748 | def _permission_structure(self): | |
751 | return { |
|
749 | return { | |
752 | 'global': self.permissions_global, |
|
750 | 'global': self.permissions_global, | |
753 | 'repositories': self.permissions_repositories, |
|
751 | 'repositories': self.permissions_repositories, | |
754 | 'repositories_groups': self.permissions_repository_groups, |
|
752 | 'repositories_groups': self.permissions_repository_groups, | |
755 | 'user_groups': self.permissions_user_groups, |
|
753 | 'user_groups': self.permissions_user_groups, | |
756 | } |
|
754 | } | |
757 |
|
755 | |||
758 |
|
756 | |||
759 | 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): | |
760 | """ |
|
758 | """ | |
761 | 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 | |
762 | """ |
|
760 | """ | |
763 | if not whitelist: |
|
761 | if not whitelist: | |
764 | from rhodecode import CONFIG |
|
762 | from rhodecode import CONFIG | |
765 | whitelist = aslist( |
|
763 | whitelist = aslist( | |
766 | CONFIG.get('api_access_controllers_whitelist'), sep=',') |
|
764 | CONFIG.get('api_access_controllers_whitelist'), sep=',') | |
767 | log.debug( |
|
765 | log.debug( | |
768 | 'Allowed controllers for AUTH TOKEN access: %s' % (whitelist,)) |
|
766 | 'Allowed controllers for AUTH TOKEN access: %s' % (whitelist,)) | |
769 |
|
767 | |||
770 | auth_token_access_valid = False |
|
768 | auth_token_access_valid = False | |
771 | for entry in whitelist: |
|
769 | for entry in whitelist: | |
772 | if fnmatch.fnmatch(controller_name, entry): |
|
770 | if fnmatch.fnmatch(controller_name, entry): | |
773 | auth_token_access_valid = True |
|
771 | auth_token_access_valid = True | |
774 | break |
|
772 | break | |
775 |
|
773 | |||
776 | if auth_token_access_valid: |
|
774 | if auth_token_access_valid: | |
777 | log.debug('controller:%s matches entry in whitelist' |
|
775 | log.debug('controller:%s matches entry in whitelist' | |
778 | % (controller_name,)) |
|
776 | % (controller_name,)) | |
779 | else: |
|
777 | else: | |
780 | msg = ('controller: %s does *NOT* match any entry in whitelist' |
|
778 | msg = ('controller: %s does *NOT* match any entry in whitelist' | |
781 | % (controller_name,)) |
|
779 | % (controller_name,)) | |
782 | if auth_token: |
|
780 | if auth_token: | |
783 | # 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 | |
784 | log.warning(msg) |
|
782 | log.warning(msg) | |
785 | else: |
|
783 | else: | |
786 | log.debug(msg) |
|
784 | log.debug(msg) | |
787 |
|
785 | |||
788 | return auth_token_access_valid |
|
786 | return auth_token_access_valid | |
789 |
|
787 | |||
790 |
|
788 | |||
791 | class AuthUser(object): |
|
789 | class AuthUser(object): | |
792 | """ |
|
790 | """ | |
793 | A simple object that handles all attributes of user in RhodeCode |
|
791 | A simple object that handles all attributes of user in RhodeCode | |
794 |
|
792 | |||
795 | 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 | |
796 | 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 | |
797 | 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 | |
798 | """ |
|
796 | """ | |
799 | GLOBAL_PERMS = [x[0] for x in Permission.PERMS] |
|
797 | GLOBAL_PERMS = [x[0] for x in Permission.PERMS] | |
800 |
|
798 | |||
801 | 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): | |
802 |
|
800 | |||
803 | self.user_id = user_id |
|
801 | self.user_id = user_id | |
804 | self._api_key = api_key |
|
802 | self._api_key = api_key | |
805 |
|
803 | |||
806 | self.api_key = None |
|
804 | self.api_key = None | |
807 | self.feed_token = '' |
|
805 | self.feed_token = '' | |
808 | self.username = username |
|
806 | self.username = username | |
809 | self.ip_addr = ip_addr |
|
807 | self.ip_addr = ip_addr | |
810 | self.name = '' |
|
808 | self.name = '' | |
811 | self.lastname = '' |
|
809 | self.lastname = '' | |
812 | self.email = '' |
|
810 | self.email = '' | |
813 | self.is_authenticated = False |
|
811 | self.is_authenticated = False | |
814 | self.admin = False |
|
812 | self.admin = False | |
815 | self.inherit_default_permissions = False |
|
813 | self.inherit_default_permissions = False | |
816 | self.password = '' |
|
814 | self.password = '' | |
817 |
|
815 | |||
818 | self.anonymous_user = None # propagated on propagate_data |
|
816 | self.anonymous_user = None # propagated on propagate_data | |
819 | self.propagate_data() |
|
817 | self.propagate_data() | |
820 | self._instance = None |
|
818 | self._instance = None | |
821 | self._permissions_scoped_cache = {} # used to bind scoped calculation |
|
819 | self._permissions_scoped_cache = {} # used to bind scoped calculation | |
822 |
|
820 | |||
823 | @LazyProperty |
|
821 | @LazyProperty | |
824 | def permissions(self): |
|
822 | def permissions(self): | |
825 | return self.get_perms(user=self, cache=False) |
|
823 | return self.get_perms(user=self, cache=False) | |
826 |
|
824 | |||
827 | def permissions_with_scope(self, scope): |
|
825 | def permissions_with_scope(self, scope): | |
828 | """ |
|
826 | """ | |
829 | 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 | |
830 | 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 | |
831 | 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 | |
832 | then it basically narrows the scope to GLOBAL permissions only. |
|
830 | then it basically narrows the scope to GLOBAL permissions only. | |
833 |
|
831 | |||
834 | :param scope: dict |
|
832 | :param scope: dict | |
835 | """ |
|
833 | """ | |
836 | if 'repo_name' in scope: |
|
834 | if 'repo_name' in scope: | |
837 | obj = Repository.get_by_repo_name(scope['repo_name']) |
|
835 | obj = Repository.get_by_repo_name(scope['repo_name']) | |
838 | if obj: |
|
836 | if obj: | |
839 | scope['repo_id'] = obj.repo_id |
|
837 | scope['repo_id'] = obj.repo_id | |
840 | _scope = { |
|
838 | _scope = { | |
841 | 'repo_id': -1, |
|
839 | 'repo_id': -1, | |
842 | 'user_group_id': -1, |
|
840 | 'user_group_id': -1, | |
843 | 'repo_group_id': -1, |
|
841 | 'repo_group_id': -1, | |
844 | } |
|
842 | } | |
845 | _scope.update(scope) |
|
843 | _scope.update(scope) | |
846 | 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, | |
847 | _scope.items()))) |
|
845 | _scope.items()))) | |
848 | if cache_key not in self._permissions_scoped_cache: |
|
846 | if cache_key not in self._permissions_scoped_cache: | |
849 | # store in cache to mimic how the @LazyProperty works, |
|
847 | # store in cache to mimic how the @LazyProperty works, | |
850 | # the difference here is that we use the unique key calculated |
|
848 | # the difference here is that we use the unique key calculated | |
851 | # from params and values |
|
849 | # from params and values | |
852 | res = self.get_perms(user=self, cache=False, scope=_scope) |
|
850 | res = self.get_perms(user=self, cache=False, scope=_scope) | |
853 | self._permissions_scoped_cache[cache_key] = res |
|
851 | self._permissions_scoped_cache[cache_key] = res | |
854 | return self._permissions_scoped_cache[cache_key] |
|
852 | return self._permissions_scoped_cache[cache_key] | |
855 |
|
853 | |||
856 | def get_instance(self): |
|
854 | def get_instance(self): | |
857 | return User.get(self.user_id) |
|
855 | return User.get(self.user_id) | |
858 |
|
856 | |||
859 | def update_lastactivity(self): |
|
857 | def update_lastactivity(self): | |
860 | if self.user_id: |
|
858 | if self.user_id: | |
861 | User.get(self.user_id).update_lastactivity() |
|
859 | User.get(self.user_id).update_lastactivity() | |
862 |
|
860 | |||
863 | def propagate_data(self): |
|
861 | def propagate_data(self): | |
864 | """ |
|
862 | """ | |
865 | 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 | |
866 | user attributes to this class instance attributes |
|
864 | user attributes to this class instance attributes | |
867 | """ |
|
865 | """ | |
868 | log.debug('starting data propagation for new potential AuthUser') |
|
866 | log.debug('starting data propagation for new potential AuthUser') | |
869 | user_model = UserModel() |
|
867 | user_model = UserModel() | |
870 | anon_user = self.anonymous_user = User.get_default_user(cache=True) |
|
868 | anon_user = self.anonymous_user = User.get_default_user(cache=True) | |
871 | is_user_loaded = False |
|
869 | is_user_loaded = False | |
872 |
|
870 | |||
873 | # lookup by userid |
|
871 | # lookup by userid | |
874 | 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: | |
875 | 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) | |
876 | 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) | |
877 |
|
875 | |||
878 | # try go get user by api key |
|
876 | # try go get user by api key | |
879 | 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: | |
880 | 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) | |
881 | 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) | |
882 |
|
880 | |||
883 | # lookup by username |
|
881 | # lookup by username | |
884 | elif self.username: |
|
882 | elif self.username: | |
885 | 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) | |
886 | is_user_loaded = user_model.fill_data(self, username=self.username) |
|
884 | is_user_loaded = user_model.fill_data(self, username=self.username) | |
887 | else: |
|
885 | else: | |
888 | 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) | |
889 |
|
887 | |||
890 | if not is_user_loaded: |
|
888 | if not is_user_loaded: | |
891 | log.debug('Failed to load user. Fallback to default user') |
|
889 | log.debug('Failed to load user. Fallback to default user') | |
892 | # if we cannot authenticate user try anonymous |
|
890 | # if we cannot authenticate user try anonymous | |
893 | if anon_user.active: |
|
891 | if anon_user.active: | |
894 | user_model.fill_data(self, user_id=anon_user.user_id) |
|
892 | user_model.fill_data(self, user_id=anon_user.user_id) | |
895 | # then we set this user is logged in |
|
893 | # then we set this user is logged in | |
896 | self.is_authenticated = True |
|
894 | self.is_authenticated = True | |
897 | else: |
|
895 | else: | |
898 | # in case of disabled anonymous user we reset some of the |
|
896 | # in case of disabled anonymous user we reset some of the | |
899 | # parameters so such user is "corrupted", skipping the fill_data |
|
897 | # parameters so such user is "corrupted", skipping the fill_data | |
900 | for attr in ['user_id', 'username', 'admin', 'active']: |
|
898 | for attr in ['user_id', 'username', 'admin', 'active']: | |
901 | setattr(self, attr, None) |
|
899 | setattr(self, attr, None) | |
902 | self.is_authenticated = False |
|
900 | self.is_authenticated = False | |
903 |
|
901 | |||
904 | if not self.username: |
|
902 | if not self.username: | |
905 | self.username = 'None' |
|
903 | self.username = 'None' | |
906 |
|
904 | |||
907 | log.debug('Auth User is now %s' % self) |
|
905 | log.debug('Auth User is now %s' % self) | |
908 |
|
906 | |||
909 | def get_perms(self, user, scope=None, explicit=True, algo='higherwin', |
|
907 | def get_perms(self, user, scope=None, explicit=True, algo='higherwin', | |
910 | cache=False): |
|
908 | cache=False): | |
911 | """ |
|
909 | """ | |
912 | Fills user permission attribute with permissions taken from database |
|
910 | Fills user permission attribute with permissions taken from database | |
913 | works for permissions given for repositories, and for permissions that |
|
911 | works for permissions given for repositories, and for permissions that | |
914 | are granted to groups |
|
912 | are granted to groups | |
915 |
|
913 | |||
916 | :param user: instance of User object from database |
|
914 | :param user: instance of User object from database | |
917 | :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 | |
918 | 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 | |
919 | explicitly override permissions from group, if it's False it will |
|
917 | explicitly override permissions from group, if it's False it will | |
920 | make decision based on the algo |
|
918 | make decision based on the algo | |
921 | :param algo: algorithm to decide what permission should be choose if |
|
919 | :param algo: algorithm to decide what permission should be choose if | |
922 | 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 | |
923 | 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 | |
924 | 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 | |
925 | """ |
|
923 | """ | |
926 | user_id = user.user_id |
|
924 | user_id = user.user_id | |
927 | user_is_admin = user.is_admin |
|
925 | user_is_admin = user.is_admin | |
928 |
|
926 | |||
929 | # inheritance of global permissions like create repo/fork repo etc |
|
927 | # inheritance of global permissions like create repo/fork repo etc | |
930 | user_inherit_default_permissions = user.inherit_default_permissions |
|
928 | user_inherit_default_permissions = user.inherit_default_permissions | |
931 |
|
929 | |||
932 | log.debug('Computing PERMISSION tree for scope %s' % (scope, )) |
|
930 | log.debug('Computing PERMISSION tree for scope %s' % (scope, )) | |
933 | compute = caches.conditional_cache( |
|
931 | compute = caches.conditional_cache( | |
934 | 'short_term', 'cache_desc', |
|
932 | 'short_term', 'cache_desc', | |
935 | condition=cache, func=_cached_perms_data) |
|
933 | condition=cache, func=_cached_perms_data) | |
936 | result = compute(user_id, scope, user_is_admin, |
|
934 | result = compute(user_id, scope, user_is_admin, | |
937 | user_inherit_default_permissions, explicit, algo) |
|
935 | user_inherit_default_permissions, explicit, algo) | |
938 |
|
936 | |||
939 | result_repr = [] |
|
937 | result_repr = [] | |
940 | for k in result: |
|
938 | for k in result: | |
941 | result_repr.append((k, len(result[k]))) |
|
939 | result_repr.append((k, len(result[k]))) | |
942 |
|
940 | |||
943 | log.debug('PERMISSION tree computed %s' % (result_repr,)) |
|
941 | log.debug('PERMISSION tree computed %s' % (result_repr,)) | |
944 | return result |
|
942 | return result | |
945 |
|
943 | |||
946 | @property |
|
944 | @property | |
947 | def is_default(self): |
|
945 | def is_default(self): | |
948 | return self.username == User.DEFAULT_USER |
|
946 | return self.username == User.DEFAULT_USER | |
949 |
|
947 | |||
950 | @property |
|
948 | @property | |
951 | def is_admin(self): |
|
949 | def is_admin(self): | |
952 | return self.admin |
|
950 | return self.admin | |
953 |
|
951 | |||
954 | @property |
|
952 | @property | |
955 | def is_user_object(self): |
|
953 | def is_user_object(self): | |
956 | return self.user_id is not None |
|
954 | return self.user_id is not None | |
957 |
|
955 | |||
958 | @property |
|
956 | @property | |
959 | def repositories_admin(self): |
|
957 | def repositories_admin(self): | |
960 | """ |
|
958 | """ | |
961 | Returns list of repositories you're an admin of |
|
959 | Returns list of repositories you're an admin of | |
962 | """ |
|
960 | """ | |
963 | return [ |
|
961 | return [ | |
964 | x[0] for x in self.permissions['repositories'].iteritems() |
|
962 | x[0] for x in self.permissions['repositories'].iteritems() | |
965 | if x[1] == 'repository.admin'] |
|
963 | if x[1] == 'repository.admin'] | |
966 |
|
964 | |||
967 | @property |
|
965 | @property | |
968 | def repository_groups_admin(self): |
|
966 | def repository_groups_admin(self): | |
969 | """ |
|
967 | """ | |
970 | Returns list of repository groups you're an admin of |
|
968 | Returns list of repository groups you're an admin of | |
971 | """ |
|
969 | """ | |
972 | return [ |
|
970 | return [ | |
973 | x[0] for x in self.permissions['repositories_groups'].iteritems() |
|
971 | x[0] for x in self.permissions['repositories_groups'].iteritems() | |
974 | if x[1] == 'group.admin'] |
|
972 | if x[1] == 'group.admin'] | |
975 |
|
973 | |||
976 | @property |
|
974 | @property | |
977 | def user_groups_admin(self): |
|
975 | def user_groups_admin(self): | |
978 | """ |
|
976 | """ | |
979 | Returns list of user groups you're an admin of |
|
977 | Returns list of user groups you're an admin of | |
980 | """ |
|
978 | """ | |
981 | return [ |
|
979 | return [ | |
982 | x[0] for x in self.permissions['user_groups'].iteritems() |
|
980 | x[0] for x in self.permissions['user_groups'].iteritems() | |
983 | if x[1] == 'usergroup.admin'] |
|
981 | if x[1] == 'usergroup.admin'] | |
984 |
|
982 | |||
985 | @property |
|
983 | @property | |
986 | def ip_allowed(self): |
|
984 | def ip_allowed(self): | |
987 | """ |
|
985 | """ | |
988 | 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 | |
989 | allowed ip_addresses for user |
|
987 | allowed ip_addresses for user | |
990 |
|
988 | |||
991 | :returns: boolean, True if ip is in allowed ip range |
|
989 | :returns: boolean, True if ip is in allowed ip range | |
992 | """ |
|
990 | """ | |
993 | # check IP |
|
991 | # check IP | |
994 | inherit = self.inherit_default_permissions |
|
992 | inherit = self.inherit_default_permissions | |
995 | return AuthUser.check_ip_allowed(self.user_id, self.ip_addr, |
|
993 | return AuthUser.check_ip_allowed(self.user_id, self.ip_addr, | |
996 | inherit_from_default=inherit) |
|
994 | inherit_from_default=inherit) | |
997 | @property |
|
995 | @property | |
998 | def personal_repo_group(self): |
|
996 | def personal_repo_group(self): | |
999 | return RepoGroup.get_user_personal_repo_group(self.user_id) |
|
997 | return RepoGroup.get_user_personal_repo_group(self.user_id) | |
1000 |
|
998 | |||
1001 | @classmethod |
|
999 | @classmethod | |
1002 | 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): | |
1003 | allowed_ips = AuthUser.get_allowed_ips( |
|
1001 | allowed_ips = AuthUser.get_allowed_ips( | |
1004 | user_id, cache=True, inherit_from_default=inherit_from_default) |
|
1002 | user_id, cache=True, inherit_from_default=inherit_from_default) | |
1005 | 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): | |
1006 | 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)) | |
1007 | return True |
|
1005 | return True | |
1008 | else: |
|
1006 | else: | |
1009 | log.info('Access for IP:%s forbidden, ' |
|
1007 | log.info('Access for IP:%s forbidden, ' | |
1010 | 'not in %s' % (ip_addr, allowed_ips)) |
|
1008 | 'not in %s' % (ip_addr, allowed_ips)) | |
1011 | return False |
|
1009 | return False | |
1012 |
|
1010 | |||
1013 | def __repr__(self): |
|
1011 | def __repr__(self): | |
1014 | return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\ |
|
1012 | return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\ | |
1015 | % (self.user_id, self.username, self.ip_addr, self.is_authenticated) |
|
1013 | % (self.user_id, self.username, self.ip_addr, self.is_authenticated) | |
1016 |
|
1014 | |||
1017 | def set_authenticated(self, authenticated=True): |
|
1015 | def set_authenticated(self, authenticated=True): | |
1018 | if self.user_id != self.anonymous_user.user_id: |
|
1016 | if self.user_id != self.anonymous_user.user_id: | |
1019 | self.is_authenticated = authenticated |
|
1017 | self.is_authenticated = authenticated | |
1020 |
|
1018 | |||
1021 | def get_cookie_store(self): |
|
1019 | def get_cookie_store(self): | |
1022 | return { |
|
1020 | return { | |
1023 | 'username': self.username, |
|
1021 | 'username': self.username, | |
1024 | 'password': md5(self.password), |
|
1022 | 'password': md5(self.password), | |
1025 | 'user_id': self.user_id, |
|
1023 | 'user_id': self.user_id, | |
1026 | 'is_authenticated': self.is_authenticated |
|
1024 | 'is_authenticated': self.is_authenticated | |
1027 | } |
|
1025 | } | |
1028 |
|
1026 | |||
1029 | @classmethod |
|
1027 | @classmethod | |
1030 | def from_cookie_store(cls, cookie_store): |
|
1028 | def from_cookie_store(cls, cookie_store): | |
1031 | """ |
|
1029 | """ | |
1032 | Creates AuthUser from a cookie store |
|
1030 | Creates AuthUser from a cookie store | |
1033 |
|
1031 | |||
1034 | :param cls: |
|
1032 | :param cls: | |
1035 | :param cookie_store: |
|
1033 | :param cookie_store: | |
1036 | """ |
|
1034 | """ | |
1037 | user_id = cookie_store.get('user_id') |
|
1035 | user_id = cookie_store.get('user_id') | |
1038 | username = cookie_store.get('username') |
|
1036 | username = cookie_store.get('username') | |
1039 | api_key = cookie_store.get('api_key') |
|
1037 | api_key = cookie_store.get('api_key') | |
1040 | return AuthUser(user_id, api_key, username) |
|
1038 | return AuthUser(user_id, api_key, username) | |
1041 |
|
1039 | |||
1042 | @classmethod |
|
1040 | @classmethod | |
1043 | 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): | |
1044 | _set = set() |
|
1042 | _set = set() | |
1045 |
|
1043 | |||
1046 | if inherit_from_default: |
|
1044 | if inherit_from_default: | |
1047 | default_ips = UserIpMap.query().filter( |
|
1045 | default_ips = UserIpMap.query().filter( | |
1048 | UserIpMap.user == User.get_default_user(cache=True)) |
|
1046 | UserIpMap.user == User.get_default_user(cache=True)) | |
1049 | if cache: |
|
1047 | if cache: | |
1050 | default_ips = default_ips.options(FromCache("sql_cache_short", |
|
1048 | default_ips = default_ips.options(FromCache("sql_cache_short", | |
1051 | "get_user_ips_default")) |
|
1049 | "get_user_ips_default")) | |
1052 |
|
1050 | |||
1053 | # populate from default user |
|
1051 | # populate from default user | |
1054 | for ip in default_ips: |
|
1052 | for ip in default_ips: | |
1055 | try: |
|
1053 | try: | |
1056 | _set.add(ip.ip_addr) |
|
1054 | _set.add(ip.ip_addr) | |
1057 | except ObjectDeletedError: |
|
1055 | except ObjectDeletedError: | |
1058 | # since we use heavy caching sometimes it happens that |
|
1056 | # since we use heavy caching sometimes it happens that | |
1059 | # we get deleted objects here, we just skip them |
|
1057 | # we get deleted objects here, we just skip them | |
1060 | pass |
|
1058 | pass | |
1061 |
|
1059 | |||
1062 | user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id) |
|
1060 | user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id) | |
1063 | if cache: |
|
1061 | if cache: | |
1064 | user_ips = user_ips.options(FromCache("sql_cache_short", |
|
1062 | user_ips = user_ips.options(FromCache("sql_cache_short", | |
1065 | "get_user_ips_%s" % user_id)) |
|
1063 | "get_user_ips_%s" % user_id)) | |
1066 |
|
1064 | |||
1067 | for ip in user_ips: |
|
1065 | for ip in user_ips: | |
1068 | try: |
|
1066 | try: | |
1069 | _set.add(ip.ip_addr) |
|
1067 | _set.add(ip.ip_addr) | |
1070 | except ObjectDeletedError: |
|
1068 | except ObjectDeletedError: | |
1071 | # since we use heavy caching sometimes it happens that we get |
|
1069 | # since we use heavy caching sometimes it happens that we get | |
1072 | # deleted objects here, we just skip them |
|
1070 | # deleted objects here, we just skip them | |
1073 | pass |
|
1071 | pass | |
1074 | return _set or set(['0.0.0.0/0', '::/0']) |
|
1072 | return _set or set(['0.0.0.0/0', '::/0']) | |
1075 |
|
1073 | |||
1076 |
|
1074 | |||
1077 | def set_available_permissions(config): |
|
1075 | def set_available_permissions(config): | |
1078 | """ |
|
1076 | """ | |
1079 | This function will propagate pylons globals with all available defined |
|
1077 | This function will propagate pylons globals with all available defined | |
1080 | 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 | |
1081 | permissions since adding a new permission also requires application restart |
|
1079 | permissions since adding a new permission also requires application restart | |
1082 | ie. to decorate new views with the newly created permission |
|
1080 | ie. to decorate new views with the newly created permission | |
1083 |
|
1081 | |||
1084 | :param config: current pylons config instance |
|
1082 | :param config: current pylons config instance | |
1085 |
|
1083 | |||
1086 | """ |
|
1084 | """ | |
1087 | log.info('getting information about all available permissions') |
|
1085 | log.info('getting information about all available permissions') | |
1088 | try: |
|
1086 | try: | |
1089 | sa = meta.Session |
|
1087 | sa = meta.Session | |
1090 | all_perms = sa.query(Permission).all() |
|
1088 | all_perms = sa.query(Permission).all() | |
1091 | config['available_permissions'] = [x.permission_name for x in all_perms] |
|
1089 | config['available_permissions'] = [x.permission_name for x in all_perms] | |
1092 | except Exception: |
|
1090 | except Exception: | |
1093 | log.error(traceback.format_exc()) |
|
1091 | log.error(traceback.format_exc()) | |
1094 | finally: |
|
1092 | finally: | |
1095 | meta.Session.remove() |
|
1093 | meta.Session.remove() | |
1096 |
|
1094 | |||
1097 |
|
1095 | |||
1098 | 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): | |
1099 | """ |
|
1097 | """ | |
1100 | Return the current authentication token, creating one if one doesn't |
|
1098 | Return the current authentication token, creating one if one doesn't | |
1101 | already exist and the save_if_missing flag is present. |
|
1099 | already exist and the save_if_missing flag is present. | |
1102 |
|
1100 | |||
1103 | :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 | |
1104 | :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 | |
1105 | :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 | |
1106 | session |
|
1104 | session | |
1107 | """ |
|
1105 | """ | |
1108 | if not session: |
|
1106 | if not session: | |
1109 | from pylons import session |
|
1107 | from pylons import session | |
1110 |
|
1108 | |||
1111 | 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: | |
1112 | token = hashlib.sha1(str(random.getrandbits(128))).hexdigest() |
|
1110 | token = hashlib.sha1(str(random.getrandbits(128))).hexdigest() | |
1113 | session[csrf_token_key] = token |
|
1111 | session[csrf_token_key] = token | |
1114 | if hasattr(session, 'save'): |
|
1112 | if hasattr(session, 'save'): | |
1115 | session.save() |
|
1113 | session.save() | |
1116 | return session.get(csrf_token_key) |
|
1114 | return session.get(csrf_token_key) | |
1117 |
|
1115 | |||
1118 |
|
1116 | |||
1119 | # CHECK DECORATORS |
|
1117 | # CHECK DECORATORS | |
1120 | class CSRFRequired(object): |
|
1118 | class CSRFRequired(object): | |
1121 | """ |
|
1119 | """ | |
1122 | Decorator for authenticating a form |
|
1120 | Decorator for authenticating a form | |
1123 |
|
1121 | |||
1124 | This decorator uses an authorization token stored in the client's |
|
1122 | This decorator uses an authorization token stored in the client's | |
1125 | session for prevention of certain Cross-site request forgery (CSRF) |
|
1123 | session for prevention of certain Cross-site request forgery (CSRF) | |
1126 | attacks (See |
|
1124 | attacks (See | |
1127 | http://en.wikipedia.org/wiki/Cross-site_request_forgery for more |
|
1125 | http://en.wikipedia.org/wiki/Cross-site_request_forgery for more | |
1128 | information). |
|
1126 | information). | |
1129 |
|
1127 | |||
1130 | For use with the ``webhelpers.secure_form`` helper functions. |
|
1128 | For use with the ``webhelpers.secure_form`` helper functions. | |
1131 |
|
1129 | |||
1132 | """ |
|
1130 | """ | |
1133 | def __init__(self, token=csrf_token_key, header='X-CSRF-Token', |
|
1131 | def __init__(self, token=csrf_token_key, header='X-CSRF-Token', | |
1134 | except_methods=None): |
|
1132 | except_methods=None): | |
1135 | self.token = token |
|
1133 | self.token = token | |
1136 | self.header = header |
|
1134 | self.header = header | |
1137 | self.except_methods = except_methods or [] |
|
1135 | self.except_methods = except_methods or [] | |
1138 |
|
1136 | |||
1139 | def __call__(self, func): |
|
1137 | def __call__(self, func): | |
1140 | return get_cython_compat_decorator(self.__wrapper, func) |
|
1138 | return get_cython_compat_decorator(self.__wrapper, func) | |
1141 |
|
1139 | |||
1142 | def _get_csrf(self, _request): |
|
1140 | def _get_csrf(self, _request): | |
1143 | return _request.POST.get(self.token, _request.headers.get(self.header)) |
|
1141 | return _request.POST.get(self.token, _request.headers.get(self.header)) | |
1144 |
|
1142 | |||
1145 | def check_csrf(self, _request, cur_token): |
|
1143 | def check_csrf(self, _request, cur_token): | |
1146 | supplied_token = self._get_csrf(_request) |
|
1144 | supplied_token = self._get_csrf(_request) | |
1147 | return supplied_token and supplied_token == cur_token |
|
1145 | return supplied_token and supplied_token == cur_token | |
1148 |
|
1146 | |||
1149 | def __wrapper(self, func, *fargs, **fkwargs): |
|
1147 | def __wrapper(self, func, *fargs, **fkwargs): | |
1150 | if request.method in self.except_methods: |
|
1148 | if request.method in self.except_methods: | |
1151 | return func(*fargs, **fkwargs) |
|
1149 | return func(*fargs, **fkwargs) | |
1152 |
|
1150 | |||
1153 | cur_token = get_csrf_token(save_if_missing=False) |
|
1151 | cur_token = get_csrf_token(save_if_missing=False) | |
1154 | if self.check_csrf(request, cur_token): |
|
1152 | if self.check_csrf(request, cur_token): | |
1155 | if request.POST.get(self.token): |
|
1153 | if request.POST.get(self.token): | |
1156 | del request.POST[self.token] |
|
1154 | del request.POST[self.token] | |
1157 | return func(*fargs, **fkwargs) |
|
1155 | return func(*fargs, **fkwargs) | |
1158 | else: |
|
1156 | else: | |
1159 | reason = 'token-missing' |
|
1157 | reason = 'token-missing' | |
1160 | supplied_token = self._get_csrf(request) |
|
1158 | supplied_token = self._get_csrf(request) | |
1161 | if supplied_token and cur_token != supplied_token: |
|
1159 | if supplied_token and cur_token != supplied_token: | |
1162 | reason = 'token-mismatch [%s:%s]' % (cur_token or ''[:6], |
|
1160 | reason = 'token-mismatch [%s:%s]' % (cur_token or ''[:6], | |
1163 | supplied_token or ''[:6]) |
|
1161 | supplied_token or ''[:6]) | |
1164 |
|
1162 | |||
1165 | csrf_message = \ |
|
1163 | csrf_message = \ | |
1166 | ("Cross-site request forgery detected, request denied. See " |
|
1164 | ("Cross-site request forgery detected, request denied. See " | |
1167 | "http://en.wikipedia.org/wiki/Cross-site_request_forgery for " |
|
1165 | "http://en.wikipedia.org/wiki/Cross-site_request_forgery for " | |
1168 | "more information.") |
|
1166 | "more information.") | |
1169 | log.warn('Cross-site request forgery detected, request %r DENIED: %s ' |
|
1167 | log.warn('Cross-site request forgery detected, request %r DENIED: %s ' | |
1170 | 'REMOTE_ADDR:%s, HEADERS:%s' % ( |
|
1168 | 'REMOTE_ADDR:%s, HEADERS:%s' % ( | |
1171 | request, reason, request.remote_addr, request.headers)) |
|
1169 | request, reason, request.remote_addr, request.headers)) | |
1172 |
|
1170 | |||
1173 | raise HTTPForbidden(explanation=csrf_message) |
|
1171 | raise HTTPForbidden(explanation=csrf_message) | |
1174 |
|
1172 | |||
1175 |
|
1173 | |||
1176 | class LoginRequired(object): |
|
1174 | class LoginRequired(object): | |
1177 | """ |
|
1175 | """ | |
1178 | Must be logged in to execute this function else |
|
1176 | Must be logged in to execute this function else | |
1179 | redirect to login page |
|
1177 | redirect to login page | |
1180 |
|
1178 | |||
1181 | :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 | |
1182 | and grants access based on valid token |
|
1180 | and grants access based on valid token | |
1183 | """ |
|
1181 | """ | |
1184 | def __init__(self, auth_token_access=None): |
|
1182 | def __init__(self, auth_token_access=None): | |
1185 | self.auth_token_access = auth_token_access |
|
1183 | self.auth_token_access = auth_token_access | |
1186 |
|
1184 | |||
1187 | def __call__(self, func): |
|
1185 | def __call__(self, func): | |
1188 | return get_cython_compat_decorator(self.__wrapper, func) |
|
1186 | return get_cython_compat_decorator(self.__wrapper, func) | |
1189 |
|
1187 | |||
1190 | def __wrapper(self, func, *fargs, **fkwargs): |
|
1188 | def __wrapper(self, func, *fargs, **fkwargs): | |
1191 | from rhodecode.lib import helpers as h |
|
1189 | from rhodecode.lib import helpers as h | |
1192 | cls = fargs[0] |
|
1190 | cls = fargs[0] | |
1193 | user = cls._rhodecode_user |
|
1191 | user = cls._rhodecode_user | |
1194 | loc = "%s:%s" % (cls.__class__.__name__, func.__name__) |
|
1192 | loc = "%s:%s" % (cls.__class__.__name__, func.__name__) | |
1195 | log.debug('Starting login restriction checks for user: %s' % (user,)) |
|
1193 | log.debug('Starting login restriction checks for user: %s' % (user,)) | |
1196 | # check if our IP is allowed |
|
1194 | # check if our IP is allowed | |
1197 | ip_access_valid = True |
|
1195 | ip_access_valid = True | |
1198 | if not user.ip_allowed: |
|
1196 | if not user.ip_allowed: | |
1199 | h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))), |
|
1197 | h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))), | |
1200 | category='warning') |
|
1198 | category='warning') | |
1201 | ip_access_valid = False |
|
1199 | ip_access_valid = False | |
1202 |
|
1200 | |||
1203 | # 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 | |
1204 | # defined white-list of controllers which API access will be enabled |
|
1202 | # defined white-list of controllers which API access will be enabled | |
1205 | _auth_token = request.GET.get( |
|
1203 | _auth_token = request.GET.get( | |
1206 | 'auth_token', '') or request.GET.get('api_key', '') |
|
1204 | 'auth_token', '') or request.GET.get('api_key', '') | |
1207 | auth_token_access_valid = allowed_auth_token_access( |
|
1205 | auth_token_access_valid = allowed_auth_token_access( | |
1208 | loc, auth_token=_auth_token) |
|
1206 | loc, auth_token=_auth_token) | |
1209 |
|
1207 | |||
1210 | # explicit controller is enabled or API is in our whitelist |
|
1208 | # explicit controller is enabled or API is in our whitelist | |
1211 | if self.auth_token_access or auth_token_access_valid: |
|
1209 | if self.auth_token_access or auth_token_access_valid: | |
1212 | log.debug('Checking AUTH TOKEN access for %s' % (cls,)) |
|
1210 | log.debug('Checking AUTH TOKEN access for %s' % (cls,)) | |
1213 | db_user = user.get_instance() |
|
1211 | db_user = user.get_instance() | |
1214 |
|
1212 | |||
1215 | if db_user: |
|
1213 | if db_user: | |
1216 | if self.auth_token_access: |
|
1214 | if self.auth_token_access: | |
1217 | roles = self.auth_token_access |
|
1215 | roles = self.auth_token_access | |
1218 | else: |
|
1216 | else: | |
1219 | roles = [UserApiKeys.ROLE_HTTP] |
|
1217 | roles = [UserApiKeys.ROLE_HTTP] | |
1220 | token_match = db_user.authenticate_by_token( |
|
1218 | token_match = db_user.authenticate_by_token( | |
1221 | _auth_token, roles=roles) |
|
1219 | _auth_token, roles=roles) | |
1222 | else: |
|
1220 | else: | |
1223 | 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) | |
1224 | token_match = False |
|
1222 | token_match = False | |
1225 |
|
1223 | |||
1226 | if _auth_token and token_match: |
|
1224 | if _auth_token and token_match: | |
1227 | auth_token_access_valid = True |
|
1225 | auth_token_access_valid = True | |
1228 | log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],)) |
|
1226 | log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],)) | |
1229 | else: |
|
1227 | else: | |
1230 | auth_token_access_valid = False |
|
1228 | auth_token_access_valid = False | |
1231 | if not _auth_token: |
|
1229 | if not _auth_token: | |
1232 | log.debug("AUTH TOKEN *NOT* present in request") |
|
1230 | log.debug("AUTH TOKEN *NOT* present in request") | |
1233 | else: |
|
1231 | else: | |
1234 | log.warning( |
|
1232 | log.warning( | |
1235 | "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:]) |
|
1233 | "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:]) | |
1236 |
|
1234 | |||
1237 | log.debug('Checking if %s is authenticated @ %s' % (user.username, loc)) |
|
1235 | log.debug('Checking if %s is authenticated @ %s' % (user.username, loc)) | |
1238 | reason = 'RHODECODE_AUTH' if user.is_authenticated \ |
|
1236 | reason = 'RHODECODE_AUTH' if user.is_authenticated \ | |
1239 | else 'AUTH_TOKEN_AUTH' |
|
1237 | else 'AUTH_TOKEN_AUTH' | |
1240 |
|
1238 | |||
1241 | if ip_access_valid and ( |
|
1239 | if ip_access_valid and ( | |
1242 | user.is_authenticated or auth_token_access_valid): |
|
1240 | user.is_authenticated or auth_token_access_valid): | |
1243 | log.info( |
|
1241 | log.info( | |
1244 | 'user %s authenticating with:%s IS authenticated on func %s' |
|
1242 | 'user %s authenticating with:%s IS authenticated on func %s' | |
1245 | % (user, reason, loc)) |
|
1243 | % (user, reason, loc)) | |
1246 |
|
1244 | |||
1247 | # update user data to check last activity |
|
1245 | # update user data to check last activity | |
1248 | user.update_lastactivity() |
|
1246 | user.update_lastactivity() | |
1249 | Session().commit() |
|
1247 | Session().commit() | |
1250 | return func(*fargs, **fkwargs) |
|
1248 | return func(*fargs, **fkwargs) | |
1251 | else: |
|
1249 | else: | |
1252 | log.warning( |
|
1250 | log.warning( | |
1253 | 'user %s authenticating with:%s NOT authenticated on ' |
|
1251 | 'user %s authenticating with:%s NOT authenticated on ' | |
1254 | 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s' |
|
1252 | 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s' | |
1255 | % (user, reason, loc, ip_access_valid, |
|
1253 | % (user, reason, loc, ip_access_valid, | |
1256 | auth_token_access_valid)) |
|
1254 | auth_token_access_valid)) | |
1257 | # we preserve the get PARAM |
|
1255 | # we preserve the get PARAM | |
1258 | came_from = request.path_qs |
|
1256 | came_from = request.path_qs | |
1259 |
|
||||
1260 | log.debug('redirecting to login page with %s' % (came_from,)) |
|
1257 | log.debug('redirecting to login page with %s' % (came_from,)) | |
1261 | return redirect( |
|
1258 | return redirect( | |
1262 | h.route_path('login', _query={'came_from': came_from})) |
|
1259 | h.route_path('login', _query={'came_from': came_from})) | |
1263 |
|
1260 | |||
1264 |
|
1261 | |||
1265 | class NotAnonymous(object): |
|
1262 | class NotAnonymous(object): | |
1266 | """ |
|
1263 | """ | |
1267 | Must be logged in to execute this function else |
|
1264 | Must be logged in to execute this function else | |
1268 | redirect to login page""" |
|
1265 | redirect to login page""" | |
1269 |
|
1266 | |||
1270 | def __call__(self, func): |
|
1267 | def __call__(self, func): | |
1271 | return get_cython_compat_decorator(self.__wrapper, func) |
|
1268 | return get_cython_compat_decorator(self.__wrapper, func) | |
1272 |
|
1269 | |||
1273 | def __wrapper(self, func, *fargs, **fkwargs): |
|
1270 | def __wrapper(self, func, *fargs, **fkwargs): | |
1274 | cls = fargs[0] |
|
1271 | cls = fargs[0] | |
1275 | self.user = cls._rhodecode_user |
|
1272 | self.user = cls._rhodecode_user | |
1276 |
|
1273 | |||
1277 | log.debug('Checking if user is not anonymous @%s' % cls) |
|
1274 | log.debug('Checking if user is not anonymous @%s' % cls) | |
1278 |
|
1275 | |||
1279 | anonymous = self.user.username == User.DEFAULT_USER |
|
1276 | anonymous = self.user.username == User.DEFAULT_USER | |
1280 |
|
1277 | |||
1281 | if anonymous: |
|
1278 | if anonymous: | |
1282 | came_from = request.path_qs |
|
1279 | came_from = request.path_qs | |
1283 |
|
1280 | |||
1284 | import rhodecode.lib.helpers as h |
|
1281 | import rhodecode.lib.helpers as h | |
1285 | h.flash(_('You need to be a registered user to ' |
|
1282 | h.flash(_('You need to be a registered user to ' | |
1286 | 'perform this action'), |
|
1283 | 'perform this action'), | |
1287 | category='warning') |
|
1284 | category='warning') | |
1288 | return redirect( |
|
1285 | return redirect( | |
1289 | h.route_path('login', _query={'came_from': came_from})) |
|
1286 | h.route_path('login', _query={'came_from': came_from})) | |
1290 | else: |
|
1287 | else: | |
1291 | return func(*fargs, **fkwargs) |
|
1288 | return func(*fargs, **fkwargs) | |
1292 |
|
1289 | |||
1293 |
|
1290 | |||
1294 | class XHRRequired(object): |
|
1291 | class XHRRequired(object): | |
1295 | def __call__(self, func): |
|
1292 | def __call__(self, func): | |
1296 | return get_cython_compat_decorator(self.__wrapper, func) |
|
1293 | return get_cython_compat_decorator(self.__wrapper, func) | |
1297 |
|
1294 | |||
1298 | def __wrapper(self, func, *fargs, **fkwargs): |
|
1295 | def __wrapper(self, func, *fargs, **fkwargs): | |
1299 | log.debug('Checking if request is XMLHttpRequest (XHR)') |
|
1296 | log.debug('Checking if request is XMLHttpRequest (XHR)') | |
1300 | xhr_message = 'This is not a valid XMLHttpRequest (XHR) request' |
|
1297 | xhr_message = 'This is not a valid XMLHttpRequest (XHR) request' | |
1301 | if not request.is_xhr: |
|
1298 | if not request.is_xhr: | |
1302 | abort(400, detail=xhr_message) |
|
1299 | abort(400, detail=xhr_message) | |
1303 |
|
1300 | |||
1304 | return func(*fargs, **fkwargs) |
|
1301 | return func(*fargs, **fkwargs) | |
1305 |
|
1302 | |||
1306 |
|
1303 | |||
1307 | class HasAcceptedRepoType(object): |
|
1304 | class HasAcceptedRepoType(object): | |
1308 | """ |
|
1305 | """ | |
1309 | Check if requested repo is within given repo type aliases |
|
1306 | Check if requested repo is within given repo type aliases | |
1310 |
|
1307 | |||
1311 | TODO: anderson: not sure where to put this decorator |
|
1308 | TODO: anderson: not sure where to put this decorator | |
1312 | """ |
|
1309 | """ | |
1313 |
|
1310 | |||
1314 | def __init__(self, *repo_type_list): |
|
1311 | def __init__(self, *repo_type_list): | |
1315 | self.repo_type_list = set(repo_type_list) |
|
1312 | self.repo_type_list = set(repo_type_list) | |
1316 |
|
1313 | |||
1317 | def __call__(self, func): |
|
1314 | def __call__(self, func): | |
1318 | return get_cython_compat_decorator(self.__wrapper, func) |
|
1315 | return get_cython_compat_decorator(self.__wrapper, func) | |
1319 |
|
1316 | |||
1320 | def __wrapper(self, func, *fargs, **fkwargs): |
|
1317 | def __wrapper(self, func, *fargs, **fkwargs): | |
1321 | cls = fargs[0] |
|
1318 | cls = fargs[0] | |
1322 | rhodecode_repo = cls.rhodecode_repo |
|
1319 | rhodecode_repo = cls.rhodecode_repo | |
1323 |
|
1320 | |||
1324 | log.debug('%s checking repo type for %s in %s', |
|
1321 | log.debug('%s checking repo type for %s in %s', | |
1325 | self.__class__.__name__, |
|
1322 | self.__class__.__name__, | |
1326 | rhodecode_repo.alias, self.repo_type_list) |
|
1323 | rhodecode_repo.alias, self.repo_type_list) | |
1327 |
|
1324 | |||
1328 | if rhodecode_repo.alias in self.repo_type_list: |
|
1325 | if rhodecode_repo.alias in self.repo_type_list: | |
1329 | return func(*fargs, **fkwargs) |
|
1326 | return func(*fargs, **fkwargs) | |
1330 | else: |
|
1327 | else: | |
1331 | import rhodecode.lib.helpers as h |
|
1328 | import rhodecode.lib.helpers as h | |
1332 | h.flash(h.literal( |
|
1329 | h.flash(h.literal( | |
1333 | _('Action not supported for %s.' % rhodecode_repo.alias)), |
|
1330 | _('Action not supported for %s.' % rhodecode_repo.alias)), | |
1334 | category='warning') |
|
1331 | category='warning') | |
1335 | return redirect( |
|
1332 | return redirect( | |
1336 | url('summary_home', repo_name=cls.rhodecode_db_repo.repo_name)) |
|
1333 | url('summary_home', repo_name=cls.rhodecode_db_repo.repo_name)) | |
1337 |
|
1334 | |||
1338 |
|
1335 | |||
1339 | class PermsDecorator(object): |
|
1336 | class PermsDecorator(object): | |
1340 | """ |
|
1337 | """ | |
1341 | Base class for controller decorators, we extract the current user from |
|
1338 | Base class for controller decorators, we extract the current user from | |
1342 | the class itself, which has it stored in base controllers |
|
1339 | the class itself, which has it stored in base controllers | |
1343 | """ |
|
1340 | """ | |
1344 |
|
1341 | |||
1345 | def __init__(self, *required_perms): |
|
1342 | def __init__(self, *required_perms): | |
1346 | self.required_perms = set(required_perms) |
|
1343 | self.required_perms = set(required_perms) | |
1347 |
|
1344 | |||
1348 | def __call__(self, func): |
|
1345 | def __call__(self, func): | |
1349 | return get_cython_compat_decorator(self.__wrapper, func) |
|
1346 | return get_cython_compat_decorator(self.__wrapper, func) | |
1350 |
|
1347 | |||
|
1348 | def _get_request(self): | |||
|
1349 | from pyramid.threadlocal import get_current_request | |||
|
1350 | pyramid_request = get_current_request() | |||
|
1351 | if not pyramid_request: | |||
|
1352 | # return global request of pylons incase pyramid one isn't available | |||
|
1353 | return request | |||
|
1354 | return pyramid_request | |||
|
1355 | ||||
|
1356 | def _get_came_from(self): | |||
|
1357 | _request = self._get_request() | |||
|
1358 | ||||
|
1359 | # both pylons/pyramid has this attribute | |||
|
1360 | return _request.path_qs | |||
|
1361 | ||||
1351 | def __wrapper(self, func, *fargs, **fkwargs): |
|
1362 | def __wrapper(self, func, *fargs, **fkwargs): | |
1352 | cls = fargs[0] |
|
1363 | cls = fargs[0] | |
1353 | _user = cls._rhodecode_user |
|
1364 | _user = cls._rhodecode_user | |
1354 |
|
1365 | |||
1355 | log.debug('checking %s permissions %s for %s %s', |
|
1366 | log.debug('checking %s permissions %s for %s %s', | |
1356 | self.__class__.__name__, self.required_perms, cls, _user) |
|
1367 | self.__class__.__name__, self.required_perms, cls, _user) | |
1357 |
|
1368 | |||
1358 | if self.check_permissions(_user): |
|
1369 | if self.check_permissions(_user): | |
1359 | log.debug('Permission granted for %s %s', cls, _user) |
|
1370 | log.debug('Permission granted for %s %s', cls, _user) | |
1360 | return func(*fargs, **fkwargs) |
|
1371 | return func(*fargs, **fkwargs) | |
1361 |
|
1372 | |||
1362 | else: |
|
1373 | else: | |
1363 | log.debug('Permission denied for %s %s', cls, _user) |
|
1374 | log.debug('Permission denied for %s %s', cls, _user) | |
1364 | anonymous = _user.username == User.DEFAULT_USER |
|
1375 | anonymous = _user.username == User.DEFAULT_USER | |
1365 |
|
1376 | |||
1366 | if anonymous: |
|
1377 | if anonymous: | |
1367 | came_from = request.path_qs |
|
|||
1368 |
|
||||
1369 | import rhodecode.lib.helpers as h |
|
1378 | import rhodecode.lib.helpers as h | |
|
1379 | came_from = self._get_came_from() | |||
1370 | h.flash(_('You need to be signed in to view this page'), |
|
1380 | h.flash(_('You need to be signed in to view this page'), | |
1371 | category='warning') |
|
1381 | category='warning') | |
1372 |
re |
|
1382 | raise HTTPFound( | |
1373 | h.route_path('login', _query={'came_from': came_from})) |
|
1383 | h.route_path('login', _query={'came_from': came_from})) | |
1374 |
|
1384 | |||
1375 | else: |
|
1385 | else: | |
1376 | # redirect with forbidden ret code |
|
1386 | # redirect with forbidden ret code | |
1377 |
re |
|
1387 | raise HTTPForbidden() | |
1378 |
|
1388 | |||
1379 | def check_permissions(self, user): |
|
1389 | def check_permissions(self, user): | |
1380 | """Dummy function for overriding""" |
|
1390 | """Dummy function for overriding""" | |
1381 | raise NotImplementedError( |
|
1391 | raise NotImplementedError( | |
1382 | 'You have to write this function in child class') |
|
1392 | 'You have to write this function in child class') | |
1383 |
|
1393 | |||
1384 |
|
1394 | |||
1385 | class HasPermissionAllDecorator(PermsDecorator): |
|
1395 | class HasPermissionAllDecorator(PermsDecorator): | |
1386 | """ |
|
1396 | """ | |
1387 | Checks for access permission for all given predicates. All of them |
|
1397 | Checks for access permission for all given predicates. All of them | |
1388 | have to be meet in order to fulfill the request |
|
1398 | have to be meet in order to fulfill the request | |
1389 | """ |
|
1399 | """ | |
1390 |
|
1400 | |||
1391 | def check_permissions(self, user): |
|
1401 | def check_permissions(self, user): | |
1392 | perms = user.permissions_with_scope({}) |
|
1402 | perms = user.permissions_with_scope({}) | |
1393 | if self.required_perms.issubset(perms['global']): |
|
1403 | if self.required_perms.issubset(perms['global']): | |
1394 | return True |
|
1404 | return True | |
1395 | return False |
|
1405 | return False | |
1396 |
|
1406 | |||
1397 |
|
1407 | |||
1398 | class HasPermissionAnyDecorator(PermsDecorator): |
|
1408 | class HasPermissionAnyDecorator(PermsDecorator): | |
1399 | """ |
|
1409 | """ | |
1400 | Checks for access permission for any of given predicates. In order to |
|
1410 | Checks for access permission for any of given predicates. In order to | |
1401 | fulfill the request any of predicates must be meet |
|
1411 | fulfill the request any of predicates must be meet | |
1402 | """ |
|
1412 | """ | |
1403 |
|
1413 | |||
1404 | def check_permissions(self, user): |
|
1414 | def check_permissions(self, user): | |
1405 | perms = user.permissions_with_scope({}) |
|
1415 | perms = user.permissions_with_scope({}) | |
1406 | if self.required_perms.intersection(perms['global']): |
|
1416 | if self.required_perms.intersection(perms['global']): | |
1407 | return True |
|
1417 | return True | |
1408 | return False |
|
1418 | return False | |
1409 |
|
1419 | |||
1410 |
|
1420 | |||
1411 | class HasRepoPermissionAllDecorator(PermsDecorator): |
|
1421 | class HasRepoPermissionAllDecorator(PermsDecorator): | |
1412 | """ |
|
1422 | """ | |
1413 | Checks for access permission for all given predicates for specific |
|
1423 | Checks for access permission for all given predicates for specific | |
1414 | repository. All of them have to be meet in order to fulfill the request |
|
1424 | repository. All of them have to be meet in order to fulfill the request | |
1415 | """ |
|
1425 | """ | |
|
1426 | def _get_repo_name(self): | |||
|
1427 | _request = self._get_request() | |||
|
1428 | return get_repo_slug(_request) | |||
1416 |
|
1429 | |||
1417 | def check_permissions(self, user): |
|
1430 | def check_permissions(self, user): | |
1418 | perms = user.permissions |
|
1431 | perms = user.permissions | |
1419 |
repo_name = get_repo_ |
|
1432 | repo_name = self._get_repo_name() | |
1420 | try: |
|
1433 | try: | |
1421 | user_perms = set([perms['repositories'][repo_name]]) |
|
1434 | user_perms = set([perms['repositories'][repo_name]]) | |
1422 | except KeyError: |
|
1435 | except KeyError: | |
1423 | return False |
|
1436 | return False | |
1424 | if self.required_perms.issubset(user_perms): |
|
1437 | if self.required_perms.issubset(user_perms): | |
1425 | return True |
|
1438 | return True | |
1426 | return False |
|
1439 | return False | |
1427 |
|
1440 | |||
1428 |
|
1441 | |||
1429 | class HasRepoPermissionAnyDecorator(PermsDecorator): |
|
1442 | class HasRepoPermissionAnyDecorator(PermsDecorator): | |
1430 | """ |
|
1443 | """ | |
1431 | Checks for access permission for any of given predicates for specific |
|
1444 | Checks for access permission for any of given predicates for specific | |
1432 | repository. In order to fulfill the request any of predicates must be meet |
|
1445 | repository. In order to fulfill the request any of predicates must be meet | |
1433 | """ |
|
1446 | """ | |
|
1447 | def _get_repo_name(self): | |||
|
1448 | _request = self._get_request() | |||
|
1449 | return get_repo_slug(_request) | |||
1434 |
|
1450 | |||
1435 | def check_permissions(self, user): |
|
1451 | def check_permissions(self, user): | |
1436 | perms = user.permissions |
|
1452 | perms = user.permissions | |
1437 |
repo_name = get_repo_ |
|
1453 | repo_name = self._get_repo_name() | |
1438 | try: |
|
1454 | try: | |
1439 | user_perms = set([perms['repositories'][repo_name]]) |
|
1455 | user_perms = set([perms['repositories'][repo_name]]) | |
1440 | except KeyError: |
|
1456 | except KeyError: | |
1441 | return False |
|
1457 | return False | |
1442 |
|
1458 | |||
1443 | if self.required_perms.intersection(user_perms): |
|
1459 | if self.required_perms.intersection(user_perms): | |
1444 | return True |
|
1460 | return True | |
1445 | return False |
|
1461 | return False | |
1446 |
|
1462 | |||
1447 |
|
1463 | |||
1448 | class HasRepoGroupPermissionAllDecorator(PermsDecorator): |
|
1464 | class HasRepoGroupPermissionAllDecorator(PermsDecorator): | |
1449 | """ |
|
1465 | """ | |
1450 | Checks for access permission for all given predicates for specific |
|
1466 | Checks for access permission for all given predicates for specific | |
1451 | repository group. All of them have to be meet in order to |
|
1467 | repository group. All of them have to be meet in order to | |
1452 | fulfill the request |
|
1468 | fulfill the request | |
1453 | """ |
|
1469 | """ | |
|
1470 | def _get_repo_group_name(self): | |||
|
1471 | _request = self._get_request() | |||
|
1472 | return get_repo_group_slug(_request) | |||
1454 |
|
1473 | |||
1455 | def check_permissions(self, user): |
|
1474 | def check_permissions(self, user): | |
1456 | perms = user.permissions |
|
1475 | perms = user.permissions | |
1457 |
group_name = get_repo_group_ |
|
1476 | group_name = self._get_repo_group_name() | |
1458 | try: |
|
1477 | try: | |
1459 | user_perms = set([perms['repositories_groups'][group_name]]) |
|
1478 | user_perms = set([perms['repositories_groups'][group_name]]) | |
1460 | except KeyError: |
|
1479 | except KeyError: | |
1461 | return False |
|
1480 | return False | |
1462 |
|
1481 | |||
1463 | if self.required_perms.issubset(user_perms): |
|
1482 | if self.required_perms.issubset(user_perms): | |
1464 | return True |
|
1483 | return True | |
1465 | return False |
|
1484 | return False | |
1466 |
|
1485 | |||
1467 |
|
1486 | |||
1468 | class HasRepoGroupPermissionAnyDecorator(PermsDecorator): |
|
1487 | class HasRepoGroupPermissionAnyDecorator(PermsDecorator): | |
1469 | """ |
|
1488 | """ | |
1470 | Checks for access permission for any of given predicates for specific |
|
1489 | Checks for access permission for any of given predicates for specific | |
1471 | repository group. In order to fulfill the request any |
|
1490 | repository group. In order to fulfill the request any | |
1472 | of predicates must be met |
|
1491 | of predicates must be met | |
1473 | """ |
|
1492 | """ | |
|
1493 | def _get_repo_group_name(self): | |||
|
1494 | _request = self._get_request() | |||
|
1495 | return get_repo_group_slug(_request) | |||
1474 |
|
1496 | |||
1475 | def check_permissions(self, user): |
|
1497 | def check_permissions(self, user): | |
1476 | perms = user.permissions |
|
1498 | perms = user.permissions | |
1477 |
group_name = get_repo_group_ |
|
1499 | group_name = self._get_repo_group_name() | |
1478 | try: |
|
1500 | try: | |
1479 | user_perms = set([perms['repositories_groups'][group_name]]) |
|
1501 | user_perms = set([perms['repositories_groups'][group_name]]) | |
1480 | except KeyError: |
|
1502 | except KeyError: | |
1481 | return False |
|
1503 | return False | |
1482 |
|
1504 | |||
1483 | if self.required_perms.intersection(user_perms): |
|
1505 | if self.required_perms.intersection(user_perms): | |
1484 | return True |
|
1506 | return True | |
1485 | return False |
|
1507 | return False | |
1486 |
|
1508 | |||
1487 |
|
1509 | |||
1488 | class HasUserGroupPermissionAllDecorator(PermsDecorator): |
|
1510 | class HasUserGroupPermissionAllDecorator(PermsDecorator): | |
1489 | """ |
|
1511 | """ | |
1490 | Checks for access permission for all given predicates for specific |
|
1512 | Checks for access permission for all given predicates for specific | |
1491 | user group. All of them have to be meet in order to fulfill the request |
|
1513 | user group. All of them have to be meet in order to fulfill the request | |
1492 | """ |
|
1514 | """ | |
|
1515 | def _get_user_group_name(self): | |||
|
1516 | _request = self._get_request() | |||
|
1517 | return get_user_group_slug(_request) | |||
1493 |
|
1518 | |||
1494 | def check_permissions(self, user): |
|
1519 | def check_permissions(self, user): | |
1495 | perms = user.permissions |
|
1520 | perms = user.permissions | |
1496 |
group_name = get_user_group_ |
|
1521 | group_name = self._get_user_group_name() | |
1497 | try: |
|
1522 | try: | |
1498 | user_perms = set([perms['user_groups'][group_name]]) |
|
1523 | user_perms = set([perms['user_groups'][group_name]]) | |
1499 | except KeyError: |
|
1524 | except KeyError: | |
1500 | return False |
|
1525 | return False | |
1501 |
|
1526 | |||
1502 | if self.required_perms.issubset(user_perms): |
|
1527 | if self.required_perms.issubset(user_perms): | |
1503 | return True |
|
1528 | return True | |
1504 | return False |
|
1529 | return False | |
1505 |
|
1530 | |||
1506 |
|
1531 | |||
1507 | class HasUserGroupPermissionAnyDecorator(PermsDecorator): |
|
1532 | class HasUserGroupPermissionAnyDecorator(PermsDecorator): | |
1508 | """ |
|
1533 | """ | |
1509 | Checks for access permission for any of given predicates for specific |
|
1534 | Checks for access permission for any of given predicates for specific | |
1510 | user group. In order to fulfill the request any of predicates must be meet |
|
1535 | user group. In order to fulfill the request any of predicates must be meet | |
1511 | """ |
|
1536 | """ | |
|
1537 | def _get_user_group_name(self): | |||
|
1538 | _request = self._get_request() | |||
|
1539 | return get_user_group_slug(_request) | |||
1512 |
|
1540 | |||
1513 | def check_permissions(self, user): |
|
1541 | def check_permissions(self, user): | |
1514 | perms = user.permissions |
|
1542 | perms = user.permissions | |
1515 |
group_name = get_user_group_ |
|
1543 | group_name = self._get_user_group_name() | |
1516 | try: |
|
1544 | try: | |
1517 | user_perms = set([perms['user_groups'][group_name]]) |
|
1545 | user_perms = set([perms['user_groups'][group_name]]) | |
1518 | except KeyError: |
|
1546 | except KeyError: | |
1519 | return False |
|
1547 | return False | |
1520 |
|
1548 | |||
1521 | if self.required_perms.intersection(user_perms): |
|
1549 | if self.required_perms.intersection(user_perms): | |
1522 | return True |
|
1550 | return True | |
1523 | return False |
|
1551 | return False | |
1524 |
|
1552 | |||
1525 |
|
1553 | |||
1526 | # CHECK FUNCTIONS |
|
1554 | # CHECK FUNCTIONS | |
1527 | class PermsFunction(object): |
|
1555 | class PermsFunction(object): | |
1528 | """Base function for other check functions""" |
|
1556 | """Base function for other check functions""" | |
1529 |
|
1557 | |||
1530 | def __init__(self, *perms): |
|
1558 | def __init__(self, *perms): | |
1531 | self.required_perms = set(perms) |
|
1559 | self.required_perms = set(perms) | |
1532 | self.repo_name = None |
|
1560 | self.repo_name = None | |
1533 | self.repo_group_name = None |
|
1561 | self.repo_group_name = None | |
1534 | self.user_group_name = None |
|
1562 | self.user_group_name = None | |
1535 |
|
1563 | |||
1536 | def __bool__(self): |
|
1564 | def __bool__(self): | |
1537 | frame = inspect.currentframe() |
|
1565 | frame = inspect.currentframe() | |
1538 | stack_trace = traceback.format_stack(frame) |
|
1566 | stack_trace = traceback.format_stack(frame) | |
1539 | log.error('Checking bool value on a class instance of perm ' |
|
1567 | log.error('Checking bool value on a class instance of perm ' | |
1540 | 'function is not allowed: %s' % ''.join(stack_trace)) |
|
1568 | 'function is not allowed: %s' % ''.join(stack_trace)) | |
1541 | # rather than throwing errors, here we always return False so if by |
|
1569 | # rather than throwing errors, here we always return False so if by | |
1542 | # accident someone checks truth for just an instance it will always end |
|
1570 | # accident someone checks truth for just an instance it will always end | |
1543 | # up in returning False |
|
1571 | # up in returning False | |
1544 | return False |
|
1572 | return False | |
1545 | __nonzero__ = __bool__ |
|
1573 | __nonzero__ = __bool__ | |
1546 |
|
1574 | |||
1547 | def __call__(self, check_location='', user=None): |
|
1575 | def __call__(self, check_location='', user=None): | |
1548 | if not user: |
|
1576 | if not user: | |
1549 | log.debug('Using user attribute from global request') |
|
1577 | log.debug('Using user attribute from global request') | |
1550 | # TODO: remove this someday,put as user as attribute here |
|
1578 | # TODO: remove this someday,put as user as attribute here | |
1551 | user = request.user |
|
1579 | user = request.user | |
1552 |
|
1580 | |||
1553 | # init auth user if not already given |
|
1581 | # init auth user if not already given | |
1554 | if not isinstance(user, AuthUser): |
|
1582 | if not isinstance(user, AuthUser): | |
1555 | log.debug('Wrapping user %s into AuthUser', user) |
|
1583 | log.debug('Wrapping user %s into AuthUser', user) | |
1556 | user = AuthUser(user.user_id) |
|
1584 | user = AuthUser(user.user_id) | |
1557 |
|
1585 | |||
1558 | cls_name = self.__class__.__name__ |
|
1586 | cls_name = self.__class__.__name__ | |
1559 | check_scope = self._get_check_scope(cls_name) |
|
1587 | check_scope = self._get_check_scope(cls_name) | |
1560 | check_location = check_location or 'unspecified location' |
|
1588 | check_location = check_location or 'unspecified location' | |
1561 |
|
1589 | |||
1562 | log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name, |
|
1590 | log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name, | |
1563 | self.required_perms, user, check_scope, check_location) |
|
1591 | self.required_perms, user, check_scope, check_location) | |
1564 | if not user: |
|
1592 | if not user: | |
1565 | log.warning('Empty user given for permission check') |
|
1593 | log.warning('Empty user given for permission check') | |
1566 | return False |
|
1594 | return False | |
1567 |
|
1595 | |||
1568 | if self.check_permissions(user): |
|
1596 | if self.check_permissions(user): | |
1569 | log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s', |
|
1597 | log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s', | |
1570 | check_scope, user, check_location) |
|
1598 | check_scope, user, check_location) | |
1571 | return True |
|
1599 | return True | |
1572 |
|
1600 | |||
1573 | else: |
|
1601 | else: | |
1574 | log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s', |
|
1602 | log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s', | |
1575 | check_scope, user, check_location) |
|
1603 | check_scope, user, check_location) | |
1576 | return False |
|
1604 | return False | |
1577 |
|
1605 | |||
|
1606 | def _get_request(self): | |||
|
1607 | from pyramid.threadlocal import get_current_request | |||
|
1608 | pyramid_request = get_current_request() | |||
|
1609 | if not pyramid_request: | |||
|
1610 | # return global request of pylons incase pyramid one isn't available | |||
|
1611 | return request | |||
|
1612 | return pyramid_request | |||
|
1613 | ||||
1578 | def _get_check_scope(self, cls_name): |
|
1614 | def _get_check_scope(self, cls_name): | |
1579 | return { |
|
1615 | return { | |
1580 | 'HasPermissionAll': 'GLOBAL', |
|
1616 | 'HasPermissionAll': 'GLOBAL', | |
1581 | 'HasPermissionAny': 'GLOBAL', |
|
1617 | 'HasPermissionAny': 'GLOBAL', | |
1582 | 'HasRepoPermissionAll': 'repo:%s' % self.repo_name, |
|
1618 | 'HasRepoPermissionAll': 'repo:%s' % self.repo_name, | |
1583 | 'HasRepoPermissionAny': 'repo:%s' % self.repo_name, |
|
1619 | 'HasRepoPermissionAny': 'repo:%s' % self.repo_name, | |
1584 | 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name, |
|
1620 | 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name, | |
1585 | 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name, |
|
1621 | 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name, | |
1586 | 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name, |
|
1622 | 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name, | |
1587 | 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name, |
|
1623 | 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name, | |
1588 | }.get(cls_name, '?:%s' % cls_name) |
|
1624 | }.get(cls_name, '?:%s' % cls_name) | |
1589 |
|
1625 | |||
1590 | def check_permissions(self, user): |
|
1626 | def check_permissions(self, user): | |
1591 | """Dummy function for overriding""" |
|
1627 | """Dummy function for overriding""" | |
1592 | raise Exception('You have to write this function in child class') |
|
1628 | raise Exception('You have to write this function in child class') | |
1593 |
|
1629 | |||
1594 |
|
1630 | |||
1595 | class HasPermissionAll(PermsFunction): |
|
1631 | class HasPermissionAll(PermsFunction): | |
1596 | def check_permissions(self, user): |
|
1632 | def check_permissions(self, user): | |
1597 | perms = user.permissions_with_scope({}) |
|
1633 | perms = user.permissions_with_scope({}) | |
1598 | if self.required_perms.issubset(perms.get('global')): |
|
1634 | if self.required_perms.issubset(perms.get('global')): | |
1599 | return True |
|
1635 | return True | |
1600 | return False |
|
1636 | return False | |
1601 |
|
1637 | |||
1602 |
|
1638 | |||
1603 | class HasPermissionAny(PermsFunction): |
|
1639 | class HasPermissionAny(PermsFunction): | |
1604 | def check_permissions(self, user): |
|
1640 | def check_permissions(self, user): | |
1605 | perms = user.permissions_with_scope({}) |
|
1641 | perms = user.permissions_with_scope({}) | |
1606 | if self.required_perms.intersection(perms.get('global')): |
|
1642 | if self.required_perms.intersection(perms.get('global')): | |
1607 | return True |
|
1643 | return True | |
1608 | return False |
|
1644 | return False | |
1609 |
|
1645 | |||
1610 |
|
1646 | |||
1611 | class HasRepoPermissionAll(PermsFunction): |
|
1647 | class HasRepoPermissionAll(PermsFunction): | |
1612 | def __call__(self, repo_name=None, check_location='', user=None): |
|
1648 | def __call__(self, repo_name=None, check_location='', user=None): | |
1613 | self.repo_name = repo_name |
|
1649 | self.repo_name = repo_name | |
1614 | return super(HasRepoPermissionAll, self).__call__(check_location, user) |
|
1650 | return super(HasRepoPermissionAll, self).__call__(check_location, user) | |
1615 |
|
1651 | |||
1616 | def check_permissions(self, user): |
|
1652 | def _get_repo_name(self): | |
1617 | if not self.repo_name: |
|
1653 | if not self.repo_name: | |
1618 | self.repo_name = get_repo_slug(request) |
|
1654 | _request = self._get_request() | |
|
1655 | self.repo_name = get_repo_slug(_request) | |||
|
1656 | return self.repo_name | |||
1619 |
|
1657 | |||
|
1658 | def check_permissions(self, user): | |||
|
1659 | self.repo_name = self._get_repo_name() | |||
1620 | perms = user.permissions |
|
1660 | perms = user.permissions | |
1621 | try: |
|
1661 | try: | |
1622 | user_perms = set([perms['repositories'][self.repo_name]]) |
|
1662 | user_perms = set([perms['repositories'][self.repo_name]]) | |
1623 | except KeyError: |
|
1663 | except KeyError: | |
1624 | return False |
|
1664 | return False | |
1625 | if self.required_perms.issubset(user_perms): |
|
1665 | if self.required_perms.issubset(user_perms): | |
1626 | return True |
|
1666 | return True | |
1627 | return False |
|
1667 | return False | |
1628 |
|
1668 | |||
1629 |
|
1669 | |||
1630 | class HasRepoPermissionAny(PermsFunction): |
|
1670 | class HasRepoPermissionAny(PermsFunction): | |
1631 | def __call__(self, repo_name=None, check_location='', user=None): |
|
1671 | def __call__(self, repo_name=None, check_location='', user=None): | |
1632 | self.repo_name = repo_name |
|
1672 | self.repo_name = repo_name | |
1633 | return super(HasRepoPermissionAny, self).__call__(check_location, user) |
|
1673 | return super(HasRepoPermissionAny, self).__call__(check_location, user) | |
1634 |
|
1674 | |||
1635 | def check_permissions(self, user): |
|
1675 | def _get_repo_name(self): | |
1636 | if not self.repo_name: |
|
1676 | if not self.repo_name: | |
1637 | self.repo_name = get_repo_slug(request) |
|
1677 | self.repo_name = get_repo_slug(request) | |
|
1678 | return self.repo_name | |||
1638 |
|
1679 | |||
|
1680 | def check_permissions(self, user): | |||
|
1681 | self.repo_name = self._get_repo_name() | |||
1639 | perms = user.permissions |
|
1682 | perms = user.permissions | |
1640 | try: |
|
1683 | try: | |
1641 | user_perms = set([perms['repositories'][self.repo_name]]) |
|
1684 | user_perms = set([perms['repositories'][self.repo_name]]) | |
1642 | except KeyError: |
|
1685 | except KeyError: | |
1643 | return False |
|
1686 | return False | |
1644 | if self.required_perms.intersection(user_perms): |
|
1687 | if self.required_perms.intersection(user_perms): | |
1645 | return True |
|
1688 | return True | |
1646 | return False |
|
1689 | return False | |
1647 |
|
1690 | |||
1648 |
|
1691 | |||
1649 | class HasRepoGroupPermissionAny(PermsFunction): |
|
1692 | class HasRepoGroupPermissionAny(PermsFunction): | |
1650 | def __call__(self, group_name=None, check_location='', user=None): |
|
1693 | def __call__(self, group_name=None, check_location='', user=None): | |
1651 | self.repo_group_name = group_name |
|
1694 | self.repo_group_name = group_name | |
1652 | return super(HasRepoGroupPermissionAny, self).__call__( |
|
1695 | return super(HasRepoGroupPermissionAny, self).__call__( | |
1653 | check_location, user) |
|
1696 | check_location, user) | |
1654 |
|
1697 | |||
1655 | def check_permissions(self, user): |
|
1698 | def check_permissions(self, user): | |
1656 | perms = user.permissions |
|
1699 | perms = user.permissions | |
1657 | try: |
|
1700 | try: | |
1658 | user_perms = set( |
|
1701 | user_perms = set( | |
1659 | [perms['repositories_groups'][self.repo_group_name]]) |
|
1702 | [perms['repositories_groups'][self.repo_group_name]]) | |
1660 | except KeyError: |
|
1703 | except KeyError: | |
1661 | return False |
|
1704 | return False | |
1662 | if self.required_perms.intersection(user_perms): |
|
1705 | if self.required_perms.intersection(user_perms): | |
1663 | return True |
|
1706 | return True | |
1664 | return False |
|
1707 | return False | |
1665 |
|
1708 | |||
1666 |
|
1709 | |||
1667 | class HasRepoGroupPermissionAll(PermsFunction): |
|
1710 | class HasRepoGroupPermissionAll(PermsFunction): | |
1668 | def __call__(self, group_name=None, check_location='', user=None): |
|
1711 | def __call__(self, group_name=None, check_location='', user=None): | |
1669 | self.repo_group_name = group_name |
|
1712 | self.repo_group_name = group_name | |
1670 | return super(HasRepoGroupPermissionAll, self).__call__( |
|
1713 | return super(HasRepoGroupPermissionAll, self).__call__( | |
1671 | check_location, user) |
|
1714 | check_location, user) | |
1672 |
|
1715 | |||
1673 | def check_permissions(self, user): |
|
1716 | def check_permissions(self, user): | |
1674 | perms = user.permissions |
|
1717 | perms = user.permissions | |
1675 | try: |
|
1718 | try: | |
1676 | user_perms = set( |
|
1719 | user_perms = set( | |
1677 | [perms['repositories_groups'][self.repo_group_name]]) |
|
1720 | [perms['repositories_groups'][self.repo_group_name]]) | |
1678 | except KeyError: |
|
1721 | except KeyError: | |
1679 | return False |
|
1722 | return False | |
1680 | if self.required_perms.issubset(user_perms): |
|
1723 | if self.required_perms.issubset(user_perms): | |
1681 | return True |
|
1724 | return True | |
1682 | return False |
|
1725 | return False | |
1683 |
|
1726 | |||
1684 |
|
1727 | |||
1685 | class HasUserGroupPermissionAny(PermsFunction): |
|
1728 | class HasUserGroupPermissionAny(PermsFunction): | |
1686 | def __call__(self, user_group_name=None, check_location='', user=None): |
|
1729 | def __call__(self, user_group_name=None, check_location='', user=None): | |
1687 | self.user_group_name = user_group_name |
|
1730 | self.user_group_name = user_group_name | |
1688 | return super(HasUserGroupPermissionAny, self).__call__( |
|
1731 | return super(HasUserGroupPermissionAny, self).__call__( | |
1689 | check_location, user) |
|
1732 | check_location, user) | |
1690 |
|
1733 | |||
1691 | def check_permissions(self, user): |
|
1734 | def check_permissions(self, user): | |
1692 | perms = user.permissions |
|
1735 | perms = user.permissions | |
1693 | try: |
|
1736 | try: | |
1694 | user_perms = set([perms['user_groups'][self.user_group_name]]) |
|
1737 | user_perms = set([perms['user_groups'][self.user_group_name]]) | |
1695 | except KeyError: |
|
1738 | except KeyError: | |
1696 | return False |
|
1739 | return False | |
1697 | if self.required_perms.intersection(user_perms): |
|
1740 | if self.required_perms.intersection(user_perms): | |
1698 | return True |
|
1741 | return True | |
1699 | return False |
|
1742 | return False | |
1700 |
|
1743 | |||
1701 |
|
1744 | |||
1702 | class HasUserGroupPermissionAll(PermsFunction): |
|
1745 | class HasUserGroupPermissionAll(PermsFunction): | |
1703 | def __call__(self, user_group_name=None, check_location='', user=None): |
|
1746 | def __call__(self, user_group_name=None, check_location='', user=None): | |
1704 | self.user_group_name = user_group_name |
|
1747 | self.user_group_name = user_group_name | |
1705 | return super(HasUserGroupPermissionAll, self).__call__( |
|
1748 | return super(HasUserGroupPermissionAll, self).__call__( | |
1706 | check_location, user) |
|
1749 | check_location, user) | |
1707 |
|
1750 | |||
1708 | def check_permissions(self, user): |
|
1751 | def check_permissions(self, user): | |
1709 | perms = user.permissions |
|
1752 | perms = user.permissions | |
1710 | try: |
|
1753 | try: | |
1711 | user_perms = set([perms['user_groups'][self.user_group_name]]) |
|
1754 | user_perms = set([perms['user_groups'][self.user_group_name]]) | |
1712 | except KeyError: |
|
1755 | except KeyError: | |
1713 | return False |
|
1756 | return False | |
1714 | if self.required_perms.issubset(user_perms): |
|
1757 | if self.required_perms.issubset(user_perms): | |
1715 | return True |
|
1758 | return True | |
1716 | return False |
|
1759 | return False | |
1717 |
|
1760 | |||
1718 |
|
1761 | |||
1719 | # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH |
|
1762 | # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH | |
1720 | class HasPermissionAnyMiddleware(object): |
|
1763 | class HasPermissionAnyMiddleware(object): | |
1721 | def __init__(self, *perms): |
|
1764 | def __init__(self, *perms): | |
1722 | self.required_perms = set(perms) |
|
1765 | self.required_perms = set(perms) | |
1723 |
|
1766 | |||
1724 | def __call__(self, user, repo_name): |
|
1767 | def __call__(self, user, repo_name): | |
1725 | # repo_name MUST be unicode, since we handle keys in permission |
|
1768 | # repo_name MUST be unicode, since we handle keys in permission | |
1726 | # dict by unicode |
|
1769 | # dict by unicode | |
1727 | repo_name = safe_unicode(repo_name) |
|
1770 | repo_name = safe_unicode(repo_name) | |
1728 | user = AuthUser(user.user_id) |
|
1771 | user = AuthUser(user.user_id) | |
1729 | log.debug( |
|
1772 | log.debug( | |
1730 | 'Checking VCS protocol permissions %s for user:%s repo:`%s`', |
|
1773 | 'Checking VCS protocol permissions %s for user:%s repo:`%s`', | |
1731 | self.required_perms, user, repo_name) |
|
1774 | self.required_perms, user, repo_name) | |
1732 |
|
1775 | |||
1733 | if self.check_permissions(user, repo_name): |
|
1776 | if self.check_permissions(user, repo_name): | |
1734 | log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s', |
|
1777 | log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s', | |
1735 | repo_name, user, 'PermissionMiddleware') |
|
1778 | repo_name, user, 'PermissionMiddleware') | |
1736 | return True |
|
1779 | return True | |
1737 |
|
1780 | |||
1738 | else: |
|
1781 | else: | |
1739 | log.debug('Permission to repo:`%s` DENIED for user:%s @ %s', |
|
1782 | log.debug('Permission to repo:`%s` DENIED for user:%s @ %s', | |
1740 | repo_name, user, 'PermissionMiddleware') |
|
1783 | repo_name, user, 'PermissionMiddleware') | |
1741 | return False |
|
1784 | return False | |
1742 |
|
1785 | |||
1743 | def check_permissions(self, user, repo_name): |
|
1786 | def check_permissions(self, user, repo_name): | |
1744 | perms = user.permissions_with_scope({'repo_name': repo_name}) |
|
1787 | perms = user.permissions_with_scope({'repo_name': repo_name}) | |
1745 |
|
1788 | |||
1746 | try: |
|
1789 | try: | |
1747 | user_perms = set([perms['repositories'][repo_name]]) |
|
1790 | user_perms = set([perms['repositories'][repo_name]]) | |
1748 | except Exception: |
|
1791 | except Exception: | |
1749 | log.exception('Error while accessing user permissions') |
|
1792 | log.exception('Error while accessing user permissions') | |
1750 | return False |
|
1793 | return False | |
1751 |
|
1794 | |||
1752 | if self.required_perms.intersection(user_perms): |
|
1795 | if self.required_perms.intersection(user_perms): | |
1753 | return True |
|
1796 | return True | |
1754 | return False |
|
1797 | return False | |
1755 |
|
1798 | |||
1756 |
|
1799 | |||
1757 | # SPECIAL VERSION TO HANDLE API AUTH |
|
1800 | # SPECIAL VERSION TO HANDLE API AUTH | |
1758 | class _BaseApiPerm(object): |
|
1801 | class _BaseApiPerm(object): | |
1759 | def __init__(self, *perms): |
|
1802 | def __init__(self, *perms): | |
1760 | self.required_perms = set(perms) |
|
1803 | self.required_perms = set(perms) | |
1761 |
|
1804 | |||
1762 | def __call__(self, check_location=None, user=None, repo_name=None, |
|
1805 | def __call__(self, check_location=None, user=None, repo_name=None, | |
1763 | group_name=None, user_group_name=None): |
|
1806 | group_name=None, user_group_name=None): | |
1764 | cls_name = self.__class__.__name__ |
|
1807 | cls_name = self.__class__.__name__ | |
1765 | check_scope = 'global:%s' % (self.required_perms,) |
|
1808 | check_scope = 'global:%s' % (self.required_perms,) | |
1766 | if repo_name: |
|
1809 | if repo_name: | |
1767 | check_scope += ', repo_name:%s' % (repo_name,) |
|
1810 | check_scope += ', repo_name:%s' % (repo_name,) | |
1768 |
|
1811 | |||
1769 | if group_name: |
|
1812 | if group_name: | |
1770 | check_scope += ', repo_group_name:%s' % (group_name,) |
|
1813 | check_scope += ', repo_group_name:%s' % (group_name,) | |
1771 |
|
1814 | |||
1772 | if user_group_name: |
|
1815 | if user_group_name: | |
1773 | check_scope += ', user_group_name:%s' % (user_group_name,) |
|
1816 | check_scope += ', user_group_name:%s' % (user_group_name,) | |
1774 |
|
1817 | |||
1775 | log.debug( |
|
1818 | log.debug( | |
1776 | 'checking cls:%s %s %s @ %s' |
|
1819 | 'checking cls:%s %s %s @ %s' | |
1777 | % (cls_name, self.required_perms, check_scope, check_location)) |
|
1820 | % (cls_name, self.required_perms, check_scope, check_location)) | |
1778 | if not user: |
|
1821 | if not user: | |
1779 | log.debug('Empty User passed into arguments') |
|
1822 | log.debug('Empty User passed into arguments') | |
1780 | return False |
|
1823 | return False | |
1781 |
|
1824 | |||
1782 | # process user |
|
1825 | # process user | |
1783 | if not isinstance(user, AuthUser): |
|
1826 | if not isinstance(user, AuthUser): | |
1784 | user = AuthUser(user.user_id) |
|
1827 | user = AuthUser(user.user_id) | |
1785 | if not check_location: |
|
1828 | if not check_location: | |
1786 | check_location = 'unspecified' |
|
1829 | check_location = 'unspecified' | |
1787 | if self.check_permissions(user.permissions, repo_name, group_name, |
|
1830 | if self.check_permissions(user.permissions, repo_name, group_name, | |
1788 | user_group_name): |
|
1831 | user_group_name): | |
1789 | log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s', |
|
1832 | log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s', | |
1790 | check_scope, user, check_location) |
|
1833 | check_scope, user, check_location) | |
1791 | return True |
|
1834 | return True | |
1792 |
|
1835 | |||
1793 | else: |
|
1836 | else: | |
1794 | log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s', |
|
1837 | log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s', | |
1795 | check_scope, user, check_location) |
|
1838 | check_scope, user, check_location) | |
1796 | return False |
|
1839 | return False | |
1797 |
|
1840 | |||
1798 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, |
|
1841 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, | |
1799 | user_group_name=None): |
|
1842 | user_group_name=None): | |
1800 | """ |
|
1843 | """ | |
1801 | implement in child class should return True if permissions are ok, |
|
1844 | implement in child class should return True if permissions are ok, | |
1802 | False otherwise |
|
1845 | False otherwise | |
1803 |
|
1846 | |||
1804 | :param perm_defs: dict with permission definitions |
|
1847 | :param perm_defs: dict with permission definitions | |
1805 | :param repo_name: repo name |
|
1848 | :param repo_name: repo name | |
1806 | """ |
|
1849 | """ | |
1807 | raise NotImplementedError() |
|
1850 | raise NotImplementedError() | |
1808 |
|
1851 | |||
1809 |
|
1852 | |||
1810 | class HasPermissionAllApi(_BaseApiPerm): |
|
1853 | class HasPermissionAllApi(_BaseApiPerm): | |
1811 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, |
|
1854 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, | |
1812 | user_group_name=None): |
|
1855 | user_group_name=None): | |
1813 | if self.required_perms.issubset(perm_defs.get('global')): |
|
1856 | if self.required_perms.issubset(perm_defs.get('global')): | |
1814 | return True |
|
1857 | return True | |
1815 | return False |
|
1858 | return False | |
1816 |
|
1859 | |||
1817 |
|
1860 | |||
1818 | class HasPermissionAnyApi(_BaseApiPerm): |
|
1861 | class HasPermissionAnyApi(_BaseApiPerm): | |
1819 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, |
|
1862 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, | |
1820 | user_group_name=None): |
|
1863 | user_group_name=None): | |
1821 | if self.required_perms.intersection(perm_defs.get('global')): |
|
1864 | if self.required_perms.intersection(perm_defs.get('global')): | |
1822 | return True |
|
1865 | return True | |
1823 | return False |
|
1866 | return False | |
1824 |
|
1867 | |||
1825 |
|
1868 | |||
1826 | class HasRepoPermissionAllApi(_BaseApiPerm): |
|
1869 | class HasRepoPermissionAllApi(_BaseApiPerm): | |
1827 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, |
|
1870 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, | |
1828 | user_group_name=None): |
|
1871 | user_group_name=None): | |
1829 | try: |
|
1872 | try: | |
1830 | _user_perms = set([perm_defs['repositories'][repo_name]]) |
|
1873 | _user_perms = set([perm_defs['repositories'][repo_name]]) | |
1831 | except KeyError: |
|
1874 | except KeyError: | |
1832 | log.warning(traceback.format_exc()) |
|
1875 | log.warning(traceback.format_exc()) | |
1833 | return False |
|
1876 | return False | |
1834 | if self.required_perms.issubset(_user_perms): |
|
1877 | if self.required_perms.issubset(_user_perms): | |
1835 | return True |
|
1878 | return True | |
1836 | return False |
|
1879 | return False | |
1837 |
|
1880 | |||
1838 |
|
1881 | |||
1839 | class HasRepoPermissionAnyApi(_BaseApiPerm): |
|
1882 | class HasRepoPermissionAnyApi(_BaseApiPerm): | |
1840 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, |
|
1883 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, | |
1841 | user_group_name=None): |
|
1884 | user_group_name=None): | |
1842 | try: |
|
1885 | try: | |
1843 | _user_perms = set([perm_defs['repositories'][repo_name]]) |
|
1886 | _user_perms = set([perm_defs['repositories'][repo_name]]) | |
1844 | except KeyError: |
|
1887 | except KeyError: | |
1845 | log.warning(traceback.format_exc()) |
|
1888 | log.warning(traceback.format_exc()) | |
1846 | return False |
|
1889 | return False | |
1847 | if self.required_perms.intersection(_user_perms): |
|
1890 | if self.required_perms.intersection(_user_perms): | |
1848 | return True |
|
1891 | return True | |
1849 | return False |
|
1892 | return False | |
1850 |
|
1893 | |||
1851 |
|
1894 | |||
1852 | class HasRepoGroupPermissionAnyApi(_BaseApiPerm): |
|
1895 | class HasRepoGroupPermissionAnyApi(_BaseApiPerm): | |
1853 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, |
|
1896 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, | |
1854 | user_group_name=None): |
|
1897 | user_group_name=None): | |
1855 | try: |
|
1898 | try: | |
1856 | _user_perms = set([perm_defs['repositories_groups'][group_name]]) |
|
1899 | _user_perms = set([perm_defs['repositories_groups'][group_name]]) | |
1857 | except KeyError: |
|
1900 | except KeyError: | |
1858 | log.warning(traceback.format_exc()) |
|
1901 | log.warning(traceback.format_exc()) | |
1859 | return False |
|
1902 | return False | |
1860 | if self.required_perms.intersection(_user_perms): |
|
1903 | if self.required_perms.intersection(_user_perms): | |
1861 | return True |
|
1904 | return True | |
1862 | return False |
|
1905 | return False | |
1863 |
|
1906 | |||
1864 |
|
1907 | |||
1865 | class HasRepoGroupPermissionAllApi(_BaseApiPerm): |
|
1908 | class HasRepoGroupPermissionAllApi(_BaseApiPerm): | |
1866 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, |
|
1909 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, | |
1867 | user_group_name=None): |
|
1910 | user_group_name=None): | |
1868 | try: |
|
1911 | try: | |
1869 | _user_perms = set([perm_defs['repositories_groups'][group_name]]) |
|
1912 | _user_perms = set([perm_defs['repositories_groups'][group_name]]) | |
1870 | except KeyError: |
|
1913 | except KeyError: | |
1871 | log.warning(traceback.format_exc()) |
|
1914 | log.warning(traceback.format_exc()) | |
1872 | return False |
|
1915 | return False | |
1873 | if self.required_perms.issubset(_user_perms): |
|
1916 | if self.required_perms.issubset(_user_perms): | |
1874 | return True |
|
1917 | return True | |
1875 | return False |
|
1918 | return False | |
1876 |
|
1919 | |||
1877 |
|
1920 | |||
1878 | class HasUserGroupPermissionAnyApi(_BaseApiPerm): |
|
1921 | class HasUserGroupPermissionAnyApi(_BaseApiPerm): | |
1879 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, |
|
1922 | def check_permissions(self, perm_defs, repo_name=None, group_name=None, | |
1880 | user_group_name=None): |
|
1923 | user_group_name=None): | |
1881 | try: |
|
1924 | try: | |
1882 | _user_perms = set([perm_defs['user_groups'][user_group_name]]) |
|
1925 | _user_perms = set([perm_defs['user_groups'][user_group_name]]) | |
1883 | except KeyError: |
|
1926 | except KeyError: | |
1884 | log.warning(traceback.format_exc()) |
|
1927 | log.warning(traceback.format_exc()) | |
1885 | return False |
|
1928 | return False | |
1886 | if self.required_perms.intersection(_user_perms): |
|
1929 | if self.required_perms.intersection(_user_perms): | |
1887 | return True |
|
1930 | return True | |
1888 | return False |
|
1931 | return False | |
1889 |
|
1932 | |||
1890 |
|
1933 | |||
1891 | def check_ip_access(source_ip, allowed_ips=None): |
|
1934 | def check_ip_access(source_ip, allowed_ips=None): | |
1892 | """ |
|
1935 | """ | |
1893 | Checks if source_ip is a subnet of any of allowed_ips. |
|
1936 | Checks if source_ip is a subnet of any of allowed_ips. | |
1894 |
|
1937 | |||
1895 | :param source_ip: |
|
1938 | :param source_ip: | |
1896 | :param allowed_ips: list of allowed ips together with mask |
|
1939 | :param allowed_ips: list of allowed ips together with mask | |
1897 | """ |
|
1940 | """ | |
1898 | log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips)) |
|
1941 | log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips)) | |
1899 | source_ip_address = ipaddress.ip_address(source_ip) |
|
1942 | source_ip_address = ipaddress.ip_address(source_ip) | |
1900 | if isinstance(allowed_ips, (tuple, list, set)): |
|
1943 | if isinstance(allowed_ips, (tuple, list, set)): | |
1901 | for ip in allowed_ips: |
|
1944 | for ip in allowed_ips: | |
1902 | try: |
|
1945 | try: | |
1903 | network_address = ipaddress.ip_network(ip, strict=False) |
|
1946 | network_address = ipaddress.ip_network(ip, strict=False) | |
1904 | if source_ip_address in network_address: |
|
1947 | if source_ip_address in network_address: | |
1905 | log.debug('IP %s is network %s' % |
|
1948 | log.debug('IP %s is network %s' % | |
1906 | (source_ip_address, network_address)) |
|
1949 | (source_ip_address, network_address)) | |
1907 | return True |
|
1950 | return True | |
1908 | # for any case we cannot determine the IP, don't crash just |
|
1951 | # for any case we cannot determine the IP, don't crash just | |
1909 | # skip it and log as error, we want to say forbidden still when |
|
1952 | # skip it and log as error, we want to say forbidden still when | |
1910 | # sending bad IP |
|
1953 | # sending bad IP | |
1911 | except Exception: |
|
1954 | except Exception: | |
1912 | log.error(traceback.format_exc()) |
|
1955 | log.error(traceback.format_exc()) | |
1913 | continue |
|
1956 | continue | |
1914 | return False |
|
1957 | return False | |
1915 |
|
1958 | |||
1916 |
|
1959 | |||
1917 | def get_cython_compat_decorator(wrapper, func): |
|
1960 | def get_cython_compat_decorator(wrapper, func): | |
1918 | """ |
|
1961 | """ | |
1919 | Creates a cython compatible decorator. The previously used |
|
1962 | Creates a cython compatible decorator. The previously used | |
1920 | decorator.decorator() function seems to be incompatible with cython. |
|
1963 | decorator.decorator() function seems to be incompatible with cython. | |
1921 |
|
1964 | |||
1922 | :param wrapper: __wrapper method of the decorator class |
|
1965 | :param wrapper: __wrapper method of the decorator class | |
1923 | :param func: decorated function |
|
1966 | :param func: decorated function | |
1924 | """ |
|
1967 | """ | |
1925 | @wraps(func) |
|
1968 | @wraps(func) | |
1926 | def local_wrapper(*args, **kwds): |
|
1969 | def local_wrapper(*args, **kwds): | |
1927 | return wrapper(func, *args, **kwds) |
|
1970 | return wrapper(func, *args, **kwds) | |
1928 | local_wrapper.__wrapped__ = func |
|
1971 | local_wrapper.__wrapped__ = func | |
1929 | return local_wrapper |
|
1972 | return local_wrapper |
@@ -1,1021 +1,1037 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 | Utilities library for RhodeCode |
|
22 | Utilities library for RhodeCode | |
23 | """ |
|
23 | """ | |
24 |
|
24 | |||
25 | import datetime |
|
25 | import datetime | |
26 | import decorator |
|
26 | import decorator | |
27 | import json |
|
27 | import json | |
28 | import logging |
|
28 | import logging | |
29 | import os |
|
29 | import os | |
30 | import re |
|
30 | import re | |
31 | import shutil |
|
31 | import shutil | |
32 | import tempfile |
|
32 | import tempfile | |
33 | import traceback |
|
33 | import traceback | |
34 | import tarfile |
|
34 | import tarfile | |
35 | import warnings |
|
35 | import warnings | |
36 | import hashlib |
|
36 | import hashlib | |
37 | from os.path import join as jn |
|
37 | from os.path import join as jn | |
38 |
|
38 | |||
39 | import paste |
|
39 | import paste | |
40 | import pkg_resources |
|
40 | import pkg_resources | |
41 | from paste.script.command import Command, BadCommand |
|
41 | from paste.script.command import Command, BadCommand | |
42 | from webhelpers.text import collapse, remove_formatting, strip_tags |
|
42 | from webhelpers.text import collapse, remove_formatting, strip_tags | |
43 | from mako import exceptions |
|
43 | from mako import exceptions | |
44 | from pyramid.threadlocal import get_current_registry |
|
44 | from pyramid.threadlocal import get_current_registry | |
|
45 | from pyramid.request import Request | |||
45 |
|
46 | |||
46 | from rhodecode.lib.fakemod import create_module |
|
47 | from rhodecode.lib.fakemod import create_module | |
47 | from rhodecode.lib.vcs.backends.base import Config |
|
48 | from rhodecode.lib.vcs.backends.base import Config | |
48 | from rhodecode.lib.vcs.exceptions import VCSError |
|
49 | from rhodecode.lib.vcs.exceptions import VCSError | |
49 | from rhodecode.lib.vcs.utils.helpers import get_scm, get_scm_backend |
|
50 | from rhodecode.lib.vcs.utils.helpers import get_scm, get_scm_backend | |
50 | from rhodecode.lib.utils2 import ( |
|
51 | from rhodecode.lib.utils2 import ( | |
51 | safe_str, safe_unicode, get_current_rhodecode_user, md5) |
|
52 | safe_str, safe_unicode, get_current_rhodecode_user, md5) | |
52 | from rhodecode.model import meta |
|
53 | from rhodecode.model import meta | |
53 | from rhodecode.model.db import ( |
|
54 | from rhodecode.model.db import ( | |
54 | Repository, User, RhodeCodeUi, UserLog, RepoGroup, UserGroup) |
|
55 | Repository, User, RhodeCodeUi, UserLog, RepoGroup, UserGroup) | |
55 | from rhodecode.model.meta import Session |
|
56 | from rhodecode.model.meta import Session | |
56 |
|
57 | |||
57 |
|
58 | |||
58 | log = logging.getLogger(__name__) |
|
59 | log = logging.getLogger(__name__) | |
59 |
|
60 | |||
60 | REMOVED_REPO_PAT = re.compile(r'rm__\d{8}_\d{6}_\d{6}__.*') |
|
61 | REMOVED_REPO_PAT = re.compile(r'rm__\d{8}_\d{6}_\d{6}__.*') | |
61 |
|
62 | |||
62 | # String which contains characters that are not allowed in slug names for |
|
63 | # String which contains characters that are not allowed in slug names for | |
63 | # repositories or repository groups. It is properly escaped to use it in |
|
64 | # repositories or repository groups. It is properly escaped to use it in | |
64 | # regular expressions. |
|
65 | # regular expressions. | |
65 | SLUG_BAD_CHARS = re.escape('`?=[]\;\'"<>,/~!@#$%^&*()+{}|:') |
|
66 | SLUG_BAD_CHARS = re.escape('`?=[]\;\'"<>,/~!@#$%^&*()+{}|:') | |
66 |
|
67 | |||
67 | # Regex that matches forbidden characters in repo/group slugs. |
|
68 | # Regex that matches forbidden characters in repo/group slugs. | |
68 | SLUG_BAD_CHAR_RE = re.compile('[{}]'.format(SLUG_BAD_CHARS)) |
|
69 | SLUG_BAD_CHAR_RE = re.compile('[{}]'.format(SLUG_BAD_CHARS)) | |
69 |
|
70 | |||
70 | # Regex that matches allowed characters in repo/group slugs. |
|
71 | # Regex that matches allowed characters in repo/group slugs. | |
71 | SLUG_GOOD_CHAR_RE = re.compile('[^{}]'.format(SLUG_BAD_CHARS)) |
|
72 | SLUG_GOOD_CHAR_RE = re.compile('[^{}]'.format(SLUG_BAD_CHARS)) | |
72 |
|
73 | |||
73 | # Regex that matches whole repo/group slugs. |
|
74 | # Regex that matches whole repo/group slugs. | |
74 | SLUG_RE = re.compile('[^{}]+'.format(SLUG_BAD_CHARS)) |
|
75 | SLUG_RE = re.compile('[^{}]+'.format(SLUG_BAD_CHARS)) | |
75 |
|
76 | |||
76 | _license_cache = None |
|
77 | _license_cache = None | |
77 |
|
78 | |||
78 |
|
79 | |||
79 | def repo_name_slug(value): |
|
80 | def repo_name_slug(value): | |
80 | """ |
|
81 | """ | |
81 | Return slug of name of repository |
|
82 | Return slug of name of repository | |
82 | This function is called on each creation/modification |
|
83 | This function is called on each creation/modification | |
83 | of repository to prevent bad names in repo |
|
84 | of repository to prevent bad names in repo | |
84 | """ |
|
85 | """ | |
85 | replacement_char = '-' |
|
86 | replacement_char = '-' | |
86 |
|
87 | |||
87 | slug = remove_formatting(value) |
|
88 | slug = remove_formatting(value) | |
88 | slug = SLUG_BAD_CHAR_RE.sub('', slug) |
|
89 | slug = SLUG_BAD_CHAR_RE.sub('', slug) | |
89 | slug = re.sub('[\s]+', '-', slug) |
|
90 | slug = re.sub('[\s]+', '-', slug) | |
90 | slug = collapse(slug, replacement_char) |
|
91 | slug = collapse(slug, replacement_char) | |
91 | return slug |
|
92 | return slug | |
92 |
|
93 | |||
93 |
|
94 | |||
94 | #============================================================================== |
|
95 | #============================================================================== | |
95 | # PERM DECORATOR HELPERS FOR EXTRACTING NAMES FOR PERM CHECKS |
|
96 | # PERM DECORATOR HELPERS FOR EXTRACTING NAMES FOR PERM CHECKS | |
96 | #============================================================================== |
|
97 | #============================================================================== | |
97 | def get_repo_slug(request): |
|
98 | def get_repo_slug(request): | |
98 | _repo = request.environ['pylons.routes_dict'].get('repo_name') |
|
99 | if isinstance(request, Request) and getattr(request, 'matchdict', None): | |
|
100 | # pyramid | |||
|
101 | _repo = request.matchdict.get('repo_name') | |||
|
102 | else: | |||
|
103 | _repo = request.environ['pylons.routes_dict'].get('repo_name') | |||
|
104 | ||||
99 | if _repo: |
|
105 | if _repo: | |
100 | _repo = _repo.rstrip('/') |
|
106 | _repo = _repo.rstrip('/') | |
101 | return _repo |
|
107 | return _repo | |
102 |
|
108 | |||
103 |
|
109 | |||
104 | def get_repo_group_slug(request): |
|
110 | def get_repo_group_slug(request): | |
105 | _group = request.environ['pylons.routes_dict'].get('group_name') |
|
111 | if isinstance(request, Request) and getattr(request, 'matchdict', None): | |
|
112 | # pyramid | |||
|
113 | _group = request.matchdict.get('group_name') | |||
|
114 | else: | |||
|
115 | _group = request.environ['pylons.routes_dict'].get('group_name') | |||
|
116 | ||||
106 | if _group: |
|
117 | if _group: | |
107 | _group = _group.rstrip('/') |
|
118 | _group = _group.rstrip('/') | |
108 | return _group |
|
119 | return _group | |
109 |
|
120 | |||
110 |
|
121 | |||
111 | def get_user_group_slug(request): |
|
122 | def get_user_group_slug(request): | |
112 | _group = request.environ['pylons.routes_dict'].get('user_group_id') |
|
123 | if isinstance(request, Request) and getattr(request, 'matchdict', None): | |
|
124 | # pyramid | |||
|
125 | _group = request.matchdict.get('user_group_id') | |||
|
126 | else: | |||
|
127 | _group = request.environ['pylons.routes_dict'].get('user_group_id') | |||
|
128 | ||||
113 | try: |
|
129 | try: | |
114 | _group = UserGroup.get(_group) |
|
130 | _group = UserGroup.get(_group) | |
115 | if _group: |
|
131 | if _group: | |
116 | _group = _group.users_group_name |
|
132 | _group = _group.users_group_name | |
117 | except Exception: |
|
133 | except Exception: | |
118 | log.debug(traceback.format_exc()) |
|
134 | log.debug(traceback.format_exc()) | |
119 | #catch all failures here |
|
135 | # catch all failures here | |
120 | pass |
|
136 | pass | |
121 |
|
137 | |||
122 | return _group |
|
138 | return _group | |
123 |
|
139 | |||
124 |
|
140 | |||
125 | def action_logger(user, action, repo, ipaddr='', sa=None, commit=False): |
|
141 | def action_logger(user, action, repo, ipaddr='', sa=None, commit=False): | |
126 | """ |
|
142 | """ | |
127 | Action logger for various actions made by users |
|
143 | Action logger for various actions made by users | |
128 |
|
144 | |||
129 | :param user: user that made this action, can be a unique username string or |
|
145 | :param user: user that made this action, can be a unique username string or | |
130 | object containing user_id attribute |
|
146 | object containing user_id attribute | |
131 | :param action: action to log, should be on of predefined unique actions for |
|
147 | :param action: action to log, should be on of predefined unique actions for | |
132 | easy translations |
|
148 | easy translations | |
133 | :param repo: string name of repository or object containing repo_id, |
|
149 | :param repo: string name of repository or object containing repo_id, | |
134 | that action was made on |
|
150 | that action was made on | |
135 | :param ipaddr: optional ip address from what the action was made |
|
151 | :param ipaddr: optional ip address from what the action was made | |
136 | :param sa: optional sqlalchemy session |
|
152 | :param sa: optional sqlalchemy session | |
137 |
|
153 | |||
138 | """ |
|
154 | """ | |
139 |
|
155 | |||
140 | if not sa: |
|
156 | if not sa: | |
141 | sa = meta.Session() |
|
157 | sa = meta.Session() | |
142 | # if we don't get explicit IP address try to get one from registered user |
|
158 | # if we don't get explicit IP address try to get one from registered user | |
143 | # in tmpl context var |
|
159 | # in tmpl context var | |
144 | if not ipaddr: |
|
160 | if not ipaddr: | |
145 | ipaddr = getattr(get_current_rhodecode_user(), 'ip_addr', '') |
|
161 | ipaddr = getattr(get_current_rhodecode_user(), 'ip_addr', '') | |
146 |
|
162 | |||
147 | try: |
|
163 | try: | |
148 | if getattr(user, 'user_id', None): |
|
164 | if getattr(user, 'user_id', None): | |
149 | user_obj = User.get(user.user_id) |
|
165 | user_obj = User.get(user.user_id) | |
150 | elif isinstance(user, basestring): |
|
166 | elif isinstance(user, basestring): | |
151 | user_obj = User.get_by_username(user) |
|
167 | user_obj = User.get_by_username(user) | |
152 | else: |
|
168 | else: | |
153 | raise Exception('You have to provide a user object or a username') |
|
169 | raise Exception('You have to provide a user object or a username') | |
154 |
|
170 | |||
155 | if getattr(repo, 'repo_id', None): |
|
171 | if getattr(repo, 'repo_id', None): | |
156 | repo_obj = Repository.get(repo.repo_id) |
|
172 | repo_obj = Repository.get(repo.repo_id) | |
157 | repo_name = repo_obj.repo_name |
|
173 | repo_name = repo_obj.repo_name | |
158 | elif isinstance(repo, basestring): |
|
174 | elif isinstance(repo, basestring): | |
159 | repo_name = repo.lstrip('/') |
|
175 | repo_name = repo.lstrip('/') | |
160 | repo_obj = Repository.get_by_repo_name(repo_name) |
|
176 | repo_obj = Repository.get_by_repo_name(repo_name) | |
161 | else: |
|
177 | else: | |
162 | repo_obj = None |
|
178 | repo_obj = None | |
163 | repo_name = '' |
|
179 | repo_name = '' | |
164 |
|
180 | |||
165 | user_log = UserLog() |
|
181 | user_log = UserLog() | |
166 | user_log.user_id = user_obj.user_id |
|
182 | user_log.user_id = user_obj.user_id | |
167 | user_log.username = user_obj.username |
|
183 | user_log.username = user_obj.username | |
168 | action = safe_unicode(action) |
|
184 | action = safe_unicode(action) | |
169 | user_log.action = action[:1200000] |
|
185 | user_log.action = action[:1200000] | |
170 |
|
186 | |||
171 | user_log.repository = repo_obj |
|
187 | user_log.repository = repo_obj | |
172 | user_log.repository_name = repo_name |
|
188 | user_log.repository_name = repo_name | |
173 |
|
189 | |||
174 | user_log.action_date = datetime.datetime.now() |
|
190 | user_log.action_date = datetime.datetime.now() | |
175 | user_log.user_ip = ipaddr |
|
191 | user_log.user_ip = ipaddr | |
176 | sa.add(user_log) |
|
192 | sa.add(user_log) | |
177 |
|
193 | |||
178 | log.info('Logging action:`%s` on repo:`%s` by user:%s ip:%s', |
|
194 | log.info('Logging action:`%s` on repo:`%s` by user:%s ip:%s', | |
179 | action, safe_unicode(repo), user_obj, ipaddr) |
|
195 | action, safe_unicode(repo), user_obj, ipaddr) | |
180 | if commit: |
|
196 | if commit: | |
181 | sa.commit() |
|
197 | sa.commit() | |
182 | except Exception: |
|
198 | except Exception: | |
183 | log.error(traceback.format_exc()) |
|
199 | log.error(traceback.format_exc()) | |
184 | raise |
|
200 | raise | |
185 |
|
201 | |||
186 |
|
202 | |||
187 | def get_filesystem_repos(path, recursive=False, skip_removed_repos=True): |
|
203 | def get_filesystem_repos(path, recursive=False, skip_removed_repos=True): | |
188 | """ |
|
204 | """ | |
189 | Scans given path for repos and return (name,(type,path)) tuple |
|
205 | Scans given path for repos and return (name,(type,path)) tuple | |
190 |
|
206 | |||
191 | :param path: path to scan for repositories |
|
207 | :param path: path to scan for repositories | |
192 | :param recursive: recursive search and return names with subdirs in front |
|
208 | :param recursive: recursive search and return names with subdirs in front | |
193 | """ |
|
209 | """ | |
194 |
|
210 | |||
195 | # remove ending slash for better results |
|
211 | # remove ending slash for better results | |
196 | path = path.rstrip(os.sep) |
|
212 | path = path.rstrip(os.sep) | |
197 | log.debug('now scanning in %s location recursive:%s...', path, recursive) |
|
213 | log.debug('now scanning in %s location recursive:%s...', path, recursive) | |
198 |
|
214 | |||
199 | def _get_repos(p): |
|
215 | def _get_repos(p): | |
200 | dirpaths = _get_dirpaths(p) |
|
216 | dirpaths = _get_dirpaths(p) | |
201 | if not _is_dir_writable(p): |
|
217 | if not _is_dir_writable(p): | |
202 | log.warning('repo path without write access: %s', p) |
|
218 | log.warning('repo path without write access: %s', p) | |
203 |
|
219 | |||
204 | for dirpath in dirpaths: |
|
220 | for dirpath in dirpaths: | |
205 | if os.path.isfile(os.path.join(p, dirpath)): |
|
221 | if os.path.isfile(os.path.join(p, dirpath)): | |
206 | continue |
|
222 | continue | |
207 | cur_path = os.path.join(p, dirpath) |
|
223 | cur_path = os.path.join(p, dirpath) | |
208 |
|
224 | |||
209 | # skip removed repos |
|
225 | # skip removed repos | |
210 | if skip_removed_repos and REMOVED_REPO_PAT.match(dirpath): |
|
226 | if skip_removed_repos and REMOVED_REPO_PAT.match(dirpath): | |
211 | continue |
|
227 | continue | |
212 |
|
228 | |||
213 | #skip .<somethin> dirs |
|
229 | #skip .<somethin> dirs | |
214 | if dirpath.startswith('.'): |
|
230 | if dirpath.startswith('.'): | |
215 | continue |
|
231 | continue | |
216 |
|
232 | |||
217 | try: |
|
233 | try: | |
218 | scm_info = get_scm(cur_path) |
|
234 | scm_info = get_scm(cur_path) | |
219 | yield scm_info[1].split(path, 1)[-1].lstrip(os.sep), scm_info |
|
235 | yield scm_info[1].split(path, 1)[-1].lstrip(os.sep), scm_info | |
220 | except VCSError: |
|
236 | except VCSError: | |
221 | if not recursive: |
|
237 | if not recursive: | |
222 | continue |
|
238 | continue | |
223 | #check if this dir containts other repos for recursive scan |
|
239 | #check if this dir containts other repos for recursive scan | |
224 | rec_path = os.path.join(p, dirpath) |
|
240 | rec_path = os.path.join(p, dirpath) | |
225 | if os.path.isdir(rec_path): |
|
241 | if os.path.isdir(rec_path): | |
226 | for inner_scm in _get_repos(rec_path): |
|
242 | for inner_scm in _get_repos(rec_path): | |
227 | yield inner_scm |
|
243 | yield inner_scm | |
228 |
|
244 | |||
229 | return _get_repos(path) |
|
245 | return _get_repos(path) | |
230 |
|
246 | |||
231 |
|
247 | |||
232 | def _get_dirpaths(p): |
|
248 | def _get_dirpaths(p): | |
233 | try: |
|
249 | try: | |
234 | # OS-independable way of checking if we have at least read-only |
|
250 | # OS-independable way of checking if we have at least read-only | |
235 | # access or not. |
|
251 | # access or not. | |
236 | dirpaths = os.listdir(p) |
|
252 | dirpaths = os.listdir(p) | |
237 | except OSError: |
|
253 | except OSError: | |
238 | log.warning('ignoring repo path without read access: %s', p) |
|
254 | log.warning('ignoring repo path without read access: %s', p) | |
239 | return [] |
|
255 | return [] | |
240 |
|
256 | |||
241 | # os.listpath has a tweak: If a unicode is passed into it, then it tries to |
|
257 | # os.listpath has a tweak: If a unicode is passed into it, then it tries to | |
242 | # decode paths and suddenly returns unicode objects itself. The items it |
|
258 | # decode paths and suddenly returns unicode objects itself. The items it | |
243 | # cannot decode are returned as strings and cause issues. |
|
259 | # cannot decode are returned as strings and cause issues. | |
244 | # |
|
260 | # | |
245 | # Those paths are ignored here until a solid solution for path handling has |
|
261 | # Those paths are ignored here until a solid solution for path handling has | |
246 | # been built. |
|
262 | # been built. | |
247 | expected_type = type(p) |
|
263 | expected_type = type(p) | |
248 |
|
264 | |||
249 | def _has_correct_type(item): |
|
265 | def _has_correct_type(item): | |
250 | if type(item) is not expected_type: |
|
266 | if type(item) is not expected_type: | |
251 | log.error( |
|
267 | log.error( | |
252 | u"Ignoring path %s since it cannot be decoded into unicode.", |
|
268 | u"Ignoring path %s since it cannot be decoded into unicode.", | |
253 | # Using "repr" to make sure that we see the byte value in case |
|
269 | # Using "repr" to make sure that we see the byte value in case | |
254 | # of support. |
|
270 | # of support. | |
255 | repr(item)) |
|
271 | repr(item)) | |
256 | return False |
|
272 | return False | |
257 | return True |
|
273 | return True | |
258 |
|
274 | |||
259 | dirpaths = [item for item in dirpaths if _has_correct_type(item)] |
|
275 | dirpaths = [item for item in dirpaths if _has_correct_type(item)] | |
260 |
|
276 | |||
261 | return dirpaths |
|
277 | return dirpaths | |
262 |
|
278 | |||
263 |
|
279 | |||
264 | def _is_dir_writable(path): |
|
280 | def _is_dir_writable(path): | |
265 | """ |
|
281 | """ | |
266 | Probe if `path` is writable. |
|
282 | Probe if `path` is writable. | |
267 |
|
283 | |||
268 | Due to trouble on Cygwin / Windows, this is actually probing if it is |
|
284 | Due to trouble on Cygwin / Windows, this is actually probing if it is | |
269 | possible to create a file inside of `path`, stat does not produce reliable |
|
285 | possible to create a file inside of `path`, stat does not produce reliable | |
270 | results in this case. |
|
286 | results in this case. | |
271 | """ |
|
287 | """ | |
272 | try: |
|
288 | try: | |
273 | with tempfile.TemporaryFile(dir=path): |
|
289 | with tempfile.TemporaryFile(dir=path): | |
274 | pass |
|
290 | pass | |
275 | except OSError: |
|
291 | except OSError: | |
276 | return False |
|
292 | return False | |
277 | return True |
|
293 | return True | |
278 |
|
294 | |||
279 |
|
295 | |||
280 | def is_valid_repo(repo_name, base_path, expect_scm=None, explicit_scm=None): |
|
296 | def is_valid_repo(repo_name, base_path, expect_scm=None, explicit_scm=None): | |
281 | """ |
|
297 | """ | |
282 | Returns True if given path is a valid repository False otherwise. |
|
298 | Returns True if given path is a valid repository False otherwise. | |
283 | If expect_scm param is given also, compare if given scm is the same |
|
299 | If expect_scm param is given also, compare if given scm is the same | |
284 | as expected from scm parameter. If explicit_scm is given don't try to |
|
300 | as expected from scm parameter. If explicit_scm is given don't try to | |
285 | detect the scm, just use the given one to check if repo is valid |
|
301 | detect the scm, just use the given one to check if repo is valid | |
286 |
|
302 | |||
287 | :param repo_name: |
|
303 | :param repo_name: | |
288 | :param base_path: |
|
304 | :param base_path: | |
289 | :param expect_scm: |
|
305 | :param expect_scm: | |
290 | :param explicit_scm: |
|
306 | :param explicit_scm: | |
291 |
|
307 | |||
292 | :return True: if given path is a valid repository |
|
308 | :return True: if given path is a valid repository | |
293 | """ |
|
309 | """ | |
294 | full_path = os.path.join(safe_str(base_path), safe_str(repo_name)) |
|
310 | full_path = os.path.join(safe_str(base_path), safe_str(repo_name)) | |
295 | log.debug('Checking if `%s` is a valid path for repository. ' |
|
311 | log.debug('Checking if `%s` is a valid path for repository. ' | |
296 | 'Explicit type: %s', repo_name, explicit_scm) |
|
312 | 'Explicit type: %s', repo_name, explicit_scm) | |
297 |
|
313 | |||
298 | try: |
|
314 | try: | |
299 | if explicit_scm: |
|
315 | if explicit_scm: | |
300 | detected_scms = [get_scm_backend(explicit_scm)] |
|
316 | detected_scms = [get_scm_backend(explicit_scm)] | |
301 | else: |
|
317 | else: | |
302 | detected_scms = get_scm(full_path) |
|
318 | detected_scms = get_scm(full_path) | |
303 |
|
319 | |||
304 | if expect_scm: |
|
320 | if expect_scm: | |
305 | return detected_scms[0] == expect_scm |
|
321 | return detected_scms[0] == expect_scm | |
306 | log.debug('path: %s is an vcs object:%s', full_path, detected_scms) |
|
322 | log.debug('path: %s is an vcs object:%s', full_path, detected_scms) | |
307 | return True |
|
323 | return True | |
308 | except VCSError: |
|
324 | except VCSError: | |
309 | log.debug('path: %s is not a valid repo !', full_path) |
|
325 | log.debug('path: %s is not a valid repo !', full_path) | |
310 | return False |
|
326 | return False | |
311 |
|
327 | |||
312 |
|
328 | |||
313 | def is_valid_repo_group(repo_group_name, base_path, skip_path_check=False): |
|
329 | def is_valid_repo_group(repo_group_name, base_path, skip_path_check=False): | |
314 | """ |
|
330 | """ | |
315 | Returns True if given path is a repository group, False otherwise |
|
331 | Returns True if given path is a repository group, False otherwise | |
316 |
|
332 | |||
317 | :param repo_name: |
|
333 | :param repo_name: | |
318 | :param base_path: |
|
334 | :param base_path: | |
319 | """ |
|
335 | """ | |
320 | full_path = os.path.join(safe_str(base_path), safe_str(repo_group_name)) |
|
336 | full_path = os.path.join(safe_str(base_path), safe_str(repo_group_name)) | |
321 | log.debug('Checking if `%s` is a valid path for repository group', |
|
337 | log.debug('Checking if `%s` is a valid path for repository group', | |
322 | repo_group_name) |
|
338 | repo_group_name) | |
323 |
|
339 | |||
324 | # check if it's not a repo |
|
340 | # check if it's not a repo | |
325 | if is_valid_repo(repo_group_name, base_path): |
|
341 | if is_valid_repo(repo_group_name, base_path): | |
326 | log.debug('Repo called %s exist, it is not a valid ' |
|
342 | log.debug('Repo called %s exist, it is not a valid ' | |
327 | 'repo group' % repo_group_name) |
|
343 | 'repo group' % repo_group_name) | |
328 | return False |
|
344 | return False | |
329 |
|
345 | |||
330 | try: |
|
346 | try: | |
331 | # we need to check bare git repos at higher level |
|
347 | # we need to check bare git repos at higher level | |
332 | # since we might match branches/hooks/info/objects or possible |
|
348 | # since we might match branches/hooks/info/objects or possible | |
333 | # other things inside bare git repo |
|
349 | # other things inside bare git repo | |
334 | scm_ = get_scm(os.path.dirname(full_path)) |
|
350 | scm_ = get_scm(os.path.dirname(full_path)) | |
335 | log.debug('path: %s is a vcs object:%s, not valid ' |
|
351 | log.debug('path: %s is a vcs object:%s, not valid ' | |
336 | 'repo group' % (full_path, scm_)) |
|
352 | 'repo group' % (full_path, scm_)) | |
337 | return False |
|
353 | return False | |
338 | except VCSError: |
|
354 | except VCSError: | |
339 | pass |
|
355 | pass | |
340 |
|
356 | |||
341 | # check if it's a valid path |
|
357 | # check if it's a valid path | |
342 | if skip_path_check or os.path.isdir(full_path): |
|
358 | if skip_path_check or os.path.isdir(full_path): | |
343 | log.debug('path: %s is a valid repo group !', full_path) |
|
359 | log.debug('path: %s is a valid repo group !', full_path) | |
344 | return True |
|
360 | return True | |
345 |
|
361 | |||
346 | log.debug('path: %s is not a valid repo group !', full_path) |
|
362 | log.debug('path: %s is not a valid repo group !', full_path) | |
347 | return False |
|
363 | return False | |
348 |
|
364 | |||
349 |
|
365 | |||
350 | def ask_ok(prompt, retries=4, complaint='[y]es or [n]o please!'): |
|
366 | def ask_ok(prompt, retries=4, complaint='[y]es or [n]o please!'): | |
351 | while True: |
|
367 | while True: | |
352 | ok = raw_input(prompt) |
|
368 | ok = raw_input(prompt) | |
353 | if ok.lower() in ('y', 'ye', 'yes'): |
|
369 | if ok.lower() in ('y', 'ye', 'yes'): | |
354 | return True |
|
370 | return True | |
355 | if ok.lower() in ('n', 'no', 'nop', 'nope'): |
|
371 | if ok.lower() in ('n', 'no', 'nop', 'nope'): | |
356 | return False |
|
372 | return False | |
357 | retries = retries - 1 |
|
373 | retries = retries - 1 | |
358 | if retries < 0: |
|
374 | if retries < 0: | |
359 | raise IOError |
|
375 | raise IOError | |
360 | print(complaint) |
|
376 | print(complaint) | |
361 |
|
377 | |||
362 | # propagated from mercurial documentation |
|
378 | # propagated from mercurial documentation | |
363 | ui_sections = [ |
|
379 | ui_sections = [ | |
364 | 'alias', 'auth', |
|
380 | 'alias', 'auth', | |
365 | 'decode/encode', 'defaults', |
|
381 | 'decode/encode', 'defaults', | |
366 | 'diff', 'email', |
|
382 | 'diff', 'email', | |
367 | 'extensions', 'format', |
|
383 | 'extensions', 'format', | |
368 | 'merge-patterns', 'merge-tools', |
|
384 | 'merge-patterns', 'merge-tools', | |
369 | 'hooks', 'http_proxy', |
|
385 | 'hooks', 'http_proxy', | |
370 | 'smtp', 'patch', |
|
386 | 'smtp', 'patch', | |
371 | 'paths', 'profiling', |
|
387 | 'paths', 'profiling', | |
372 | 'server', 'trusted', |
|
388 | 'server', 'trusted', | |
373 | 'ui', 'web', ] |
|
389 | 'ui', 'web', ] | |
374 |
|
390 | |||
375 |
|
391 | |||
376 | def config_data_from_db(clear_session=True, repo=None): |
|
392 | def config_data_from_db(clear_session=True, repo=None): | |
377 | """ |
|
393 | """ | |
378 | Read the configuration data from the database and return configuration |
|
394 | Read the configuration data from the database and return configuration | |
379 | tuples. |
|
395 | tuples. | |
380 | """ |
|
396 | """ | |
381 | from rhodecode.model.settings import VcsSettingsModel |
|
397 | from rhodecode.model.settings import VcsSettingsModel | |
382 |
|
398 | |||
383 | config = [] |
|
399 | config = [] | |
384 |
|
400 | |||
385 | sa = meta.Session() |
|
401 | sa = meta.Session() | |
386 | settings_model = VcsSettingsModel(repo=repo, sa=sa) |
|
402 | settings_model = VcsSettingsModel(repo=repo, sa=sa) | |
387 |
|
403 | |||
388 | ui_settings = settings_model.get_ui_settings() |
|
404 | ui_settings = settings_model.get_ui_settings() | |
389 |
|
405 | |||
390 | for setting in ui_settings: |
|
406 | for setting in ui_settings: | |
391 | if setting.active: |
|
407 | if setting.active: | |
392 | log.debug( |
|
408 | log.debug( | |
393 | 'settings ui from db: [%s] %s=%s', |
|
409 | 'settings ui from db: [%s] %s=%s', | |
394 | setting.section, setting.key, setting.value) |
|
410 | setting.section, setting.key, setting.value) | |
395 | config.append(( |
|
411 | config.append(( | |
396 | safe_str(setting.section), safe_str(setting.key), |
|
412 | safe_str(setting.section), safe_str(setting.key), | |
397 | safe_str(setting.value))) |
|
413 | safe_str(setting.value))) | |
398 | if setting.key == 'push_ssl': |
|
414 | if setting.key == 'push_ssl': | |
399 | # force set push_ssl requirement to False, rhodecode |
|
415 | # force set push_ssl requirement to False, rhodecode | |
400 | # handles that |
|
416 | # handles that | |
401 | config.append(( |
|
417 | config.append(( | |
402 | safe_str(setting.section), safe_str(setting.key), False)) |
|
418 | safe_str(setting.section), safe_str(setting.key), False)) | |
403 | if clear_session: |
|
419 | if clear_session: | |
404 | meta.Session.remove() |
|
420 | meta.Session.remove() | |
405 |
|
421 | |||
406 | # TODO: mikhail: probably it makes no sense to re-read hooks information. |
|
422 | # TODO: mikhail: probably it makes no sense to re-read hooks information. | |
407 | # It's already there and activated/deactivated |
|
423 | # It's already there and activated/deactivated | |
408 | skip_entries = [] |
|
424 | skip_entries = [] | |
409 | enabled_hook_classes = get_enabled_hook_classes(ui_settings) |
|
425 | enabled_hook_classes = get_enabled_hook_classes(ui_settings) | |
410 | if 'pull' not in enabled_hook_classes: |
|
426 | if 'pull' not in enabled_hook_classes: | |
411 | skip_entries.append(('hooks', RhodeCodeUi.HOOK_PRE_PULL)) |
|
427 | skip_entries.append(('hooks', RhodeCodeUi.HOOK_PRE_PULL)) | |
412 | if 'push' not in enabled_hook_classes: |
|
428 | if 'push' not in enabled_hook_classes: | |
413 | skip_entries.append(('hooks', RhodeCodeUi.HOOK_PRE_PUSH)) |
|
429 | skip_entries.append(('hooks', RhodeCodeUi.HOOK_PRE_PUSH)) | |
414 | skip_entries.append(('hooks', RhodeCodeUi.HOOK_PRETX_PUSH)) |
|
430 | skip_entries.append(('hooks', RhodeCodeUi.HOOK_PRETX_PUSH)) | |
415 |
|
431 | |||
416 | config = [entry for entry in config if entry[:2] not in skip_entries] |
|
432 | config = [entry for entry in config if entry[:2] not in skip_entries] | |
417 |
|
433 | |||
418 | return config |
|
434 | return config | |
419 |
|
435 | |||
420 |
|
436 | |||
421 | def make_db_config(clear_session=True, repo=None): |
|
437 | def make_db_config(clear_session=True, repo=None): | |
422 | """ |
|
438 | """ | |
423 | Create a :class:`Config` instance based on the values in the database. |
|
439 | Create a :class:`Config` instance based on the values in the database. | |
424 | """ |
|
440 | """ | |
425 | config = Config() |
|
441 | config = Config() | |
426 | config_data = config_data_from_db(clear_session=clear_session, repo=repo) |
|
442 | config_data = config_data_from_db(clear_session=clear_session, repo=repo) | |
427 | for section, option, value in config_data: |
|
443 | for section, option, value in config_data: | |
428 | config.set(section, option, value) |
|
444 | config.set(section, option, value) | |
429 | return config |
|
445 | return config | |
430 |
|
446 | |||
431 |
|
447 | |||
432 | def get_enabled_hook_classes(ui_settings): |
|
448 | def get_enabled_hook_classes(ui_settings): | |
433 | """ |
|
449 | """ | |
434 | Return the enabled hook classes. |
|
450 | Return the enabled hook classes. | |
435 |
|
451 | |||
436 | :param ui_settings: List of ui_settings as returned |
|
452 | :param ui_settings: List of ui_settings as returned | |
437 | by :meth:`VcsSettingsModel.get_ui_settings` |
|
453 | by :meth:`VcsSettingsModel.get_ui_settings` | |
438 |
|
454 | |||
439 | :return: a list with the enabled hook classes. The order is not guaranteed. |
|
455 | :return: a list with the enabled hook classes. The order is not guaranteed. | |
440 | :rtype: list |
|
456 | :rtype: list | |
441 | """ |
|
457 | """ | |
442 | enabled_hooks = [] |
|
458 | enabled_hooks = [] | |
443 | active_hook_keys = [ |
|
459 | active_hook_keys = [ | |
444 | key for section, key, value, active in ui_settings |
|
460 | key for section, key, value, active in ui_settings | |
445 | if section == 'hooks' and active] |
|
461 | if section == 'hooks' and active] | |
446 |
|
462 | |||
447 | hook_names = { |
|
463 | hook_names = { | |
448 | RhodeCodeUi.HOOK_PUSH: 'push', |
|
464 | RhodeCodeUi.HOOK_PUSH: 'push', | |
449 | RhodeCodeUi.HOOK_PULL: 'pull', |
|
465 | RhodeCodeUi.HOOK_PULL: 'pull', | |
450 | RhodeCodeUi.HOOK_REPO_SIZE: 'repo_size' |
|
466 | RhodeCodeUi.HOOK_REPO_SIZE: 'repo_size' | |
451 | } |
|
467 | } | |
452 |
|
468 | |||
453 | for key in active_hook_keys: |
|
469 | for key in active_hook_keys: | |
454 | hook = hook_names.get(key) |
|
470 | hook = hook_names.get(key) | |
455 | if hook: |
|
471 | if hook: | |
456 | enabled_hooks.append(hook) |
|
472 | enabled_hooks.append(hook) | |
457 |
|
473 | |||
458 | return enabled_hooks |
|
474 | return enabled_hooks | |
459 |
|
475 | |||
460 |
|
476 | |||
461 | def set_rhodecode_config(config): |
|
477 | def set_rhodecode_config(config): | |
462 | """ |
|
478 | """ | |
463 | Updates pylons config with new settings from database |
|
479 | Updates pylons config with new settings from database | |
464 |
|
480 | |||
465 | :param config: |
|
481 | :param config: | |
466 | """ |
|
482 | """ | |
467 | from rhodecode.model.settings import SettingsModel |
|
483 | from rhodecode.model.settings import SettingsModel | |
468 | app_settings = SettingsModel().get_all_settings() |
|
484 | app_settings = SettingsModel().get_all_settings() | |
469 |
|
485 | |||
470 | for k, v in app_settings.items(): |
|
486 | for k, v in app_settings.items(): | |
471 | config[k] = v |
|
487 | config[k] = v | |
472 |
|
488 | |||
473 |
|
489 | |||
474 | def get_rhodecode_realm(): |
|
490 | def get_rhodecode_realm(): | |
475 | """ |
|
491 | """ | |
476 | Return the rhodecode realm from database. |
|
492 | Return the rhodecode realm from database. | |
477 | """ |
|
493 | """ | |
478 | from rhodecode.model.settings import SettingsModel |
|
494 | from rhodecode.model.settings import SettingsModel | |
479 | realm = SettingsModel().get_setting_by_name('realm') |
|
495 | realm = SettingsModel().get_setting_by_name('realm') | |
480 | return safe_str(realm.app_settings_value) |
|
496 | return safe_str(realm.app_settings_value) | |
481 |
|
497 | |||
482 |
|
498 | |||
483 | def get_rhodecode_base_path(): |
|
499 | def get_rhodecode_base_path(): | |
484 | """ |
|
500 | """ | |
485 | Returns the base path. The base path is the filesystem path which points |
|
501 | Returns the base path. The base path is the filesystem path which points | |
486 | to the repository store. |
|
502 | to the repository store. | |
487 | """ |
|
503 | """ | |
488 | from rhodecode.model.settings import SettingsModel |
|
504 | from rhodecode.model.settings import SettingsModel | |
489 | paths_ui = SettingsModel().get_ui_by_section_and_key('paths', '/') |
|
505 | paths_ui = SettingsModel().get_ui_by_section_and_key('paths', '/') | |
490 | return safe_str(paths_ui.ui_value) |
|
506 | return safe_str(paths_ui.ui_value) | |
491 |
|
507 | |||
492 |
|
508 | |||
493 | def map_groups(path): |
|
509 | def map_groups(path): | |
494 | """ |
|
510 | """ | |
495 | Given a full path to a repository, create all nested groups that this |
|
511 | Given a full path to a repository, create all nested groups that this | |
496 | repo is inside. This function creates parent-child relationships between |
|
512 | repo is inside. This function creates parent-child relationships between | |
497 | groups and creates default perms for all new groups. |
|
513 | groups and creates default perms for all new groups. | |
498 |
|
514 | |||
499 | :param paths: full path to repository |
|
515 | :param paths: full path to repository | |
500 | """ |
|
516 | """ | |
501 | from rhodecode.model.repo_group import RepoGroupModel |
|
517 | from rhodecode.model.repo_group import RepoGroupModel | |
502 | sa = meta.Session() |
|
518 | sa = meta.Session() | |
503 | groups = path.split(Repository.NAME_SEP) |
|
519 | groups = path.split(Repository.NAME_SEP) | |
504 | parent = None |
|
520 | parent = None | |
505 | group = None |
|
521 | group = None | |
506 |
|
522 | |||
507 | # last element is repo in nested groups structure |
|
523 | # last element is repo in nested groups structure | |
508 | groups = groups[:-1] |
|
524 | groups = groups[:-1] | |
509 | rgm = RepoGroupModel(sa) |
|
525 | rgm = RepoGroupModel(sa) | |
510 | owner = User.get_first_super_admin() |
|
526 | owner = User.get_first_super_admin() | |
511 | for lvl, group_name in enumerate(groups): |
|
527 | for lvl, group_name in enumerate(groups): | |
512 | group_name = '/'.join(groups[:lvl] + [group_name]) |
|
528 | group_name = '/'.join(groups[:lvl] + [group_name]) | |
513 | group = RepoGroup.get_by_group_name(group_name) |
|
529 | group = RepoGroup.get_by_group_name(group_name) | |
514 | desc = '%s group' % group_name |
|
530 | desc = '%s group' % group_name | |
515 |
|
531 | |||
516 | # skip folders that are now removed repos |
|
532 | # skip folders that are now removed repos | |
517 | if REMOVED_REPO_PAT.match(group_name): |
|
533 | if REMOVED_REPO_PAT.match(group_name): | |
518 | break |
|
534 | break | |
519 |
|
535 | |||
520 | if group is None: |
|
536 | if group is None: | |
521 | log.debug('creating group level: %s group_name: %s', |
|
537 | log.debug('creating group level: %s group_name: %s', | |
522 | lvl, group_name) |
|
538 | lvl, group_name) | |
523 | group = RepoGroup(group_name, parent) |
|
539 | group = RepoGroup(group_name, parent) | |
524 | group.group_description = desc |
|
540 | group.group_description = desc | |
525 | group.user = owner |
|
541 | group.user = owner | |
526 | sa.add(group) |
|
542 | sa.add(group) | |
527 | perm_obj = rgm._create_default_perms(group) |
|
543 | perm_obj = rgm._create_default_perms(group) | |
528 | sa.add(perm_obj) |
|
544 | sa.add(perm_obj) | |
529 | sa.flush() |
|
545 | sa.flush() | |
530 |
|
546 | |||
531 | parent = group |
|
547 | parent = group | |
532 | return group |
|
548 | return group | |
533 |
|
549 | |||
534 |
|
550 | |||
535 | def repo2db_mapper(initial_repo_list, remove_obsolete=False): |
|
551 | def repo2db_mapper(initial_repo_list, remove_obsolete=False): | |
536 | """ |
|
552 | """ | |
537 | maps all repos given in initial_repo_list, non existing repositories |
|
553 | maps all repos given in initial_repo_list, non existing repositories | |
538 | are created, if remove_obsolete is True it also checks for db entries |
|
554 | are created, if remove_obsolete is True it also checks for db entries | |
539 | that are not in initial_repo_list and removes them. |
|
555 | that are not in initial_repo_list and removes them. | |
540 |
|
556 | |||
541 | :param initial_repo_list: list of repositories found by scanning methods |
|
557 | :param initial_repo_list: list of repositories found by scanning methods | |
542 | :param remove_obsolete: check for obsolete entries in database |
|
558 | :param remove_obsolete: check for obsolete entries in database | |
543 | """ |
|
559 | """ | |
544 | from rhodecode.model.repo import RepoModel |
|
560 | from rhodecode.model.repo import RepoModel | |
545 | from rhodecode.model.scm import ScmModel |
|
561 | from rhodecode.model.scm import ScmModel | |
546 | from rhodecode.model.repo_group import RepoGroupModel |
|
562 | from rhodecode.model.repo_group import RepoGroupModel | |
547 | from rhodecode.model.settings import SettingsModel |
|
563 | from rhodecode.model.settings import SettingsModel | |
548 |
|
564 | |||
549 | sa = meta.Session() |
|
565 | sa = meta.Session() | |
550 | repo_model = RepoModel() |
|
566 | repo_model = RepoModel() | |
551 | user = User.get_first_super_admin() |
|
567 | user = User.get_first_super_admin() | |
552 | added = [] |
|
568 | added = [] | |
553 |
|
569 | |||
554 | # creation defaults |
|
570 | # creation defaults | |
555 | defs = SettingsModel().get_default_repo_settings(strip_prefix=True) |
|
571 | defs = SettingsModel().get_default_repo_settings(strip_prefix=True) | |
556 | enable_statistics = defs.get('repo_enable_statistics') |
|
572 | enable_statistics = defs.get('repo_enable_statistics') | |
557 | enable_locking = defs.get('repo_enable_locking') |
|
573 | enable_locking = defs.get('repo_enable_locking') | |
558 | enable_downloads = defs.get('repo_enable_downloads') |
|
574 | enable_downloads = defs.get('repo_enable_downloads') | |
559 | private = defs.get('repo_private') |
|
575 | private = defs.get('repo_private') | |
560 |
|
576 | |||
561 | for name, repo in initial_repo_list.items(): |
|
577 | for name, repo in initial_repo_list.items(): | |
562 | group = map_groups(name) |
|
578 | group = map_groups(name) | |
563 | unicode_name = safe_unicode(name) |
|
579 | unicode_name = safe_unicode(name) | |
564 | db_repo = repo_model.get_by_repo_name(unicode_name) |
|
580 | db_repo = repo_model.get_by_repo_name(unicode_name) | |
565 | # found repo that is on filesystem not in RhodeCode database |
|
581 | # found repo that is on filesystem not in RhodeCode database | |
566 | if not db_repo: |
|
582 | if not db_repo: | |
567 | log.info('repository %s not found, creating now', name) |
|
583 | log.info('repository %s not found, creating now', name) | |
568 | added.append(name) |
|
584 | added.append(name) | |
569 | desc = (repo.description |
|
585 | desc = (repo.description | |
570 | if repo.description != 'unknown' |
|
586 | if repo.description != 'unknown' | |
571 | else '%s repository' % name) |
|
587 | else '%s repository' % name) | |
572 |
|
588 | |||
573 | db_repo = repo_model._create_repo( |
|
589 | db_repo = repo_model._create_repo( | |
574 | repo_name=name, |
|
590 | repo_name=name, | |
575 | repo_type=repo.alias, |
|
591 | repo_type=repo.alias, | |
576 | description=desc, |
|
592 | description=desc, | |
577 | repo_group=getattr(group, 'group_id', None), |
|
593 | repo_group=getattr(group, 'group_id', None), | |
578 | owner=user, |
|
594 | owner=user, | |
579 | enable_locking=enable_locking, |
|
595 | enable_locking=enable_locking, | |
580 | enable_downloads=enable_downloads, |
|
596 | enable_downloads=enable_downloads, | |
581 | enable_statistics=enable_statistics, |
|
597 | enable_statistics=enable_statistics, | |
582 | private=private, |
|
598 | private=private, | |
583 | state=Repository.STATE_CREATED |
|
599 | state=Repository.STATE_CREATED | |
584 | ) |
|
600 | ) | |
585 | sa.commit() |
|
601 | sa.commit() | |
586 | # we added that repo just now, and make sure we updated server info |
|
602 | # we added that repo just now, and make sure we updated server info | |
587 | if db_repo.repo_type == 'git': |
|
603 | if db_repo.repo_type == 'git': | |
588 | git_repo = db_repo.scm_instance() |
|
604 | git_repo = db_repo.scm_instance() | |
589 | # update repository server-info |
|
605 | # update repository server-info | |
590 | log.debug('Running update server info') |
|
606 | log.debug('Running update server info') | |
591 | git_repo._update_server_info() |
|
607 | git_repo._update_server_info() | |
592 |
|
608 | |||
593 | db_repo.update_commit_cache() |
|
609 | db_repo.update_commit_cache() | |
594 |
|
610 | |||
595 | config = db_repo._config |
|
611 | config = db_repo._config | |
596 | config.set('extensions', 'largefiles', '') |
|
612 | config.set('extensions', 'largefiles', '') | |
597 | ScmModel().install_hooks( |
|
613 | ScmModel().install_hooks( | |
598 | db_repo.scm_instance(config=config), |
|
614 | db_repo.scm_instance(config=config), | |
599 | repo_type=db_repo.repo_type) |
|
615 | repo_type=db_repo.repo_type) | |
600 |
|
616 | |||
601 | removed = [] |
|
617 | removed = [] | |
602 | if remove_obsolete: |
|
618 | if remove_obsolete: | |
603 | # remove from database those repositories that are not in the filesystem |
|
619 | # remove from database those repositories that are not in the filesystem | |
604 | for repo in sa.query(Repository).all(): |
|
620 | for repo in sa.query(Repository).all(): | |
605 | if repo.repo_name not in initial_repo_list.keys(): |
|
621 | if repo.repo_name not in initial_repo_list.keys(): | |
606 | log.debug("Removing non-existing repository found in db `%s`", |
|
622 | log.debug("Removing non-existing repository found in db `%s`", | |
607 | repo.repo_name) |
|
623 | repo.repo_name) | |
608 | try: |
|
624 | try: | |
609 | RepoModel(sa).delete(repo, forks='detach', fs_remove=False) |
|
625 | RepoModel(sa).delete(repo, forks='detach', fs_remove=False) | |
610 | sa.commit() |
|
626 | sa.commit() | |
611 | removed.append(repo.repo_name) |
|
627 | removed.append(repo.repo_name) | |
612 | except Exception: |
|
628 | except Exception: | |
613 | # don't hold further removals on error |
|
629 | # don't hold further removals on error | |
614 | log.error(traceback.format_exc()) |
|
630 | log.error(traceback.format_exc()) | |
615 | sa.rollback() |
|
631 | sa.rollback() | |
616 |
|
632 | |||
617 | def splitter(full_repo_name): |
|
633 | def splitter(full_repo_name): | |
618 | _parts = full_repo_name.rsplit(RepoGroup.url_sep(), 1) |
|
634 | _parts = full_repo_name.rsplit(RepoGroup.url_sep(), 1) | |
619 | gr_name = None |
|
635 | gr_name = None | |
620 | if len(_parts) == 2: |
|
636 | if len(_parts) == 2: | |
621 | gr_name = _parts[0] |
|
637 | gr_name = _parts[0] | |
622 | return gr_name |
|
638 | return gr_name | |
623 |
|
639 | |||
624 | initial_repo_group_list = [splitter(x) for x in |
|
640 | initial_repo_group_list = [splitter(x) for x in | |
625 | initial_repo_list.keys() if splitter(x)] |
|
641 | initial_repo_list.keys() if splitter(x)] | |
626 |
|
642 | |||
627 | # remove from database those repository groups that are not in the |
|
643 | # remove from database those repository groups that are not in the | |
628 | # filesystem due to parent child relationships we need to delete them |
|
644 | # filesystem due to parent child relationships we need to delete them | |
629 | # in a specific order of most nested first |
|
645 | # in a specific order of most nested first | |
630 | all_groups = [x.group_name for x in sa.query(RepoGroup).all()] |
|
646 | all_groups = [x.group_name for x in sa.query(RepoGroup).all()] | |
631 | nested_sort = lambda gr: len(gr.split('/')) |
|
647 | nested_sort = lambda gr: len(gr.split('/')) | |
632 | for group_name in sorted(all_groups, key=nested_sort, reverse=True): |
|
648 | for group_name in sorted(all_groups, key=nested_sort, reverse=True): | |
633 | if group_name not in initial_repo_group_list: |
|
649 | if group_name not in initial_repo_group_list: | |
634 | repo_group = RepoGroup.get_by_group_name(group_name) |
|
650 | repo_group = RepoGroup.get_by_group_name(group_name) | |
635 | if (repo_group.children.all() or |
|
651 | if (repo_group.children.all() or | |
636 | not RepoGroupModel().check_exist_filesystem( |
|
652 | not RepoGroupModel().check_exist_filesystem( | |
637 | group_name=group_name, exc_on_failure=False)): |
|
653 | group_name=group_name, exc_on_failure=False)): | |
638 | continue |
|
654 | continue | |
639 |
|
655 | |||
640 | log.info( |
|
656 | log.info( | |
641 | 'Removing non-existing repository group found in db `%s`', |
|
657 | 'Removing non-existing repository group found in db `%s`', | |
642 | group_name) |
|
658 | group_name) | |
643 | try: |
|
659 | try: | |
644 | RepoGroupModel(sa).delete(group_name, fs_remove=False) |
|
660 | RepoGroupModel(sa).delete(group_name, fs_remove=False) | |
645 | sa.commit() |
|
661 | sa.commit() | |
646 | removed.append(group_name) |
|
662 | removed.append(group_name) | |
647 | except Exception: |
|
663 | except Exception: | |
648 | # don't hold further removals on error |
|
664 | # don't hold further removals on error | |
649 | log.exception( |
|
665 | log.exception( | |
650 | 'Unable to remove repository group `%s`', |
|
666 | 'Unable to remove repository group `%s`', | |
651 | group_name) |
|
667 | group_name) | |
652 | sa.rollback() |
|
668 | sa.rollback() | |
653 | raise |
|
669 | raise | |
654 |
|
670 | |||
655 | return added, removed |
|
671 | return added, removed | |
656 |
|
672 | |||
657 |
|
673 | |||
658 | def get_default_cache_settings(settings): |
|
674 | def get_default_cache_settings(settings): | |
659 | cache_settings = {} |
|
675 | cache_settings = {} | |
660 | for key in settings.keys(): |
|
676 | for key in settings.keys(): | |
661 | for prefix in ['beaker.cache.', 'cache.']: |
|
677 | for prefix in ['beaker.cache.', 'cache.']: | |
662 | if key.startswith(prefix): |
|
678 | if key.startswith(prefix): | |
663 | name = key.split(prefix)[1].strip() |
|
679 | name = key.split(prefix)[1].strip() | |
664 | cache_settings[name] = settings[key].strip() |
|
680 | cache_settings[name] = settings[key].strip() | |
665 | return cache_settings |
|
681 | return cache_settings | |
666 |
|
682 | |||
667 |
|
683 | |||
668 | # set cache regions for beaker so celery can utilise it |
|
684 | # set cache regions for beaker so celery can utilise it | |
669 | def add_cache(settings): |
|
685 | def add_cache(settings): | |
670 | from rhodecode.lib import caches |
|
686 | from rhodecode.lib import caches | |
671 | cache_settings = {'regions': None} |
|
687 | cache_settings = {'regions': None} | |
672 | # main cache settings used as default ... |
|
688 | # main cache settings used as default ... | |
673 | cache_settings.update(get_default_cache_settings(settings)) |
|
689 | cache_settings.update(get_default_cache_settings(settings)) | |
674 |
|
690 | |||
675 | if cache_settings['regions']: |
|
691 | if cache_settings['regions']: | |
676 | for region in cache_settings['regions'].split(','): |
|
692 | for region in cache_settings['regions'].split(','): | |
677 | region = region.strip() |
|
693 | region = region.strip() | |
678 | region_settings = {} |
|
694 | region_settings = {} | |
679 | for key, value in cache_settings.items(): |
|
695 | for key, value in cache_settings.items(): | |
680 | if key.startswith(region): |
|
696 | if key.startswith(region): | |
681 | region_settings[key.split('.')[1]] = value |
|
697 | region_settings[key.split('.')[1]] = value | |
682 |
|
698 | |||
683 | caches.configure_cache_region( |
|
699 | caches.configure_cache_region( | |
684 | region, region_settings, cache_settings) |
|
700 | region, region_settings, cache_settings) | |
685 |
|
701 | |||
686 |
|
702 | |||
687 | def load_rcextensions(root_path): |
|
703 | def load_rcextensions(root_path): | |
688 | import rhodecode |
|
704 | import rhodecode | |
689 | from rhodecode.config import conf |
|
705 | from rhodecode.config import conf | |
690 |
|
706 | |||
691 | path = os.path.join(root_path, 'rcextensions', '__init__.py') |
|
707 | path = os.path.join(root_path, 'rcextensions', '__init__.py') | |
692 | if os.path.isfile(path): |
|
708 | if os.path.isfile(path): | |
693 | rcext = create_module('rc', path) |
|
709 | rcext = create_module('rc', path) | |
694 | EXT = rhodecode.EXTENSIONS = rcext |
|
710 | EXT = rhodecode.EXTENSIONS = rcext | |
695 | log.debug('Found rcextensions now loading %s...', rcext) |
|
711 | log.debug('Found rcextensions now loading %s...', rcext) | |
696 |
|
712 | |||
697 | # Additional mappings that are not present in the pygments lexers |
|
713 | # Additional mappings that are not present in the pygments lexers | |
698 | conf.LANGUAGES_EXTENSIONS_MAP.update(getattr(EXT, 'EXTRA_MAPPINGS', {})) |
|
714 | conf.LANGUAGES_EXTENSIONS_MAP.update(getattr(EXT, 'EXTRA_MAPPINGS', {})) | |
699 |
|
715 | |||
700 | # auto check if the module is not missing any data, set to default if is |
|
716 | # auto check if the module is not missing any data, set to default if is | |
701 | # this will help autoupdate new feature of rcext module |
|
717 | # this will help autoupdate new feature of rcext module | |
702 | #from rhodecode.config import rcextensions |
|
718 | #from rhodecode.config import rcextensions | |
703 | #for k in dir(rcextensions): |
|
719 | #for k in dir(rcextensions): | |
704 | # if not k.startswith('_') and not hasattr(EXT, k): |
|
720 | # if not k.startswith('_') and not hasattr(EXT, k): | |
705 | # setattr(EXT, k, getattr(rcextensions, k)) |
|
721 | # setattr(EXT, k, getattr(rcextensions, k)) | |
706 |
|
722 | |||
707 |
|
723 | |||
708 | def get_custom_lexer(extension): |
|
724 | def get_custom_lexer(extension): | |
709 | """ |
|
725 | """ | |
710 | returns a custom lexer if it is defined in rcextensions module, or None |
|
726 | returns a custom lexer if it is defined in rcextensions module, or None | |
711 | if there's no custom lexer defined |
|
727 | if there's no custom lexer defined | |
712 | """ |
|
728 | """ | |
713 | import rhodecode |
|
729 | import rhodecode | |
714 | from pygments import lexers |
|
730 | from pygments import lexers | |
715 | # check if we didn't define this extension as other lexer |
|
731 | # check if we didn't define this extension as other lexer | |
716 | extensions = rhodecode.EXTENSIONS and getattr(rhodecode.EXTENSIONS, 'EXTRA_LEXERS', None) |
|
732 | extensions = rhodecode.EXTENSIONS and getattr(rhodecode.EXTENSIONS, 'EXTRA_LEXERS', None) | |
717 | if extensions and extension in rhodecode.EXTENSIONS.EXTRA_LEXERS: |
|
733 | if extensions and extension in rhodecode.EXTENSIONS.EXTRA_LEXERS: | |
718 | _lexer_name = rhodecode.EXTENSIONS.EXTRA_LEXERS[extension] |
|
734 | _lexer_name = rhodecode.EXTENSIONS.EXTRA_LEXERS[extension] | |
719 | return lexers.get_lexer_by_name(_lexer_name) |
|
735 | return lexers.get_lexer_by_name(_lexer_name) | |
720 |
|
736 | |||
721 |
|
737 | |||
722 | #============================================================================== |
|
738 | #============================================================================== | |
723 | # TEST FUNCTIONS AND CREATORS |
|
739 | # TEST FUNCTIONS AND CREATORS | |
724 | #============================================================================== |
|
740 | #============================================================================== | |
725 | def create_test_index(repo_location, config): |
|
741 | def create_test_index(repo_location, config): | |
726 | """ |
|
742 | """ | |
727 | Makes default test index. |
|
743 | Makes default test index. | |
728 | """ |
|
744 | """ | |
729 | import rc_testdata |
|
745 | import rc_testdata | |
730 |
|
746 | |||
731 | rc_testdata.extract_search_index( |
|
747 | rc_testdata.extract_search_index( | |
732 | 'vcs_search_index', os.path.dirname(config['search.location'])) |
|
748 | 'vcs_search_index', os.path.dirname(config['search.location'])) | |
733 |
|
749 | |||
734 |
|
750 | |||
735 | def create_test_directory(test_path): |
|
751 | def create_test_directory(test_path): | |
736 | """ |
|
752 | """ | |
737 | Create test directory if it doesn't exist. |
|
753 | Create test directory if it doesn't exist. | |
738 | """ |
|
754 | """ | |
739 | if not os.path.isdir(test_path): |
|
755 | if not os.path.isdir(test_path): | |
740 | log.debug('Creating testdir %s', test_path) |
|
756 | log.debug('Creating testdir %s', test_path) | |
741 | os.makedirs(test_path) |
|
757 | os.makedirs(test_path) | |
742 |
|
758 | |||
743 |
|
759 | |||
744 | def create_test_database(test_path, config): |
|
760 | def create_test_database(test_path, config): | |
745 | """ |
|
761 | """ | |
746 | Makes a fresh database. |
|
762 | Makes a fresh database. | |
747 | """ |
|
763 | """ | |
748 | from rhodecode.lib.db_manage import DbManage |
|
764 | from rhodecode.lib.db_manage import DbManage | |
749 |
|
765 | |||
750 | # PART ONE create db |
|
766 | # PART ONE create db | |
751 | dbconf = config['sqlalchemy.db1.url'] |
|
767 | dbconf = config['sqlalchemy.db1.url'] | |
752 | log.debug('making test db %s', dbconf) |
|
768 | log.debug('making test db %s', dbconf) | |
753 |
|
769 | |||
754 | dbmanage = DbManage(log_sql=False, dbconf=dbconf, root=config['here'], |
|
770 | dbmanage = DbManage(log_sql=False, dbconf=dbconf, root=config['here'], | |
755 | tests=True, cli_args={'force_ask': True}) |
|
771 | tests=True, cli_args={'force_ask': True}) | |
756 | dbmanage.create_tables(override=True) |
|
772 | dbmanage.create_tables(override=True) | |
757 | dbmanage.set_db_version() |
|
773 | dbmanage.set_db_version() | |
758 | # for tests dynamically set new root paths based on generated content |
|
774 | # for tests dynamically set new root paths based on generated content | |
759 | dbmanage.create_settings(dbmanage.config_prompt(test_path)) |
|
775 | dbmanage.create_settings(dbmanage.config_prompt(test_path)) | |
760 | dbmanage.create_default_user() |
|
776 | dbmanage.create_default_user() | |
761 | dbmanage.create_test_admin_and_users() |
|
777 | dbmanage.create_test_admin_and_users() | |
762 | dbmanage.create_permissions() |
|
778 | dbmanage.create_permissions() | |
763 | dbmanage.populate_default_permissions() |
|
779 | dbmanage.populate_default_permissions() | |
764 | Session().commit() |
|
780 | Session().commit() | |
765 |
|
781 | |||
766 |
|
782 | |||
767 | def create_test_repositories(test_path, config): |
|
783 | def create_test_repositories(test_path, config): | |
768 | """ |
|
784 | """ | |
769 | Creates test repositories in the temporary directory. Repositories are |
|
785 | Creates test repositories in the temporary directory. Repositories are | |
770 | extracted from archives within the rc_testdata package. |
|
786 | extracted from archives within the rc_testdata package. | |
771 | """ |
|
787 | """ | |
772 | import rc_testdata |
|
788 | import rc_testdata | |
773 | from rhodecode.tests import HG_REPO, GIT_REPO, SVN_REPO |
|
789 | from rhodecode.tests import HG_REPO, GIT_REPO, SVN_REPO | |
774 |
|
790 | |||
775 | log.debug('making test vcs repositories') |
|
791 | log.debug('making test vcs repositories') | |
776 |
|
792 | |||
777 | idx_path = config['search.location'] |
|
793 | idx_path = config['search.location'] | |
778 | data_path = config['cache_dir'] |
|
794 | data_path = config['cache_dir'] | |
779 |
|
795 | |||
780 | # clean index and data |
|
796 | # clean index and data | |
781 | if idx_path and os.path.exists(idx_path): |
|
797 | if idx_path and os.path.exists(idx_path): | |
782 | log.debug('remove %s', idx_path) |
|
798 | log.debug('remove %s', idx_path) | |
783 | shutil.rmtree(idx_path) |
|
799 | shutil.rmtree(idx_path) | |
784 |
|
800 | |||
785 | if data_path and os.path.exists(data_path): |
|
801 | if data_path and os.path.exists(data_path): | |
786 | log.debug('remove %s', data_path) |
|
802 | log.debug('remove %s', data_path) | |
787 | shutil.rmtree(data_path) |
|
803 | shutil.rmtree(data_path) | |
788 |
|
804 | |||
789 | rc_testdata.extract_hg_dump('vcs_test_hg', jn(test_path, HG_REPO)) |
|
805 | rc_testdata.extract_hg_dump('vcs_test_hg', jn(test_path, HG_REPO)) | |
790 | rc_testdata.extract_git_dump('vcs_test_git', jn(test_path, GIT_REPO)) |
|
806 | rc_testdata.extract_git_dump('vcs_test_git', jn(test_path, GIT_REPO)) | |
791 |
|
807 | |||
792 | # Note: Subversion is in the process of being integrated with the system, |
|
808 | # Note: Subversion is in the process of being integrated with the system, | |
793 | # until we have a properly packed version of the test svn repository, this |
|
809 | # until we have a properly packed version of the test svn repository, this | |
794 | # tries to copy over the repo from a package "rc_testdata" |
|
810 | # tries to copy over the repo from a package "rc_testdata" | |
795 | svn_repo_path = rc_testdata.get_svn_repo_archive() |
|
811 | svn_repo_path = rc_testdata.get_svn_repo_archive() | |
796 | with tarfile.open(svn_repo_path) as tar: |
|
812 | with tarfile.open(svn_repo_path) as tar: | |
797 | tar.extractall(jn(test_path, SVN_REPO)) |
|
813 | tar.extractall(jn(test_path, SVN_REPO)) | |
798 |
|
814 | |||
799 |
|
815 | |||
800 | #============================================================================== |
|
816 | #============================================================================== | |
801 | # PASTER COMMANDS |
|
817 | # PASTER COMMANDS | |
802 | #============================================================================== |
|
818 | #============================================================================== | |
803 | class BasePasterCommand(Command): |
|
819 | class BasePasterCommand(Command): | |
804 | """ |
|
820 | """ | |
805 | Abstract Base Class for paster commands. |
|
821 | Abstract Base Class for paster commands. | |
806 |
|
822 | |||
807 | The celery commands are somewhat aggressive about loading |
|
823 | The celery commands are somewhat aggressive about loading | |
808 | celery.conf, and since our module sets the `CELERY_LOADER` |
|
824 | celery.conf, and since our module sets the `CELERY_LOADER` | |
809 | environment variable to our loader, we have to bootstrap a bit and |
|
825 | environment variable to our loader, we have to bootstrap a bit and | |
810 | make sure we've had a chance to load the pylons config off of the |
|
826 | make sure we've had a chance to load the pylons config off of the | |
811 | command line, otherwise everything fails. |
|
827 | command line, otherwise everything fails. | |
812 | """ |
|
828 | """ | |
813 | min_args = 1 |
|
829 | min_args = 1 | |
814 | min_args_error = "Please provide a paster config file as an argument." |
|
830 | min_args_error = "Please provide a paster config file as an argument." | |
815 | takes_config_file = 1 |
|
831 | takes_config_file = 1 | |
816 | requires_config_file = True |
|
832 | requires_config_file = True | |
817 |
|
833 | |||
818 | def notify_msg(self, msg, log=False): |
|
834 | def notify_msg(self, msg, log=False): | |
819 | """Make a notification to user, additionally if logger is passed |
|
835 | """Make a notification to user, additionally if logger is passed | |
820 | it logs this action using given logger |
|
836 | it logs this action using given logger | |
821 |
|
837 | |||
822 | :param msg: message that will be printed to user |
|
838 | :param msg: message that will be printed to user | |
823 | :param log: logging instance, to use to additionally log this message |
|
839 | :param log: logging instance, to use to additionally log this message | |
824 |
|
840 | |||
825 | """ |
|
841 | """ | |
826 | if log and isinstance(log, logging): |
|
842 | if log and isinstance(log, logging): | |
827 | log(msg) |
|
843 | log(msg) | |
828 |
|
844 | |||
829 | def run(self, args): |
|
845 | def run(self, args): | |
830 | """ |
|
846 | """ | |
831 | Overrides Command.run |
|
847 | Overrides Command.run | |
832 |
|
848 | |||
833 | Checks for a config file argument and loads it. |
|
849 | Checks for a config file argument and loads it. | |
834 | """ |
|
850 | """ | |
835 | if len(args) < self.min_args: |
|
851 | if len(args) < self.min_args: | |
836 | raise BadCommand( |
|
852 | raise BadCommand( | |
837 | self.min_args_error % {'min_args': self.min_args, |
|
853 | self.min_args_error % {'min_args': self.min_args, | |
838 | 'actual_args': len(args)}) |
|
854 | 'actual_args': len(args)}) | |
839 |
|
855 | |||
840 | # Decrement because we're going to lob off the first argument. |
|
856 | # Decrement because we're going to lob off the first argument. | |
841 | # @@ This is hacky |
|
857 | # @@ This is hacky | |
842 | self.min_args -= 1 |
|
858 | self.min_args -= 1 | |
843 | self.bootstrap_config(args[0]) |
|
859 | self.bootstrap_config(args[0]) | |
844 | self.update_parser() |
|
860 | self.update_parser() | |
845 | return super(BasePasterCommand, self).run(args[1:]) |
|
861 | return super(BasePasterCommand, self).run(args[1:]) | |
846 |
|
862 | |||
847 | def update_parser(self): |
|
863 | def update_parser(self): | |
848 | """ |
|
864 | """ | |
849 | Abstract method. Allows for the class' parser to be updated |
|
865 | Abstract method. Allows for the class' parser to be updated | |
850 | before the superclass' `run` method is called. Necessary to |
|
866 | before the superclass' `run` method is called. Necessary to | |
851 | allow options/arguments to be passed through to the underlying |
|
867 | allow options/arguments to be passed through to the underlying | |
852 | celery command. |
|
868 | celery command. | |
853 | """ |
|
869 | """ | |
854 | raise NotImplementedError("Abstract Method.") |
|
870 | raise NotImplementedError("Abstract Method.") | |
855 |
|
871 | |||
856 | def bootstrap_config(self, conf): |
|
872 | def bootstrap_config(self, conf): | |
857 | """ |
|
873 | """ | |
858 | Loads the pylons configuration. |
|
874 | Loads the pylons configuration. | |
859 | """ |
|
875 | """ | |
860 | from pylons import config as pylonsconfig |
|
876 | from pylons import config as pylonsconfig | |
861 |
|
877 | |||
862 | self.path_to_ini_file = os.path.realpath(conf) |
|
878 | self.path_to_ini_file = os.path.realpath(conf) | |
863 | conf = paste.deploy.appconfig('config:' + self.path_to_ini_file) |
|
879 | conf = paste.deploy.appconfig('config:' + self.path_to_ini_file) | |
864 | pylonsconfig.init_app(conf.global_conf, conf.local_conf) |
|
880 | pylonsconfig.init_app(conf.global_conf, conf.local_conf) | |
865 |
|
881 | |||
866 | def _init_session(self): |
|
882 | def _init_session(self): | |
867 | """ |
|
883 | """ | |
868 | Inits SqlAlchemy Session |
|
884 | Inits SqlAlchemy Session | |
869 | """ |
|
885 | """ | |
870 | logging.config.fileConfig(self.path_to_ini_file) |
|
886 | logging.config.fileConfig(self.path_to_ini_file) | |
871 | from pylons import config |
|
887 | from pylons import config | |
872 | from rhodecode.config.utils import initialize_database |
|
888 | from rhodecode.config.utils import initialize_database | |
873 |
|
889 | |||
874 | # get to remove repos !! |
|
890 | # get to remove repos !! | |
875 | add_cache(config) |
|
891 | add_cache(config) | |
876 | initialize_database(config) |
|
892 | initialize_database(config) | |
877 |
|
893 | |||
878 |
|
894 | |||
879 | @decorator.decorator |
|
895 | @decorator.decorator | |
880 | def jsonify(func, *args, **kwargs): |
|
896 | def jsonify(func, *args, **kwargs): | |
881 | """Action decorator that formats output for JSON |
|
897 | """Action decorator that formats output for JSON | |
882 |
|
898 | |||
883 | Given a function that will return content, this decorator will turn |
|
899 | Given a function that will return content, this decorator will turn | |
884 | the result into JSON, with a content-type of 'application/json' and |
|
900 | the result into JSON, with a content-type of 'application/json' and | |
885 | output it. |
|
901 | output it. | |
886 |
|
902 | |||
887 | """ |
|
903 | """ | |
888 | from pylons.decorators.util import get_pylons |
|
904 | from pylons.decorators.util import get_pylons | |
889 | from rhodecode.lib.ext_json import json |
|
905 | from rhodecode.lib.ext_json import json | |
890 | pylons = get_pylons(args) |
|
906 | pylons = get_pylons(args) | |
891 | pylons.response.headers['Content-Type'] = 'application/json; charset=utf-8' |
|
907 | pylons.response.headers['Content-Type'] = 'application/json; charset=utf-8' | |
892 | data = func(*args, **kwargs) |
|
908 | data = func(*args, **kwargs) | |
893 | if isinstance(data, (list, tuple)): |
|
909 | if isinstance(data, (list, tuple)): | |
894 | msg = "JSON responses with Array envelopes are susceptible to " \ |
|
910 | msg = "JSON responses with Array envelopes are susceptible to " \ | |
895 | "cross-site data leak attacks, see " \ |
|
911 | "cross-site data leak attacks, see " \ | |
896 | "http://wiki.pylonshq.com/display/pylonsfaq/Warnings" |
|
912 | "http://wiki.pylonshq.com/display/pylonsfaq/Warnings" | |
897 | warnings.warn(msg, Warning, 2) |
|
913 | warnings.warn(msg, Warning, 2) | |
898 | log.warning(msg) |
|
914 | log.warning(msg) | |
899 | log.debug("Returning JSON wrapped action output") |
|
915 | log.debug("Returning JSON wrapped action output") | |
900 | return json.dumps(data, encoding='utf-8') |
|
916 | return json.dumps(data, encoding='utf-8') | |
901 |
|
917 | |||
902 |
|
918 | |||
903 | class PartialRenderer(object): |
|
919 | class PartialRenderer(object): | |
904 | """ |
|
920 | """ | |
905 | Partial renderer used to render chunks of html used in datagrids |
|
921 | Partial renderer used to render chunks of html used in datagrids | |
906 | use like:: |
|
922 | use like:: | |
907 |
|
923 | |||
908 | _render = PartialRenderer('data_table/_dt_elements.mako') |
|
924 | _render = PartialRenderer('data_table/_dt_elements.mako') | |
909 | _render('quick_menu', args, kwargs) |
|
925 | _render('quick_menu', args, kwargs) | |
910 | PartialRenderer.h, |
|
926 | PartialRenderer.h, | |
911 | c, |
|
927 | c, | |
912 | _, |
|
928 | _, | |
913 | ungettext |
|
929 | ungettext | |
914 | are the template stuff initialized inside and can be re-used later |
|
930 | are the template stuff initialized inside and can be re-used later | |
915 |
|
931 | |||
916 | :param tmpl_name: template path relate to /templates/ dir |
|
932 | :param tmpl_name: template path relate to /templates/ dir | |
917 | """ |
|
933 | """ | |
918 |
|
934 | |||
919 | def __init__(self, tmpl_name): |
|
935 | def __init__(self, tmpl_name): | |
920 | import rhodecode |
|
936 | import rhodecode | |
921 | from pylons import request, tmpl_context as c |
|
937 | from pylons import request, tmpl_context as c | |
922 | from pylons.i18n.translation import _, ungettext |
|
938 | from pylons.i18n.translation import _, ungettext | |
923 | from rhodecode.lib import helpers as h |
|
939 | from rhodecode.lib import helpers as h | |
924 |
|
940 | |||
925 | self.tmpl_name = tmpl_name |
|
941 | self.tmpl_name = tmpl_name | |
926 | self.rhodecode = rhodecode |
|
942 | self.rhodecode = rhodecode | |
927 | self.c = c |
|
943 | self.c = c | |
928 | self._ = _ |
|
944 | self._ = _ | |
929 | self.ungettext = ungettext |
|
945 | self.ungettext = ungettext | |
930 | self.h = h |
|
946 | self.h = h | |
931 | self.request = request |
|
947 | self.request = request | |
932 |
|
948 | |||
933 | def _mako_lookup(self): |
|
949 | def _mako_lookup(self): | |
934 | _tmpl_lookup = self.rhodecode.CONFIG['pylons.app_globals'].mako_lookup |
|
950 | _tmpl_lookup = self.rhodecode.CONFIG['pylons.app_globals'].mako_lookup | |
935 | return _tmpl_lookup.get_template(self.tmpl_name) |
|
951 | return _tmpl_lookup.get_template(self.tmpl_name) | |
936 |
|
952 | |||
937 | def _update_kwargs_for_render(self, kwargs): |
|
953 | def _update_kwargs_for_render(self, kwargs): | |
938 | """ |
|
954 | """ | |
939 | Inject params required for Mako rendering |
|
955 | Inject params required for Mako rendering | |
940 | """ |
|
956 | """ | |
941 | _kwargs = { |
|
957 | _kwargs = { | |
942 | '_': self._, |
|
958 | '_': self._, | |
943 | 'h': self.h, |
|
959 | 'h': self.h, | |
944 | 'c': self.c, |
|
960 | 'c': self.c, | |
945 | 'request': self.request, |
|
961 | 'request': self.request, | |
946 | 'ungettext': self.ungettext, |
|
962 | 'ungettext': self.ungettext, | |
947 | } |
|
963 | } | |
948 | _kwargs.update(kwargs) |
|
964 | _kwargs.update(kwargs) | |
949 | return _kwargs |
|
965 | return _kwargs | |
950 |
|
966 | |||
951 | def _render_with_exc(self, render_func, args, kwargs): |
|
967 | def _render_with_exc(self, render_func, args, kwargs): | |
952 | try: |
|
968 | try: | |
953 | return render_func.render(*args, **kwargs) |
|
969 | return render_func.render(*args, **kwargs) | |
954 | except: |
|
970 | except: | |
955 | log.error(exceptions.text_error_template().render()) |
|
971 | log.error(exceptions.text_error_template().render()) | |
956 | raise |
|
972 | raise | |
957 |
|
973 | |||
958 | def _get_template(self, template_obj, def_name): |
|
974 | def _get_template(self, template_obj, def_name): | |
959 | if def_name: |
|
975 | if def_name: | |
960 | tmpl = template_obj.get_def(def_name) |
|
976 | tmpl = template_obj.get_def(def_name) | |
961 | else: |
|
977 | else: | |
962 | tmpl = template_obj |
|
978 | tmpl = template_obj | |
963 | return tmpl |
|
979 | return tmpl | |
964 |
|
980 | |||
965 | def render(self, def_name, *args, **kwargs): |
|
981 | def render(self, def_name, *args, **kwargs): | |
966 | lookup_obj = self._mako_lookup() |
|
982 | lookup_obj = self._mako_lookup() | |
967 | tmpl = self._get_template(lookup_obj, def_name=def_name) |
|
983 | tmpl = self._get_template(lookup_obj, def_name=def_name) | |
968 | kwargs = self._update_kwargs_for_render(kwargs) |
|
984 | kwargs = self._update_kwargs_for_render(kwargs) | |
969 | return self._render_with_exc(tmpl, args, kwargs) |
|
985 | return self._render_with_exc(tmpl, args, kwargs) | |
970 |
|
986 | |||
971 | def __call__(self, tmpl, *args, **kwargs): |
|
987 | def __call__(self, tmpl, *args, **kwargs): | |
972 | return self.render(tmpl, *args, **kwargs) |
|
988 | return self.render(tmpl, *args, **kwargs) | |
973 |
|
989 | |||
974 |
|
990 | |||
975 | def password_changed(auth_user, session): |
|
991 | def password_changed(auth_user, session): | |
976 | # Never report password change in case of default user or anonymous user. |
|
992 | # Never report password change in case of default user or anonymous user. | |
977 | if auth_user.username == User.DEFAULT_USER or auth_user.user_id is None: |
|
993 | if auth_user.username == User.DEFAULT_USER or auth_user.user_id is None: | |
978 | return False |
|
994 | return False | |
979 |
|
995 | |||
980 | password_hash = md5(auth_user.password) if auth_user.password else None |
|
996 | password_hash = md5(auth_user.password) if auth_user.password else None | |
981 | rhodecode_user = session.get('rhodecode_user', {}) |
|
997 | rhodecode_user = session.get('rhodecode_user', {}) | |
982 | session_password_hash = rhodecode_user.get('password', '') |
|
998 | session_password_hash = rhodecode_user.get('password', '') | |
983 | return password_hash != session_password_hash |
|
999 | return password_hash != session_password_hash | |
984 |
|
1000 | |||
985 |
|
1001 | |||
986 | def read_opensource_licenses(): |
|
1002 | def read_opensource_licenses(): | |
987 | global _license_cache |
|
1003 | global _license_cache | |
988 |
|
1004 | |||
989 | if not _license_cache: |
|
1005 | if not _license_cache: | |
990 | licenses = pkg_resources.resource_string( |
|
1006 | licenses = pkg_resources.resource_string( | |
991 | 'rhodecode', 'config/licenses.json') |
|
1007 | 'rhodecode', 'config/licenses.json') | |
992 | _license_cache = json.loads(licenses) |
|
1008 | _license_cache = json.loads(licenses) | |
993 |
|
1009 | |||
994 | return _license_cache |
|
1010 | return _license_cache | |
995 |
|
1011 | |||
996 |
|
1012 | |||
997 | def get_registry(request): |
|
1013 | def get_registry(request): | |
998 | """ |
|
1014 | """ | |
999 | Utility to get the pyramid registry from a request. During migration to |
|
1015 | Utility to get the pyramid registry from a request. During migration to | |
1000 | pyramid we sometimes want to use the pyramid registry from pylons context. |
|
1016 | pyramid we sometimes want to use the pyramid registry from pylons context. | |
1001 | Therefore this utility returns `request.registry` for pyramid requests and |
|
1017 | Therefore this utility returns `request.registry` for pyramid requests and | |
1002 | uses `get_current_registry()` for pylons requests. |
|
1018 | uses `get_current_registry()` for pylons requests. | |
1003 | """ |
|
1019 | """ | |
1004 | try: |
|
1020 | try: | |
1005 | return request.registry |
|
1021 | return request.registry | |
1006 | except AttributeError: |
|
1022 | except AttributeError: | |
1007 | return get_current_registry() |
|
1023 | return get_current_registry() | |
1008 |
|
1024 | |||
1009 |
|
1025 | |||
1010 | def generate_platform_uuid(): |
|
1026 | def generate_platform_uuid(): | |
1011 | """ |
|
1027 | """ | |
1012 | Generates platform UUID based on it's name |
|
1028 | Generates platform UUID based on it's name | |
1013 | """ |
|
1029 | """ | |
1014 | import platform |
|
1030 | import platform | |
1015 |
|
1031 | |||
1016 | try: |
|
1032 | try: | |
1017 | uuid_list = [platform.platform()] |
|
1033 | uuid_list = [platform.platform()] | |
1018 | return hashlib.sha256(':'.join(uuid_list)).hexdigest() |
|
1034 | return hashlib.sha256(':'.join(uuid_list)).hexdigest() | |
1019 | except Exception as e: |
|
1035 | except Exception as e: | |
1020 | log.error('Failed to generate host uuid: %s' % e) |
|
1036 | log.error('Failed to generate host uuid: %s' % e) | |
1021 | return 'UNDEFINED' |
|
1037 | return 'UNDEFINED' |
@@ -1,623 +1,620 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 pytest |
|
21 | import pytest | |
22 | from sqlalchemy.orm.exc import NoResultFound |
|
22 | from sqlalchemy.orm.exc import NoResultFound | |
23 |
|
23 | |||
24 | from rhodecode.lib.auth import check_password |
|
24 | from rhodecode.lib.auth import check_password | |
25 | from rhodecode.lib import helpers as h |
|
25 | from rhodecode.lib import helpers as h | |
26 | from rhodecode.model import validators |
|
26 | from rhodecode.model import validators | |
27 | from rhodecode.model.db import User, UserIpMap, UserApiKeys |
|
27 | from rhodecode.model.db import User, UserIpMap, UserApiKeys | |
28 | from rhodecode.model.meta import Session |
|
28 | from rhodecode.model.meta import Session | |
29 | from rhodecode.model.user import UserModel |
|
29 | from rhodecode.model.user import UserModel | |
30 | from rhodecode.tests import ( |
|
30 | from rhodecode.tests import ( | |
31 | TestController, url, link_to, TEST_USER_ADMIN_LOGIN, |
|
31 | TestController, url, link_to, TEST_USER_ADMIN_LOGIN, | |
32 | TEST_USER_REGULAR_LOGIN, assert_session_flash) |
|
32 | TEST_USER_REGULAR_LOGIN, assert_session_flash) | |
33 | from rhodecode.tests.fixture import Fixture |
|
33 | from rhodecode.tests.fixture import Fixture | |
34 | from rhodecode.tests.utils import AssertResponse |
|
34 | from rhodecode.tests.utils import AssertResponse | |
35 |
|
35 | |||
36 | fixture = Fixture() |
|
36 | fixture = Fixture() | |
37 |
|
37 | |||
38 |
|
38 | |||
39 | class TestAdminUsersController(TestController): |
|
39 | class TestAdminUsersController(TestController): | |
40 | test_user_1 = 'testme' |
|
40 | test_user_1 = 'testme' | |
41 | destroy_users = set() |
|
41 | destroy_users = set() | |
42 |
|
42 | |||
43 | @classmethod |
|
43 | @classmethod | |
44 | def teardown_method(cls, method): |
|
44 | def teardown_method(cls, method): | |
45 | fixture.destroy_users(cls.destroy_users) |
|
45 | fixture.destroy_users(cls.destroy_users) | |
46 |
|
46 | |||
47 | def test_index(self): |
|
47 | def test_index(self): | |
48 | self.log_user() |
|
48 | self.log_user() | |
49 | self.app.get(url('users')) |
|
49 | self.app.get(url('users')) | |
50 |
|
50 | |||
51 | def test_create(self): |
|
51 | def test_create(self): | |
52 | self.log_user() |
|
52 | self.log_user() | |
53 | username = 'newtestuser' |
|
53 | username = 'newtestuser' | |
54 | password = 'test12' |
|
54 | password = 'test12' | |
55 | password_confirmation = password |
|
55 | password_confirmation = password | |
56 | name = 'name' |
|
56 | name = 'name' | |
57 | lastname = 'lastname' |
|
57 | lastname = 'lastname' | |
58 | email = 'mail@mail.com' |
|
58 | email = 'mail@mail.com' | |
59 |
|
59 | |||
60 | response = self.app.get(url('new_user')) |
|
60 | response = self.app.get(url('new_user')) | |
61 |
|
61 | |||
62 | response = self.app.post(url('users'), params={ |
|
62 | response = self.app.post(url('users'), params={ | |
63 | 'username': username, |
|
63 | 'username': username, | |
64 | 'password': password, |
|
64 | 'password': password, | |
65 | 'password_confirmation': password_confirmation, |
|
65 | 'password_confirmation': password_confirmation, | |
66 | 'firstname': name, |
|
66 | 'firstname': name, | |
67 | 'active': True, |
|
67 | 'active': True, | |
68 | 'lastname': lastname, |
|
68 | 'lastname': lastname, | |
69 | 'extern_name': 'rhodecode', |
|
69 | 'extern_name': 'rhodecode', | |
70 | 'extern_type': 'rhodecode', |
|
70 | 'extern_type': 'rhodecode', | |
71 | 'email': email, |
|
71 | 'email': email, | |
72 | 'csrf_token': self.csrf_token, |
|
72 | 'csrf_token': self.csrf_token, | |
73 | }) |
|
73 | }) | |
74 | user_link = link_to( |
|
74 | user_link = link_to( | |
75 | username, |
|
75 | username, | |
76 | url('edit_user', user_id=User.get_by_username(username).user_id)) |
|
76 | url('edit_user', user_id=User.get_by_username(username).user_id)) | |
77 | assert_session_flash(response, 'Created user %s' % (user_link,)) |
|
77 | assert_session_flash(response, 'Created user %s' % (user_link,)) | |
78 | self.destroy_users.add(username) |
|
78 | self.destroy_users.add(username) | |
79 |
|
79 | |||
80 | new_user = User.query().filter(User.username == username).one() |
|
80 | new_user = User.query().filter(User.username == username).one() | |
81 |
|
81 | |||
82 | assert new_user.username == username |
|
82 | assert new_user.username == username | |
83 | assert check_password(password, new_user.password) |
|
83 | assert check_password(password, new_user.password) | |
84 | assert new_user.name == name |
|
84 | assert new_user.name == name | |
85 | assert new_user.lastname == lastname |
|
85 | assert new_user.lastname == lastname | |
86 | assert new_user.email == email |
|
86 | assert new_user.email == email | |
87 |
|
87 | |||
88 | response.follow() |
|
88 | response.follow() | |
89 | response = response.follow() |
|
89 | response = response.follow() | |
90 | response.mustcontain(username) |
|
90 | response.mustcontain(username) | |
91 |
|
91 | |||
92 | def test_create_err(self): |
|
92 | def test_create_err(self): | |
93 | self.log_user() |
|
93 | self.log_user() | |
94 | username = 'new_user' |
|
94 | username = 'new_user' | |
95 | password = '' |
|
95 | password = '' | |
96 | name = 'name' |
|
96 | name = 'name' | |
97 | lastname = 'lastname' |
|
97 | lastname = 'lastname' | |
98 | email = 'errmail.com' |
|
98 | email = 'errmail.com' | |
99 |
|
99 | |||
100 | response = self.app.get(url('new_user')) |
|
100 | response = self.app.get(url('new_user')) | |
101 |
|
101 | |||
102 | response = self.app.post(url('users'), params={ |
|
102 | response = self.app.post(url('users'), params={ | |
103 | 'username': username, |
|
103 | 'username': username, | |
104 | 'password': password, |
|
104 | 'password': password, | |
105 | 'name': name, |
|
105 | 'name': name, | |
106 | 'active': False, |
|
106 | 'active': False, | |
107 | 'lastname': lastname, |
|
107 | 'lastname': lastname, | |
108 | 'email': email, |
|
108 | 'email': email, | |
109 | 'csrf_token': self.csrf_token, |
|
109 | 'csrf_token': self.csrf_token, | |
110 | }) |
|
110 | }) | |
111 |
|
111 | |||
112 | msg = validators.ValidUsername( |
|
112 | msg = validators.ValidUsername( | |
113 | False, {})._messages['system_invalid_username'] |
|
113 | False, {})._messages['system_invalid_username'] | |
114 | msg = h.html_escape(msg % {'username': 'new_user'}) |
|
114 | msg = h.html_escape(msg % {'username': 'new_user'}) | |
115 | response.mustcontain('<span class="error-message">%s</span>' % msg) |
|
115 | response.mustcontain('<span class="error-message">%s</span>' % msg) | |
116 | response.mustcontain( |
|
116 | response.mustcontain( | |
117 | '<span class="error-message">Please enter a value</span>') |
|
117 | '<span class="error-message">Please enter a value</span>') | |
118 | response.mustcontain( |
|
118 | response.mustcontain( | |
119 | '<span class="error-message">An email address must contain a' |
|
119 | '<span class="error-message">An email address must contain a' | |
120 | ' single @</span>') |
|
120 | ' single @</span>') | |
121 |
|
121 | |||
122 | def get_user(): |
|
122 | def get_user(): | |
123 | Session().query(User).filter(User.username == username).one() |
|
123 | Session().query(User).filter(User.username == username).one() | |
124 |
|
124 | |||
125 | with pytest.raises(NoResultFound): |
|
125 | with pytest.raises(NoResultFound): | |
126 | get_user() |
|
126 | get_user() | |
127 |
|
127 | |||
128 | def test_new(self): |
|
128 | def test_new(self): | |
129 | self.log_user() |
|
129 | self.log_user() | |
130 | self.app.get(url('new_user')) |
|
130 | self.app.get(url('new_user')) | |
131 |
|
131 | |||
132 | @pytest.mark.parametrize("name, attrs", [ |
|
132 | @pytest.mark.parametrize("name, attrs", [ | |
133 | ('firstname', {'firstname': 'new_username'}), |
|
133 | ('firstname', {'firstname': 'new_username'}), | |
134 | ('lastname', {'lastname': 'new_username'}), |
|
134 | ('lastname', {'lastname': 'new_username'}), | |
135 | ('admin', {'admin': True}), |
|
135 | ('admin', {'admin': True}), | |
136 | ('admin', {'admin': False}), |
|
136 | ('admin', {'admin': False}), | |
137 | ('extern_type', {'extern_type': 'ldap'}), |
|
137 | ('extern_type', {'extern_type': 'ldap'}), | |
138 | ('extern_type', {'extern_type': None}), |
|
138 | ('extern_type', {'extern_type': None}), | |
139 | ('extern_name', {'extern_name': 'test'}), |
|
139 | ('extern_name', {'extern_name': 'test'}), | |
140 | ('extern_name', {'extern_name': None}), |
|
140 | ('extern_name', {'extern_name': None}), | |
141 | ('active', {'active': False}), |
|
141 | ('active', {'active': False}), | |
142 | ('active', {'active': True}), |
|
142 | ('active', {'active': True}), | |
143 | ('email', {'email': 'some@email.com'}), |
|
143 | ('email', {'email': 'some@email.com'}), | |
144 | ('language', {'language': 'de'}), |
|
144 | ('language', {'language': 'de'}), | |
145 | ('language', {'language': 'en'}), |
|
145 | ('language', {'language': 'en'}), | |
146 | # ('new_password', {'new_password': 'foobar123', |
|
146 | # ('new_password', {'new_password': 'foobar123', | |
147 | # 'password_confirmation': 'foobar123'}) |
|
147 | # 'password_confirmation': 'foobar123'}) | |
148 | ]) |
|
148 | ]) | |
149 | def test_update(self, name, attrs): |
|
149 | def test_update(self, name, attrs): | |
150 | self.log_user() |
|
150 | self.log_user() | |
151 | usr = fixture.create_user(self.test_user_1, password='qweqwe', |
|
151 | usr = fixture.create_user(self.test_user_1, password='qweqwe', | |
152 | email='testme@rhodecode.org', |
|
152 | email='testme@rhodecode.org', | |
153 | extern_type='rhodecode', |
|
153 | extern_type='rhodecode', | |
154 | extern_name=self.test_user_1, |
|
154 | extern_name=self.test_user_1, | |
155 | skip_if_exists=True) |
|
155 | skip_if_exists=True) | |
156 | Session().commit() |
|
156 | Session().commit() | |
157 | self.destroy_users.add(self.test_user_1) |
|
157 | self.destroy_users.add(self.test_user_1) | |
158 | params = usr.get_api_data() |
|
158 | params = usr.get_api_data() | |
159 | cur_lang = params['language'] or 'en' |
|
159 | cur_lang = params['language'] or 'en' | |
160 | params.update({ |
|
160 | params.update({ | |
161 | 'password_confirmation': '', |
|
161 | 'password_confirmation': '', | |
162 | 'new_password': '', |
|
162 | 'new_password': '', | |
163 | 'language': cur_lang, |
|
163 | 'language': cur_lang, | |
164 | '_method': 'put', |
|
164 | '_method': 'put', | |
165 | 'csrf_token': self.csrf_token, |
|
165 | 'csrf_token': self.csrf_token, | |
166 | }) |
|
166 | }) | |
167 | params.update({'new_password': ''}) |
|
167 | params.update({'new_password': ''}) | |
168 | params.update(attrs) |
|
168 | params.update(attrs) | |
169 | if name == 'email': |
|
169 | if name == 'email': | |
170 | params['emails'] = [attrs['email']] |
|
170 | params['emails'] = [attrs['email']] | |
171 | elif name == 'extern_type': |
|
171 | elif name == 'extern_type': | |
172 | # cannot update this via form, expected value is original one |
|
172 | # cannot update this via form, expected value is original one | |
173 | params['extern_type'] = "rhodecode" |
|
173 | params['extern_type'] = "rhodecode" | |
174 | elif name == 'extern_name': |
|
174 | elif name == 'extern_name': | |
175 | # cannot update this via form, expected value is original one |
|
175 | # cannot update this via form, expected value is original one | |
176 | params['extern_name'] = self.test_user_1 |
|
176 | params['extern_name'] = self.test_user_1 | |
177 | # special case since this user is not |
|
177 | # special case since this user is not | |
178 | # logged in yet his data is not filled |
|
178 | # logged in yet his data is not filled | |
179 | # so we use creation data |
|
179 | # so we use creation data | |
180 |
|
180 | |||
181 | response = self.app.post(url('user', user_id=usr.user_id), params) |
|
181 | response = self.app.post(url('user', user_id=usr.user_id), params) | |
182 | assert response.status_int == 302 |
|
182 | assert response.status_int == 302 | |
183 | assert_session_flash(response, 'User updated successfully') |
|
183 | assert_session_flash(response, 'User updated successfully') | |
184 |
|
184 | |||
185 | updated_user = User.get_by_username(self.test_user_1) |
|
185 | updated_user = User.get_by_username(self.test_user_1) | |
186 | updated_params = updated_user.get_api_data() |
|
186 | updated_params = updated_user.get_api_data() | |
187 | updated_params.update({'password_confirmation': ''}) |
|
187 | updated_params.update({'password_confirmation': ''}) | |
188 | updated_params.update({'new_password': ''}) |
|
188 | updated_params.update({'new_password': ''}) | |
189 |
|
189 | |||
190 | del params['_method'] |
|
190 | del params['_method'] | |
191 | del params['csrf_token'] |
|
191 | del params['csrf_token'] | |
192 | assert params == updated_params |
|
192 | assert params == updated_params | |
193 |
|
193 | |||
194 | def test_update_and_migrate_password( |
|
194 | def test_update_and_migrate_password( | |
195 | self, autologin_user, real_crypto_backend): |
|
195 | self, autologin_user, real_crypto_backend): | |
196 | from rhodecode.lib import auth |
|
196 | from rhodecode.lib import auth | |
197 |
|
197 | |||
198 | # create new user, with sha256 password |
|
198 | # create new user, with sha256 password | |
199 | temp_user = 'test_admin_sha256' |
|
199 | temp_user = 'test_admin_sha256' | |
200 | user = fixture.create_user(temp_user) |
|
200 | user = fixture.create_user(temp_user) | |
201 | user.password = auth._RhodeCodeCryptoSha256().hash_create( |
|
201 | user.password = auth._RhodeCodeCryptoSha256().hash_create( | |
202 | b'test123') |
|
202 | b'test123') | |
203 | Session().add(user) |
|
203 | Session().add(user) | |
204 | Session().commit() |
|
204 | Session().commit() | |
205 | self.destroy_users.add('test_admin_sha256') |
|
205 | self.destroy_users.add('test_admin_sha256') | |
206 |
|
206 | |||
207 | params = user.get_api_data() |
|
207 | params = user.get_api_data() | |
208 |
|
208 | |||
209 | params.update({ |
|
209 | params.update({ | |
210 | 'password_confirmation': 'qweqwe123', |
|
210 | 'password_confirmation': 'qweqwe123', | |
211 | 'new_password': 'qweqwe123', |
|
211 | 'new_password': 'qweqwe123', | |
212 | 'language': 'en', |
|
212 | 'language': 'en', | |
213 | '_method': 'put', |
|
213 | '_method': 'put', | |
214 | 'csrf_token': autologin_user.csrf_token, |
|
214 | 'csrf_token': autologin_user.csrf_token, | |
215 | }) |
|
215 | }) | |
216 |
|
216 | |||
217 | response = self.app.post(url('user', user_id=user.user_id), params) |
|
217 | response = self.app.post(url('user', user_id=user.user_id), params) | |
218 | assert response.status_int == 302 |
|
218 | assert response.status_int == 302 | |
219 | assert_session_flash(response, 'User updated successfully') |
|
219 | assert_session_flash(response, 'User updated successfully') | |
220 |
|
220 | |||
221 | # new password should be bcrypted, after log-in and transfer |
|
221 | # new password should be bcrypted, after log-in and transfer | |
222 | user = User.get_by_username(temp_user) |
|
222 | user = User.get_by_username(temp_user) | |
223 | assert user.password.startswith('$') |
|
223 | assert user.password.startswith('$') | |
224 |
|
224 | |||
225 | updated_user = User.get_by_username(temp_user) |
|
225 | updated_user = User.get_by_username(temp_user) | |
226 | updated_params = updated_user.get_api_data() |
|
226 | updated_params = updated_user.get_api_data() | |
227 | updated_params.update({'password_confirmation': 'qweqwe123'}) |
|
227 | updated_params.update({'password_confirmation': 'qweqwe123'}) | |
228 | updated_params.update({'new_password': 'qweqwe123'}) |
|
228 | updated_params.update({'new_password': 'qweqwe123'}) | |
229 |
|
229 | |||
230 | del params['_method'] |
|
230 | del params['_method'] | |
231 | del params['csrf_token'] |
|
231 | del params['csrf_token'] | |
232 | assert params == updated_params |
|
232 | assert params == updated_params | |
233 |
|
233 | |||
234 | def test_delete(self): |
|
234 | def test_delete(self): | |
235 | self.log_user() |
|
235 | self.log_user() | |
236 | username = 'newtestuserdeleteme' |
|
236 | username = 'newtestuserdeleteme' | |
237 |
|
237 | |||
238 | fixture.create_user(name=username) |
|
238 | fixture.create_user(name=username) | |
239 |
|
239 | |||
240 | new_user = Session().query(User)\ |
|
240 | new_user = Session().query(User)\ | |
241 | .filter(User.username == username).one() |
|
241 | .filter(User.username == username).one() | |
242 | response = self.app.post(url('user', user_id=new_user.user_id), |
|
242 | response = self.app.post(url('user', user_id=new_user.user_id), | |
243 | params={'_method': 'delete', |
|
243 | params={'_method': 'delete', | |
244 | 'csrf_token': self.csrf_token}) |
|
244 | 'csrf_token': self.csrf_token}) | |
245 |
|
245 | |||
246 | assert_session_flash(response, 'Successfully deleted user') |
|
246 | assert_session_flash(response, 'Successfully deleted user') | |
247 |
|
247 | |||
248 | def test_delete_owner_of_repository(self): |
|
248 | def test_delete_owner_of_repository(self): | |
249 | self.log_user() |
|
249 | self.log_user() | |
250 | username = 'newtestuserdeleteme_repo_owner' |
|
250 | username = 'newtestuserdeleteme_repo_owner' | |
251 | obj_name = 'test_repo' |
|
251 | obj_name = 'test_repo' | |
252 | usr = fixture.create_user(name=username) |
|
252 | usr = fixture.create_user(name=username) | |
253 | self.destroy_users.add(username) |
|
253 | self.destroy_users.add(username) | |
254 | fixture.create_repo(obj_name, cur_user=usr.username) |
|
254 | fixture.create_repo(obj_name, cur_user=usr.username) | |
255 |
|
255 | |||
256 | new_user = Session().query(User)\ |
|
256 | new_user = Session().query(User)\ | |
257 | .filter(User.username == username).one() |
|
257 | .filter(User.username == username).one() | |
258 | response = self.app.post(url('user', user_id=new_user.user_id), |
|
258 | response = self.app.post(url('user', user_id=new_user.user_id), | |
259 | params={'_method': 'delete', |
|
259 | params={'_method': 'delete', | |
260 | 'csrf_token': self.csrf_token}) |
|
260 | 'csrf_token': self.csrf_token}) | |
261 |
|
261 | |||
262 | msg = 'user "%s" still owns 1 repositories and cannot be removed. ' \ |
|
262 | msg = 'user "%s" still owns 1 repositories and cannot be removed. ' \ | |
263 | 'Switch owners or remove those repositories:%s' % (username, |
|
263 | 'Switch owners or remove those repositories:%s' % (username, | |
264 | obj_name) |
|
264 | obj_name) | |
265 | assert_session_flash(response, msg) |
|
265 | assert_session_flash(response, msg) | |
266 | fixture.destroy_repo(obj_name) |
|
266 | fixture.destroy_repo(obj_name) | |
267 |
|
267 | |||
268 | def test_delete_owner_of_repository_detaching(self): |
|
268 | def test_delete_owner_of_repository_detaching(self): | |
269 | self.log_user() |
|
269 | self.log_user() | |
270 | username = 'newtestuserdeleteme_repo_owner_detach' |
|
270 | username = 'newtestuserdeleteme_repo_owner_detach' | |
271 | obj_name = 'test_repo' |
|
271 | obj_name = 'test_repo' | |
272 | usr = fixture.create_user(name=username) |
|
272 | usr = fixture.create_user(name=username) | |
273 | self.destroy_users.add(username) |
|
273 | self.destroy_users.add(username) | |
274 | fixture.create_repo(obj_name, cur_user=usr.username) |
|
274 | fixture.create_repo(obj_name, cur_user=usr.username) | |
275 |
|
275 | |||
276 | new_user = Session().query(User)\ |
|
276 | new_user = Session().query(User)\ | |
277 | .filter(User.username == username).one() |
|
277 | .filter(User.username == username).one() | |
278 | response = self.app.post(url('user', user_id=new_user.user_id), |
|
278 | response = self.app.post(url('user', user_id=new_user.user_id), | |
279 | params={'_method': 'delete', |
|
279 | params={'_method': 'delete', | |
280 | 'user_repos': 'detach', |
|
280 | 'user_repos': 'detach', | |
281 | 'csrf_token': self.csrf_token}) |
|
281 | 'csrf_token': self.csrf_token}) | |
282 |
|
282 | |||
283 | msg = 'Detached 1 repositories' |
|
283 | msg = 'Detached 1 repositories' | |
284 | assert_session_flash(response, msg) |
|
284 | assert_session_flash(response, msg) | |
285 | fixture.destroy_repo(obj_name) |
|
285 | fixture.destroy_repo(obj_name) | |
286 |
|
286 | |||
287 | def test_delete_owner_of_repository_deleting(self): |
|
287 | def test_delete_owner_of_repository_deleting(self): | |
288 | self.log_user() |
|
288 | self.log_user() | |
289 | username = 'newtestuserdeleteme_repo_owner_delete' |
|
289 | username = 'newtestuserdeleteme_repo_owner_delete' | |
290 | obj_name = 'test_repo' |
|
290 | obj_name = 'test_repo' | |
291 | usr = fixture.create_user(name=username) |
|
291 | usr = fixture.create_user(name=username) | |
292 | self.destroy_users.add(username) |
|
292 | self.destroy_users.add(username) | |
293 | fixture.create_repo(obj_name, cur_user=usr.username) |
|
293 | fixture.create_repo(obj_name, cur_user=usr.username) | |
294 |
|
294 | |||
295 | new_user = Session().query(User)\ |
|
295 | new_user = Session().query(User)\ | |
296 | .filter(User.username == username).one() |
|
296 | .filter(User.username == username).one() | |
297 | response = self.app.post(url('user', user_id=new_user.user_id), |
|
297 | response = self.app.post(url('user', user_id=new_user.user_id), | |
298 | params={'_method': 'delete', |
|
298 | params={'_method': 'delete', | |
299 | 'user_repos': 'delete', |
|
299 | 'user_repos': 'delete', | |
300 | 'csrf_token': self.csrf_token}) |
|
300 | 'csrf_token': self.csrf_token}) | |
301 |
|
301 | |||
302 | msg = 'Deleted 1 repositories' |
|
302 | msg = 'Deleted 1 repositories' | |
303 | assert_session_flash(response, msg) |
|
303 | assert_session_flash(response, msg) | |
304 |
|
304 | |||
305 | def test_delete_owner_of_repository_group(self): |
|
305 | def test_delete_owner_of_repository_group(self): | |
306 | self.log_user() |
|
306 | self.log_user() | |
307 | username = 'newtestuserdeleteme_repo_group_owner' |
|
307 | username = 'newtestuserdeleteme_repo_group_owner' | |
308 | obj_name = 'test_group' |
|
308 | obj_name = 'test_group' | |
309 | usr = fixture.create_user(name=username) |
|
309 | usr = fixture.create_user(name=username) | |
310 | self.destroy_users.add(username) |
|
310 | self.destroy_users.add(username) | |
311 | fixture.create_repo_group(obj_name, cur_user=usr.username) |
|
311 | fixture.create_repo_group(obj_name, cur_user=usr.username) | |
312 |
|
312 | |||
313 | new_user = Session().query(User)\ |
|
313 | new_user = Session().query(User)\ | |
314 | .filter(User.username == username).one() |
|
314 | .filter(User.username == username).one() | |
315 | response = self.app.post(url('user', user_id=new_user.user_id), |
|
315 | response = self.app.post(url('user', user_id=new_user.user_id), | |
316 | params={'_method': 'delete', |
|
316 | params={'_method': 'delete', | |
317 | 'csrf_token': self.csrf_token}) |
|
317 | 'csrf_token': self.csrf_token}) | |
318 |
|
318 | |||
319 | msg = 'user "%s" still owns 1 repository groups and cannot be removed. ' \ |
|
319 | msg = 'user "%s" still owns 1 repository groups and cannot be removed. ' \ | |
320 | 'Switch owners or remove those repository groups:%s' % (username, |
|
320 | 'Switch owners or remove those repository groups:%s' % (username, | |
321 | obj_name) |
|
321 | obj_name) | |
322 | assert_session_flash(response, msg) |
|
322 | assert_session_flash(response, msg) | |
323 | fixture.destroy_repo_group(obj_name) |
|
323 | fixture.destroy_repo_group(obj_name) | |
324 |
|
324 | |||
325 | def test_delete_owner_of_repository_group_detaching(self): |
|
325 | def test_delete_owner_of_repository_group_detaching(self): | |
326 | self.log_user() |
|
326 | self.log_user() | |
327 | username = 'newtestuserdeleteme_repo_group_owner_detach' |
|
327 | username = 'newtestuserdeleteme_repo_group_owner_detach' | |
328 | obj_name = 'test_group' |
|
328 | obj_name = 'test_group' | |
329 | usr = fixture.create_user(name=username) |
|
329 | usr = fixture.create_user(name=username) | |
330 | self.destroy_users.add(username) |
|
330 | self.destroy_users.add(username) | |
331 | fixture.create_repo_group(obj_name, cur_user=usr.username) |
|
331 | fixture.create_repo_group(obj_name, cur_user=usr.username) | |
332 |
|
332 | |||
333 | new_user = Session().query(User)\ |
|
333 | new_user = Session().query(User)\ | |
334 | .filter(User.username == username).one() |
|
334 | .filter(User.username == username).one() | |
335 | response = self.app.post(url('user', user_id=new_user.user_id), |
|
335 | response = self.app.post(url('user', user_id=new_user.user_id), | |
336 | params={'_method': 'delete', |
|
336 | params={'_method': 'delete', | |
337 | 'user_repo_groups': 'delete', |
|
337 | 'user_repo_groups': 'delete', | |
338 | 'csrf_token': self.csrf_token}) |
|
338 | 'csrf_token': self.csrf_token}) | |
339 |
|
339 | |||
340 | msg = 'Deleted 1 repository groups' |
|
340 | msg = 'Deleted 1 repository groups' | |
341 | assert_session_flash(response, msg) |
|
341 | assert_session_flash(response, msg) | |
342 |
|
342 | |||
343 | def test_delete_owner_of_repository_group_deleting(self): |
|
343 | def test_delete_owner_of_repository_group_deleting(self): | |
344 | self.log_user() |
|
344 | self.log_user() | |
345 | username = 'newtestuserdeleteme_repo_group_owner_delete' |
|
345 | username = 'newtestuserdeleteme_repo_group_owner_delete' | |
346 | obj_name = 'test_group' |
|
346 | obj_name = 'test_group' | |
347 | usr = fixture.create_user(name=username) |
|
347 | usr = fixture.create_user(name=username) | |
348 | self.destroy_users.add(username) |
|
348 | self.destroy_users.add(username) | |
349 | fixture.create_repo_group(obj_name, cur_user=usr.username) |
|
349 | fixture.create_repo_group(obj_name, cur_user=usr.username) | |
350 |
|
350 | |||
351 | new_user = Session().query(User)\ |
|
351 | new_user = Session().query(User)\ | |
352 | .filter(User.username == username).one() |
|
352 | .filter(User.username == username).one() | |
353 | response = self.app.post(url('user', user_id=new_user.user_id), |
|
353 | response = self.app.post(url('user', user_id=new_user.user_id), | |
354 | params={'_method': 'delete', |
|
354 | params={'_method': 'delete', | |
355 | 'user_repo_groups': 'detach', |
|
355 | 'user_repo_groups': 'detach', | |
356 | 'csrf_token': self.csrf_token}) |
|
356 | 'csrf_token': self.csrf_token}) | |
357 |
|
357 | |||
358 | msg = 'Detached 1 repository groups' |
|
358 | msg = 'Detached 1 repository groups' | |
359 | assert_session_flash(response, msg) |
|
359 | assert_session_flash(response, msg) | |
360 | fixture.destroy_repo_group(obj_name) |
|
360 | fixture.destroy_repo_group(obj_name) | |
361 |
|
361 | |||
362 | def test_delete_owner_of_user_group(self): |
|
362 | def test_delete_owner_of_user_group(self): | |
363 | self.log_user() |
|
363 | self.log_user() | |
364 | username = 'newtestuserdeleteme_user_group_owner' |
|
364 | username = 'newtestuserdeleteme_user_group_owner' | |
365 | obj_name = 'test_user_group' |
|
365 | obj_name = 'test_user_group' | |
366 | usr = fixture.create_user(name=username) |
|
366 | usr = fixture.create_user(name=username) | |
367 | self.destroy_users.add(username) |
|
367 | self.destroy_users.add(username) | |
368 | fixture.create_user_group(obj_name, cur_user=usr.username) |
|
368 | fixture.create_user_group(obj_name, cur_user=usr.username) | |
369 |
|
369 | |||
370 | new_user = Session().query(User)\ |
|
370 | new_user = Session().query(User)\ | |
371 | .filter(User.username == username).one() |
|
371 | .filter(User.username == username).one() | |
372 | response = self.app.post(url('user', user_id=new_user.user_id), |
|
372 | response = self.app.post(url('user', user_id=new_user.user_id), | |
373 | params={'_method': 'delete', |
|
373 | params={'_method': 'delete', | |
374 | 'csrf_token': self.csrf_token}) |
|
374 | 'csrf_token': self.csrf_token}) | |
375 |
|
375 | |||
376 | msg = 'user "%s" still owns 1 user groups and cannot be removed. ' \ |
|
376 | msg = 'user "%s" still owns 1 user groups and cannot be removed. ' \ | |
377 | 'Switch owners or remove those user groups:%s' % (username, |
|
377 | 'Switch owners or remove those user groups:%s' % (username, | |
378 | obj_name) |
|
378 | obj_name) | |
379 | assert_session_flash(response, msg) |
|
379 | assert_session_flash(response, msg) | |
380 | fixture.destroy_user_group(obj_name) |
|
380 | fixture.destroy_user_group(obj_name) | |
381 |
|
381 | |||
382 | def test_delete_owner_of_user_group_detaching(self): |
|
382 | def test_delete_owner_of_user_group_detaching(self): | |
383 | self.log_user() |
|
383 | self.log_user() | |
384 | username = 'newtestuserdeleteme_user_group_owner_detaching' |
|
384 | username = 'newtestuserdeleteme_user_group_owner_detaching' | |
385 | obj_name = 'test_user_group' |
|
385 | obj_name = 'test_user_group' | |
386 | usr = fixture.create_user(name=username) |
|
386 | usr = fixture.create_user(name=username) | |
387 | self.destroy_users.add(username) |
|
387 | self.destroy_users.add(username) | |
388 | fixture.create_user_group(obj_name, cur_user=usr.username) |
|
388 | fixture.create_user_group(obj_name, cur_user=usr.username) | |
389 |
|
389 | |||
390 | new_user = Session().query(User)\ |
|
390 | new_user = Session().query(User)\ | |
391 | .filter(User.username == username).one() |
|
391 | .filter(User.username == username).one() | |
392 | try: |
|
392 | try: | |
393 | response = self.app.post(url('user', user_id=new_user.user_id), |
|
393 | response = self.app.post(url('user', user_id=new_user.user_id), | |
394 | params={'_method': 'delete', |
|
394 | params={'_method': 'delete', | |
395 | 'user_user_groups': 'detach', |
|
395 | 'user_user_groups': 'detach', | |
396 | 'csrf_token': self.csrf_token}) |
|
396 | 'csrf_token': self.csrf_token}) | |
397 |
|
397 | |||
398 | msg = 'Detached 1 user groups' |
|
398 | msg = 'Detached 1 user groups' | |
399 | assert_session_flash(response, msg) |
|
399 | assert_session_flash(response, msg) | |
400 | finally: |
|
400 | finally: | |
401 | fixture.destroy_user_group(obj_name) |
|
401 | fixture.destroy_user_group(obj_name) | |
402 |
|
402 | |||
403 | def test_delete_owner_of_user_group_deleting(self): |
|
403 | def test_delete_owner_of_user_group_deleting(self): | |
404 | self.log_user() |
|
404 | self.log_user() | |
405 | username = 'newtestuserdeleteme_user_group_owner_deleting' |
|
405 | username = 'newtestuserdeleteme_user_group_owner_deleting' | |
406 | obj_name = 'test_user_group' |
|
406 | obj_name = 'test_user_group' | |
407 | usr = fixture.create_user(name=username) |
|
407 | usr = fixture.create_user(name=username) | |
408 | self.destroy_users.add(username) |
|
408 | self.destroy_users.add(username) | |
409 | fixture.create_user_group(obj_name, cur_user=usr.username) |
|
409 | fixture.create_user_group(obj_name, cur_user=usr.username) | |
410 |
|
410 | |||
411 | new_user = Session().query(User)\ |
|
411 | new_user = Session().query(User)\ | |
412 | .filter(User.username == username).one() |
|
412 | .filter(User.username == username).one() | |
413 | response = self.app.post(url('user', user_id=new_user.user_id), |
|
413 | response = self.app.post(url('user', user_id=new_user.user_id), | |
414 | params={'_method': 'delete', |
|
414 | params={'_method': 'delete', | |
415 | 'user_user_groups': 'delete', |
|
415 | 'user_user_groups': 'delete', | |
416 | 'csrf_token': self.csrf_token}) |
|
416 | 'csrf_token': self.csrf_token}) | |
417 |
|
417 | |||
418 | msg = 'Deleted 1 user groups' |
|
418 | msg = 'Deleted 1 user groups' | |
419 | assert_session_flash(response, msg) |
|
419 | assert_session_flash(response, msg) | |
420 |
|
420 | |||
421 | def test_show(self): |
|
|||
422 | self.app.get(url('user', user_id=1)) |
|
|||
423 |
|
||||
424 | def test_edit(self): |
|
421 | def test_edit(self): | |
425 | self.log_user() |
|
422 | self.log_user() | |
426 | user = User.get_by_username(TEST_USER_ADMIN_LOGIN) |
|
423 | user = User.get_by_username(TEST_USER_ADMIN_LOGIN) | |
427 | self.app.get(url('edit_user', user_id=user.user_id)) |
|
424 | self.app.get(url('edit_user', user_id=user.user_id)) | |
428 |
|
425 | |||
429 | @pytest.mark.parametrize( |
|
426 | @pytest.mark.parametrize( | |
430 | 'repo_create, repo_create_write, user_group_create, repo_group_create,' |
|
427 | 'repo_create, repo_create_write, user_group_create, repo_group_create,' | |
431 | 'fork_create, inherit_default_permissions, expect_error,' |
|
428 | 'fork_create, inherit_default_permissions, expect_error,' | |
432 | 'expect_form_error', [ |
|
429 | 'expect_form_error', [ | |
433 | ('hg.create.none', 'hg.create.write_on_repogroup.false', |
|
430 | ('hg.create.none', 'hg.create.write_on_repogroup.false', | |
434 | 'hg.usergroup.create.false', 'hg.repogroup.create.false', |
|
431 | 'hg.usergroup.create.false', 'hg.repogroup.create.false', | |
435 | 'hg.fork.none', 'hg.inherit_default_perms.false', False, False), |
|
432 | 'hg.fork.none', 'hg.inherit_default_perms.false', False, False), | |
436 | ('hg.create.repository', 'hg.create.write_on_repogroup.false', |
|
433 | ('hg.create.repository', 'hg.create.write_on_repogroup.false', | |
437 | 'hg.usergroup.create.false', 'hg.repogroup.create.false', |
|
434 | 'hg.usergroup.create.false', 'hg.repogroup.create.false', | |
438 | 'hg.fork.none', 'hg.inherit_default_perms.false', False, False), |
|
435 | 'hg.fork.none', 'hg.inherit_default_perms.false', False, False), | |
439 | ('hg.create.repository', 'hg.create.write_on_repogroup.true', |
|
436 | ('hg.create.repository', 'hg.create.write_on_repogroup.true', | |
440 | 'hg.usergroup.create.true', 'hg.repogroup.create.true', |
|
437 | 'hg.usergroup.create.true', 'hg.repogroup.create.true', | |
441 | 'hg.fork.repository', 'hg.inherit_default_perms.false', False, |
|
438 | 'hg.fork.repository', 'hg.inherit_default_perms.false', False, | |
442 | False), |
|
439 | False), | |
443 | ('hg.create.XXX', 'hg.create.write_on_repogroup.true', |
|
440 | ('hg.create.XXX', 'hg.create.write_on_repogroup.true', | |
444 | 'hg.usergroup.create.true', 'hg.repogroup.create.true', |
|
441 | 'hg.usergroup.create.true', 'hg.repogroup.create.true', | |
445 | 'hg.fork.repository', 'hg.inherit_default_perms.false', False, |
|
442 | 'hg.fork.repository', 'hg.inherit_default_perms.false', False, | |
446 | True), |
|
443 | True), | |
447 | ('', '', '', '', '', '', True, False), |
|
444 | ('', '', '', '', '', '', True, False), | |
448 | ]) |
|
445 | ]) | |
449 | def test_global_perms_on_user( |
|
446 | def test_global_perms_on_user( | |
450 | self, repo_create, repo_create_write, user_group_create, |
|
447 | self, repo_create, repo_create_write, user_group_create, | |
451 | repo_group_create, fork_create, expect_error, expect_form_error, |
|
448 | repo_group_create, fork_create, expect_error, expect_form_error, | |
452 | inherit_default_permissions): |
|
449 | inherit_default_permissions): | |
453 | self.log_user() |
|
450 | self.log_user() | |
454 | user = fixture.create_user('dummy') |
|
451 | user = fixture.create_user('dummy') | |
455 | uid = user.user_id |
|
452 | uid = user.user_id | |
456 |
|
453 | |||
457 | # ENABLE REPO CREATE ON A GROUP |
|
454 | # ENABLE REPO CREATE ON A GROUP | |
458 | perm_params = { |
|
455 | perm_params = { | |
459 | 'inherit_default_permissions': False, |
|
456 | 'inherit_default_permissions': False, | |
460 | 'default_repo_create': repo_create, |
|
457 | 'default_repo_create': repo_create, | |
461 | 'default_repo_create_on_write': repo_create_write, |
|
458 | 'default_repo_create_on_write': repo_create_write, | |
462 | 'default_user_group_create': user_group_create, |
|
459 | 'default_user_group_create': user_group_create, | |
463 | 'default_repo_group_create': repo_group_create, |
|
460 | 'default_repo_group_create': repo_group_create, | |
464 | 'default_fork_create': fork_create, |
|
461 | 'default_fork_create': fork_create, | |
465 | 'default_inherit_default_permissions': inherit_default_permissions, |
|
462 | 'default_inherit_default_permissions': inherit_default_permissions, | |
466 | '_method': 'put', |
|
463 | '_method': 'put', | |
467 | 'csrf_token': self.csrf_token, |
|
464 | 'csrf_token': self.csrf_token, | |
468 | } |
|
465 | } | |
469 | response = self.app.post( |
|
466 | response = self.app.post( | |
470 | url('edit_user_global_perms', user_id=uid), |
|
467 | url('edit_user_global_perms', user_id=uid), | |
471 | params=perm_params) |
|
468 | params=perm_params) | |
472 |
|
469 | |||
473 | if expect_form_error: |
|
470 | if expect_form_error: | |
474 | assert response.status_int == 200 |
|
471 | assert response.status_int == 200 | |
475 | response.mustcontain('Value must be one of') |
|
472 | response.mustcontain('Value must be one of') | |
476 | else: |
|
473 | else: | |
477 | if expect_error: |
|
474 | if expect_error: | |
478 | msg = 'An error occurred during permissions saving' |
|
475 | msg = 'An error occurred during permissions saving' | |
479 | else: |
|
476 | else: | |
480 | msg = 'User global permissions updated successfully' |
|
477 | msg = 'User global permissions updated successfully' | |
481 | ug = User.get(uid) |
|
478 | ug = User.get(uid) | |
482 | del perm_params['_method'] |
|
479 | del perm_params['_method'] | |
483 | del perm_params['inherit_default_permissions'] |
|
480 | del perm_params['inherit_default_permissions'] | |
484 | del perm_params['csrf_token'] |
|
481 | del perm_params['csrf_token'] | |
485 | assert perm_params == ug.get_default_perms() |
|
482 | assert perm_params == ug.get_default_perms() | |
486 | assert_session_flash(response, msg) |
|
483 | assert_session_flash(response, msg) | |
487 | fixture.destroy_user(uid) |
|
484 | fixture.destroy_user(uid) | |
488 |
|
485 | |||
489 | def test_global_permissions_initial_values(self, user_util): |
|
486 | def test_global_permissions_initial_values(self, user_util): | |
490 | self.log_user() |
|
487 | self.log_user() | |
491 | user = user_util.create_user() |
|
488 | user = user_util.create_user() | |
492 | uid = user.user_id |
|
489 | uid = user.user_id | |
493 | response = self.app.get(url('edit_user_global_perms', user_id=uid)) |
|
490 | response = self.app.get(url('edit_user_global_perms', user_id=uid)) | |
494 | default_user = User.get_default_user() |
|
491 | default_user = User.get_default_user() | |
495 | default_permissions = default_user.get_default_perms() |
|
492 | default_permissions = default_user.get_default_perms() | |
496 | assert_response = AssertResponse(response) |
|
493 | assert_response = AssertResponse(response) | |
497 | expected_permissions = ( |
|
494 | expected_permissions = ( | |
498 | 'default_repo_create', 'default_repo_create_on_write', |
|
495 | 'default_repo_create', 'default_repo_create_on_write', | |
499 | 'default_fork_create', 'default_repo_group_create', |
|
496 | 'default_fork_create', 'default_repo_group_create', | |
500 | 'default_user_group_create', 'default_inherit_default_permissions') |
|
497 | 'default_user_group_create', 'default_inherit_default_permissions') | |
501 | for permission in expected_permissions: |
|
498 | for permission in expected_permissions: | |
502 | css_selector = '[name={}][checked=checked]'.format(permission) |
|
499 | css_selector = '[name={}][checked=checked]'.format(permission) | |
503 | element = assert_response.get_element(css_selector) |
|
500 | element = assert_response.get_element(css_selector) | |
504 | assert element.value == default_permissions[permission] |
|
501 | assert element.value == default_permissions[permission] | |
505 |
|
502 | |||
506 | def test_ips(self): |
|
503 | def test_ips(self): | |
507 | self.log_user() |
|
504 | self.log_user() | |
508 | user = User.get_by_username(TEST_USER_REGULAR_LOGIN) |
|
505 | user = User.get_by_username(TEST_USER_REGULAR_LOGIN) | |
509 | response = self.app.get(url('edit_user_ips', user_id=user.user_id)) |
|
506 | response = self.app.get(url('edit_user_ips', user_id=user.user_id)) | |
510 | response.mustcontain('All IP addresses are allowed') |
|
507 | response.mustcontain('All IP addresses are allowed') | |
511 |
|
508 | |||
512 | @pytest.mark.parametrize("test_name, ip, ip_range, failure", [ |
|
509 | @pytest.mark.parametrize("test_name, ip, ip_range, failure", [ | |
513 | ('127/24', '127.0.0.1/24', '127.0.0.0 - 127.0.0.255', False), |
|
510 | ('127/24', '127.0.0.1/24', '127.0.0.0 - 127.0.0.255', False), | |
514 | ('10/32', '10.0.0.10/32', '10.0.0.10 - 10.0.0.10', False), |
|
511 | ('10/32', '10.0.0.10/32', '10.0.0.10 - 10.0.0.10', False), | |
515 | ('0/16', '0.0.0.0/16', '0.0.0.0 - 0.0.255.255', False), |
|
512 | ('0/16', '0.0.0.0/16', '0.0.0.0 - 0.0.255.255', False), | |
516 | ('0/8', '0.0.0.0/8', '0.0.0.0 - 0.255.255.255', False), |
|
513 | ('0/8', '0.0.0.0/8', '0.0.0.0 - 0.255.255.255', False), | |
517 | ('127_bad_mask', '127.0.0.1/99', '127.0.0.1 - 127.0.0.1', True), |
|
514 | ('127_bad_mask', '127.0.0.1/99', '127.0.0.1 - 127.0.0.1', True), | |
518 | ('127_bad_ip', 'foobar', 'foobar', True), |
|
515 | ('127_bad_ip', 'foobar', 'foobar', True), | |
519 | ]) |
|
516 | ]) | |
520 | def test_add_ip(self, test_name, ip, ip_range, failure): |
|
517 | def test_add_ip(self, test_name, ip, ip_range, failure): | |
521 | self.log_user() |
|
518 | self.log_user() | |
522 | user = User.get_by_username(TEST_USER_REGULAR_LOGIN) |
|
519 | user = User.get_by_username(TEST_USER_REGULAR_LOGIN) | |
523 | user_id = user.user_id |
|
520 | user_id = user.user_id | |
524 |
|
521 | |||
525 | response = self.app.post(url('edit_user_ips', user_id=user_id), |
|
522 | response = self.app.post(url('edit_user_ips', user_id=user_id), | |
526 | params={'new_ip': ip, '_method': 'put', |
|
523 | params={'new_ip': ip, '_method': 'put', | |
527 | 'csrf_token': self.csrf_token}) |
|
524 | 'csrf_token': self.csrf_token}) | |
528 |
|
525 | |||
529 | if failure: |
|
526 | if failure: | |
530 | assert_session_flash( |
|
527 | assert_session_flash( | |
531 | response, 'Please enter a valid IPv4 or IpV6 address') |
|
528 | response, 'Please enter a valid IPv4 or IpV6 address') | |
532 | response = self.app.get(url('edit_user_ips', user_id=user_id)) |
|
529 | response = self.app.get(url('edit_user_ips', user_id=user_id)) | |
533 | response.mustcontain(no=[ip]) |
|
530 | response.mustcontain(no=[ip]) | |
534 | response.mustcontain(no=[ip_range]) |
|
531 | response.mustcontain(no=[ip_range]) | |
535 |
|
532 | |||
536 | else: |
|
533 | else: | |
537 | response = self.app.get(url('edit_user_ips', user_id=user_id)) |
|
534 | response = self.app.get(url('edit_user_ips', user_id=user_id)) | |
538 | response.mustcontain(ip) |
|
535 | response.mustcontain(ip) | |
539 | response.mustcontain(ip_range) |
|
536 | response.mustcontain(ip_range) | |
540 |
|
537 | |||
541 | # cleanup |
|
538 | # cleanup | |
542 | for del_ip in UserIpMap.query().filter( |
|
539 | for del_ip in UserIpMap.query().filter( | |
543 | UserIpMap.user_id == user_id).all(): |
|
540 | UserIpMap.user_id == user_id).all(): | |
544 | Session().delete(del_ip) |
|
541 | Session().delete(del_ip) | |
545 | Session().commit() |
|
542 | Session().commit() | |
546 |
|
543 | |||
547 | def test_delete_ip(self): |
|
544 | def test_delete_ip(self): | |
548 | self.log_user() |
|
545 | self.log_user() | |
549 | user = User.get_by_username(TEST_USER_REGULAR_LOGIN) |
|
546 | user = User.get_by_username(TEST_USER_REGULAR_LOGIN) | |
550 | user_id = user.user_id |
|
547 | user_id = user.user_id | |
551 | ip = '127.0.0.1/32' |
|
548 | ip = '127.0.0.1/32' | |
552 | ip_range = '127.0.0.1 - 127.0.0.1' |
|
549 | ip_range = '127.0.0.1 - 127.0.0.1' | |
553 | new_ip = UserModel().add_extra_ip(user_id, ip) |
|
550 | new_ip = UserModel().add_extra_ip(user_id, ip) | |
554 | Session().commit() |
|
551 | Session().commit() | |
555 | new_ip_id = new_ip.ip_id |
|
552 | new_ip_id = new_ip.ip_id | |
556 |
|
553 | |||
557 | response = self.app.get(url('edit_user_ips', user_id=user_id)) |
|
554 | response = self.app.get(url('edit_user_ips', user_id=user_id)) | |
558 | response.mustcontain(ip) |
|
555 | response.mustcontain(ip) | |
559 | response.mustcontain(ip_range) |
|
556 | response.mustcontain(ip_range) | |
560 |
|
557 | |||
561 | self.app.post(url('edit_user_ips', user_id=user_id), |
|
558 | self.app.post(url('edit_user_ips', user_id=user_id), | |
562 | params={'_method': 'delete', 'del_ip_id': new_ip_id, |
|
559 | params={'_method': 'delete', 'del_ip_id': new_ip_id, | |
563 | 'csrf_token': self.csrf_token}) |
|
560 | 'csrf_token': self.csrf_token}) | |
564 |
|
561 | |||
565 | response = self.app.get(url('edit_user_ips', user_id=user_id)) |
|
562 | response = self.app.get(url('edit_user_ips', user_id=user_id)) | |
566 | response.mustcontain('All IP addresses are allowed') |
|
563 | response.mustcontain('All IP addresses are allowed') | |
567 | response.mustcontain(no=[ip]) |
|
564 | response.mustcontain(no=[ip]) | |
568 | response.mustcontain(no=[ip_range]) |
|
565 | response.mustcontain(no=[ip_range]) | |
569 |
|
566 | |||
570 | def test_auth_tokens(self): |
|
567 | def test_auth_tokens(self): | |
571 | self.log_user() |
|
568 | self.log_user() | |
572 |
|
569 | |||
573 | user = User.get_by_username(TEST_USER_REGULAR_LOGIN) |
|
570 | user = User.get_by_username(TEST_USER_REGULAR_LOGIN) | |
574 | response = self.app.get( |
|
571 | response = self.app.get( | |
575 | url('edit_user_auth_tokens', user_id=user.user_id)) |
|
572 | url('edit_user_auth_tokens', user_id=user.user_id)) | |
576 | for token in user.auth_tokens: |
|
573 | for token in user.auth_tokens: | |
577 | response.mustcontain(token) |
|
574 | response.mustcontain(token) | |
578 | response.mustcontain('never') |
|
575 | response.mustcontain('never') | |
579 |
|
576 | |||
580 | @pytest.mark.parametrize("desc, lifetime", [ |
|
577 | @pytest.mark.parametrize("desc, lifetime", [ | |
581 | ('forever', -1), |
|
578 | ('forever', -1), | |
582 | ('5mins', 60*5), |
|
579 | ('5mins', 60*5), | |
583 | ('30days', 60*60*24*30), |
|
580 | ('30days', 60*60*24*30), | |
584 | ]) |
|
581 | ]) | |
585 | def test_add_auth_token(self, desc, lifetime, user_util): |
|
582 | def test_add_auth_token(self, desc, lifetime, user_util): | |
586 | self.log_user() |
|
583 | self.log_user() | |
587 | user = user_util.create_user() |
|
584 | user = user_util.create_user() | |
588 | user_id = user.user_id |
|
585 | user_id = user.user_id | |
589 |
|
586 | |||
590 | response = self.app.post( |
|
587 | response = self.app.post( | |
591 | url('edit_user_auth_tokens', user_id=user_id), |
|
588 | url('edit_user_auth_tokens', user_id=user_id), | |
592 | {'_method': 'put', 'description': desc, 'lifetime': lifetime, |
|
589 | {'_method': 'put', 'description': desc, 'lifetime': lifetime, | |
593 | 'csrf_token': self.csrf_token}) |
|
590 | 'csrf_token': self.csrf_token}) | |
594 | assert_session_flash(response, 'Auth token successfully created') |
|
591 | assert_session_flash(response, 'Auth token successfully created') | |
595 |
|
592 | |||
596 | response = response.follow() |
|
593 | response = response.follow() | |
597 | user = User.get(user_id) |
|
594 | user = User.get(user_id) | |
598 | for auth_token in user.auth_tokens: |
|
595 | for auth_token in user.auth_tokens: | |
599 | response.mustcontain(auth_token) |
|
596 | response.mustcontain(auth_token) | |
600 |
|
597 | |||
601 | def test_remove_auth_token(self, user_util): |
|
598 | def test_remove_auth_token(self, user_util): | |
602 | self.log_user() |
|
599 | self.log_user() | |
603 | user = user_util.create_user() |
|
600 | user = user_util.create_user() | |
604 | user_id = user.user_id |
|
601 | user_id = user.user_id | |
605 |
|
602 | |||
606 | response = self.app.post( |
|
603 | response = self.app.post( | |
607 | url('edit_user_auth_tokens', user_id=user_id), |
|
604 | url('edit_user_auth_tokens', user_id=user_id), | |
608 | {'_method': 'put', 'description': 'desc', 'lifetime': -1, |
|
605 | {'_method': 'put', 'description': 'desc', 'lifetime': -1, | |
609 | 'csrf_token': self.csrf_token}) |
|
606 | 'csrf_token': self.csrf_token}) | |
610 | assert_session_flash(response, 'Auth token successfully created') |
|
607 | assert_session_flash(response, 'Auth token successfully created') | |
611 | response = response.follow() |
|
608 | response = response.follow() | |
612 |
|
609 | |||
613 | # now delete our key |
|
610 | # now delete our key | |
614 | keys = UserApiKeys.query().filter(UserApiKeys.user_id == user_id).all() |
|
611 | keys = UserApiKeys.query().filter(UserApiKeys.user_id == user_id).all() | |
615 | assert 3 == len(keys) |
|
612 | assert 3 == len(keys) | |
616 |
|
613 | |||
617 | response = self.app.post( |
|
614 | response = self.app.post( | |
618 | url('edit_user_auth_tokens', user_id=user_id), |
|
615 | url('edit_user_auth_tokens', user_id=user_id), | |
619 | {'_method': 'delete', 'del_auth_token': keys[0].api_key, |
|
616 | {'_method': 'delete', 'del_auth_token': keys[0].api_key, | |
620 | 'csrf_token': self.csrf_token}) |
|
617 | 'csrf_token': self.csrf_token}) | |
621 | assert_session_flash(response, 'Auth token successfully deleted') |
|
618 | assert_session_flash(response, 'Auth token successfully deleted') | |
622 | keys = UserApiKeys.query().filter(UserApiKeys.user_id == user_id).all() |
|
619 | keys = UserApiKeys.query().filter(UserApiKeys.user_id == user_id).all() | |
623 | assert 2 == len(keys) |
|
620 | assert 2 == len(keys) |
General Comments 0
You need to be logged in to leave comments.
Login now