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