Commit 8b69bf4a authored by Hubert Denkmair's avatar Hubert Denkmair
Browse files

implement basic functionality

parent c333191a
......@@ -35,7 +35,8 @@ INSTALLED_APPS = [
......@@ -18,4 +18,5 @@ urlpatterns = [
path('snake/', include('ide.urls')),
path('highscore/', include('highscore.urls')),
path('docs/', include('docs.urls')),
path('api/', include('api.urls')),
from django.contrib import admin
# Register your models here.
from django.apps import AppConfig
class ApiConfig(AppConfig):
name = 'api'
from django.db import models
# Create your models here.
from django.test import TestCase
# Create your tests here.
from django.urls import path
from . import views
urlpatterns = [
path('version', views.version, name='version'),
path('version/<int:version_id>', views.get_version, name='get_version'),
import json
from core.models import ApiKey, SnakeVersion
from django.http import JsonResponse, HttpResponseBadRequest, HttpResponseNotAllowed
from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404
def get_user(request):
key = request.META.get('HTTP_AUTHORIZATION', None)
if key is not None:
return ApiKey.objects.get(key=key)
key = request.POST.get('token', None) or request.GET.get('token', None)
if key is not None:
return ApiKey.objects.get(key=key)
if request.user:
return request.user
raise PermissionDenied('API access needs login or api key')
except ApiKey.DoesNotExist:
raise PermissionDenied('invalid API key')
def version_dict(v):
return {
'parent': None if v.parent is None else,
'version': v.version,
'created': v.created,
'comment': v.comment,
'error': v.server_error_message
def full_version_dict(v):
d = version_dict(v)
d['code'] = v.code
return d
def version(request):
if request.method in ['PUT', 'POST']:
return put_version(request)
elif request.method == 'GET':
return JsonResponse({ 'versions': [version_dict(v) for v in SnakeVersion.objects.filter(user=get_user(request))]})
return HttpResponseNotAllowed(permitted_methods=['GET', 'PUT', 'POST'])
def get_version(request, version_id):
user = get_user(request)
v = get_object_or_404(SnakeVersion, user=user, id=version_id)
return JsonResponse(full_version_dict(v))
def put_version(request):
user = get_user(request)
permitted_methods = ['PUT', 'POST']
if request.method not in permitted_methods:
return HttpResponseNotAllowed(permitted_methods=permitted_methods)
data = json.loads(request.body)
if not isinstance(data, dict):
return HttpResponseBadRequest('need to send a json dict as request body')
v = SnakeVersion()
v.user = user
v.parent = data.get('parent', None)
v.comment = data.get('comment', None)
v.code = data.get('code', None)
if v.code is None:
return HttpResponseBadRequest('need to provide lua script in code field');
return get_version(request,
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment