Example #1
0
    def create_permission(self, resource_uri):
        """
        Creates a new Pulp permission.

        @param resource_uri: resource_uri for the permission
        @type  resource_uri: str

        @raise DuplicateResource: if there is already a permission with the requested resource
        @raise InvalidValue: if any of the fields are unacceptable
        """

        existing_permission = Permission.get_collection().find_one(
            {'resource': resource_uri})
        if existing_permission is not None:
            raise DuplicateResource(resource_uri)

        # Creation
        create_me = Permission(resource=resource_uri)
        Permission.get_collection().save(create_me, safe=True)

        # Retrieve the permission to return the SON object
        created = Permission.get_collection().find_one(
            {'resource': resource_uri})

        return created
Example #2
0
    def grant(resource, login, operations):
        """
        Grant permission on a resource for a user and a set of operations.

        :param resource: uri path representing a pulp resource
        :type resource: str
        :param login: login of user to grant permissions to
        :type login: str
        :param operations:list of allowed operations being granted
        :type operations: list or tuple of integers
        """
        # we don't grant permissions to the system
        if login == system.SYSTEM_LOGIN:
            return

        user = User.get_collection().find_one({'login' : login})
        if user is None:
            raise MissingResource(user=login)

        # Make sure resource is a valid string or unicode
        if not isinstance(resource, basestring):
            raise InvalidValue(resource)

        # Get or create permission if it doesn't already exist
        permission = Permission.get_collection().find_one({'resource' : resource})
        if permission is None:
            permission = PermissionManager.create_permission(resource)

        current_ops = permission['users'].setdefault(user['login'], [])
        for o in operations:
            if o in current_ops:
                continue
            current_ops.append(o)

        Permission.get_collection().save(permission, safe=True)
Example #3
0
    def update_permission(self, resource_uri, delta):
        """
        Updates a permission object.

        @param resource_uri: identifies the resource URI of the permission being deleted
        @type resource_uri: str

        @param delta: A dict containing update keywords.
        @type delta: dict

        @return: The updated object
        @rtype: dict
        """

        # Check whether the permission exists
        found = Permission.get_collection().find_one(
            {'resource': resource_uri})
        if found is None:
            raise MissingResource(resource_uri)

        for key, value in delta.items():
            # simple changes
            if key in ('users', ):
                found[key] = value
                continue

            # unsupported
            raise PulpDataException(
                _("Update Keyword [%s] is not supported" % key))

        Permission.get_collection().save(found, safe=True)
Example #4
0
    def update_permission(resource_uri, delta):
        """
        Updates a permission object.

        :param resource_uri: identifies the resource URI of the permission being deleted
        :type resource_uri: str
        :param delta: A dict containing update keywords.
        :type delta: dict

        :raises MissingResource: if the permission does not exist
        :raises PulpDataException: if some usupported keys were specified
        """

        # Check whether the permission exists
        found = Permission.get_collection().find_one({'resource': resource_uri})
        if found is None:
            raise MissingResource(resource_uri)

        for key, value in delta.items():
            # simple changes
            if key in ('users',):
                found[key] = value
                continue

            # unsupported
            raise PulpDataException(_("Update Keyword [%s] is not supported" % key))

        Permission.get_collection().save(found, safe=True)
Example #5
0
File: cud.py Project: ehelms/pulp
    def grant(self, resource, login, operations):
        """
        Grant permission on a resource for a user and a set of operations.
        
        @type resource: str
        @param resource: uri path representing a pulp resource
        
        @type user: str
        @param user: login of user to grant permissions to
        
        @type operations: list or tuple of integers
        @param operations:list of allowed operations being granted
        """
        user = User.get_collection().find_one({'login' : login})
        if user is None:
            raise MissingResource(user=login)
        
        # Get or create permission if it doesn't already exist
        permission = Permission.get_collection().find_one({'resource' : resource})
        if permission is None:
            permission = self.create_permission(resource)
            
        current_ops = permission['users'].setdefault(user['login'], [])
        for o in operations:
            if o in current_ops:
                continue
            current_ops.append(o)

        Permission.get_collection().save(permission, safe=True)
