vpnmanager/manager/views.py
2018-11-26 20:55:09 +01:00

105 lines
3.2 KiB
Python

from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse
from django.contrib.auth.forms import AuthenticationForm
from django.db.models import Q
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from .models import Device, Organization, Network
import os
import socket
def index(request):
if request.user.is_authenticated:
return redirect("/devices")
else:
return redirect("/accounts/login")
@csrf_exempt
def heartbeat(request):
device = get_object_or_404(Device, secret=request.POST.get("secret", ""))
device.curip = request.POST.get("ip", "")
device.lasttime = timezone.now()
device.save()
return HttpResponse("")
@csrf_exempt
def hosts(request):
device = get_object_or_404(Device, secret=request.POST.get("secret", ""))
return render(request, "manager/hosts", {"device": device})
def ping(request, device_id):
if request.user.is_authenticated:
device = None
for organization in Organization.objects.filter(users=request.user):
device = device or Device.objects.filter(id=device_id, organization=organization)
if not device:
return HttpResponse("-1")
try:
socket.inet_aton(device[0].curip)
return HttpResponse(str(int(not os.WEXITSTATUS(os.system("ping -c1 -w1 " + device[0].curip + " > /dev/null 2>&1"))))) # This monster is not long enough yet.
except:
return HttpResponse("-3")
else:
return HttpResponse("-2")
def devices(request):
if request.user.is_authenticated:
user = request.user
devices = set()
orga = None
for organization in Organization.objects.filter(users=user):
orga = orga or organization
for device in Device.objects.filter(organization=organization):
devices.add(device)
return render(request, "manager/index.html",
{
"title": "Device Administration",
"user": user,
"organization": orga,
"devices": devices
}
)
else:
return redirect("/")
def editdevice(request, device_id):
if request.user.is_authenticated:
device = None
subnets = set()
for organization in Organization.objects.filter(users=request.user):
device = device or Device.objects.filter(id=device_id, organization=organization)
for subnet in Network.objects.filter(organizations=organization):
subnets.add(subnet)
if not device:
return redirect("/")
if request.POST.get("subnet", ""):
subnet = Network.objects.filter(intip=request.POST.get("subnet", device[0].network.intip))
if subnet[0] in subnets:
device[0].name = request.POST.get("name", "")
device[0].network = subnet[0]
device[0].save()
return redirect("/")
return render(request, "manager/edit.html",
{
"title": "Edit Device",
"device": device[0],
"subnets": subnets
}
)
else:
return redirect("/")