validators.py 4.16 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
from django.core.exceptions import ValidationError
from django.utils.deconstruct import deconstructible
from jsonschema import FormatChecker
from jsonschema.exceptions import ValidationError as JsonValidationError
from jsonschema.validators import validator_for

from backend_app.validation.schemas import (
    USEFUL_LINKS_SCHEMA,
    PHOTOS_SCHEMA,
    TAGS_SCHEMA_COLLECTION,
11
    THEME_SCHEMA,
12 13 14 15 16 17 18 19 20 21 22 23 24
)
from backend_app.validation.utils import DEFINITIONS_RESOLVER, get_schema_for_tag

# Format checker to use with jsonschemas to make sure errors are thrown
FORMAT_CHECKER = FormatChecker(["uri"])


class JsonValidator(object):
    """
    Class to hold the similar logic between the classes that are used validate JSON
    """

    # Value to override
25 26 27 28 29 30
    schema = None

    def __init__(self):
        self.validator = validator_for(self.schema)(
            self.schema, resolver=DEFINITIONS_RESOLVER, format_checker=FORMAT_CHECKER
        )
31 32 33 34 35 36

    def __call__(self, value):
        """
        Perform validation

        :param value: Value to validate
37
        :type value: list, dict
38 39 40 41 42 43 44 45 46 47 48 49 50 51
        :raises: ValidationErrort
        """
        try:
            self.validator.validate(value)
        except JsonValidationError as e:
            raise ValidationError(e.message)


@deconstructible()
class UsefulLinksValidator(JsonValidator):
    """
    Validator to be used on a JSON field that is suppose to store Useful links
    """

52
    schema = USEFUL_LINKS_SCHEMA
53 54 55 56 57 58 59 60


@deconstructible()
class PhotosValidator(JsonValidator):
    """
    Validator to be used on a JSON field that is suppose to store photos
    """

61 62 63 64 65 66 67 68 69 70
    schema = PHOTOS_SCHEMA


@deconstructible()
class ThemeValidator(JsonValidator):
    """
    Validator to be used on a JSON field that is suppose to store the theme data
    """

    schema = THEME_SCHEMA
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152


@deconstructible()
class TaggedItemValidator(object):
    def __init__(self):
        self.validators = dict()
        for tag_name, schema in TAGS_SCHEMA_COLLECTION.items():
            self.validators[tag_name] = validator_for(schema)(
                schema, resolver=DEFINITIONS_RESOLVER, format_checker=FORMAT_CHECKER
            )

    def __call__(self, tag_name, value):
        """
        Perform validation

        :param value: Value to validate
        :type value: list
        :raises: ValidationErrort
        """
        try:
            try:
                self.validators[tag_name].validate(value)
            except KeyError:
                raise ValidationError("tag with name `{}` not fount".format(tag_name))
        except JsonValidationError as e:
            raise ValidationError(e.message)


@deconstructible()
class PathExtensionValidator(object):
    """
    Validator to be used to check if a string ends with .(ext) from a list
    of allowed extensions.
    """

    def __init__(self, allowed_extensions):
        """
        :param allowed_extensions:
        :type allowed_extensions: iterable
        """
        self.allowed_extensions = [ext.lower() for ext in allowed_extensions]

    def __call__(self, string):
        """
        Perform validation

        :param string: Value to validate
        :type string: str
        :raises: ValidationError
        """
        try:
            if string.split(".")[-1].lower() not in self.allowed_extensions:
                raise ValidationError(
                    "The file you submitted has an unauthorized extension"
                )
        except KeyError:
            raise ValidationError("File extension not recognized")


@deconstructible()
class TagNameValidator(object):
    """
    Validator to be used to check that a provided tag name can checked in the app.
    (A schema needs to be provided for it in tags_schema_collection.json).
    """

    def __call__(self, tag_name):
        """
        Perform validation

        :param tag_name: name of the tag
        :type tag_name: str
        :raises: ValidationError
        """
        try:
            get_schema_for_tag(tag_name)
        except KeyError:
            raise ValidationError(
                "{} doesn't have a validation schema associated with it. Check `tags_schema_collection.json`".format(
                    tag_name
                )
            )