wg-backend-django/wg_api/views.py
2022-12-17 01:45:33 +07:00

520 lines
14 KiB
Python

from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth import authenticate
# from django.core import serializer
from rest_framework import viewsets
from rest_framework.decorators import api_view, permission_classes
from rest_framework.views import APIView
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from rest_framework.permissions import IsAdminUser
from .serializers import wgSerializer
from .models import user_model
from .utils.html_parser import get_logs, get_profiles
import json
from .utils.statistics import count_clients, count_traffic, count_connection, count_percentage, count_broken
from .utils.reqs_handler import req_edit_state, req_edit_user, req_apply_sys, req_ip_recommendation, reg_bulk
from django.middleware.csrf import get_token
from django.views.decorators.csrf import csrf_exempt
class wgLogin(APIView):
authentication_classes = [SessionAuthentication, BasicAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request, format=None):
# serializer = self.get_serializer(data=request.data)
# serializer.is_valid(raise_exception=True) user = serializer.validated_data['user']
user = request.GET.get('username')
password = request.GET.get('password')
content = {
'user': str(request.user), # `django.contrib.auth.User` instance.
'auth': str(request.auth), # None
}
# user = content['user']
print(request.META['HTTP_AUTHORIZATION'])
print(user)
print(password)
user = authenticate(username=user, password=password)
print("****-> ",user.id)
token, _ = Token.objects.get_or_create(user=user)
response = Response(content)
response.set_cookie('Token', token.key)
# print(response)
return response
# return response
# return Response(content)
# Create your views here.
class wgView(viewsets.ModelViewSet):
# queryset = user_model.objects.all()
queryset = user_model.objects.all()
serializer_class = wgSerializer
# print(">"*100," ",inf_data)
def get(self, request):
return self.inf_connector()
# iserializer = wgSerializer
# queryset = user_model.objects.all()
# serializers_class = wgSerializer
# serializer = wgSerializer
# permission_classes = [IsAdminUser]
@csrf_exempt
@api_view(["GET"])
@permission_classes([IsAuthenticated])
def wgCheckAuth(request):
return HttpResponse(json.dumps({"Auth":True}))
@csrf_exempt
@api_view(["GET"])
@permission_classes([IsAuthenticated])
def wgViewLogs(request):
param = request.GET.get('param', '')
data = get_logs()
data = json.loads(data)
final_data = []
if param == "d2201":
print("x"*100)
i = 1
for x in data:
if "DTS22_PNUP_01" in str(x["wgName"]):
print(x)
x["data_id"]=i
final_data.append(x)
i = i+1
elif param == "d2202":
print("x"*100)
i = 1
for x in data:
if "DTS22_PNUP_02" in str(x["wgName"]):
print(x)
x["data_id"]=i
final_data.append(x)
i = i+1
elif param == "d2203":
print("x"*100)
i = 1
for x in data:
if "DTS22_PNUP_03" in str(x["wgName"]):
print(x)
x["data_id"]=i
final_data.append(x)
i = i+1
elif param == "d2204":
print("x"*100)
i = 1
for x in data:
if "DTS22_PNUP_04" in str(x["wgName"]):
print(x)
x["data_id"]=i
final_data.append(x)
i = i+1
elif param == "d2205":
print("x"*100)
i = 1
for x in data:
if "DTS22_PNUP_05" in str(x["wgName"]):
print(x)
x["data_id"]=i
final_data.append(x)
i = i+1
elif param == "d2206":
print("x"*100)
i = 1
for x in data:
if "DTS22_TELU" in str(x["wgName"]):
print(x)
x["data_id"]=i
final_data.append(x)
i = i+1
elif param == "GCI":
print("x"*100)
i = 1
for x in data:
if "GCI" in str(x["wgName"]):
x["data_id"]=i
print(x)
final_data.append(x)
i = i+1
elif param == "META":
print("x"*100)
i = 1
for x in data:
if "NIS" in str(x["wgName"]):
print(x["data_id"])
x["data_id"]=i
print(x["data_id"])
final_data.append(x)
i = i+1
else:
final_data = data
final_data = json.dumps(final_data)
return HttpResponse(final_data, content_type='application')
@csrf_exempt
@api_view(["GET"])
@permission_classes([IsAuthenticated])
def wgViewClients(request):
param = request.GET.get('param', '')
filter = request.GET.get('filter', '')
data = get_profiles()
data = json.loads(data)
final_data = []
# if request.user.is_authenticated:
if filter :
filter = str(filter).split(" ")
for x in filter:
print("-> ",x)
final_data = data
if not (filter[0] == "" and filter[1] == "undefined" and filter[2] == "undefined" and filter[3] == "undefined"):
if filter[0] != "":
f_name = filter[0]
i = 0
tmp_data = []
for x in final_data:
if str(f_name).lower() in str(x["name"]).lower():
x["data_id"]=i
tmp_data.append(x)
i = i+1
final_data = tmp_data
if filter[1] != "undefined":
f_orgs = filter[1]
i = 0
tmp_data = []
for x in final_data:
if str(f_orgs).lower() in str(x["name"]).lower():
x["data_id"]=i
tmp_data.append(x)
i = i+1
final_data = tmp_data
if filter[2] != "undefined":
i = 0
f_email = filter[2]
tmp_data = []
if f_email == "" :
print("Empty mails...")
for x in final_data:
if str(x["email"]).lower() == "":
x["data_id"]=i
tmp_data.append(x)
i = i+1
else:
for x in final_data:
if str(f_email).lower() in str(x["email"]).lower():
x["data_id"]=i
tmp_data.append(x)
i = i+1
final_data = tmp_data
if filter[3] != "undefined":
i = 0
f_state = filter[3]
tmp_data = []
if f_state == "" :
print("Empty State...")
for x in final_data:
if str(x["enabled"]).lower() == "":
x["data_id"]=i
tmp_data.append(x)
i = i+1
else:
for x in final_data:
if str(f_state).lower() in str(x["enabled"]).lower():
x["data_id"]=i
tmp_data.append(x)
i = i+1
final_data = tmp_data
else:
final_data = data
final_data = json.dumps(final_data)
elif len(param)>0:
if param == "email":
groups = []
for x in data:
if str("@").lower() in str(x["email"]).lower():
tmp_val = x["email"]
tmp_val = str(tmp_val).split("@")[1]
tmp_val = tmp_val.lower()
if tmp_val not in groups:
groups.append(tmp_val)
# if {"email": tmp_val} not in groups:
# # print("-> ",tmp_val)
# groups.append({"email": tmp_val})
final_data = json.dumps({"email":groups})
if param == "orgs":
groups = []
for x in data:
if str("-").lower() in str(x["name"]).lower():
tmp_val = x["name"]
tmp_val = str(tmp_val).split("-")[0]
tmp_val = tmp_val.upper()
if tmp_val not in groups:
groups.append(tmp_val)
# if {"orgs": tmp_val} not in groups:
# # print("-> ",tmp_val)
# groups.append({"orgs": tmp_val})
final_data = json.dumps({"orgs": groups})
if param == "stats":
data_logs = get_logs()
data = json.loads(data_logs)
sum_data = count_clients(data)
connected_data = count_connection(data)
traffic_data = len(data)
percentage_data = count_percentage(data)
broken_data = count_broken(data)
traffic_data = count_traffic(data)
if traffic_data > 1000000000:
traffic_data="{:.2f}".format(traffic_data/1000000000)+" GB"
else:
traffic_data="{:.2f}".format(traffic_data/1000000)+" MB"
data = {}
data["clienttotal"]=sum_data
data["traffictotal"]=traffic_data
data["connectedtotal"]=connected_data
data["percentagetotal"]=percentage_data
data["brokentotal"]=broken_data
final_data = json.dumps(data)
else :
final_data = json.dumps(data)
# else:
# final_data = {"Not Logged In"}
# print(request.GET.get('param', ''))
return HttpResponse(final_data, content_type='application')
@csrf_exempt
@api_view(["GET"])
@permission_classes([IsAuthenticated])
def get_ApplyConfig(request):
# id = request.GET.get('id', '')
# state = request.GET.get('state', '')
# print("Edit Request...")
req_response = req_apply_sys()
return HttpResponse(req_response)
@csrf_exempt
@api_view(["GET", "POST"])
@permission_classes([IsAuthenticated])
def get_EditState(request):
id = request.GET.get('id', '')
state = request.GET.get('state', '')
print("Edit Request...")
if state and id:
if id != "bulk":
print("[ Edit ]=======")
print(id)
print(state)
req_edit_state(id, state)
else:
print("[ Bulk handler ]=======")
print(request.body)
target_ids = request.body
for x in json.loads(target_ids):
req_edit_state(str(x), state)
print(x)
final_data = json.dumps({"state":"Success"})
return HttpResponse(final_data, content_type='application')
# def get_Cookie(request):
#
# return get_token()
# @csrf_exempt
@csrf_exempt
@api_view(["GET"])
@permission_classes([IsAuthenticated])
def get_EditClient(request):
my_token = get_token()
print("TOKEN ...")
print(my_token)
id = request.GET.get('id', '')
if request.method == "POST":
print(request)
if id:
print(id)
ret_val = req_edit_user(id)
else:
ret_val = {"data": "Failed"}
# ret_val = json.dumps(ret_val)
ret_val = ret_val["Client"]
ret_val = json.dumps(ret_val)
return HttpResponse(ret_val, content_type='application')
@csrf_exempt
@api_view(["GET"])
@permission_classes([IsAuthenticated])
def get_user_param_recommendation(request):
ret_val = req_ip_recommendation()
return HttpResponse(ret_val, content_type='application')
@csrf_exempt
@api_view(["GET"])
@permission_classes([IsAuthenticated])
def wgFilterClients(request):
param = request.GET.get('param', '')
filter = request.GET.get('filter', '')
name = request.GET.get('names', '')
orgs = request.GET.get('orgs', '')
emails = request.GET.get('emails', '')
state = request.GET.get('state', '')
print("param ",param)
print("filter ",filter)
print("name ",name)
print("orgs ",orgs)
print("emails ",emails)
print("state ",state)
data = get_profiles()
data = json.loads(data)
final_data = []
if orgs:
orgs = str(orgs).split(", ")
tmp_data = []
for x in orgs:
print(x)
f_orgs = x
i = 0
for x in data:
if str(f_orgs).lower() in str(x["name"]).lower():
x["data_id"]=i
tmp_data.append(x)
i = i+1
print(tmp_data)
if len(final_data) < 1:
final_data = tmp_data
else:
for x in tmp_data:
final_data.append(x)
if emails:
emails = str(emails).split(", ")
tmp_data = []
for x in emails:
print(x)
f_emails = x
i = 0
for x in data:
if str(f_emails).lower() in str(x["email"]).lower():
x["data_id"]=i
tmp_data.append(x)
i = i+1
if len(final_data) < 1:
final_data = tmp_data
else:
for x in tmp_data:
final_data.append(x)
if not (orgs or filter or name or emails):
final_data = data
# SANITY Starts here -------------------------------
no_duplicate = []
for x in final_data:
if x not in no_duplicate:
no_duplicate.append(x)
ret_val = json.dumps(no_duplicate)
return HttpResponse(ret_val, content_type='application')
@csrf_exempt
@api_view(["POST"])
@permission_classes([IsAuthenticated])
def wgBulkReg(request):
print("-> Bulk Registration")
RegData = json.loads(request.body)
req_ip = req_ip_recommendation()
req_commit = reg_bulk(RegData)
return HttpResponse(json.dumps({"Reg":"Success"}), content_type='application')