vpnmanager/manager/views.py
2018-11-28 16:38:35 +01:00

114 lines
3.6 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("reboot" if device.reboot else "")
@csrf_exempt
def hosts(request):
device = get_object_or_404(Device, secret=request.POST.get("secret", ""))
device.reboot = False
device.save()
return render(request, "manager/hosts", {"device": device})
def ping(request, device_id):
if request.user.is_authenticated:
device = None
ajax = '{\n "status": '
for organization in Organization.objects.filter(users=request.user):
device = device or Device.objects.filter(id=device_id, organization=organization)
if not device:
ajax += "-1"
else:
try:
socket.inet_aton(device[0].curip)
ajax += str(int(not os.WEXITSTATUS(os.system("ping -c1 -w1 " + device[0].curip + " > /dev/null 2>&1")))) # This monster is not long enough yet.
ajax += ',\n "ip": "%s"' % device[0].curip
ajax += ',\n "time": "%s"' % device[0].lasttime
except:
ajax += "-3"
else:
ajax += "-2"
ajax += "\n}"
return HttpResponse(ajax)
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].reboot = True if request.POST.get("reboot", "0") == "True" else False
device[0].save()
return redirect("/")
return render(request, "manager/edit.html",
{
"title": "Edit Device",
"device": device[0],
"subnets": subnets
}
)
else:
return redirect("/")