Example #6
0
File: cud.py Project: ktdreyer/pulp
    def create_permission(resource_uri):
        """
        Creates a new Pulp permission.

        :param resource_uri: resource_uri for the permission
        :type  resource_uri: str

        :raises DuplicateResource: if there is already a permission with the requested resource
        :return: The created object
        :rtype: dict
        """

        existing_permission = Permission.get_collection().find_one(
            {'resource': resource_uri})
        if existing_permission is not None:
            raise DuplicateResource(resource_uri)

        # Creation
        create_me = Permission(resource=resource_uri)
        Permission.get_collection().save(create_me)

        # Retrieve the permission to return the SON object
        created = Permission.get_collection().find_one(
            {'resource': resource_uri})

        return created
Example #7
0
File: cud.py Project: ashcrow/pulp
    def update_permission(self, resource_uri, delta):
        """
        Updates a permission object.

        @param resource_uri: identifies the resource URI of the permission being deleted
        @type resource_uri: str

        @param delta: A dict containing update keywords.
        @type delta: dict

        @return: The updated object
        @rtype: dict
        """

        # Check whether the permission exists
        found = Permission.get_collection().find_one({'resource' : resource_uri})
        if found is None:
            raise MissingResource(resource_uri)

        for key, value in delta.items():
            # simple changes
            if key in ('users',):
                found[key] = value
                continue

            # unsupported
            raise PulpDataException(_("Update Keyword [%s] is not supported" % key))

        Permission.get_collection().save(found, safe=True)
Example #8
0
File: cud.py Project: ktdreyer/pulp
    def revoke(resource, login, operations):
        """
        Revoke permission on a resource for a user and a set of operations.

        :param resource:   uri path representing a pulp resource
        :type  resource:   str
        :param login:      login of user to revoke permissions from
        :type  login:      str
        :param operations: list of allowed operations being revoked
        :type  operations: list or tuple of integers

        :raises InvalidValue: if some params are invalid
        """
        permission_query_manager = factory.permission_query_manager()
        # we don't revoke permissions from the system
        if login == system.SYSTEM_LOGIN:
            return

        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise InvalidValue(['login'])

        permission = Permission.get_collection().find_one(
            {'resource': resource})
        if permission is None:
            return

        current_ops = permission_query_manager.find_user_permission(
            permission, user['login'])
        if not current_ops:
            return

        for o in operations:
            if o not in current_ops:
                continue
            current_ops.remove(o)

        # delete the user from this permission if there are no more allowed operations
        if not current_ops:
            permission_query_manager.delete_user_permission(
                permission, user['login'])

        # delete the permission if there are no more users
        if not permission['users']:
            PermissionManager.delete_permission(resource)
            return

        Permission.get_collection().save(permission)
    def test_user_default_permissions(self):
        """
        Tests default permissions given to the user after creation.
        """

        # Setup
        params = {
            'login' : 'user-1',
            'name' : 'User 1',
            'password' : 'test-password',
        }

        # Test
        self.post('/v2/users/', params=params)

        # Verify
        user = User.get_collection().find_one({'login' : 'user-1'})
        self.assertTrue(user is not None)
        
        permission = Permission.get_collection().find_one({'resource' : '/v2/users/user-1/'})
        self.assertTrue(permission is not None)
        self.assertTrue(next(d for (index, d) in enumerate(permission['users'])
                             if d['username'] == 'user-1') is not None)
        self.assertTrue(next(d for (index, d) in enumerate(permission['users'])
                             if d['username'] == 'ws-user') is not None)
Example #10
0
    def DELETE(self, login):
        """
        Delete a given user object
        :param login: the login id of the user to delete
        :type login: str
        """

        manager = managers.user_manager()
        result = manager.delete_user(login)

        # Delete any existing user permissions given to the creator of the user
        user_link = serialization.link.current_link_obj()['_href']
        if Permission.get_collection().find_one({'resource': user_link}):
            Permission.get_collection().remove({'resource': user_link}, safe=True)

        return self.ok(result)
