auth.py
823 lines
| 27.6 KiB
| text/x-python
|
PythonLexer
r895 | # -*- coding: utf-8 -*- | |||
""" | ||||
rhodecode.lib.auth | ||||
~~~~~~~~~~~~~~~~~~ | ||||
r1203 | ||||
r895 | authentication and permission libraries | |||
r1203 | ||||
r895 | :created_on: Apr 4, 2010 | |||
r1824 | :author: marcink | |||
:copyright: (C) 2010-2012 Marcin Kuzminski <marcin@python-works.com> | ||||
r1532 | :license: GPLv3, see COPYING for more details. | |||
r895 | """ | |||
r1206 | # 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, either version 3 of the License, or | ||||
# (at your option) any later version. | ||||
r1203 | # | |||
r547 | # 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. | ||||
r1203 | # | |||
r547 | # You should have received a copy of the GNU General Public License | |||
r1206 | # along with this program. If not, see <http://www.gnu.org/licenses/>. | |||
r547 | ||||
r895 | import random | |||
import logging | ||||
import traceback | ||||
r1116 | import hashlib | |||
r1118 | ||||
r1116 | from tempfile import _RandomNameSequence | |||
r895 | from decorator import decorator | |||
r1982 | from pylons import config, url, request | |||
r547 | from pylons.controllers.util import abort, redirect | |||
r1056 | from pylons.i18n.translation import _ | |||
r895 | ||||
r2634 | from rhodecode import __platform__, is_windows, is_unix | |||
r1749 | from rhodecode.model.meta import Session | |||
r1118 | ||||
r2109 | from rhodecode.lib.utils2 import str2bool, safe_unicode | |||
r895 | from rhodecode.lib.exceptions import LdapPasswordError, LdapUsernameError | |||
r1982 | from rhodecode.lib.utils import get_repo_slug, get_repos_group_slug | |||
r713 | from rhodecode.lib.auth_ldap import AuthLdap | |||
r895 | ||||
r547 | from rhodecode.model import meta | |||
r673 | from rhodecode.model.user import UserModel | |||
r1633 | from rhodecode.model.db import Permission, RhodeCodeSetting, User | |||
r895 | ||||
r1246 | log = logging.getLogger(__name__) | |||
r547 | ||||
class PasswordGenerator(object): | ||||
r1716 | """ | |||
r1818 | This is a simple class for generating password from different sets of | |||
r1716 | characters | |||
usage:: | ||||
r547 | passwd_gen = PasswordGenerator() | |||
r1246 | #print 8-letter password containing only big and small letters | |||
of alphabet | ||||
r2278 | passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL) | |||
r547 | """ | |||
r1246 | ALPHABETS_NUM = r'''1234567890''' | |||
ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm''' | ||||
ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM''' | ||||
ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?''' | ||||
ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \ | ||||
+ ALPHABETS_NUM + ALPHABETS_SPECIAL | ||||
ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM | ||||
r547 | ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL | |||
r1246 | ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM | |||
ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM | ||||
r673 | ||||
r547 | def __init__(self, passwd=''): | |||
self.passwd = passwd | ||||
r1993 | def gen_password(self, length, type_=None): | |||
if type_ is None: | ||||
type_ = self.ALPHABETS_FULL | ||||
r1982 | self.passwd = ''.join([random.choice(type_) for _ in xrange(length)]) | |||
r547 | return self.passwd | |||
r1246 | ||||
r1118 | class RhodeCodeCrypto(object): | |||
@classmethod | ||||
def hash_string(cls, str_): | ||||
""" | ||||
Cryptographic function used for password hashing based on pybcrypt | ||||
or pycrypto in windows | ||||
r1203 | ||||
r1118 | :param password: password to hash | |||
""" | ||||
r2634 | if is_windows: | |||
r2479 | from hashlib import sha256 | |||
r1118 | return sha256(str_).hexdigest() | |||
r2634 | elif is_unix: | |||
r2479 | import bcrypt | |||
r1118 | return bcrypt.hashpw(str_, bcrypt.gensalt(10)) | |||
else: | ||||
r1246 | raise Exception('Unknown or unsupported platform %s' \ | |||
% __platform__) | ||||
r1118 | ||||
@classmethod | ||||
def hash_check(cls, password, hashed): | ||||
""" | ||||
Checks matching password with it's hashed value, runs different | ||||
implementation based on platform it runs on | ||||
r1203 | ||||
r1118 | :param password: password | |||
:param hashed: password in hashed form | ||||
""" | ||||
r2634 | if is_windows: | |||
r2479 | from hashlib import sha256 | |||
r1118 | return sha256(password).hexdigest() == hashed | |||
r2634 | elif is_unix: | |||
r2479 | import bcrypt | |||
r1118 | return bcrypt.hashpw(password, hashed) == hashed | |||
else: | ||||
r1246 | raise Exception('Unknown or unsupported platform %s' \ | |||
% __platform__) | ||||
r1118 | ||||
r673 | ||||
r547 | def get_crypt_password(password): | |||
r1118 | return RhodeCodeCrypto.hash_string(password) | |||
r1246 | ||||
r1118 | def check_password(password, hashed): | |||
return RhodeCodeCrypto.hash_check(password, hashed) | ||||
r547 | ||||
r1950 | ||||
r1628 | def generate_api_key(str_, salt=None): | |||
""" | ||||
Generates API KEY from given string | ||||
r1818 | ||||
r1628 | :param str_: | |||
:param salt: | ||||
""" | ||||
r1718 | ||||
r1116 | if salt is None: | |||
salt = _RandomNameSequence().next() | ||||
r1628 | return hashlib.sha1(str_ + salt).hexdigest() | |||
r1116 | ||||
r1246 | ||||
r547 | def authfunc(environ, username, password): | |||
r1628 | """ | |||
r1818 | Dummy authentication wrapper function used in Mercurial and Git for | |||
r1644 | access control. | |||
r1203 | ||||
r761 | :param environ: needed only for using in Basic auth | |||
""" | ||||
return authenticate(username, password) | ||||
def authenticate(username, password): | ||||
r1628 | """ | |||
Authentication function used for access control, | ||||
r699 | firstly checks for db authentication then if ldap is enabled for ldap | |||
r705 | authentication, also creates ldap user if not in database | |||
r1203 | ||||
r699 | :param username: username | |||
:param password: password | ||||
""" | ||||
r1292 | ||||
r705 | user_model = UserModel() | |||
r1530 | user = User.get_by_username(username) | |||
r699 | ||||
r761 | log.debug('Authenticating user using RhodeCode account') | |||
Thayne Harbaugh
|
r991 | if user is not None and not user.ldap_dn: | ||
r547 | if user.active: | |||
r674 | if user.username == 'default' and user.active: | |||
r2025 | log.info('user %s authenticated correctly as anonymous user' % | |||
r761 | username) | |||
r674 | return True | |||
r1246 | elif user.username == username and check_password(password, | |||
user.password): | ||||
r1976 | log.info('user %s authenticated correctly' % username) | |||
r547 | return True | |||
else: | ||||
r2025 | log.warning('user %s tried auth but is disabled' % username) | |||
r705 | ||||
else: | ||||
r761 | log.debug('Regular authentication failed') | |||
r1530 | user_obj = User.get_by_username(username, case_insensitive=True) | |||
r761 | ||||
Thayne Harbaugh
|
r991 | if user_obj is not None and not user_obj.ldap_dn: | ||
r749 | log.debug('this user already exists as non ldap') | |||
r748 | return False | |||
r1633 | ldap_settings = RhodeCodeSetting.get_ldap_settings() | |||
r705 | #====================================================================== | |||
r1203 | # FALLBACK TO LDAP AUTH IF ENABLE | |||
r705 | #====================================================================== | |||
r1135 | if str2bool(ldap_settings.get('ldap_active')): | |||
r761 | log.debug("Authenticating user using ldap") | |||
r705 | kwargs = { | |||
r1246 | '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'), | ||||
"Lorenzo M. Catucci"
|
r1290 | 'tls_kind': ldap_settings.get('ldap_tls_kind'), | ||
r1246 | '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, | ||||
r705 | } | |||
log.debug('Checking for ldap authentication') | ||||
try: | ||||
aldap = AuthLdap(**kwargs) | ||||
r1246 | (user_dn, ldap_attrs) = aldap.authenticate_ldap(username, | |||
password) | ||||
r1976 | log.debug('Got ldap DN response %s' % user_dn) | |||
r705 | ||||
r1307 | get_ldap_attr = lambda k: ldap_attrs.get(ldap_settings\ | |||
r1292 | .get(k), [''])[0] | |||
Thayne Harbaugh
|
r991 | user_attrs = { | ||
r1425 | 'name': safe_unicode(get_ldap_attr('ldap_attr_firstname')), | |||
'lastname': safe_unicode(get_ldap_attr('ldap_attr_lastname')), | ||||
'email': get_ldap_attr('ldap_attr_email'), | ||||
} | ||||
r2000 | ||||
# don't store LDAP password since we don't need it. Override | ||||
r1992 | # with some random generated password | |||
_password = PasswordGenerator().gen_password(length=8) | ||||
# create this user on the fly if it doesn't exist in rhodecode | ||||
# database | ||||
if user_model.create_ldap(username, _password, user_dn, | ||||
r1246 | user_attrs): | |||
r1976 | log.info('created new ldap user %s' % username) | |||
r1818 | ||||
r2634 | Session().commit() | |||
r761 | return True | |||
except (LdapUsernameError, LdapPasswordError,): | ||||
pass | ||||
except (Exception,): | ||||
r705 | log.error(traceback.format_exc()) | |||
r761 | pass | |||
r547 | return False | |||
r1950 | ||||
Liad Shani
|
r1621 | def login_container_auth(username): | ||
user = User.get_by_username(username) | ||||
if user is None: | ||||
user_attrs = { | ||||
r1628 | 'name': username, | |||
'lastname': None, | ||||
'email': None, | ||||
} | ||||
r1749 | user = UserModel().create_for_container_auth(username, user_attrs) | |||
r1628 | if not user: | |||
Liad Shani
|
r1621 | return None | ||
r1976 | log.info('User %s was created by container authentication' % username) | |||
Liad Shani
|
r1621 | |||
if not user.active: | ||||
return None | ||||
user.update_lastlogin() | ||||
r2634 | Session().commit() | |||
r1818 | ||||
r1718 | log.debug('User %s is now logged in by container authentication', | |||
r1628 | user.username) | |||
Liad Shani
|
r1621 | return user | ||
r1950 | ||||
Liad Shani
|
r1630 | def get_container_username(environ, config): | ||
username = None | ||||
Liad Shani
|
r1621 | |||
Liad Shani
|
r1630 | if str2bool(config.get('container_auth_enabled', False)): | ||
from paste.httpheaders import REMOTE_USER | ||||
username = REMOTE_USER(environ) | ||||
if not username and str2bool(config.get('proxypass_auth_enabled', False)): | ||||
Liad Shani
|
r1617 | username = environ.get('HTTP_X_FORWARDED_USER') | ||
Liad Shani
|
r1630 | if username: | ||
r1628 | # Removing realm and domain from username | |||
Liad Shani
|
r1617 | username = username.partition('@')[0] | ||
username = username.rpartition('\\')[2] | ||||
r1976 | log.debug('Received username %s from container' % username) | |||
Liad Shani
|
r1617 | |||
return username | ||||
r1246 | ||||
r1950 | ||||
r2030 | class CookieStoreWrapper(object): | |||
def __init__(self, cookie_store): | ||||
self.cookie_store = cookie_store | ||||
def __repr__(self): | ||||
return 'CookieStore<%s>' % (self.cookie_store) | ||||
def get(self, key, other=None): | ||||
if isinstance(self.cookie_store, dict): | ||||
return self.cookie_store.get(key, other) | ||||
elif isinstance(self.cookie_store, AuthUser): | ||||
return self.cookie_store.__dict__.get(key, other) | ||||
r547 | class AuthUser(object): | |||
r1117 | """ | |||
A simple object that handles all attributes of user in RhodeCode | ||||
r1203 | ||||
r1117 | It does lookup based on API key,given user, or user present in session | |||
r1203 | Then it fills all required information for such user. It also checks if | |||
r1117 | anonymous access is enabled and if so, it returns default user as logged | |||
in | ||||
r547 | """ | |||
r1016 | ||||
Liad Shani
|
r1613 | def __init__(self, user_id=None, api_key=None, username=None): | ||
r1117 | ||||
self.user_id = user_id | ||||
r1120 | self.api_key = None | |||
Liad Shani
|
r1617 | self.username = username | ||
r1628 | ||||
r547 | self.name = '' | |||
self.lastname = '' | ||||
self.email = '' | ||||
self.is_authenticated = False | ||||
r1117 | self.admin = False | |||
r2714 | self.inherit_default_permissions = False | |||
r547 | self.permissions = {} | |||
r1120 | self._api_key = api_key | |||
r1117 | self.propagate_data() | |||
r1950 | self._instance = None | |||
r1117 | ||||
def propagate_data(self): | ||||
user_model = UserModel() | ||||
r1728 | self.anonymous_user = User.get_by_username('default', cache=True) | |||
Liad Shani
|
r1613 | is_user_loaded = False | ||
r1718 | ||||
r1628 | # try go get user by api key | |||
r1122 | if self._api_key and self._api_key != self.anonymous_user.api_key: | |||
r1976 | log.debug('Auth User lookup by API KEY %s' % self._api_key) | |||
Liad Shani
|
r1618 | is_user_loaded = user_model.fill_data(self, api_key=self._api_key) | ||
r1818 | # lookup by userid | |||
r1718 | elif (self.user_id is not None and | |||
r1628 | self.user_id != self.anonymous_user.user_id): | |||
r1976 | log.debug('Auth User lookup by USER ID %s' % self.user_id) | |||
Liad Shani
|
r1618 | is_user_loaded = user_model.fill_data(self, user_id=self.user_id) | ||
r1808 | # lookup by username | |||
elif self.username and \ | ||||
str2bool(config.get('container_auth_enabled', False)): | ||||
r1818 | ||||
r1976 | log.debug('Auth User lookup by USER NAME %s' % self.username) | |||
Liad Shani
|
r1621 | dbuser = login_container_auth(self.username) | ||
if dbuser is not None: | ||||
r2709 | log.debug('filling all attributes to object') | |||
Liad Shani
|
r1613 | for k, v in dbuser.get_dict().items(): | ||
setattr(self, k, v) | ||||
self.set_authenticated() | ||||
is_user_loaded = True | ||||
r2045 | else: | |||
log.debug('No data in %s that could been used to log in' % self) | ||||
Liad Shani
|
r1613 | |||
if not is_user_loaded: | ||||
r1628 | # if we cannot authenticate user try anonymous | |||
Liad Shani
|
r1613 | if self.anonymous_user.active is True: | ||
r1718 | user_model.fill_data(self, user_id=self.anonymous_user.user_id) | |||
r1628 | # then we set this user is logged in | |||
Liad Shani
|
r1613 | self.is_authenticated = True | ||
r1117 | else: | |||
Liad Shani
|
r1618 | self.user_id = None | ||
self.username = None | ||||
Liad Shani
|
r1613 | self.is_authenticated = False | ||
r1117 | ||||
Liad Shani
|
r1617 | if not self.username: | ||
self.username = 'None' | ||||
r1976 | log.debug('Auth User is now %s' % self) | |||
r1117 | user_model.fill_perms(self) | |||
@property | ||||
def is_admin(self): | ||||
return self.admin | ||||
r547 | ||||
r673 | def __repr__(self): | |||
r1117 | 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 | ||||
r1718 | def get_cookie_store(self): | |||
r1950 | return {'username': self.username, | |||
r1718 | 'user_id': self.user_id, | |||
r1950 | 'is_authenticated': self.is_authenticated} | |||
r1718 | ||||
@classmethod | ||||
def from_cookie_store(cls, cookie_store): | ||||
r2030 | """ | |||
Creates AuthUser from a cookie store | ||||
:param cls: | ||||
:param cookie_store: | ||||
""" | ||||
r1718 | user_id = cookie_store.get('user_id') | |||
username = cookie_store.get('username') | ||||
api_key = cookie_store.get('api_key') | ||||
return AuthUser(user_id, api_key, username) | ||||
r547 | ||||
r1950 | ||||
r547 | def set_available_permissions(config): | |||
r1628 | """ | |||
This function will propagate pylons globals with all available defined | ||||
r1203 | permission given in db. We don't want to check each time from db for new | |||
r547 | permissions since adding a new permission also requires application restart | |||
ie. to decorate new views with the newly created permission | ||||
r1203 | ||||
r895 | :param config: current pylons config instance | |||
r1203 | ||||
r547 | """ | |||
log.info('getting information about all available permissions') | ||||
try: | ||||
r1749 | sa = meta.Session | |||
r547 | all_perms = sa.query(Permission).all() | |||
r1950 | except Exception: | |||
r629 | pass | |||
r547 | finally: | |||
meta.Session.remove() | ||||
r673 | ||||
r547 | config['available_permissions'] = [x.permission_name for x in all_perms] | |||
r1246 | ||||
#============================================================================== | ||||
r547 | # CHECK DECORATORS | |||
r1246 | #============================================================================== | |||
r547 | class LoginRequired(object): | |||
r1117 | """ | |||
r1203 | Must be logged in to execute this function else | |||
r1117 | redirect to login page | |||
r1203 | ||||
r1117 | :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 | ||||
r673 | ||||
r547 | def __call__(self, func): | |||
return decorator(self.__wrapper, func) | ||||
r673 | ||||
r547 | def __wrapper(self, func, *fargs, **fkwargs): | |||
r1117 | cls = fargs[0] | |||
user = cls.rhodecode_user | ||||
api_access_ok = False | ||||
if self.api_access: | ||||
r1976 | log.debug('Checking API KEY access for %s' % cls) | |||
r1117 | if user.api_key == request.GET.get('api_key'): | |||
api_access_ok = True | ||||
else: | ||||
log.debug("API KEY token not valid") | ||||
r2025 | loc = "%s:%s" % (cls.__class__.__name__, func.__name__) | |||
log.debug('Checking if %s is authenticated @ %s' % (user.username, loc)) | ||||
r1117 | if user.is_authenticated or api_access_ok: | |||
r2458 | reason = 'RegularAuth' if user.is_authenticated else 'APIAuth' | |||
log.info('user %s is authenticated and granted access to %s ' | ||||
'using %s' % (user.username, loc, reason) | ||||
r2025 | ) | |||
r547 | return func(*fargs, **fkwargs) | |||
else: | ||||
r2025 | log.warn('user %s NOT authenticated on func: %s' % ( | |||
user, loc) | ||||
) | ||||
r1207 | p = url.current() | |||
r673 | ||||
r1976 | log.debug('redirecting to login page with %s' % p) | |||
r547 | return redirect(url('login_home', came_from=p)) | |||
r1246 | ||||
r779 | class NotAnonymous(object): | |||
r1716 | """ | |||
Must be logged in to execute this function else | ||||
r779 | redirect to login page""" | |||
def __call__(self, func): | ||||
return decorator(self.__wrapper, func) | ||||
def __wrapper(self, func, *fargs, **fkwargs): | ||||
r1117 | cls = fargs[0] | |||
self.user = cls.rhodecode_user | ||||
r779 | ||||
r1976 | log.debug('Checking if user is not anonymous @%s' % cls) | |||
r1117 | ||||
anonymous = self.user.username == 'default' | ||||
r779 | ||||
if anonymous: | ||||
r1335 | p = url.current() | |||
r1056 | ||||
import rhodecode.lib.helpers as h | ||||
r1246 | h.flash(_('You need to be a registered user to ' | |||
'perform this action'), | ||||
r1056 | category='warning') | |||
r779 | return redirect(url('login_home', came_from=p)) | |||
else: | ||||
return func(*fargs, **fkwargs) | ||||
r1246 | ||||
r547 | class PermsDecorator(object): | |||
r1117 | """Base class for controller decorators""" | |||
r673 | ||||
r547 | 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 | ||||
r673 | ||||
r547 | def __call__(self, func): | |||
return decorator(self.__wrapper, func) | ||||
r673 | ||||
r547 | def __wrapper(self, func, *fargs, **fkwargs): | |||
r1117 | cls = fargs[0] | |||
self.user = cls.rhodecode_user | ||||
r673 | self.user_perms = self.user.permissions | |||
log.debug('checking %s permissions %s for %s %s', | ||||
r2125 | self.__class__.__name__, self.required_perms, cls, self.user) | |||
r547 | ||||
if self.check_permissions(): | ||||
r1976 | log.debug('Permission granted for %s %s' % (cls, self.user)) | |||
r547 | return func(*fargs, **fkwargs) | |||
r673 | ||||
r547 | else: | |||
r2025 | log.debug('Permission denied for %s %s' % (cls, self.user)) | |||
r1336 | anonymous = self.user.username == 'default' | |||
if anonymous: | ||||
p = url.current() | ||||
import rhodecode.lib.helpers as h | ||||
h.flash(_('You need to be a signed in to ' | ||||
'view this page'), | ||||
category='warning') | ||||
return redirect(url('login_home', came_from=p)) | ||||
else: | ||||
r1628 | # redirect with forbidden ret code | |||
r1336 | return abort(403) | |||
r547 | ||||
def check_permissions(self): | ||||
"""Dummy function for overriding""" | ||||
raise Exception('You have to write this function in child class') | ||||
r1246 | ||||
r547 | class HasPermissionAllDecorator(PermsDecorator): | |||
r1716 | """ | |||
Checks for access permission for all given predicates. All of them | ||||
r547 | have to be meet in order to fulfill the request | |||
""" | ||||
r673 | ||||
r547 | def check_permissions(self): | |||
if self.required_perms.issubset(self.user_perms.get('global')): | ||||
return True | ||||
return False | ||||
r673 | ||||
r547 | ||||
class HasPermissionAnyDecorator(PermsDecorator): | ||||
r1716 | """ | |||
Checks for access permission for any of given predicates. In order to | ||||
r547 | fulfill the request any of predicates must be meet | |||
""" | ||||
r673 | ||||
r547 | def check_permissions(self): | |||
if self.required_perms.intersection(self.user_perms.get('global')): | ||||
return True | ||||
return False | ||||
r1246 | ||||
r547 | class HasRepoPermissionAllDecorator(PermsDecorator): | |||
r1716 | """ | |||
Checks for access permission for all given predicates for specific | ||||
r547 | repository. All of them have to be meet in order to fulfill the request | |||
""" | ||||
r673 | ||||
r547 | 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 | ||||
r673 | ||||
r547 | ||||
class HasRepoPermissionAnyDecorator(PermsDecorator): | ||||
r1716 | """ | |||
Checks for access permission for any of given predicates for specific | ||||
r547 | repository. In order to fulfill the request any of predicates must be meet | |||
""" | ||||
r673 | ||||
r547 | def check_permissions(self): | |||
repo_name = get_repo_slug(request) | ||||
r673 | ||||
r547 | try: | |||
user_perms = set([self.user_perms['repositories'][repo_name]]) | ||||
except KeyError: | ||||
return False | ||||
r2125 | ||||
r547 | if self.required_perms.intersection(user_perms): | |||
return True | ||||
return False | ||||
r1246 | ||||
r1982 | class HasReposGroupPermissionAllDecorator(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): | ||||
group_name = get_repos_group_slug(request) | ||||
try: | ||||
user_perms = set([self.user_perms['repositories_groups'][group_name]]) | ||||
except KeyError: | ||||
return False | ||||
if self.required_perms.issubset(user_perms): | ||||
return True | ||||
return False | ||||
class HasReposGroupPermissionAnyDecorator(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): | ||||
group_name = get_repos_group_slug(request) | ||||
try: | ||||
user_perms = set([self.user_perms['repositories_groups'][group_name]]) | ||||
except KeyError: | ||||
return False | ||||
if self.required_perms.intersection(user_perms): | ||||
return True | ||||
return False | ||||
r1246 | #============================================================================== | |||
r547 | # CHECK FUNCTIONS | |||
r1246 | #============================================================================== | |||
r547 | class PermsFunction(object): | |||
"""Base function for other check functions""" | ||||
r673 | ||||
r547 | def __init__(self, *perms): | |||
available_perms = config['available_permissions'] | ||||
r673 | ||||
r547 | for perm in perms: | |||
if perm not in available_perms: | ||||
r2105 | raise Exception("'%s' permission is not defined" % perm) | |||
r547 | self.required_perms = set(perms) | |||
self.user_perms = None | ||||
self.repo_name = None | ||||
r2125 | self.group_name = None | |||
r673 | ||||
r547 | def __call__(self, check_Location=''): | |||
r1728 | user = request.user | |||
r2125 | cls_name = self.__class__.__name__ | |||
check_scope = { | ||||
'HasPermissionAll': '', | ||||
'HasPermissionAny': '', | ||||
'HasRepoPermissionAll': 'repo:%s' % self.repo_name, | ||||
'HasRepoPermissionAny': 'repo:%s' % self.repo_name, | ||||
'HasReposGroupPermissionAll': 'group:%s' % self.group_name, | ||||
'HasReposGroupPermissionAny': 'group:%s' % self.group_name, | ||||
}.get(cls_name, '?') | ||||
log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name, | ||||
self.required_perms, user, check_scope, | ||||
check_Location or 'unspecified location') | ||||
r547 | if not user: | |||
r2045 | log.debug('Empty request user') | |||
r547 | return False | |||
self.user_perms = user.permissions | ||||
if self.check_permissions(): | ||||
r2125 | log.debug('Permission granted for user: %s @ %s', user, | |||
r1117 | check_Location or 'unspecified location') | |||
r547 | return True | |||
r673 | ||||
r547 | else: | |||
r2125 | log.debug('Permission denied for user: %s @ %s', user, | |||
r1117 | check_Location or 'unspecified location') | |||
r673 | return False | |||
r547 | def check_permissions(self): | |||
"""Dummy function for overriding""" | ||||
raise Exception('You have to write this function in child class') | ||||
r673 | ||||
r1246 | ||||
r547 | class HasPermissionAll(PermsFunction): | |||
def check_permissions(self): | ||||
if self.required_perms.issubset(self.user_perms.get('global')): | ||||
return True | ||||
return False | ||||
r1246 | ||||
r547 | class HasPermissionAny(PermsFunction): | |||
def check_permissions(self): | ||||
if self.required_perms.intersection(self.user_perms.get('global')): | ||||
return True | ||||
return False | ||||
r1246 | ||||
r547 | class HasRepoPermissionAll(PermsFunction): | |||
def __call__(self, repo_name=None, check_Location=''): | ||||
self.repo_name = repo_name | ||||
return super(HasRepoPermissionAll, self).__call__(check_Location) | ||||
r673 | ||||
r547 | def check_permissions(self): | |||
if not self.repo_name: | ||||
self.repo_name = get_repo_slug(request) | ||||
try: | ||||
r2125 | self._user_perms = set( | |||
r1982 | [self.user_perms['repositories'][self.repo_name]] | |||
) | ||||
r547 | except KeyError: | |||
return False | ||||
r2125 | if self.required_perms.issubset(self._user_perms): | |||
r547 | return True | |||
return False | ||||
r673 | ||||
r1246 | ||||
r547 | class HasRepoPermissionAny(PermsFunction): | |||
def __call__(self, repo_name=None, check_Location=''): | ||||
self.repo_name = repo_name | ||||
return super(HasRepoPermissionAny, self).__call__(check_Location) | ||||
r673 | ||||
r547 | def check_permissions(self): | |||
if not self.repo_name: | ||||
self.repo_name = get_repo_slug(request) | ||||
try: | ||||
r2125 | self._user_perms = set( | |||
r1982 | [self.user_perms['repositories'][self.repo_name]] | |||
) | ||||
r547 | except KeyError: | |||
return False | ||||
r2125 | if self.required_perms.intersection(self._user_perms): | |||
r547 | return True | |||
return False | ||||
r1246 | ||||
r1982 | class HasReposGroupPermissionAny(PermsFunction): | |||
def __call__(self, group_name=None, check_Location=''): | ||||
self.group_name = group_name | ||||
return super(HasReposGroupPermissionAny, self).__call__(check_Location) | ||||
def check_permissions(self): | ||||
try: | ||||
r2125 | self._user_perms = set( | |||
r1982 | [self.user_perms['repositories_groups'][self.group_name]] | |||
) | ||||
except KeyError: | ||||
return False | ||||
r2125 | if self.required_perms.intersection(self._user_perms): | |||
r1982 | return True | |||
return False | ||||
class HasReposGroupPermissionAll(PermsFunction): | ||||
def __call__(self, group_name=None, check_Location=''): | ||||
self.group_name = group_name | ||||
r2634 | return super(HasReposGroupPermissionAll, self).__call__(check_Location) | |||
r1982 | ||||
def check_permissions(self): | ||||
try: | ||||
r2125 | self._user_perms = set( | |||
r1982 | [self.user_perms['repositories_groups'][self.group_name]] | |||
) | ||||
except KeyError: | ||||
return False | ||||
r2125 | if self.required_perms.issubset(self._user_perms): | |||
r1982 | return True | |||
return False | ||||
r1246 | #============================================================================== | |||
r547 | # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH | |||
r1246 | #============================================================================== | |||
r547 | class HasPermissionAnyMiddleware(object): | |||
def __init__(self, *perms): | ||||
self.required_perms = set(perms) | ||||
r673 | ||||
r547 | def __call__(self, user, repo_name): | |||
r2100 | # repo_name MUST be unicode, since we handle keys in permission | |||
# dict by unicode | ||||
repo_name = safe_unicode(repo_name) | ||||
r1117 | usr = AuthUser(user.user_id) | |||
r547 | try: | |||
r1117 | self.user_perms = set([usr.permissions['repositories'][repo_name]]) | |||
r2100 | except Exception: | |||
r2109 | log.error('Exception while accessing permissions %s' % | |||
r2100 | traceback.format_exc()) | |||
r547 | self.user_perms = set() | |||
self.username = user.username | ||||
r673 | self.repo_name = repo_name | |||
r547 | return self.check_permissions() | |||
r673 | ||||
r547 | def check_permissions(self): | |||
log.debug('checking mercurial protocol ' | ||||
r1040 | 'permissions %s for user:%s repository:%s', self.user_perms, | |||
r547 | self.username, self.repo_name) | |||
if self.required_perms.intersection(self.user_perms): | ||||
r2125 | log.debug('permission granted for user:%s on repo:%s' % ( | |||
self.username, self.repo_name | ||||
) | ||||
) | ||||
r547 | return True | |||
r2125 | log.debug('permission denied for user:%s on repo:%s' % ( | |||
self.username, self.repo_name | ||||
) | ||||
) | ||||
r547 | return False | |||