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