Example #11
0
    def is_authorized(self, resource, login, operation):
        """
        Check to see if a user is authorized to perform an operation on a resource

        @type resource: str
        @param resource: pulp resource path

        @type login: str
        @param login: login of user to check permissions for

        @type operation: int
        @param operation: operation to be performed on resource

        @rtype: bool
        @return: True if the user is authorized for the operation on the resource,
                 False otherwise
        """
        if self.is_superuser(login):
            return True

        permission_query_manager = factory.permission_query_manager()

        parts = [p for p in resource.split('/') if p]
        while parts:
            current_resource = '/%s/' % '/'.join(parts)
            permission = permission_query_manager.find_by_resource(current_resource)
            if permission is not None:
                if operation in permission_query_manager.find_user_permission(permission, login):
                    return True
            parts = parts[:-1]

        permission = Permission.get_collection().find_one({'resource': '/'})
        return (permission is not None and
                operation in permission_query_manager.find_user_permission(permission, login))
Example #12
0
def is_authorized(resource, login, operation):
    """
    Check to see if a user is authorized to perform an operation on a resource.

    :param resource: pulp resource url
    :type  resource: str
    :param login: login of user to check permissions for
    :type  login: str
    :param operation: operation to be performed on resource
    :type  operation: int

    :return: True if the user is authorized for the operation on the resource, False otherwise
    :rtype: bool
    """
    user = model.User.objects.get_or_404(login=login)
    if user.is_superuser():
        return True

    permission_query_manager = manager_factory.permission_query_manager()

    # User is authorized if they have access to the resource or any of the its base resources.
    parts = [p for p in resource.split('/') if p]
    while parts:
        current_resource = '/%s/' % '/'.join(parts)
        permission = permission_query_manager.find_by_resource(current_resource)
        if permission is not None:
            if operation in permission_query_manager.find_user_permission(permission, login):
                return True
        parts = parts[:-1]

    permission = Permission.get_collection().find_one({'resource': '/'})
    return (permission is not None and
            operation in permission_query_manager.find_user_permission(permission, login))
Example #13
0
    def test_user_default_permissions(self):
        """
        Tests default permissions given to the user after creation.
        """

        # Setup
        params = {
            'login': '******',
            'name': 'User 1',
            'password': '******',
        }

        # Test
        self.post('/v2/users/', params=params)

        # Verify
        user = User.get_collection().find_one({'login': '******'})
        self.assertTrue(user is not None)

        permission = Permission.get_collection().find_one(
            {'resource': '/v2/users/user-1/'})
        self.assertTrue(permission is not None)
        self.assertTrue(
            next(d for (index, d) in enumerate(permission['users'])
                 if d['username'] == 'user-1') is not None)
        self.assertTrue(
            next(d for (index, d) in enumerate(permission['users'])
                 if d['username'] == 'ws-user') is not None)
Example #14
0
    def is_authorized(self, resource, login, operation):
        """
        Check to see if a user is authorized to perform an operation on a resource

        @type resource: str
        @param resource: pulp resource path

        @type login: str
        @param login: login of user to check permissions for

        @type operation: int
        @param operation: operation to be performed on resource

        @rtype: bool
        @return: True if the user is authorized for the operation on the resource,
                 False otherwise
        """
        if self.is_superuser(login):
            return True

        permission_query_manager = factory.permission_query_manager()

        parts = [p for p in resource.split('/') if p]
        while parts:
            current_resource = '/%s/' % '/'.join(parts)
            permission = permission_query_manager.find_by_resource(
                current_resource)
            if permission is not None:
                if operation in permission['users'].get(login, []):
                    return True
            parts = parts[:-1]

        permission = Permission.get_collection().find_one({'resource': '/'})
        return (permission is not None
                and operation in permission['users'].get(login, []))
