change def for views in api views

This commit is contained in:
Cayo Puigdefabregas 2024-10-23 09:23:45 +02:00
parent 0f8815eb43
commit 9b96955c30
2 changed files with 110 additions and 72 deletions

View File

@ -6,7 +6,7 @@ from django.urls import path
app_name = 'api' app_name = 'api'
urlpatterns = [ urlpatterns = [
path('v1/snapshot/', views.NewSnapshot, name='new_snapshot'), path('v1/snapshot/', views.NewSnapshotView.as_view(), name='new_snapshot'),
path('v1/tokens/', views.TokenView.as_view(), name='tokens'), path('v1/tokens/', views.TokenView.as_view(), name='tokens'),
path('v1/tokens/new', views.TokenNewView.as_view(), name='new_token'), path('v1/tokens/new', views.TokenNewView.as_view(), name='new_token'),
path("v1/tokens/<int:pk>/edit", views.EditTokenView.as_view(), name="edit_token"), path("v1/tokens/<int:pk>/edit", views.EditTokenView.as_view(), name="edit_token"),

View File

@ -9,6 +9,7 @@ from django.http import JsonResponse
from django.shortcuts import get_object_or_404, redirect from django.shortcuts import get_object_or_404, redirect
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django_tables2 import SingleTableView from django_tables2 import SingleTableView
from django.views.generic.edit import ( from django.views.generic.edit import (
CreateView, CreateView,
@ -17,6 +18,7 @@ from django.views.generic.edit import (
) )
from utils.save_snapshots import move_json, save_in_disk from utils.save_snapshots import move_json, save_in_disk
from django.views.generic.edit import View
from dashboard.mixins import DashboardView from dashboard.mixins import DashboardView
from evidence.models import Annotation from evidence.models import Annotation
from evidence.parse import Build from evidence.parse import Build
@ -27,14 +29,15 @@ from api.tables import TokensTable
logger = logging.getLogger('django') logger = logging.getLogger('django')
@csrf_exempt class ApiMixing(View):
def NewSnapshot(request):
# Accept only posts
if request.method != 'POST':
return JsonResponse({'error': 'Invalid request method'}, status=400)
@method_decorator(csrf_exempt)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def auth(self):
# Authentication # Authentication
auth_header = request.headers.get('Authorization') auth_header = self.request.headers.get('Authorization')
if not auth_header or not auth_header.startswith('Bearer '): if not auth_header or not auth_header.startswith('Bearer '):
logger.exception("Invalid or missing token {}".format(auth_header)) logger.exception("Invalid or missing token {}".format(auth_header))
return JsonResponse({'error': 'Invalid or missing token'}, status=401) return JsonResponse({'error': 'Invalid or missing token'}, status=401)
@ -46,24 +49,43 @@ def NewSnapshot(request):
logger.exception("Invalid token {}".format(token)) logger.exception("Invalid token {}".format(token))
return JsonResponse({'error': 'Invalid or missing token'}, status=401) return JsonResponse({'error': 'Invalid or missing token'}, status=401)
tk = Token.objects.filter(token=token).first() self.tk = Token.objects.filter(token=token).first()
if not tk: if not self.tk:
logger.exception("Invalid or missing token {}".format(token)) logger.exception("Invalid or missing token {}".format(token))
return JsonResponse({'error': 'Invalid or missing token'}, status=401) return JsonResponse({'error': 'Invalid or missing token'}, status=401)
class NewSnapshotView(ApiMixing):
def get(self, request, *args, **kwargs):
return JsonResponse({}, status=404)
def post(self, request, *args, **kwargs):
response = self.auth()
if response:
return response
# Validation snapshot # Validation snapshot
try: try:
data = json.loads(request.body) data = json.loads(request.body)
except json.JSONDecodeError: except json.JSONDecodeError:
logger.exception("Invalid Snapshot of user {}".format(tk.owner)) logger.exception("Invalid Snapshot of user {}".format(self.tk.owner))
return JsonResponse({'error': 'Invalid JSON'}, status=500) return JsonResponse({'error': 'Invalid JSON'}, status=500)
# Process snapshot
path_name = save_in_disk(data, self.tk.owner.institution.name)
# try: # try:
# Build(data, None, check=True) # Build(data, None, check=True)
# except Exception: # except Exception:
# return JsonResponse({'error': 'Invalid Snapshot'}, status=400) # return JsonResponse({'error': 'Invalid Snapshot'}, status=400)
if not data.get("uuid"):
txt = "error: the snapshot not have uuid"
logger.exception(txt)
return JsonResponse({'status': txt}, status=500)
exist_annotation = Annotation.objects.filter( exist_annotation = Annotation.objects.filter(
uuid=data['uuid'] uuid=data['uuid']
).first() ).first()
@ -73,11 +95,9 @@ def NewSnapshot(request):
logger.exception(txt) logger.exception(txt)
return JsonResponse({'status': txt}, status=500) return JsonResponse({'status': txt}, status=500)
# Process snapshot
path_name = save_in_disk(data, tk.owner.institution.name)
try: try:
Build(data, tk.owner) Build(data, self.tk.owner)
except Exception as err: except Exception as err:
logger.exception(err) logger.exception(err)
return JsonResponse({'status': f"fail: {err}"}, status=500) return JsonResponse({'status': f"fail: {err}"}, status=500)
@ -87,7 +107,7 @@ def NewSnapshot(request):
type=Annotation.Type.SYSTEM, type=Annotation.Type.SYSTEM,
# TODO this is hardcoded, it should select the user preferred algorithm # TODO this is hardcoded, it should select the user preferred algorithm
key="hidalgo1", key="hidalgo1",
owner=tk.owner.institution owner=self.tk.owner.institution
).first() ).first()
@ -105,7 +125,7 @@ def NewSnapshot(request):
# TODO replace with public_url when available # TODO replace with public_url when available
"public_url": url "public_url": url
} }
move_json(path_name, tk.owner.institution.name) move_json(path_name, self.tk.owner.institution.name)
return JsonResponse(response, status=200) return JsonResponse(response, status=200)
@ -183,3 +203,21 @@ class EditTokenView(DashboardView, UpdateView):
) )
kwargs = super().get_form_kwargs() kwargs = super().get_form_kwargs()
return kwargs return kwargs
class DetailsComputerView(ApiMixing):
def get(self, request, *args, **kwargs):
response = self.auth()
if response:
return response
try:
data = json.loads(request.body)
except:
pass
return JsonResponse({}, status=404)
def post(self, request, *args, **kwargs):
return JsonResponse({}, status=404)