from django.views.generic.edit import CreateView from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.messages.views import SuccessMessageMixin from rest_framework.response import Response from django.shortcuts import render from rest_framework import viewsets, permissions from .models import * from .serializers import * from .selectors import * from .services import * from .forms import * from .tasks import * # class VPNPoolViewSet(viewsets.ModelViewSet): # serializer_class = VPNPoolSerializer # permission_classes = [permissions.IsAdminUser] # queryset = VPNPool.objects.all() class WireGuardVPNViewSet(viewsets.ModelViewSet): serializer_class = WireGuardVPNSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): if self.request.user.is_superuser: obj = WireGuardVPN.objects.all() else: obj = WireGuardVPN.objects.filter(owner=self.request.user) return obj def create(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) vpn = create_wireguard_vpn( owner=self.request.user, public_key=serializer.validated_data['wireguard_public_key'], network_mask=serializer.validated_data['network_mask'] ) configure_wireguard_server.apply_async((vpn.vpnpool,)) return Response(WireGuardVPNSerializer(vpn).data) class WireGuardVPNCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = WireGuardVPN login_url = '/login/' success_url = '/' success_message = "%(network) was created successfully" form_class = WireGuardVPNForm def get_success_message(self, cleaned_data): return self.success_message % dict(cleaned_data, the_prefix = self.object.prefix)