Example #15
0
    def revoke_all_permissions_from_user(self, login):
        """
        Revoke all the permissions from a given user

        :param login: login of the user to revoke all permissions from
        :type login: str
        """
        permission_query_manager = factory.permission_query_manager()
        for permission in permission_query_manager.find_all():
            if permission_query_manager.get_user_permission(permission, login) is None:
                continue
            permission_query_manager.delete_user_permission(permission, login)
            if len(permission['users']) > 0:
                Permission.get_collection().save(permission, safe=True)
            else:
                # Delete entire permission if there are no more users
                Permission.get_collection().remove({'resource': permission['resource']}, safe=True)
Example #16
0
    def DELETE(self, login):
        """
        Delete a given user object
        :param login: the login id of the user to delete
        :type login: str
        """

        manager = managers.user_manager()
        result = manager.delete_user(login)

        # Delete any existing user permissions given to the creator of the user
        user_link = serialization.link.current_link_obj()['_href']
        if Permission.get_collection().find_one({'resource': user_link}):
            Permission.get_collection().remove({'resource': user_link},
                                               safe=True)

        return self.ok(result)
Example #17
0
File: cud.py Project: ehelms/pulp
    def revoke_all_permissions_from_user(self, login):
        """
        Revoke all the permissions from a given user

        @type login: str
        @param login: login of the user to revoke all permissions from

        @rtype: bool
        @return: True on success
        """
        for permission in factory.permission_query_manager().find_all():
            if login not in permission['users']:
                continue
            del permission['users'][login]
            Permission.get_collection().save(permission, safe=True)
            
        return True
Example #18
0
    def revoke(self, resource, login, operations):
        """
        Revoke permission on a resource for a user and a set of operations.

        @type resource: str
        @param resource: uri path representing a pulp resource

        @type user: str
        @param user: login of user to revoke permissions from

        @type operations: list or tuple of integers
        @param operations:list of allowed operations being revoked
        """
        # we don't revoke permissions from the system
        if login == system.SYSTEM_LOGIN:
            return

        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise MissingResource(user=login)

        permission = Permission.get_collection().find_one(
            {'resource': resource})
        if permission is None:
            return

        current_ops = permission['users'].get(user['login'], [])
        if not current_ops:
            return

        for o in operations:
            if o not in current_ops:
                continue
            current_ops.remove(o)

        # delete the user if there are no more allowed operations
        if not current_ops:
            del permission['users'][user['login']]

        # delete the permission if there are no more users
        if not permission['users']:
            self.delete_permission(resource)
            return

        Permission.get_collection().save(permission, safe=True)
Example #19
0
File: cud.py Project: credativ/pulp
    def revoke(resource, login, operations):
        """
        Revoke permission on a resource for a user and a set of operations.

        :param resource:   uri path representing a pulp resource
        :type  resource:   str
        :param login:      login of user to revoke permissions from
        :type  login:      str
        :param operations: list of allowed operations being revoked
        :type  operations: list or tuple of integers

        :raises InvalidValue: if some params are invalid
        """
        permission_query_manager = factory.permission_query_manager()
        # we don't revoke permissions from the system
        if login == system.SYSTEM_LOGIN:
            return

        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise InvalidValue(['login'])

        permission = Permission.get_collection().find_one({'resource': resource})
        if permission is None:
            return

        current_ops = permission_query_manager.find_user_permission(permission, user['login'])
        if not current_ops:
            return

        for o in operations:
            if o not in current_ops:
                continue
            current_ops.remove(o)

        # delete the user from this permission if there are no more allowed operations
        if not current_ops:
            permission_query_manager.delete_user_permission(permission, user['login'])

        # delete the permission if there are no more users
        if not permission['users']:
            PermissionManager.delete_permission(resource)
            return

        Permission.get_collection().save(permission, safe=True)
