from django.db import models from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from base64 import b64decode from django.utils.translation import gettext_lazy as _ import ipaddress def key_validator(value): try: k = b64decode(value) except Exception: raise ValidationError(_("Key is not a valid b64 string")) if len(k) != 32: raise ValidationError(_("Key must be a 32 byte value")) def cidr_validator(value): try: a = ipaddress.ip_network(value) except Exception: raise ValidationError(_("Not a valid ip addres")) if a.version != 4: raise ValidationError(_("Not a ipv4 addres")) class UserConnection(models.Model): public_key = models.fields.CharField(max_length=512, blank=False, null=False, unique=True, validators=[key_validator]) preshared_key = models.fields.CharField(max_length=512, blank=True, null=True, unique=False, validators=[key_validator]) vpn_ip = models.fields.CharField(max_length=128, blank=False, null=False, unique=True, validators=[cidr_validator]) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, blank=True) active = models.BooleanField(default=False, blank=False, null=False) notes = models.fields.CharField(max_length=512, blank=True, null=True) create_ts = models.DateTimeField(auto_now_add=True, blank=False, null=False) update_ts = models.DateTimeField(auto_now=True, blank=False, null=False) def save(self, **kwargs): if "/" not in self.vpn_ip: # have always a cidr self.vpn_ip += "/32" super().save(**kwargs) def __str__(self): user = self.user.username if self.user else "da assegnare" return f"[{user}] ip: {self.vpn_ip} key: {self.public_key}"