blob: 80a378db264b046e2b6c90a66b2335e02284f5d7 [file] [log] [blame]
Tony Macke4cee7a2013-04-09 12:45:32 -04001from django.http import Http404
2from rest_framework.views import APIView
3from rest_framework.response import Response
4from rest_framework import status
5
Tony Mackf1c12242013-04-09 16:08:43 -04006from plstackapi.core.api.keys import add_key, delete_key, get_keys, update_key
7from plstackapi.core.serializers import KeySerializer
Tony Macke4cee7a2013-04-09 12:45:32 -04008from plstackapi.util.request import parse_request
9
10
11class KeyListCreate(APIView):
12 """
Tony Mack46262d52013-04-09 12:51:34 -040013 List all users or create a new key.
Tony Macke4cee7a2013-04-09 12:45:32 -040014 """
15
16 def post(self, request, format = None):
17 data = parse_request(request.DATA)
18 if 'auth' not in data:
19 return Response(status=status.HTTP_400_BAD_REQUEST)
20 elif 'key' in data:
Tony Mack46262d52013-04-09 12:51:34 -040021 key = add_key(data['auth'], data['key'])
22 serializer = KeySerializer(key)
Tony Macke4cee7a2013-04-09 12:45:32 -040023 return Response(serializer.data, status=status.HTTP_201_CREATED)
24 else:
25 keys = get_keys(data['auth'])
Tony Mack46262d52013-04-09 12:51:34 -040026 serializer = KeySerializer(keys, many=True)
Tony Macke4cee7a2013-04-09 12:45:32 -040027 return Response(serializer.data)
28
29
30class KeyRetrieveUpdateDestroy(APIView):
31 """
Tony Mack46262d52013-04-09 12:51:34 -040032 Retrieve, update or delete a key
Tony Macke4cee7a2013-04-09 12:45:32 -040033 """
34
35 def post(self, request, pk, format=None):
36 """Retrieve a key"""
37 data = parse_request(request.DATA)
38 if 'auth' not in data:
39 return Response(status=status.HTTP_400_BAD_REQUEST)
Tony Mack29c287f2013-04-11 21:07:16 -040040 keys = get_keys(data['auth'], pk)
Tony Macke4cee7a2013-04-09 12:45:32 -040041 if not keys:
42 return Response(status=status.HTTP_404_NOT_FOUND)
Tony Mack46262d52013-04-09 12:51:34 -040043 serializer = KeySerializer(keys[0])
Tony Macke4cee7a2013-04-09 12:45:32 -040044 return Response(serializer.data)
45
46 def put(self, request, pk, format=None):
47 """update a key"""
48 data = parse_request(request.DATA)
49 if 'auth' not in data:
50 return Response(status=status.HTTP_400_BAD_REQUEST)
51 elif 'key' not in data:
52 return Response(status=status.HTTP_400_BAD_REQUEST)
53
54 key = update_key(pk, data['key'])
Tony Mack46262d52013-04-09 12:51:34 -040055 serializer = KeySerializer(key)
Tony Macke4cee7a2013-04-09 12:45:32 -040056 return Response(serializer.data)
57
58 def delete(self, request, pk, format=None):
59 data = parse_request(request.DATA)
60 if 'auth' not in data:
61 return Response(status=status.HTTP_400_BAD_REQUEST)
Tony Mack29c287f2013-04-11 21:07:16 -040062 delete_key(data['auth'], pk)
Tony Macke4cee7a2013-04-09 12:45:32 -040063 return Response(status=status.HTTP_204_NO_CONTENT)
64
65
66