Example #20
0
    def DELETE(self, login):

        manager = managers.user_manager()

        tags = [resource_tag(dispatch_constants.RESOURCE_USER_TYPE, login),
                action_tag('delete')]
        call_request = CallRequest(manager.delete_user,
                                   [login],
                                   tags=tags)
        call_request.deletes_resource(dispatch_constants.RESOURCE_USER_TYPE, login)
        result = execution.execute(call_request)

        # Delete any existing user permissions given to the creator of the user
        user_link = serialization.link.current_link_obj()['_href']
        if Permission.get_collection().find_one({'resource' : user_link}):
            Permission.get_collection().remove({'resource' : user_link}, safe=True)

        return self.ok(result)
Example #21
0
    def find_all(self):
        """
        Returns serialized versions of all permissions in the database.

        @return: list of serialized permissions
        @rtype:  list of dict
        """
        all_permissions = list(Permission.get_collection().find())
        return all_permissions
Example #22
0
    def find_all(self):
        """
        Returns serialized versions of all permissions in the database.

        @return: list of serialized permissions
        @rtype:  list of dict
        """
        all_permissions = list(Permission.get_collection().find())
        return all_permissions
Example #23
0
File: cud.py Project: ashcrow/pulp
    def revoke(self, resource, login, operations):
        """
        Revoke permission on a resource for a user and a set of operations.

        @type resource: str
        @param resource: uri path representing a pulp resource

        @type user: str
        @param user: login of user to revoke permissions from

        @type operations: list or tuple of integers
        @param operations:list of allowed operations being revoked
        """
        # we don't revoke permissions from the system
        if login == system.SYSTEM_LOGIN:
            return

        user = User.get_collection().find_one({'login' : login})
        if user is None:
            raise MissingResource(user=login)

        permission = Permission.get_collection().find_one({'resource' : resource})
        if permission is None:
            return

        current_ops = permission['users'].get(user['login'], [])
        if not current_ops:
            return

        for o in operations:
            if o not in current_ops:
                continue
            current_ops.remove(o)

        # delete the user if there are no more allowed operations
        if not current_ops:
            del permission['users'][user['login']]

        # delete the permission if there are no more users
        if not permission['users']:
            self.delete_permission(resource)
            return

        Permission.get_collection().save(permission, safe=True)
Example #24
0
    def delete(self, request, login):
        """
        Delete a user.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param login: login for the requested user
        :type login: str

        :return: An empty response
        :rtype: django.http.HttpResponse
        """
        user_controller.delete_user(login)

        # Delete any existing user permissions given to the creator of the user
        link = reverse('user_resource', kwargs={'login': login})
        if Permission.get_collection().find_one({'resource': link}):
            Permission.get_collection().remove({'resource': link})
        return generate_json_response()
Example #25
0
    def find_by_resource(self, resource_uri):
        """
        Returns a serialized version of the given permission if it exists.
        If a resource cannot be found with the given URI, None is returned.

        @return: serialized data describing the permission
        @rtype:  dict or None
        """
        permission = Permission.get_collection().find_one({'resource': resource_uri})
        return permission
Example #26
0
File: cud.py Project: ashcrow/pulp
    def revoke_all_permissions_from_user(self, login):
        """
        Revoke all the permissions from a given user

        @type login: str
        @param login: login of the user to revoke all permissions from

        @rtype: bool
        @return: True on success
        """
        for permission in factory.permission_query_manager().find_all():
            if login not in permission['users']:
                continue
            del permission['users'][login]
            if permission['users']:
                Permission.get_collection().save(permission, safe=True)
            else:
                # Delete entire permission if there are no more users
                Permission.get_collection().remove({'resource':permission['resource']}, safe=True)
Example #27
0
    def DELETE(self, login):

        manager = managers.user_manager()

        resources = {dispatch_constants.RESOURCE_USER_TYPE: {login: dispatch_constants.RESOURCE_DELETE_OPERATION}}
        tags = [resource_tag(dispatch_constants.RESOURCE_USER_TYPE, login),
                action_tag('delete')]
        call_request = CallRequest(manager.delete_user,
                                   [login],
                                   resources=resources,
                                   tags=tags)
        result = execution.execute(call_request)

        # Delete any existing user permissions given to the creator of the user
        user_link = serialization.link.current_link_obj()['_href']
        if Permission.get_collection().find_one({'resource' : user_link}):
            Permission.get_collection().remove({'resource' : user_link}, safe=True)

        return self.ok(result)
