@@ -534,384 +534,385 @@ class AuthUser(object):
if not is_user_loaded:
# if we cannot authenticate user try anonymous
if self.anonymous_user.active:
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.user_id = None
self.username = None
self.is_authenticated = False
if not self.username:
self.username = 'None'
log.debug('Auth User is now %s' % self)
def get_perms(self, user, explicit=True, algo='higherwin', cache=False):
"""
Fills user permission attribute with permissions taken from database
works for permissions given for repositories, and for permissions that
are granted to groups
:param user: instance of User object from database
:param explicit: In case there are permissions both for user and a group
that user is part of, explicit flag will define if user will
explicitly override permissions from group, if it's False it will
make decision based on the algo
:param algo: algorithm to decide what permission should be choose if
it's multiple defined, eg user in two different groups. It also
decides if explicit flag is turned off how to specify the permission
for case when user is in a group + have defined separate permission
user_id = user.user_id
user_is_admin = user.is_admin
user_inherit_default_permissions = user.inherit_default_permissions
log.debug('Getting PERMISSION tree')
compute = conditional_cache('short_term', 'cache_desc',
condition=cache, func=_cached_perms_data)
return compute(user_id, user_is_admin,
user_inherit_default_permissions, explicit, algo)
def get_api_keys(self):
api_keys = [self.api_key]
for api_key in UserApiKeys.query()\
.filter(UserApiKeys.user_id == self.user_id)\
.filter(or_(UserApiKeys.expires == -1,
UserApiKeys.expires >= time.time())).all():
api_keys.append(api_key.api_key)
return api_keys
@property
def is_admin(self):
return self.admin
def repositories_admin(self):
Returns list of repositories you're an admin of
return [x[0] for x in self.permissions['repositories'].iteritems()
if x[1] == 'repository.admin']
def repository_groups_admin(self):
Returns list of repository groups you're an admin of
return [x[0] for x in self.permissions['repositories_groups'].iteritems()
if x[1] == 'group.admin']
def user_groups_admin(self):
Returns list of user groups you're an admin of
return [x[0] for x in self.permissions['user_groups'].iteritems()
if x[1] == 'usergroup.admin']
def ip_allowed(self):
Checks if ip_addr used in constructor is allowed from defined list of
allowed ip_addresses for user
:returns: boolean, True if ip is in allowed ip range
# check IP
inherit = self.inherit_default_permissions
return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
inherit_from_default=inherit)
@classmethod
def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
allowed_ips = AuthUser.get_allowed_ips(user_id, cache=True,
inherit_from_default=inherit_from_default)
if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
log.debug('IP:%s is in range of %s' % (ip_addr, allowed_ips))
return True
log.info('Access for IP:%s forbidden, '
'not in %s' % (ip_addr, allowed_ips))
return False
def __repr__(self):
return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
% (self.user_id, self.username, self.ip_addr, 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}
def from_cookie_store(cls, cookie_store):
Creates AuthUser from a cookie store
:param cls:
:param 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 get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
_set = set()
if inherit_from_default:
default_ips = UserIpMap.query().filter(UserIpMap.user ==
User.get_default_user(cache=True))
if cache:
default_ips = default_ips.options(FromCache("sql_cache_short",
"get_user_ips_default"))
# populate from default user
for ip in default_ips:
try:
_set.add(ip.ip_addr)
except ObjectDeletedError:
# since we use heavy caching sometimes it happens that we get
# deleted objects here, we just skip them
pass
user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
user_ips = user_ips.options(FromCache("sql_cache_short",
"get_user_ips_%s" % user_id))
for ip in user_ips:
return _set or set(['0.0.0.0/0', '::/0'])
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()
config['available_permissions'] = [x.permission_name for x in all_perms]
finally:
meta.Session.remove()
#==============================================================================
# CHECK DECORATORS
def redirect_to_login(message=None):
from kallithea.lib import helpers as h
p = url.current()
if message:
h.flash(h.literal(message), category='warning')
log.debug('Redirecting to login page, origin: %s' % p)
return redirect(url('login_home', came_from=p))
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.authuser
loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
log.debug('Checking access for user %s @ %s' % (user, loc))
# check if our IP is allowed
if not user.ip_allowed:
return redirect_to_login(_('IP %s not allowed' % (user.ip_addr)))
# check if we used an API key and it's a valid one
api_key = request.GET.get('api_key')
if api_key is not None:
# explicit controller is enabled or API is in our whitelist
if self.api_access or allowed_api_access(loc, api_key=api_key):
if api_key in user.api_keys:
log.info('user %s authenticated with API key ****%s @ %s'
% (user, api_key[-4:], loc))
return func(*fargs, **fkwargs)
log.warning('API key ****%s is NOT valid' % api_key[-4:])
return redirect_to_login(_('Invalid API key'))
# controller does not allow API access
log.warning('API access to %s is not allowed' % loc)
return abort(403)
# CSRF protection - POSTs with session auth must contain correct token
if request.POST and user.is_authenticated:
token = request.POST.get(secure_form.token_key)
if not token or token != secure_form.authentication_token():
log.error('CSRF check failed')
log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
reason = 'RegularAuth' if user.is_authenticated else 'APIAuth'
if user.is_authenticated:
log.info('user %s authenticating with:%s IS authenticated on func %s '
% (user, reason, loc)
)
log.warning('user %s authenticating with:%s NOT authenticated on func: %s: '
return redirect_to_login()
class NotAnonymous(object):
redirect to login page"""
self.user = cls.authuser
log.debug('Checking if user is not anonymous @%s' % cls)
anonymous = self.user.username == User.DEFAULT_USER
if anonymous:
return redirect_to_login(_('You need to be a registered user to '
'perform this action'))
class PermsDecorator(object):
"""Base class for controller decorators"""
def __init__(self, *required_perms):
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.debug('Permission denied for %s %s' % (cls, self.user))
return redirect_to_login(_('You need to be signed in to view this page'))
# redirect with forbidden ret code
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
if self.required_perms.issubset(self.user_perms.get('global')):
class HasPermissionAnyDecorator(PermsDecorator):
Checks for access permission for any of given predicates. In order to
fulfill the request any of predicates must be meet
if self.required_perms.intersection(self.user_perms.get('global')):
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
repo_name = get_repo_slug(request)
user_perms = set([self.user_perms['repositories'][repo_name]])
except KeyError:
if self.required_perms.issubset(user_perms):
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
if self.required_perms.intersection(user_perms):
class HasRepoGroupPermissionAllDecorator(PermsDecorator):
repository group. All of them have to be meet in order to fulfill the request
Status change: