validators.py 5.23 KB
Newer Older
1
2
3
import imghdr
import xml.etree.cElementTree as et

4
5
6
7
8
9
10
11
12
13
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,
14
    THEME_SCHEMA,
15
16
17
18
19
20
21
22
23
24
25
26
27
)
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
28
29
30
31
32
33
    schema = None

    def __init__(self):
        self.validator = validator_for(self.schema)(
            self.schema, resolver=DEFINITIONS_RESOLVER, format_checker=FORMAT_CHECKER
        )
34
35
36
37
38
39

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

        :param value: Value to validate
40
        :type value: list, dict
41
42
43
44
45
46
47
48
49
50
51
52
53
54
        :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
    """

55
    schema = USEFUL_LINKS_SCHEMA
56
57
58
59
60
61
62
63


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

64
65
66
67
68
69
70
71
72
73
    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
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
153
154
155


@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
                )
            )
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194


@deconstructible()
class ImageValidator(object):
    """
    Validator to be check that a file is a valid image.
    Can't be tricked, definitely bulletproof.
    """

    # Plus svg
    allowed_format = ["jpeg", "png", "webp"]

    def __call__(self, file):
        self.is_image(file)

    def is_image(self, fp):
        if imghdr.what(fp) not in self.allowed_format:
            if type(fp) is str:
                with open(fp, "r") as f:
                    if not self.is_svg(f):
                        raise ValidationError("Image not recognized")
            else:
                if not self.is_svg(fp):
                    raise ValidationError("Image not recognized")

    @staticmethod
    def is_svg(f):
        """
        Check if the provided file is svg
        """
        f.seek(0)
        tag = None
        try:
            for event, el in et.iterparse(f, ("start",)):
                tag = el.tag
                break
        except et.ParseError:
            pass
        return tag == "{http://www.w3.org/2000/svg}svg"