Example #28
0
File: users.py Project: alanoe/pulp
    def delete(self, request, login):
        """
        Delete a user.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param login: login for the requested user
        :type login: str

        :return: An empty response
        :rtype: django.http.HttpResponse
        """
        user_controller.delete_user(login)

        # Delete any existing user permissions given to the creator of the user
        link = reverse('user_resource', kwargs={'login': login})
        if Permission.get_collection().find_one({'resource': link}):
            Permission.get_collection().remove({'resource': link})
        return generate_json_response()
Example #29
0
def _validate_permission():
    """
    Validate the Permission model
    @rtype: int
    @return: number of errors found during validation
    """
    objectdb = Permission.get_collection()
    reference = Permission(u'')
    _base_id(reference)
    return _validate_model(Permission.__name__, objectdb, reference)
Example #30
0
    def delete_permission(resource_uri):
        """
        Deletes the given permission.
        :param resource_uri: identifies the resource URI of the permission being deleted
        :type  resource_uri: str

        :raises MissingResource: if permission for a given resource does not exist
        :raises InvalidValue: if resource URI is invalid
        """

        # Raise exception if resource is invalid
        if resource_uri is None or not isinstance(resource_uri, basestring):
            raise InvalidValue(['resource_uri'])

        # Check whether the permission exists
        found = Permission.get_collection().find_one({'resource': resource_uri})
        if found is None:
            raise MissingResource(resource_uri)

        Permission.get_collection().remove({'resource': resource_uri}, safe=True)
Example #31
0
    def revoke_all_permissions_from_user(self, login):
        """
        Revoke all the permissions from a given user

        @type login: str
        @param login: login of the user to revoke all permissions from

        @rtype: bool
        @return: True on success
        """
        for permission in factory.permission_query_manager().find_all():
            if login not in permission['users']:
                continue
            del permission['users'][login]
            if permission['users']:
                Permission.get_collection().save(permission, safe=True)
            else:
                # Delete entire permission if there are no more users
                Permission.get_collection().remove(
                    {'resource': permission['resource']}, safe=True)
Example #32
0
    def find_by_resource(self, resource_uri):
        """
        Returns a serialized version of the given permission if it exists.
        If a resource cannot be found with the given URI, None is returned.

        @return: serialized data describing the permission
        @rtype:  dict or None
        """
        permission = Permission.get_collection().find_one(
            {'resource': resource_uri})
        return permission
Example #33
0
    def grant(resource, login, operations):
        """
        Grant permission on a resource for a user and a set of operations.

        :param resource: uri path representing a pulp resource
        :type resource: str
        :param login: login of user to grant permissions to
        :type login: str
        :param operations:list of allowed operations being granted
        :type operations: list or tuple of integers

        :raises InvalidValue: if some params are invalid
        """
        # we don't grant permissions to the system
        if login == model.SYSTEM_LOGIN:
            return

        user = model.User.objects(login=login).first()
        if user is None:
            raise InvalidValue(['login'])

        # Make sure resource is a valid string or unicode
        if not isinstance(resource, basestring):
            raise InvalidValue(resource)

        # Get or create permission if it doesn't already exist
        permission = Permission.get_collection().find_one({'resource': resource})
        if permission is None:
            permission = PermissionManager.create_permission(resource)

        current_ops = factory.permission_query_manager().find_user_permission(permission,
                                                                              user['login'],
                                                                              create=True)
        for o in operations:
            if o in current_ops:
                continue
            current_ops.append(o)

        Permission.get_collection().save(permission)
Example #34
0
def migrate(*args, **kwargs):
    """
    Modify the permissions collection schema to allow '.' in usernames
    """
    collection = Permission.get_collection()
    for permission in collection.find({}):
        updated_permissions = []
        if isinstance(permission['users'], dict):
            for username, user_permission in permission['users'].items():
                new_permission = dict(username=username, permissions=user_permission)
                updated_permissions.append(new_permission)
            permission['users'] = updated_permissions
            collection.save(permission, safe=True)
