@@ -127,386 +127,388 @@ def get_crypt_password(password):
def check_password(password, hashed):
return RhodeCodeCrypto.hash_check(password, hashed)
def generate_api_key(str_, salt=None):
"""
Generates API KEY from given string
:param str_:
:param salt:
if salt is None:
salt = _RandomNameSequence().next()
return hashlib.sha1(str_ + salt).hexdigest()
def authfunc(environ, username, password):
Dummy authentication wrapper function used in Mercurial and Git for
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.get_by_username(username)
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)
else:
log.warning('user %s is disabled', username)
log.debug('Regular authentication failed')
user_obj = User.get_by_username(username, 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
ldap_settings = RhodeCodeSetting.get_ldap_settings()
#======================================================================
# FALLBACK TO LDAP AUTH IF ENABLE
if str2bool(ldap_settings.get('ldap_active')):
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'),
'tls_kind': ldap_settings.get('ldap_tls_kind'),
'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)
get_ldap_attr = lambda k: ldap_attrs.get(ldap_settings\
.get(k), [''])[0]
user_attrs = {
'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'),
if user_model.create_ldap(username, password, user_dn,
user_attrs):
log.info('created new ldap user %s', username)
Session.commit()
except (LdapUsernameError, LdapPasswordError,):
pass
except (Exception,):
log.error(traceback.format_exc())
def login_container_auth(username):
if user is None:
'name': username,
'lastname': None,
'email': None,
user = UserModel().create_for_container_auth(username, user_attrs)
if not user:
return None
log.info('User %s was created by container authentication', username)
if not user.active:
user.update_lastlogin()
log.debug('User %s is now logged in by container authentication',
user.username)
return user
def get_container_username(environ, config):
username = None
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)):
username = environ.get('HTTP_X_FORWARDED_USER')
if username:
# Removing realm and domain from username
username = username.partition('@')[0]
username = username.rpartition('\\')[2]
log.debug('Received username %s from container', username)
return username
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, username=None):
self.user_id = user_id
self.api_key = None
self.username = username
self.name = ''
self.lastname = ''
self.email = ''
self.is_authenticated = False
self.admin = False
self.permissions = {}
self._api_key = api_key
self.propagate_data()
def propagate_data(self):
self.anonymous_user = User.get_by_username('default', cache=True)
is_user_loaded = False
# try go get user by api key
if self._api_key and self._api_key != self.anonymous_user.api_key:
log.debug('Auth User lookup by API KEY %s', self._api_key)
is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
# lookup by userid
elif (self.user_id is not None and
self.user_id != self.anonymous_user.user_id):
log.debug('Auth User lookup by USER ID %s', self.user_id)
is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
# lookup by username
elif self.username:
elif self.username and \
str2bool(config.get('container_auth_enabled', False)):
log.debug('Auth User lookup by USER NAME %s', self.username)
dbuser = login_container_auth(self.username)
if dbuser is not None:
for k, v in dbuser.get_dict().items():
setattr(self, k, v)
self.set_authenticated()
is_user_loaded = True
if not is_user_loaded:
# if we cannot authenticate user try anonymous
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
self.user_id = None
self.username = None
if not self.username:
self.username = 'None'
log.debug('Auth User is now %s', self)
user_model.fill_perms(self)
@property
def is_admin(self):
return self.admin
def full_contact(self):
return '%s %s <%s>' % (self.name, self.lastname, self.email)
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 get_cookie_store(self):
return {'username':self.username,
'user_id': self.user_id,
'is_authenticated':self.is_authenticated}
@classmethod
def from_cookie_store(cls, cookie_store):
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)
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')
sa = meta.Session
all_perms = sa.query(Permission).all()
except:
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
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)
log.warn('user %s NOT authenticated', user.username)
p = url.current()
log.debug('redirecting to login page with %s', p)
return redirect(url('login_home', came_from=p))
class NotAnonymous(object):
redirect to login page"""
self.user = cls.rhodecode_user
log.debug('Checking if user is not anonymous @%s', cls)
anonymous = self.user.username == 'default'
if anonymous:
import rhodecode.lib.helpers as h
h.flash(_('You need to be a registered user to '
'perform this action'),
category='warning')
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
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)
log.warning('Permission denied for %s %s', cls, self.user)
h.flash(_('You need to be a signed in to '
'view this page'),
# 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')
Status change: