Repository navigation
Expand file tree
/
Copy pathsecurity.py
More file actions
executable file
·81 lines (69 loc) · 2.67 KB
/
Copy pathsecurity.py
File metadata and controls
executable file
·81 lines (69 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
from copy import deepcopy
from functools import wraps
from flask import request
from library.api.exceptions import (
FieldMissingException, InvalidDataException, FieldLengthErrorException,
DataTypeErrorException,
)
class Validation(object):
def __init__(self, yaml_json):
self.yaml_json = yaml_json
self.key_func_map = {
'required': self.validate_required,
'min_length': self.validate_min_length,
'max_length': self.validate_max_length,
'type': self.validate_type,
}
@staticmethod
def validate_required(*args):
key = args[0]
try:
request_value = request.json.get(key)
if request_value is None:
raise FieldMissingException("{} is required".format(key))
except AttributeError:
raise InvalidDataException()
@staticmethod
def validate_min_length(*args):
key = args[0]
expect_value = args[1]
request_value = request.json.get(key)
if request_value is not None and len(request_value) < expect_value:
raise FieldLengthErrorException("{} min length is {}".format(key, expect_value))
@staticmethod
def validate_max_length(*args):
key = args[0]
expect_value = args[1]
request_value = request.json.get(key)
if request_value is not None and len(request_value) > expect_value:
raise FieldLengthErrorException("{} max length is {}".format(key, expect_value))
@staticmethod
def validate_type(*args):
ttype_dict = {
'list': list,
'basestring': str,
'dict': dict,
'int': int,
'bool': bool,
}
key = args[0]
value = args[1]
request_value = request.json.get(key)
if request_value is not None and not isinstance(request_value, ttype_dict.get(value)):
raise DataTypeErrorException("{} should be a {}".format(key, value))
def validation(self, validate_name=None):
def wrapper(func):
@wraps(func)
def _(*args, **kwargs):
protocol, vname = validate_name.split(':')
if request.method == protocol:
all_json = self.yaml_json
validate_json = deepcopy(all_json.get(vname))
del validate_json['returnvalue']
for item, settings in validate_json.items():
for key, value in settings.items():
f = self.key_func_map.get(key)
f(item, value)
return func(*args, **kwargs)
return _
return wrapper