Пример #1
0
    def validate_risk_data(self, data):
        """Return risk data object after successful loading of data"""

        risk_type_id = data.get('risk_type_id')

        data = data.get('data')

        from api.models.risk_type import RiskType

        risk_type = RiskType.get(risk_type_id)

        if not risk_type:
            raise ValidationError(
                {'message': ERROR_MESSAGES['EXISTS'].format('Risk Type')}, 400)

        attributes = risk_type.attributes.all()

        errors = {}
        for attribute in attributes:
            if not attribute.is_required and attribute._key not in data:
                errors[attribute._key] = ERROR_MESSAGES['ATTRIBUTE_NOT_FOUND']

        attribute_keys = [attribute._key for attribute in attributes]

        for key, value in data.items():
            if key not in attribute_keys:
                errors[key] = ERROR_MESSAGES['ATTRIBUTE_NOT_RELATED_1'].format(
                    risk_type.name)

        if errors:
            raise ValidationError(
                {
                    'message': ERROR_MESSAGES['BAD_DATA_ATTRIBUTE'],
                    'error': errors
                }, 400)
Пример #2
0
def validate_exist(model, error_key, **kwargs):
    obj = model.filter(**kwargs).first()
    if obj:
        raise ValidationError(
        {
            'message': ERROR_MESSAGES[error_key]
        }, 409)
Пример #3
0
    def validate_risk_type(self, data):
        """Return risk type object after successful loading of data"""

        record_id = data.get('id')
        name = data.get('name')
        company_id = data.get('company_id')

        data.pop('id', None)  # remove id from kwargs if found or return None

        if record_id:
            result = RiskType.filter(**data).filter(
                RiskType.id == record_id).first(
                )  # selects the first query object for model records

            if result:
                return None  # return None if query object is found

        # check name column for duplications
        if name and company_id:
            result = RiskType.query.with_entities(RiskType.name)\
                .filter(RiskType.name.ilike(name), RiskType.company_id==company_id).first()

            if result and result[0].lower() == name.lower():
                raise ValidationError(
                    {'message': ERROR_MESSAGES['EXISTS'].format('Risk Type')},
                    409)
Пример #4
0
    def delete(self):
        """ Delete a Risk Type """

        if self.risks.count() > 0:
            raise ValidationError(
                {
                    'message':
                    ERROR_MESSAGES['DELETING_RELATED_OBJECTS'].format(
                        'Risk type', 'Risks'),
                }, 400)

        #Remove attributes
        self.attributes.delete()
        return super(RiskType, self).delete()
Пример #5
0
    def get_or_404(cls, id):
        """
        return entries by id
        """

        record = cls.get(id)

        if not record:
            raise ValidationError(
                {
                    'message':
                    f'{re.sub(r"(?<=[a-z])[A-Z]+",lambda x: f" {x.group(0).lower()}" , (cls.__name__))} not found'
                }, 404)

        return record
Пример #6
0
    def delete(self):
        """ Delete a Category """

        if self.favorites.count() > 0:
            raise ValidationError(
                {
                    'message':
                    ERROR_MESSAGES['DELETING_RELATED_OBJECTS'].format(
                        'Category', 'Favorites'),
                }, 400)

        status = super(Category, self).delete()
        Audit.log_delete(self, 'category',
                         f'Category with name {self.name} was removed')
        return status
Пример #7
0
 def decode_auth_token(auth_token):
     """
     Decodes the auth token
     :param auth_token:
     :return: integer|string
     """
     try:
         payload = jwt.decode(auth_token, AppConfig.JWT_SECRET_KEY)
         suspended_token = SuspendedToken.filter(token=auth_token).first()
         if suspended_token:
             raise jwt.ExpiredSignature
         return payload
     except (
             ValueError,
             TypeError,
             jwt.ExpiredSignatureError,
             jwt.DecodeError,
             jwt.InvalidTokenError,
             jwt.InvalidSignatureError,
             jwt.InvalidAlgorithmError,
             jwt.InvalidIssuerError,
     ) as error:
         exception_mapper = {
             ValueError: (ERROR_MESSAGES['SERVER'], 500),
             TypeError: (ERROR_MESSAGES['SERVER'], 500),
             jwt.ExpiredSignatureError:
             (ERROR_MESSAGES['JWT_EXPIRED_TOKEN'], 401),
             jwt.DecodeError: (ERROR_MESSAGES['JWT_INVALID_TOKEN'], 401),
             jwt.InvalidTokenError:
             (ERROR_MESSAGES['JWT_INVALID_TOKEN'], 401),
             jwt.InvalidIssuerError: (ERROR_MESSAGES['JWT_ISSUER'], 401),
             jwt.InvalidAlgorithmError:
             (ERROR_MESSAGES['JWT_ALGORITHM'], 401),
             jwt.InvalidSignatureError:
             (ERROR_MESSAGES['JWT_SIGNATURE'], 500)
         }
         message, status_code = exception_mapper.get(
             type(error), (ERROR_MESSAGES['SERVER'], 500))
         raise ValidationError({'message': message}, status_code)
Пример #8
0
    def post(self):
        """
        POST method for creating risk-types.

        Payload should have the following parameters:
            name(str): name of the risk-type
        """

        request_data = request.get_json()

        request_data['companyId'] = request.decoded_token.get('sub').get(
            'company')['id']

        risk_type_schema = RiskTypeSchema()
        risk_type_data = risk_type_schema.load_object_into_schema(request_data)

        risk_type = RiskType(**risk_type_data)

        attributes_data = request_data.get('customAttributes')

        if attributes_data:
            attributes_schema = AttributeSchema(many=True, exclude=['id'])

            attributes = attributes_schema.load_object_into_schema(
                attributes_data)
            risk_type.attributes = attributes
            attributes = attributes_schema.dump(attributes).data
        else:
            raise ValidationError(
                {'message': ERROR_MESSAGES['PROVIDE_CUSTOM_ATTRIBUTES']})

        risk_type = risk_type.save()

        return {
            'status': 'success',
            'message': SUCCESS_MESSAGES['RISK_TYPE_CREATED'],
            'data': risk_type_schema.dump(risk_type).data
        }, 201
Пример #9
0
    def is_valid(self, data):
        """
        Ensure id fields reference existing resource
        and name supplied is not owned by an exising category

        Arguments:
            data (dict): request body

        Raises:
            ValidationError: Used to raise exception if request body is empty
        """
        if not data.get('name'):
            raise ValidationError(
                {'message': ERROR_MESSAGES['NOT_FOUND'].format('Name')}, 400)
        if data.get('id'):
            category = Category.get(data.get('id'))
            if category.name == data.get('name'):
                return

        validate_duplicate(Category,
                           'EXISTS',
                           'Category',
                           name=data.get('name'))
Пример #10
0
def validate(model, *args, **kwargs):
    error_key, obj, status_code = args
    instance = model.filter(**kwargs).first()
    if instance:
        raise ValidationError(
            {'message': ERROR_MESSAGES[error_key].format(obj)}, status_code)
Пример #11
0
 def raise_errors(errors):
     if errors:
         raise ValidationError(
             dict(errors=errors, message=ERROR_MESSAGES['DEFAULT']), 400)