コード例 #1
0
def insert_type(data: dict):
    """
    HTTP `POST` route for insert a single type resource.

    Args:
        data (TypeModel.SCHEMA): Insert data of a new type.

    Raises:
        ManagerGetError: If the inserted resource could not be found after inserting.
        ManagerInsertError: If something went wrong during insertion.

    Returns:
        InsertSingleResponse: Insert response with the new type and its public_id.
    """
    type_manager = TypeManager(database_manager=current_app.database_manager)
    data.setdefault('creation_time', datetime.utcnow())
    try:
        result_id: PublicID = type_manager.insert(data)
        raw_doc = type_manager.get(public_id=result_id)
    except ManagerGetError as err:
        return abort(404, err.message)
    except ManagerInsertError as err:
        return abort(400, err.message)
    api_response = InsertSingleResponse(result_id,
                                        raw=TypeModel.to_json(raw_doc),
                                        url=request.url,
                                        model=TypeModel.MODEL)
    return api_response.make_response(prefix='types')
コード例 #2
0
def get_type(public_id: int):
    """
    HTTP `GET`/`HEAD` route for a single type resource.

    Args:
        public_id (int): Public ID of the type.

    Raises:
        ManagerGetError: When the selected type does not exists.

    Returns:
        GetSingleResponse: Which includes the json data of a TypeModel.
    """
    type_manager = TypeManager(database_manager=current_app.database_manager)
    body = request.method == 'HEAD'

    try:
        type_ = type_manager.get(public_id)
    except ManagerGetError as err:
        return abort(404, err.message)
    api_response = GetSingleResponse(TypeModel.to_json(type_),
                                     url=request.url,
                                     model=TypeModel.MODEL,
                                     body=body)
    return api_response.make_response()
コード例 #3
0
def verify_import_access(user: UserModel, _type: TypeModel, _manager: TypeManager):
    """Validate if a user has access to objects of this type."""

    location = 'acl.groups.includes.' + str(user.group_id)
    query = {'$and': [{'$or': [
        {'$or': [
            {'acl': {'$exists': False}}, {'acl.activated': False}]
        },
        {'$and': [
            {'acl.activated': True},
            {'$and': [
                {location: {'$exists': True}},
                {location: {'$all': [
                    AccessControlPermission.READ.value,
                    AccessControlPermission.CREATE.value,
                    AccessControlPermission.UPDATE.value]
                    }
                }
            ]
            }
        ]
        }]
    }, {'public_id': _type.public_id}]}
    types_ = _manager.iterate(filter=query, limit=1, skip=0, sort='public_id', order=1)
    if len([TypeModel.to_json(_) for _ in types_.results]) == 0:
        raise AccessDeniedError(f'The objects of the type `{_type.name}` are protected by ACL permission!')
コード例 #4
0
    def update_type(self, data: (TypeModel, dict)):
        if isinstance(data, TypeModel):
            update_type = data
        elif isinstance(data, dict):
            update_type = TypeModel.from_data(data)
        else:
            raise WrongInputFormatError(TypeModel, data,
                                        "Possible data: dict or TypeModel")

        ack = self._update(collection=TypeModel.COLLECTION,
                           public_id=update_type.get_public_id(),
                           data=TypeModel.to_json(update_type))
        if self._event_queue:
            event = Event("cmdb.core.objecttype.updated",
                          {"id": update_type.get_public_id()})
            self._event_queue.put(event)
        return ack
コード例 #5
0
 def get_types_by(self, sort='public_id', **requirements):
     try:
         return [
             TypeModel.from_data(data) for data in self._get_many(
                 collection=TypeModel.COLLECTION, sort=sort, **requirements)
         ]
     except Exception as err:
         raise ObjectManagerGetError(err=err)
コード例 #6
0
 def get_all_types(self) -> List[TypeModel]:
     try:
         raw_types: List[dict] = self._get_many(collection=TypeModel.COLLECTION)
     except Exception as err:
         raise ObjectManagerGetError(err=err)
     try:
         return [TypeModel.from_data(type) for type in raw_types]
     except Exception as err:
         raise ObjectManagerInitError(err=err)
