blob: f249ff4f1e0363ffbb59fc3f0d1bec1af5ee34d9 [file] [log] [blame]
Dirk Vogtf2a33422016-10-11 17:17:26 +02001from rest_framework import generics
2from rest_framework.response import Response
Dirk Vogtf2a33422016-10-11 17:17:26 +02003from rest_framework.decorators import api_view
4from rest_framework.decorators import permission_classes
Dirk Vogtf2a33422016-10-11 17:17:26 +02005from rest_framework.permissions import AllowAny
Dirk Vogtf2a33422016-10-11 17:17:26 +02006from rest_framework.permissions import IsAuthenticated
Dirk Vogtf2a33422016-10-11 17:17:26 +02007from rest_framework.authtoken.models import Token
Dirk Vogtf2a33422016-10-11 17:17:26 +02008from django.contrib.auth.models import Permission
9
10from crashreports.models import Device
11from crashreports.models import User
12
13from crashreports.serializers import DeviceSerializer
14
Dirk Vogt7160b5e2016-10-12 17:04:40 +020015
Dirk Vogtf2a33422016-10-11 17:17:26 +020016class ListCreateDevices(generics.ListCreateAPIView):
17 queryset = Device.objects.all()
18 paginate_by = 20
19 permission_classes = (IsAuthenticated, )
20 serializer_class = DeviceSerializer
21 pass
22
Dirk Vogt7160b5e2016-10-12 17:04:40 +020023
Dirk Vogtf2a33422016-10-11 17:17:26 +020024class RetrieveUpdateDestroyDevice(generics.RetrieveUpdateDestroyAPIView):
25 queryset = Device.objects.all()
26 permission_classes = (IsAuthenticated, )
27 serializer_class = DeviceSerializer
28 lookup_field = 'uuid'
29 pass
30
Dirk Vogt7160b5e2016-10-12 17:04:40 +020031
Dirk Vogtf2a33422016-10-11 17:17:26 +020032@api_view(http_method_names=['POST'], )
33@permission_classes((AllowAny,))
34def register_device(request):
Dirk Vogt7160b5e2016-10-12 17:04:40 +020035 """ Register a new device. This endpoint will generate a django user for
36 the new device. The device is identified by a uuid, and authenticated with
37 a token.
38 We generate the uuid here as this makes it easier to deal with collisions.
Dirk Vogtf2a33422016-10-11 17:17:26 +020039 """
40 device = Device()
Dirk Vogt7160b5e2016-10-12 17:04:40 +020041 user = User.objects.create_user("device_" + str(device.uuid), '', None)
Dirk Vogtf2a33422016-10-11 17:17:26 +020042 permission = Permission.objects.get(name='Can add crashreport')
43 user.user_permissions.add(permission)
44 user.save()
45 device.user = user
Dirk Vogt7160b5e2016-10-12 17:04:40 +020046 device.token = Token.objects.create(user=user).key
Dirk Vogtf2a33422016-10-11 17:17:26 +020047 device.save()
Dirk Vogt7160b5e2016-10-12 17:04:40 +020048 return Response({'uuid': device.uuid, 'token': device.token})