Example #35
0
    def grant(resource, login, operations):
        """
        Grant permission on a resource for a user and a set of operations.

        :param resource: uri path representing a pulp resource
        :type resource: str
        :param login: login of user to grant permissions to
        :type login: str
        :param operations:list of allowed operations being granted
        :type operations: list or tuple of integers

        :raises InvalidValue: if some params are invalid
        """
        # we don't grant permissions to the system
        if login == system.SYSTEM_LOGIN:
            return

        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise InvalidValue(['login'])

        # Make sure resource is a valid string or unicode
        if not isinstance(resource, basestring):
            raise InvalidValue(resource)

        # Get or create permission if it doesn't already exist
        permission = Permission.get_collection().find_one({'resource': resource})
        if permission is None:
            permission = PermissionManager.create_permission(resource)

        current_ops = factory.permission_query_manager().find_user_permission(permission,
                                                                              user['login'],
                                                                              create=True)
        for o in operations:
            if o in current_ops:
                continue
            current_ops.append(o)

        Permission.get_collection().save(permission, safe=True)
def migrate(*args, **kwargs):
    """
    Modify the permissions collection schema to allow '.' in usernames
    """
    collection = Permission.get_collection()
    for permission in collection.find({}):
        updated_permissions = []
        if isinstance(permission['users'], dict):
            for username, user_permission in permission['users'].items():
                new_permission = dict(username=username, permissions=user_permission)
                updated_permissions.append(new_permission)
            permission['users'] = updated_permissions
            collection.save(permission)
Example #37
0
    def grant(self, resource, login, operations):
        """
        Grant permission on a resource for a user and a set of operations.

        @type resource: str
        @param resource: uri path representing a pulp resource

        @type user: str
        @param user: login of user to grant permissions to

        @type operations: list or tuple of integers
        @param operations:list of allowed operations being granted
        """
        # we don't grant permissions to the system
        if login == system.SYSTEM_LOGIN:
            return

        user = User.get_collection().find_one({'login': login})
        if user is None:
            raise MissingResource(user=login)

        # Make sure resource is a valid string or unicode
        if not isinstance(resource, basestring):
            raise InvalidValue(resource)

        # Get or create permission if it doesn't already exist
        permission = Permission.get_collection().find_one(
            {'resource': resource})
        if permission is None:
            permission = self.create_permission(resource)

        current_ops = permission['users'].setdefault(user['login'], [])
        for o in operations:
            if o in current_ops:
                continue
            current_ops.append(o)

        Permission.get_collection().save(permission, safe=True)
Example #38
0
File: cud.py Project: ashcrow/pulp
    def create_permission(self, resource_uri):
        """
        Creates a new Pulp permission.

        @param resource_uri: resource_uri for the permission
        @type  resource_uri: str

        @raise DuplicateResource: if there is already a permission with the requested resource
        @raise InvalidValue: if any of the fields are unacceptable
        """

        existing_permission = Permission.get_collection().find_one({'resource' : resource_uri})
        if existing_permission is not None:
            raise DuplicateResource(resource_uri)

        # Creation
        create_me = Permission(resource=resource_uri)
        Permission.get_collection().save(create_me, safe=True)

        # Retrieve the permission to return the SON object
        created = Permission.get_collection().find_one({'resource' : resource_uri})

        return created