コード例 #7
0
 def get_type(self, public_id: int):
     try:
         return TypeModel.from_data(
             self.dbm.find_one(collection=TypeModel.COLLECTION,
                               public_id=public_id))
     except RequiredInitKeyNotFoundError as err:
         raise ObjectManagerInitError(err=err.message)
     except Exception as err:
         raise ObjectManagerGetError(err=err)
コード例 #8
0
 def get_type_by(self, **requirements) -> TypeModel:
     try:
         found_type_list = self._get_many(collection=TypeModel.COLLECTION,
                                          limit=1,
                                          **requirements)
         if len(found_type_list) > 0:
             return TypeModel.from_data(found_type_list[0])
         else:
             raise ObjectManagerGetError(
                 err='More than 1 type matches this requirement')
     except (CMDBError, Exception) as e:
         raise ObjectManagerGetError(err=e)
コード例 #9
0
    def get_type_aggregate(self, arguments):
        """This method does not actually
           performs the find() operation
           but instead returns
           a objects sorted by value of the documents that meet the selection criteria.

           Args:
               arguments: query search for
           Returns:
               returns the list of CMDB Types sorted by value of the documents
           """
        type_list = []
        cursor = self.dbm.aggregate(TypeModel.COLLECTION, arguments)
        for document in cursor:
            put_data = json.loads(json_util.dumps(document), object_hook=object_hook)
            type_list.append(TypeModel.from_data(put_data))
        return type_list
コード例 #10
0
def get_types(params: CollectionParameters):
    """
    HTTP `GET`/`HEAD` route for getting a iterable collection of resources.

    Args:
        params (CollectionParameters): Passed parameters over the http query string

    Returns:
        GetMultiResponse: Which includes a IterationResult of the TypeModel.

    Example:
        You can pass any parameter based on the CollectionParameters.
        Optional parameters are passed over the function declaration.

    Raises:
        FrameworkIterationError: If the collection could not be iterated.
        ManagerGetError: If the collection could not be found.

    """
    type_manager = TypeManager(database_manager=current_app.database_manager)
    body = request.method == 'HEAD'

    try:
        iteration_result: IterationResult[TypeModel] = type_manager.iterate(
            filter=params.filter,
            limit=params.limit,
            skip=params.skip,
            sort=params.sort,
            order=params.order)
        types = [TypeModel.to_json(type) for type in iteration_result.results]
        api_response = GetMultiResponse(types,
                                        total=iteration_result.total,
                                        params=params,
                                        url=request.url,
                                        model=TypeModel.MODEL,
                                        body=body)
    except FrameworkIterationError as err:
        return abort(400, err.message)
    except ManagerGetError as err:
        return abort(404, err.message)
    return api_response.make_response()
コード例 #11
0
def delete_type(public_id: int):
    """
    HTTP `DELETE` route for delete a single type resource.

    Args:
        public_id (int): Public ID of the deletable type

    Raises:
        ManagerGetError: When the type with the `public_id` was not found.
        ManagerDeleteError: When something went wrong during the deletion.

    Notes:
        Deleting the type will also delete all objects in this type!

    Returns:
        DeleteSingleResponse: Delete result with the deleted type as data.
    """
    type_manager = TypeManager(database_manager=current_app.database_manager)
    from cmdb.framework.cmdb_object_manager import CmdbObjectManager
    deprecated_object_manager = CmdbObjectManager(
        database_manager=current_app.database_manager)

    try:
        objects_ids = [
            object_.get_public_id() for object_ in
            deprecated_object_manager.get_objects_by_type(public_id)
        ]
        deprecated_object_manager.delete_many_objects({'type_id': public_id},
                                                      objects_ids, None)
        deleted_type = type_manager.delete(public_id=PublicID(public_id))
        api_response = DeleteSingleResponse(
            raw=TypeModel.to_json(deleted_type), model=TypeModel.MODEL)
    except ManagerGetError as err:
        return abort(404, err.message)
    except ManagerDeleteError as err:
        return abort(400, err.message)
    except Exception as err:
        return abort(400, str(err))
    return api_response.make_response()