##// END OF EJS Templates
refreshed how_to on translations
refreshed how_to on translations

File last commit:

r1217:a3b2b4b4 default
r1225:357b0c18 beta
Show More
auth.py
579 lines | 20.2 KiB | text/x-python | PythonLexer
Added some more details into user edit permissions view
r895 # -*- coding: utf-8 -*-
"""
rhodecode.lib.auth
~~~~~~~~~~~~~~~~~~
source code cleanup: remove trailing white space, normalize file endings
r1203
Added some more details into user edit permissions view
r895 authentication and permission libraries
source code cleanup: remove trailing white space, normalize file endings
r1203
Added some more details into user edit permissions view
r895 :created_on: Apr 4, 2010
:copyright: (c) 2010 by marcink.
:license: LICENSE_NAME, see LICENSE_FILE for more details.
"""
fixed license issue #149
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.
source code cleanup: remove trailing white space, normalize file endings
r1203 #
renamed project to rhodecode
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.
source code cleanup: remove trailing white space, normalize file endings
r1203 #
renamed project to rhodecode
r547 # You should have received a copy of the GNU General Public License
fixed license issue #149
r1206 # along with this program. If not, see <http://www.gnu.org/licenses/>.
renamed project to rhodecode
r547
Added some more details into user edit permissions view
r895 import random
import logging
import traceback
Added api_key into user, api key get's generated again after password change...
r1116 import hashlib
Fixed Windows installation based on work of Mantis406 fork: "Replace py-bcrypt to make Windows installation easier"...
r1118
Added api_key into user, api key get's generated again after password change...
r1116 from tempfile import _RandomNameSequence
Added some more details into user edit permissions view
r895 from decorator import decorator
renamed project to rhodecode
r547 from pylons import config, session, url, request
from pylons.controllers.util import abort, redirect
#113 removed anonymous access from forking, added system messages in login box.
r1056 from pylons.i18n.translation import _
Added some more details into user edit permissions view
r895
merged freebsd support issue from default
r1195 from rhodecode import __platform__, PLATFORM_WIN, PLATFORM_OTHERS
Fixed Windows installation based on work of Mantis406 fork: "Replace py-bcrypt to make Windows installation easier"...
r1118
merged freebsd support issue from default
r1195 if __platform__ in PLATFORM_WIN:
Fixed Windows installation based on work of Mantis406 fork: "Replace py-bcrypt to make Windows installation easier"...
r1118 from hashlib import sha256
merged freebsd support issue from default
r1195 if __platform__ in PLATFORM_OTHERS:
Fixed Windows installation based on work of Mantis406 fork: "Replace py-bcrypt to make Windows installation easier"...
r1118 import bcrypt
fixed some config bool converter problems with ldap
r1135 from rhodecode.lib import str2bool
Added some more details into user edit permissions view
r895 from rhodecode.lib.exceptions import LdapPasswordError, LdapUsernameError
renamed project to rhodecode
r547 from rhodecode.lib.utils import get_repo_slug
fixed #72 show warning on removal when user still is owner of existing repositories...
r713 from rhodecode.lib.auth_ldap import AuthLdap
Added some more details into user edit permissions view
r895
renamed project to rhodecode
r547 from rhodecode.model import meta
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673 from rhodecode.model.user import UserModel
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 from rhodecode.model.db import Permission
Added some more details into user edit permissions view
r895
renamed project to rhodecode
r547
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673 log = logging.getLogger(__name__)
renamed project to rhodecode
r547
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
source code cleanup: remove trailing white space, normalize file endings
r1203 print passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
renamed project to rhodecode
r547 """
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]
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 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
Fixed Windows installation based on work of Mantis406 fork: "Replace py-bcrypt to make Windows installation easier"...
r1118 class RhodeCodeCrypto(object):
@classmethod
def hash_string(cls, str_):
"""
Cryptographic function used for password hashing based on pybcrypt
or pycrypto in windows
source code cleanup: remove trailing white space, normalize file endings
r1203
Fixed Windows installation based on work of Mantis406 fork: "Replace py-bcrypt to make Windows installation easier"...
r1118 :param password: password to hash
"""
merged freebsd support issue from default
r1195 if __platform__ in PLATFORM_WIN:
Fixed Windows installation based on work of Mantis406 fork: "Replace py-bcrypt to make Windows installation easier"...
r1118 return sha256(str_).hexdigest()
merged freebsd support issue from default
r1195 elif __platform__ in PLATFORM_OTHERS:
Fixed Windows installation based on work of Mantis406 fork: "Replace py-bcrypt to make Windows installation easier"...
r1118 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
else:
merged freebsd support issue from default
r1195 raise Exception('Unknown or unsupported platform %s' % __platform__)
Fixed Windows installation based on work of Mantis406 fork: "Replace py-bcrypt to make Windows installation easier"...
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
source code cleanup: remove trailing white space, normalize file endings
r1203
Fixed Windows installation based on work of Mantis406 fork: "Replace py-bcrypt to make Windows installation easier"...
r1118 :param password: password
:param hashed: password in hashed form
"""
merged freebsd support issue from default
r1195 if __platform__ in PLATFORM_WIN:
Fixed Windows installation based on work of Mantis406 fork: "Replace py-bcrypt to make Windows installation easier"...
r1118 return sha256(password).hexdigest() == hashed
merged freebsd support issue from default
r1195 elif __platform__ in PLATFORM_OTHERS:
Fixed Windows installation based on work of Mantis406 fork: "Replace py-bcrypt to make Windows installation easier"...
r1118 return bcrypt.hashpw(password, hashed) == hashed
else:
merged freebsd support issue from default
r1195 raise Exception('Unknown or unsupported platform %s' % __platform__)
Fixed Windows installation based on work of Mantis406 fork: "Replace py-bcrypt to make Windows installation easier"...
r1118
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 def get_crypt_password(password):
Fixed Windows installation based on work of Mantis406 fork: "Replace py-bcrypt to make Windows installation easier"...
r1118 return RhodeCodeCrypto.hash_string(password)
def check_password(password, hashed):
return RhodeCodeCrypto.hash_check(password, hashed)
renamed project to rhodecode
r547
Added api_key into user, api key get's generated again after password change...
r1116 def generate_api_key(username, salt=None):
if salt is None:
salt = _RandomNameSequence().next()
return hashlib.sha1(username + salt).hexdigest()
renamed project to rhodecode
r547 def authfunc(environ, username, password):
#56 added propagation of permission from group
r1016 """Dummy authentication function used in Mercurial/Git/ and access control,
source code cleanup: remove trailing white space, normalize file endings
r1203
ldap auth rewrite, moved split authfunc into two functions,...
r761 :param environ: needed only for using in Basic auth
"""
return authenticate(username, password)
def authenticate(username, password):
#56 added propagation of permission from group
r1016 """Authentication function used for access control,
Code refactor for auth func, preparing for ldap support...
r699 firstly checks for db authentication then if ldap is enabled for ldap
implements #60, ldap configuration and authentication....
r705 authentication, also creates ldap user if not in database
source code cleanup: remove trailing white space, normalize file endings
r1203
Code refactor for auth func, preparing for ldap support...
r699 :param username: username
:param password: password
"""
implements #60, ldap configuration and authentication....
r705 user_model = UserModel()
user = user_model.get_by_username(username, cache=False)
Code refactor for auth func, preparing for ldap support...
r699
ldap auth rewrite, moved split authfunc into two functions,...
r761 log.debug('Authenticating user using RhodeCode account')
Thayne Harbaugh
Improve LDAP authentication...
r991 if user is not None and not user.ldap_dn:
renamed project to rhodecode
r547 if user.active:
#49 Enabled anonymous access push and pull commands
r674
if user.username == 'default' and user.active:
ldap auth rewrite, moved split authfunc into two functions,...
r761 log.info('user %s authenticated correctly as anonymous user',
username)
#49 Enabled anonymous access push and pull commands
r674 return True
elif user.username == username and check_password(password, user.password):
renamed project to rhodecode
r547 log.info('user %s authenticated correctly', username)
return True
else:
ldap auth rewrite, moved split authfunc into two functions,...
r761 log.warning('user %s is disabled', username)
implements #60, ldap configuration and authentication....
r705
else:
ldap auth rewrite, moved split authfunc into two functions,...
r761 log.debug('Regular authentication failed')
#78, fixed more reliable case insensitive searches
r742 user_obj = user_model.get_by_username(username, cache=False,
case_insensitive=True)
ldap auth rewrite, moved split authfunc into two functions,...
r761
Thayne Harbaugh
Improve LDAP authentication...
r991 if user_obj is not None and not user_obj.ldap_dn:
added debug message for ldap auth
r749 log.debug('this user already exists as non ldap')
fixed ldap issue and small template fix
r748 return False
implements #60, ldap configuration and authentication....
r705 from rhodecode.model.settings import SettingsModel
ldap_settings = SettingsModel().get_ldap_settings()
#======================================================================
source code cleanup: remove trailing white space, normalize file endings
r1203 # FALLBACK TO LDAP AUTH IF ENABLE
implements #60, ldap configuration and authentication....
r705 #======================================================================
fixed some config bool converter problems with ldap
r1135 if str2bool(ldap_settings.get('ldap_active')):
ldap auth rewrite, moved split authfunc into two functions,...
r761 log.debug("Authenticating user using ldap")
implements #60, ldap configuration and authentication....
r705 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'),
fixed some config bool converter problems with ldap
r1135 'use_ldaps':str2bool(ldap_settings.get('ldap_ldaps')),
Thayne Harbaugh
Improve LDAP authentication...
r991 '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'),
implements #60, ldap configuration and authentication....
r705 'ldap_version':3,
}
log.debug('Checking for ldap authentication')
try:
aldap = AuthLdap(**kwargs)
Thayne Harbaugh
Improve LDAP authentication...
r991 (user_dn, ldap_attrs) = aldap.authenticate_ldap(username, password)
log.debug('Got ldap DN response %s', user_dn)
implements #60, ldap configuration and authentication....
r705
Thayne Harbaugh
Improve LDAP authentication...
r991 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):
#56 added propagation of permission from group
r1016 log.info('created new ldap user %s', username)
implements #60, ldap configuration and authentication....
r705
ldap auth rewrite, moved split authfunc into two functions,...
r761 return True
except (LdapUsernameError, LdapPasswordError,):
pass
except (Exception,):
implements #60, ldap configuration and authentication....
r705 log.error(traceback.format_exc())
ldap auth rewrite, moved split authfunc into two functions,...
r761 pass
renamed project to rhodecode
r547 return False
class AuthUser(object):
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 """
A simple object that handles all attributes of user in RhodeCode
source code cleanup: remove trailing white space, normalize file endings
r1203
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 It does lookup based on API key,given user, or user present in session
source code cleanup: remove trailing white space, normalize file endings
r1203 Then it fills all required information for such user. It also checks if
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 anonymous access is enabled and if so, it returns default user as logged
in
renamed project to rhodecode
r547 """
#56 added propagation of permission from group
r1016
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 def __init__(self, user_id=None, api_key=None):
self.user_id = user_id
fixed some bugs in api key auth, added access by api key into rss/atom feeds in global journal...
r1120 self.api_key = None
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117
renamed project to rhodecode
r547 self.username = 'None'
self.name = ''
self.lastname = ''
self.email = ''
self.is_authenticated = False
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 self.admin = False
renamed project to rhodecode
r547 self.permissions = {}
fixed some bugs in api key auth, added access by api key into rss/atom feeds in global journal...
r1120 self._api_key = api_key
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 self.propagate_data()
def propagate_data(self):
user_model = UserModel()
fixed some bugs in api key auth, added access by api key into rss/atom feeds in global journal...
r1120 self.anonymous_user = user_model.get_by_username('default', cache=True)
disabled api key for anonymous users, and added api_key to rss/atom links for other users
r1122 if self._api_key and self._api_key != self.anonymous_user.api_key:
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 #try go get user by api key
fixed some bugs in api key auth, added access by api key into rss/atom feeds in global journal...
r1120 log.debug('Auth User lookup by API KEY %s', self._api_key)
user_model.fill_data(self, api_key=self._api_key)
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 else:
log.debug('Auth User lookup by USER ID %s', self.user_id)
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
renamed project to rhodecode
r547
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673 def __repr__(self):
Major rewrite of auth objects. Moved parts of filling user data into user model....
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
renamed project to rhodecode
r547
def set_available_permissions(config):
Added some more details into user edit permissions view
r895 """This function will propagate pylons globals with all available defined
source code cleanup: remove trailing white space, normalize file endings
r1203 permission given in db. We don't want to check each time from db for new
renamed project to rhodecode
r547 permissions since adding a new permission also requires application restart
ie. to decorate new views with the newly created permission
source code cleanup: remove trailing white space, normalize file endings
r1203
Added some more details into user edit permissions view
r895 :param config: current pylons config instance
source code cleanup: remove trailing white space, normalize file endings
r1203
renamed project to rhodecode
r547 """
log.info('getting information about all available permissions')
try:
Code refactoring,models renames...
r629 sa = meta.Session()
renamed project to rhodecode
r547 all_perms = sa.query(Permission).all()
Code refactoring,models renames...
r629 except:
pass
renamed project to rhodecode
r547 finally:
meta.Session.remove()
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 config['available_permissions'] = [x.permission_name for x in all_perms]
#===============================================================================
# CHECK DECORATORS
#===============================================================================
class LoginRequired(object):
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 """
source code cleanup: remove trailing white space, normalize file endings
r1203 Must be logged in to execute this function else
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 redirect to login page
source code cleanup: remove trailing white space, normalize file endings
r1203
Major rewrite of auth objects. Moved parts of filling user data into user model....
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
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 def __call__(self, func):
return decorator(self.__wrapper, func)
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 def __wrapper(self, func, *fargs, **fkwargs):
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 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:
renamed project to rhodecode
r547 log.debug('user %s is authenticated', user.username)
return func(*fargs, **fkwargs)
else:
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 log.warn('user %s NOT authenticated', user.username)
changed the way of generating url for came_from
r1207 p = url.current()
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
log.debug('redirecting to login page with %s', p)
renamed project to rhodecode
r547 return redirect(url('login_home', came_from=p))
Added isanonymous decorator for checking permissions for anonymous access
r779 class NotAnonymous(object):
source code cleanup: remove trailing white space, normalize file endings
r1203 """Must be logged in to execute this function else
Added isanonymous decorator for checking permissions for anonymous access
r779 redirect to login page"""
def __call__(self, func):
return decorator(self.__wrapper, func)
def __wrapper(self, func, *fargs, **fkwargs):
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 cls = fargs[0]
self.user = cls.rhodecode_user
Added isanonymous decorator for checking permissions for anonymous access
r779
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 log.debug('Checking if user is not anonymous @%s', cls)
anonymous = self.user.username == 'default'
Added isanonymous decorator for checking permissions for anonymous access
r779
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')
#113 removed anonymous access from forking, added system messages in login box.
r1056
import rhodecode.lib.helpers as h
h.flash(_('You need to be a registered user to perform this action'),
category='warning')
Added isanonymous decorator for checking permissions for anonymous access
r779 return redirect(url('login_home', came_from=p))
else:
return func(*fargs, **fkwargs)
renamed project to rhodecode
r547 class PermsDecorator(object):
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 """Base class for controller decorators"""
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
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
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 def __call__(self, func):
return decorator(self.__wrapper, func)
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 def __wrapper(self, func, *fargs, **fkwargs):
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 cls = fargs[0]
self.user = cls.rhodecode_user
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673 self.user_perms = self.user.permissions
log.debug('checking %s permissions %s for %s %s',
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 self.__class__.__name__, self.required_perms, cls,
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673 self.user)
renamed project to rhodecode
r547
if self.check_permissions():
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 log.debug('Permission granted for %s %s', cls, self.user)
renamed project to rhodecode
r547 return func(*fargs, **fkwargs)
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 else:
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 log.warning('Permission denied for %s %s', cls, self.user)
renamed project to rhodecode
r547 #redirect with forbidden ret code
return abort(403)
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 def check_permissions(self):
"""Dummy function for overriding"""
raise Exception('You have to write this function in child class')
class HasPermissionAllDecorator(PermsDecorator):
source code cleanup: remove trailing white space, normalize file endings
r1203 """Checks for access permission for all given predicates. All of them
renamed project to rhodecode
r547 have to be meet in order to fulfill the request
"""
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 def check_permissions(self):
if self.required_perms.issubset(self.user_perms.get('global')):
return True
return False
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547
class HasPermissionAnyDecorator(PermsDecorator):
source code cleanup: remove trailing white space, normalize file endings
r1203 """Checks for access permission for any of given predicates. In order to
renamed project to rhodecode
r547 fulfill the request any of predicates must be meet
"""
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 def check_permissions(self):
if self.required_perms.intersection(self.user_perms.get('global')):
return True
return False
class HasRepoPermissionAllDecorator(PermsDecorator):
source code cleanup: remove trailing white space, normalize file endings
r1203 """Checks for access permission for all given predicates for specific
renamed project to rhodecode
r547 repository. All of them have to be meet in order to fulfill the request
"""
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
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
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547
class HasRepoPermissionAnyDecorator(PermsDecorator):
source code cleanup: remove trailing white space, normalize file endings
r1203 """Checks for access permission for any of given predicates for specific
renamed project to rhodecode
r547 repository. In order to fulfill the request any of predicates must be meet
"""
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 def check_permissions(self):
repo_name = get_repo_slug(request)
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 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"""
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 def __init__(self, *perms):
available_perms = config['available_permissions']
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 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
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 def __call__(self, check_Location=''):
renamed hg_app to rhodecode
r548 user = session.get('rhodecode_user', False)
renamed project to rhodecode
r547 if not user:
return False
self.user_perms = user.permissions
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 self.granted_for = user
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673 log.debug('checking %s %s %s', self.__class__.__name__,
self.required_perms, user)
renamed project to rhodecode
r547 if self.check_permissions():
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 log.debug('Permission granted %s @ %s', self.granted_for,
check_Location or 'unspecified location')
renamed project to rhodecode
r547 return True
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 else:
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 log.warning('Permission denied for %s @ %s', self.granted_for,
check_Location or 'unspecified location')
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673 return False
renamed project to rhodecode
r547 def check_permissions(self):
"""Dummy function for overriding"""
raise Exception('You have to write this function in child class')
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 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):
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 def __call__(self, repo_name=None, check_Location=''):
self.repo_name = repo_name
return super(HasRepoPermissionAll, self).__call__(check_Location)
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 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
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673 self.granted_for = self.repo_name
renamed project to rhodecode
r547 if self.required_perms.issubset(self.user_perms):
return True
return False
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 class HasRepoPermissionAny(PermsFunction):
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 def __call__(self, repo_name=None, check_Location=''):
self.repo_name = repo_name
return super(HasRepoPermissionAny, self).__call__(check_Location)
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 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)
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 def __call__(self, user, repo_name):
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 usr = AuthUser(user.user_id)
renamed project to rhodecode
r547 try:
Major rewrite of auth objects. Moved parts of filling user data into user model....
r1117 self.user_perms = set([usr.permissions['repositories'][repo_name]])
renamed project to rhodecode
r547 except:
self.user_perms = set()
self.granted_for = ''
self.username = user.username
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673 self.repo_name = repo_name
renamed project to rhodecode
r547 return self.check_permissions()
#49 Enabled anonymous access for web interface controllable from permissions pannel
r673
renamed project to rhodecode
r547 def check_permissions(self):
log.debug('checking mercurial protocol '
fixes fixes fixes ! optimized queries on journal...
r1040 'permissions %s for user:%s repository:%s', self.user_perms,
renamed project to rhodecode
r547 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