Example #39
0
File: cud.py Project: credativ/pulp
    def create_permission(resource_uri):
        """
        Creates a new Pulp permission.

        :param resource_uri: resource_uri for the permission
        :type  resource_uri: str

        :raises DuplicateResource: if there is already a permission with the requested resource
        :return: The created object
        :rtype: dict
        """

        existing_permission = Permission.get_collection().find_one({'resource': resource_uri})
        if existing_permission is not None:
            raise DuplicateResource(resource_uri)

        # Creation
        create_me = Permission(resource=resource_uri)
        Permission.get_collection().save(create_me, safe=True)

        # Retrieve the permission to return the SON object
        created = Permission.get_collection().find_one({'resource': resource_uri})

        return created
    def test_delete_user_permissions(self):
        """
        Tests deleting an existing user.
        """

        # Setup
        params = {"login": "******", "name": "User 1", "password": "******"}
        self.post("/v2/users/", params=params)

        # Test
        status, body = self.delete("/v2/users/user-1/")

        # Verify that permissions are removed
        self.assertEqual(200, status)
        permission = Permission.get_collection().find_one({"resource": "/v2/users/user-1/"})
        self.assertTrue(permission is None)
    def test_user_default_permissions(self):
        """
        Tests default permissions given to the user after creation.
        """

        # Setup
        params = {"login": "******", "name": "User 1", "password": "******"}

        # Test
        self.post("/v2/users/", params=params)

        # Verify
        user = User.get_collection().find_one({"login": "******"})
        self.assertTrue(user is not None)

        permission = Permission.get_collection().find_one({"resource": "/v2/users/user-1/"})
        self.assertTrue(permission is not None)
        self.assertTrue("user-1" in permission["users"])
        self.assertTrue("ws-user" in permission["users"])
Example #42
0
    def test_delete_user_permissions(self):
        """
        Tests deleting an existing user.
        """

        # Setup
        params = {
            'login' : 'user-1',
            'name' : 'User 1',
            'password' : 'test-password',
        }
        self.post('/v2/users/', params=params)

        # Test
        status, body = self.delete('/v2/users/user-1/')

        # Verify that permissions are removed
        self.assertEqual(200, status)
        permission = Permission.get_collection().find_one({'resource' : '/v2/users/user-1/'})
        self.assertTrue(permission is None)
Example #43
0
    def test_delete_user_permissions(self):
        """
        Tests deleting an existing user.
        """

        # Setup
        params = {
            'login': '******',
            'name': 'User 1',
            'password': '******',
        }
        self.post('/v2/users/', params=params)

        # Test
        status, body = self.delete('/v2/users/user-1/')

        # Verify that permissions are removed
        self.assertEqual(200, status)
        permission = Permission.get_collection().find_one(
            {'resource': '/v2/users/user-1/'})
        self.assertTrue(permission is None)
Example #44
0
def is_authorized(resource, login, operation):
    """
    Check to see if a user is authorized to perform an operation on a resource.

    :param resource: pulp resource url
    :type  resource: str
    :param login: login of user to check permissions for
    :type  login: str
    :param operation: operation to be performed on resource
    :type  operation: int

    :return: True if the user is authorized for the operation on the resource, False otherwise
    :rtype: bool
    """
    user = model.User.objects.get_or_404(login=login)
    if user.is_superuser():
        return True

    permission_query_manager = manager_factory.permission_query_manager()

    # User is authorized if they have access to the resource or any of the its base resources.
    parts = [p for p in resource.split('/') if p]
    while parts:
        current_resource = '/%s/' % '/'.join(parts)
        permission = permission_query_manager.find_by_resource(
            current_resource)
        if permission is not None:
            if operation in permission_query_manager.find_user_permission(
                    permission, login):
                return True
        parts = parts[:-1]

    permission = Permission.get_collection().find_one({'resource': '/'})
    return (permission is not None
            and operation in permission_query_manager.find_user_permission(
                permission, login))
Example #45
0
 def clean(self):
     super(AuthControllersTests, self).clean()
     User.get_collection().remove(safe=True)
     Role.get_collection().remove(safe=True)
     Permission.get_collection().remove(safe=True)
Example #46
0
 def _getcollection(self):
     return Permission.get_collection()
Example #47
0
 def clean(self):
     super(AuthControllersTests, self).clean()
     User.get_collection().remove(safe=True)
     Role.get_collection().remove(safe=True)
     Permission.get_collection().remove(safe=True)