uncloud-mravi/uncloud_net/serializers.py

59 lines
1.7 KiB
Python
Raw Normal View History

import base64
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from .models import *
2020-12-13 12:28:43 +00:00
from .services import *
2020-12-20 20:45:47 +00:00
from .selectors import *
2020-12-13 12:28:43 +00:00
class WireGuardVPNSerializer(serializers.ModelSerializer):
2020-12-13 16:59:35 +00:00
address = serializers.CharField(read_only=True)
2020-12-13 17:05:48 +00:00
vpn_server = serializers.CharField(read_only=True)
vpn_server_public_key = serializers.CharField(read_only=True)
2020-12-13 16:59:35 +00:00
network_mask = serializers.IntegerField()
2020-12-13 12:28:43 +00:00
class Meta:
model = WireGuardVPN
2020-12-13 17:05:48 +00:00
fields = [ 'wireguard_public_key', 'address', 'network_mask', 'vpn_server',
'vpn_server_public_key' ]
2020-12-13 12:28:43 +00:00
2020-12-13 16:59:35 +00:00
extra_kwargs = {
'network_mask': {'write_only': True }
}
2020-12-20 20:45:47 +00:00
def validate_network_mask(self, value):
msg = _(f"No pool for network size {value}")
sizes = allowed_vpn_network_reservation_size()
if not value in sizes:
raise serializers.ValidationError(msg)
2020-12-20 21:03:43 +00:00
return value
2020-12-20 20:45:47 +00:00
2020-12-20 18:37:12 +00:00
def validate_wireguard_public_key(self, value):
msg = _("Supplied key is not a valid wireguard public key")
2020-12-20 18:37:12 +00:00
"""
FIXME: verify that this does not create broken wireguard config files,
i.e. contains \n or similar!
We might even need to be more strict to not break wireguard...
"""
2020-12-20 18:37:12 +00:00
try:
base64.standard_b64decode(value)
except Exception as e:
raise serializers.ValidationError(msg)
2020-12-20 18:37:12 +00:00
if '\n' in value:
raise serializers.ValidationError(msg)
2020-12-20 18:37:12 +00:00
return value
2020-12-20 20:45:47 +00:00
class WireGuardVPNSizesSerializer(serializers.Serializer):
size = serializers.IntegerField(min_value=0, max_value=128)