Files
@ 6eb5bb24a948
Branch filter:
Location: kallithea/rhodecode/lib/auth.py - annotation
6eb5bb24a948
19.4 KiB
text/x-python
Major rewrite of auth objects. Moved parts of filling user data into user model.
Rewrote AuthUser adding access by api key.
Rewrote AuthUser adding access by api key.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 | 62c04c5cc971 62c04c5cc971 62c04c5cc971 62c04c5cc971 62c04c5cc971 62c04c5cc971 62c04c5cc971 62c04c5cc971 62c04c5cc971 62c04c5cc971 62c04c5cc971 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 62c04c5cc971 62c04c5cc971 62c04c5cc971 62c04c5cc971 716911af91e1 716911af91e1 62c04c5cc971 62c04c5cc971 1e757ac98988 1e757ac98988 520d27f40b51 62c04c5cc971 62c04c5cc971 1e757ac98988 1bb0fcdec895 62c04c5cc971 1e757ac98988 dd532af216d9 6eb5bb24a948 62c04c5cc971 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 3790279d2538 3790279d2538 5cc96df705b9 dd532af216d9 1e757ac98988 1e757ac98988 716911af91e1 716911af91e1 716911af91e1 716911af91e1 716911af91e1 716911af91e1 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 3790279d2538 56c2850a5b5f 56c2850a5b5f 56c2850a5b5f 56c2850a5b5f 56c2850a5b5f 56c2850a5b5f 56c2850a5b5f 3790279d2538 52da7cba88a6 9e9f1b919c0c 9e9f1b919c0c 52da7cba88a6 52da7cba88a6 52da7cba88a6 9e9f1b919c0c 9e9f1b919c0c 52da7cba88a6 56c2850a5b5f b232a36cc51f 1e757ac98988 99875a8f2ad1 99875a8f2ad1 56c2850a5b5f 56c2850a5b5f 99875a8f2ad1 99875a8f2ad1 99875a8f2ad1 1e757ac98988 1e757ac98988 1e757ac98988 56c2850a5b5f 9e9f1b919c0c 9e9f1b919c0c 56c2850a5b5f 1377a9d4bdb9 1377a9d4bdb9 56c2850a5b5f b232a36cc51f fcd4fb51526e 88338675a0f7 88338675a0f7 9e9f1b919c0c 9e9f1b919c0c 9e9f1b919c0c 9e9f1b919c0c 3790279d2538 9e9f1b919c0c 9e9f1b919c0c 56c2850a5b5f 9e9f1b919c0c 9e9f1b919c0c 9e9f1b919c0c 9e9f1b919c0c 9e9f1b919c0c 9e9f1b919c0c 9e9f1b919c0c b232a36cc51f b232a36cc51f b232a36cc51f b232a36cc51f 9e9f1b919c0c 9e9f1b919c0c 9e9f1b919c0c 9e9f1b919c0c 9e9f1b919c0c b232a36cc51f b232a36cc51f 9e9f1b919c0c b232a36cc51f b232a36cc51f b232a36cc51f b232a36cc51f b232a36cc51f b232a36cc51f b232a36cc51f 3790279d2538 9e9f1b919c0c 56c2850a5b5f 56c2850a5b5f 56c2850a5b5f 56c2850a5b5f 9e9f1b919c0c 56c2850a5b5f 1e757ac98988 1e757ac98988 1e757ac98988 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 1e757ac98988 3790279d2538 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 6eb5bb24a948 1e757ac98988 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 1e757ac98988 dd532af216d9 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 1e757ac98988 1e757ac98988 62c04c5cc971 3790279d2538 1e757ac98988 1e757ac98988 62c04c5cc971 62c04c5cc971 62c04c5cc971 1e757ac98988 1e757ac98988 1e757ac98988 7e536d1af60d 1e757ac98988 7e536d1af60d 7e536d1af60d 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 dd532af216d9 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 1e757ac98988 1e757ac98988 1e757ac98988 6eb5bb24a948 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 dd532af216d9 1e757ac98988 1e757ac98988 389d02a5df52 389d02a5df52 389d02a5df52 389d02a5df52 389d02a5df52 389d02a5df52 389d02a5df52 389d02a5df52 6eb5bb24a948 6eb5bb24a948 389d02a5df52 6eb5bb24a948 6eb5bb24a948 6eb5bb24a948 389d02a5df52 389d02a5df52 389d02a5df52 389d02a5df52 389d02a5df52 389d02a5df52 389d02a5df52 389d02a5df52 389d02a5df52 520d27f40b51 520d27f40b51 520d27f40b51 520d27f40b51 389d02a5df52 389d02a5df52 389d02a5df52 389d02a5df52 1e757ac98988 6eb5bb24a948 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 dd532af216d9 dd532af216d9 1e757ac98988 6eb5bb24a948 6eb5bb24a948 dd532af216d9 dd532af216d9 6eb5bb24a948 dd532af216d9 1e757ac98988 1e757ac98988 6eb5bb24a948 1e757ac98988 dd532af216d9 1e757ac98988 6eb5bb24a948 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 b75b77ef649d 1e757ac98988 1e757ac98988 1e757ac98988 6eb5bb24a948 dd532af216d9 dd532af216d9 dd532af216d9 1e757ac98988 6eb5bb24a948 6eb5bb24a948 1e757ac98988 dd532af216d9 1e757ac98988 6eb5bb24a948 6eb5bb24a948 dd532af216d9 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 6eb5bb24a948 1e757ac98988 6eb5bb24a948 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 dd532af216d9 1e757ac98988 dd532af216d9 1e757ac98988 1e757ac98988 8e49b6ceffe1 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 1e757ac98988 | # -*- coding: utf-8 -*-
"""
rhodecode.lib.auth
~~~~~~~~~~~~~~~~~~
authentication and permission libraries
:created_on: Apr 4, 2010
:copyright: (c) 2010 by marcink.
:license: LICENSE_NAME, see LICENSE_FILE for more details.
"""
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2
# of the License or (at your opinion) any later version of the license.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
import bcrypt
import random
import logging
import traceback
import hashlib
from tempfile import _RandomNameSequence
from decorator import decorator
from pylons import config, session, url, request
from pylons.controllers.util import abort, redirect
from pylons.i18n.translation import _
from rhodecode.lib.exceptions import LdapPasswordError, LdapUsernameError
from rhodecode.lib.utils import get_repo_slug
from rhodecode.lib.auth_ldap import AuthLdap
from rhodecode.model import meta
from rhodecode.model.user import UserModel
from rhodecode.model.db import Permission
log = logging.getLogger(__name__)
class PasswordGenerator(object):
"""This is a simple class for generating password from
different sets of characters
usage:
passwd_gen = PasswordGenerator()
#print 8-letter password containing only big and small letters of alphabet
print passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
"""
ALPHABETS_NUM = r'''1234567890'''#[0]
ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''#[1]
ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''#[2]
ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?''' #[3]
ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM + ALPHABETS_SPECIAL#[4]
ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM#[5]
ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM#[6]
ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM#[7]
def __init__(self, passwd=''):
self.passwd = passwd
def gen_password(self, len, type):
self.passwd = ''.join([random.choice(type) for _ in xrange(len)])
return self.passwd
def get_crypt_password(password):
"""Cryptographic function used for password hashing based on pybcrypt
:param password: password to hash
"""
return bcrypt.hashpw(password, bcrypt.gensalt(10))
def generate_api_key(username, salt=None):
if salt is None:
salt = _RandomNameSequence().next()
return hashlib.sha1(username + salt).hexdigest()
def check_password(password, hashed):
return bcrypt.hashpw(password, hashed) == hashed
def authfunc(environ, username, password):
"""Dummy authentication function used in Mercurial/Git/ and access control,
:param environ: needed only for using in Basic auth
"""
return authenticate(username, password)
def authenticate(username, password):
"""Authentication function used for access control,
firstly checks for db authentication then if ldap is enabled for ldap
authentication, also creates ldap user if not in database
:param username: username
:param password: password
"""
user_model = UserModel()
user = user_model.get_by_username(username, cache=False)
log.debug('Authenticating user using RhodeCode account')
if user is not None and not user.ldap_dn:
if user.active:
if user.username == 'default' and user.active:
log.info('user %s authenticated correctly as anonymous user',
username)
return True
elif user.username == username and check_password(password, user.password):
log.info('user %s authenticated correctly', username)
return True
else:
log.warning('user %s is disabled', username)
else:
log.debug('Regular authentication failed')
user_obj = user_model.get_by_username(username, cache=False,
case_insensitive=True)
if user_obj is not None and not user_obj.ldap_dn:
log.debug('this user already exists as non ldap')
return False
from rhodecode.model.settings import SettingsModel
ldap_settings = SettingsModel().get_ldap_settings()
#======================================================================
# FALLBACK TO LDAP AUTH IF ENABLE
#======================================================================
if ldap_settings.get('ldap_active', False):
log.debug("Authenticating user using ldap")
kwargs = {
'server':ldap_settings.get('ldap_host', ''),
'base_dn':ldap_settings.get('ldap_base_dn', ''),
'port':ldap_settings.get('ldap_port'),
'bind_dn':ldap_settings.get('ldap_dn_user'),
'bind_pass':ldap_settings.get('ldap_dn_pass'),
'use_ldaps':ldap_settings.get('ldap_ldaps'),
'tls_reqcert':ldap_settings.get('ldap_tls_reqcert'),
'ldap_filter':ldap_settings.get('ldap_filter'),
'search_scope':ldap_settings.get('ldap_search_scope'),
'attr_login':ldap_settings.get('ldap_attr_login'),
'ldap_version':3,
}
log.debug('Checking for ldap authentication')
try:
aldap = AuthLdap(**kwargs)
(user_dn, ldap_attrs) = aldap.authenticate_ldap(username, password)
log.debug('Got ldap DN response %s', user_dn)
user_attrs = {
'name' : ldap_attrs[ldap_settings.get('ldap_attr_firstname')][0],
'lastname' : ldap_attrs[ldap_settings.get('ldap_attr_lastname')][0],
'email' : ldap_attrs[ldap_settings.get('ldap_attr_email')][0],
}
if user_model.create_ldap(username, password, user_dn, user_attrs):
log.info('created new ldap user %s', username)
return True
except (LdapUsernameError, LdapPasswordError,):
pass
except (Exception,):
log.error(traceback.format_exc())
pass
return False
class AuthUser(object):
"""
A simple object that handles all attributes of user in RhodeCode
It does lookup based on API key,given user, or user present in session
Then it fills all required information for such user. It also checks if
anonymous access is enabled and if so, it returns default user as logged
in
"""
def __init__(self, user_id=None, api_key=None):
self.user_id = user_id
self.api_key = api_key
self.username = 'None'
self.name = ''
self.lastname = ''
self.email = ''
self.is_authenticated = False
self.admin = False
self.permissions = {}
self.propagate_data()
def propagate_data(self):
user_model = UserModel()
if self.api_key:
#try go get user by api key
log.debug('Auth User lookup by API KEY %s', self.api_key)
user_model.fill_data(self, api_key=self.api_key)
else:
log.debug('Auth User lookup by USER ID %s', self.user_id)
self.anonymous_user = user_model.get_by_username('default', cache=True)
if self.user_id is not None and self.user_id != self.anonymous_user.user_id:
user_model.fill_data(self, user_id=self.user_id)
else:
if self.anonymous_user.active is True:
user_model.fill_data(self, user_id=self.anonymous_user.user_id)
#then we set this user is logged in
self.is_authenticated = True
else:
self.is_authenticated = False
log.debug('Auth User is now %s', self)
user_model.fill_perms(self)
@property
def is_admin(self):
return self.admin
def __repr__(self):
return "<AuthUser('id:%s:%s|%s')>" % (self.user_id, self.username,
self.is_authenticated)
def set_authenticated(self, authenticated=True):
if self.user_id != self.anonymous_user.user_id:
self.is_authenticated = authenticated
def set_available_permissions(config):
"""This function will propagate pylons globals with all available defined
permission given in db. We don't want to check each time from db for new
permissions since adding a new permission also requires application restart
ie. to decorate new views with the newly created permission
:param config: current pylons config instance
"""
log.info('getting information about all available permissions')
try:
sa = meta.Session()
all_perms = sa.query(Permission).all()
except:
pass
finally:
meta.Session.remove()
config['available_permissions'] = [x.permission_name for x in all_perms]
#===============================================================================
# CHECK DECORATORS
#===============================================================================
class LoginRequired(object):
"""
Must be logged in to execute this function else
redirect to login page
:param api_access: if enabled this checks only for valid auth token
and grants access based on valid token
"""
def __init__(self, api_access=False):
self.api_access = api_access
def __call__(self, func):
return decorator(self.__wrapper, func)
def __wrapper(self, func, *fargs, **fkwargs):
cls = fargs[0]
user = cls.rhodecode_user
api_access_ok = False
if self.api_access:
log.debug('Checking API KEY access for %s', cls)
if user.api_key == request.GET.get('api_key'):
api_access_ok = True
else:
log.debug("API KEY token not valid")
log.debug('Checking if %s is authenticated @ %s', user.username, cls)
if user.is_authenticated or api_access_ok:
log.debug('user %s is authenticated', user.username)
return func(*fargs, **fkwargs)
else:
log.warn('user %s NOT authenticated', user.username)
p = ''
if request.environ.get('SCRIPT_NAME') != '/':
p += request.environ.get('SCRIPT_NAME')
p += request.environ.get('PATH_INFO')
if request.environ.get('QUERY_STRING'):
p += '?' + request.environ.get('QUERY_STRING')
log.debug('redirecting to login page with %s', p)
return redirect(url('login_home', came_from=p))
class NotAnonymous(object):
"""Must be logged in to execute this function else
redirect to login page"""
def __call__(self, func):
return decorator(self.__wrapper, func)
def __wrapper(self, func, *fargs, **fkwargs):
cls = fargs[0]
self.user = cls.rhodecode_user
log.debug('Checking if user is not anonymous @%s', cls)
anonymous = self.user.username == 'default'
if anonymous:
p = ''
if request.environ.get('SCRIPT_NAME') != '/':
p += request.environ.get('SCRIPT_NAME')
p += request.environ.get('PATH_INFO')
if request.environ.get('QUERY_STRING'):
p += '?' + request.environ.get('QUERY_STRING')
import rhodecode.lib.helpers as h
h.flash(_('You need to be a registered user to perform this action'),
category='warning')
return redirect(url('login_home', came_from=p))
else:
return func(*fargs, **fkwargs)
class PermsDecorator(object):
"""Base class for controller decorators"""
def __init__(self, *required_perms):
available_perms = config['available_permissions']
for perm in required_perms:
if perm not in available_perms:
raise Exception("'%s' permission is not defined" % perm)
self.required_perms = set(required_perms)
self.user_perms = None
def __call__(self, func):
return decorator(self.__wrapper, func)
def __wrapper(self, func, *fargs, **fkwargs):
cls = fargs[0]
self.user = cls.rhodecode_user
self.user_perms = self.user.permissions
log.debug('checking %s permissions %s for %s %s',
self.__class__.__name__, self.required_perms, cls,
self.user)
if self.check_permissions():
log.debug('Permission granted for %s %s', cls, self.user)
return func(*fargs, **fkwargs)
else:
log.warning('Permission denied for %s %s', cls, self.user)
#redirect with forbidden ret code
return abort(403)
def check_permissions(self):
"""Dummy function for overriding"""
raise Exception('You have to write this function in child class')
class HasPermissionAllDecorator(PermsDecorator):
"""Checks for access permission for all given predicates. All of them
have to be meet in order to fulfill the request
"""
def check_permissions(self):
if self.required_perms.issubset(self.user_perms.get('global')):
return True
return False
class HasPermissionAnyDecorator(PermsDecorator):
"""Checks for access permission for any of given predicates. In order to
fulfill the request any of predicates must be meet
"""
def check_permissions(self):
if self.required_perms.intersection(self.user_perms.get('global')):
return True
return False
class HasRepoPermissionAllDecorator(PermsDecorator):
"""Checks for access permission for all given predicates for specific
repository. All of them have to be meet in order to fulfill the request
"""
def check_permissions(self):
repo_name = get_repo_slug(request)
try:
user_perms = set([self.user_perms['repositories'][repo_name]])
except KeyError:
return False
if self.required_perms.issubset(user_perms):
return True
return False
class HasRepoPermissionAnyDecorator(PermsDecorator):
"""Checks for access permission for any of given predicates for specific
repository. In order to fulfill the request any of predicates must be meet
"""
def check_permissions(self):
repo_name = get_repo_slug(request)
try:
user_perms = set([self.user_perms['repositories'][repo_name]])
except KeyError:
return False
if self.required_perms.intersection(user_perms):
return True
return False
#===============================================================================
# CHECK FUNCTIONS
#===============================================================================
class PermsFunction(object):
"""Base function for other check functions"""
def __init__(self, *perms):
available_perms = config['available_permissions']
for perm in perms:
if perm not in available_perms:
raise Exception("'%s' permission in not defined" % perm)
self.required_perms = set(perms)
self.user_perms = None
self.granted_for = ''
self.repo_name = None
def __call__(self, check_Location=''):
user = session.get('rhodecode_user', False)
if not user:
return False
self.user_perms = user.permissions
self.granted_for = user
log.debug('checking %s %s %s', self.__class__.__name__,
self.required_perms, user)
if self.check_permissions():
log.debug('Permission granted %s @ %s', self.granted_for,
check_Location or 'unspecified location')
return True
else:
log.warning('Permission denied for %s @ %s', self.granted_for,
check_Location or 'unspecified location')
return False
def check_permissions(self):
"""Dummy function for overriding"""
raise Exception('You have to write this function in child class')
class HasPermissionAll(PermsFunction):
def check_permissions(self):
if self.required_perms.issubset(self.user_perms.get('global')):
return True
return False
class HasPermissionAny(PermsFunction):
def check_permissions(self):
if self.required_perms.intersection(self.user_perms.get('global')):
return True
return False
class HasRepoPermissionAll(PermsFunction):
def __call__(self, repo_name=None, check_Location=''):
self.repo_name = repo_name
return super(HasRepoPermissionAll, self).__call__(check_Location)
def check_permissions(self):
if not self.repo_name:
self.repo_name = get_repo_slug(request)
try:
self.user_perms = set([self.user_perms['repositories']\
[self.repo_name]])
except KeyError:
return False
self.granted_for = self.repo_name
if self.required_perms.issubset(self.user_perms):
return True
return False
class HasRepoPermissionAny(PermsFunction):
def __call__(self, repo_name=None, check_Location=''):
self.repo_name = repo_name
return super(HasRepoPermissionAny, self).__call__(check_Location)
def check_permissions(self):
if not self.repo_name:
self.repo_name = get_repo_slug(request)
try:
self.user_perms = set([self.user_perms['repositories']\
[self.repo_name]])
except KeyError:
return False
self.granted_for = self.repo_name
if self.required_perms.intersection(self.user_perms):
return True
return False
#===============================================================================
# SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
#===============================================================================
class HasPermissionAnyMiddleware(object):
def __init__(self, *perms):
self.required_perms = set(perms)
def __call__(self, user, repo_name):
usr = AuthUser(user.user_id)
try:
self.user_perms = set([usr.permissions['repositories'][repo_name]])
except:
self.user_perms = set()
self.granted_for = ''
self.username = user.username
self.repo_name = repo_name
return self.check_permissions()
def check_permissions(self):
log.debug('checking mercurial protocol '
'permissions %s for user:%s repository:%s', self.user_perms,
self.username, self.repo_name)
if self.required_perms.intersection(self.user_perms):
log.debug('permission granted')
return True
log.debug('permission denied')
return False
|