This repository was archived by the owner on Nov 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathvalidators.py
63 lines (49 loc) · 1.81 KB
/
validators.py
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
import ipaddress
from rest_framework import serializers
from .models import Consumer
class BaseValidator(object):
def __init__(self, config):
self.config = config
def __call__(self):
# Method should only raise serializer.ValidationError in case of errors
pass
class ConsumerValidator(BaseValidator):
def __call__(self):
# Check valid consumer_id if any given
if (
self.config.get('consumer_id') and
not Consumer.objects.filter(pk=self.config['consumer_id']).first()
):
raise serializers.ValidationError({
'config': 'Invalid consumer'
})
class IPListValidator(BaseValidator):
def __call__(self):
# Remove duplicated values
self.config['whitelist'] = list(set(self.config.get('whitelist', [])))
self.config['blacklist'] = list(set(self.config.get('blacklist', [])))
try:
[
ipaddress.ip_network(ip)
for ip in self.config['whitelist']+self.config['blacklist']
]
except (ipaddress.AddressValueError, ValueError) as err:
raise serializers.ValidationError({
'config': err
})
class WhitelistBlacklistMutuallyExclusive(BaseValidator):
def __call__(self):
# Whitelist and blacklist are mutually exclusives
if self.config.get('whitelist') and self.config.get('blacklist'):
raise serializers.ValidationError({
'config': 'Whitelist and blacklist are mutually exclusive',
})
validator_classes = {
'ip-restriction': [
WhitelistBlacklistMutuallyExclusive,
IPListValidator,
ConsumerValidator,
],
'request-termination': [ConsumerValidator, ],
'acl': [WhitelistBlacklistMutuallyExclusive, ]
}