import logging from flask.ext.principal import identity_loaded, UserNeed, Permission from flask.ext.login import current_user from collections import namedtuple from functools import partial from data import model from app import app from auth import get_authenticated_user, get_validated_token logger = logging.getLogger(__name__) _ResourceNeed = namedtuple('resource', ['type', 'namespace', 'name', 'role']) _RepositoryNeed = partial(_ResourceNeed, 'repository') class ModifyRepositoryPermission(Permission): def __init__(self, namespace, name): admin_need = _RepositoryNeed(namespace, name, 'admin') write_need = _RepositoryNeed(namespace, name, 'write') super(ModifyRepositoryPermission, self).__init__(admin_need, write_need) class ReadRepositoryPermission(Permission): def __init__(self, namespace, name): admin_need = _RepositoryNeed(namespace, name, 'admin') write_need = _RepositoryNeed(namespace, name, 'write') read_need = _RepositoryNeed(namespace, name, 'read') super(ReadRepositoryPermission, self).__init__(admin_need, write_need, read_need) class UserPermission(Permission): def __init__(self, username): user_need = UserNeed(username) super(UserPermission, self).__init__(user_need) @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): logger.debug('Identity loaded: %s' % identity) # We have verified an identity, load in all of the permissions if identity.auth_type == 'username': logger.debug('Computing permissions for user: %s' % identity.id) user_object = model.get_user(identity.id) identity.provides.add(UserNeed(user_object.username)) for user in model.get_all_repo_permissions(user_object): grant = _RepositoryNeed(user.repositorypermission.repository.namespace, user.repositorypermission.repository.name, user.repositorypermission.role.name) logger.debug('User added permission: {0}'.format(grant)) identity.provides.add(grant) elif identity.auth_type == 'token': logger.debug('Computing permissions for token: %s' % identity.id) token = model.get_token(identity.id) query = model.get_user_repo_permissions(token.user, token.repository) for permission in query: t_grant = _RepositoryNeed(token.repository.namespace, token.repository.name, permission.role.name) logger.debug('Token added permission: {0}'.format(t_grant)) identity.provides.add(t_grant) else: logger.error('Unknown identity auth type: %s' % identity.auth_type)