uncloud/uncloud_net/serializers.py
2020-12-25 10:08:34 +01:00

57 lines
1.6 KiB
Python

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 *
from .services import *
from .selectors import *
class WireGuardVPNSerializer(serializers.ModelSerializer):
address = serializers.CharField(read_only=True)
vpn_server = serializers.CharField(read_only=True)
vpn_server_public_key = serializers.CharField(read_only=True)
network_mask = serializers.IntegerField()
class Meta:
model = WireGuardVPN
fields = [ 'wireguard_public_key', 'address', 'network_mask', 'vpn_server',
'vpn_server_public_key' ]
extra_kwargs = {
'network_mask': {'write_only': True }
}
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)
return value
def validate_wireguard_public_key(self, value):
msg = _("Supplied key is not a valid wireguard public key")
"""
Verify wireguard key.
See https://lists.zx2c4.com/pipermail/wireguard/2020-December/006221.html
"""
try:
decoded_key = base64.standard_b64decode(value)
except Exception as e:
raise serializers.ValidationError(msg)
if not len(decoded_key) == 32:
raise serializers.ValidationError(msg)
return value
class WireGuardVPNSizesSerializer(serializers.Serializer):
size = serializers.IntegerField(min_value=0, max_value=128)