Dirk Vogt | f2a3342 | 2016-10-11 17:17:26 +0200 | [diff] [blame] | 1 | from rest_framework import filters |
| 2 | from rest_framework import generics |
| 3 | from rest_framework.response import Response |
| 4 | |
| 5 | from rest_framework.decorators import api_view |
| 6 | from rest_framework.decorators import permission_classes |
| 7 | |
| 8 | from rest_framework.permissions import AllowAny |
| 9 | |
| 10 | from rest_framework.permissions import IsAdminUser |
| 11 | from rest_framework.permissions import IsAuthenticated |
| 12 | |
| 13 | from rest_framework.permissions import BasePermission |
| 14 | from rest_framework.authtoken.models import Token |
| 15 | |
| 16 | from django.contrib.auth.models import Permission |
| 17 | |
| 18 | from crashreports.models import Device |
| 19 | from crashreports.models import User |
| 20 | |
| 21 | from crashreports.serializers import DeviceSerializer |
| 22 | |
| 23 | class ListCreateDevices(generics.ListCreateAPIView): |
| 24 | queryset = Device.objects.all() |
| 25 | paginate_by = 20 |
| 26 | permission_classes = (IsAuthenticated, ) |
| 27 | serializer_class = DeviceSerializer |
| 28 | pass |
| 29 | |
| 30 | class RetrieveUpdateDestroyDevice(generics.RetrieveUpdateDestroyAPIView): |
| 31 | queryset = Device.objects.all() |
| 32 | permission_classes = (IsAuthenticated, ) |
| 33 | serializer_class = DeviceSerializer |
| 34 | lookup_field = 'uuid' |
| 35 | pass |
| 36 | |
| 37 | @api_view(http_method_names=['POST'], ) |
| 38 | @permission_classes((AllowAny,)) |
| 39 | def register_device(request): |
| 40 | """ Register a new device. This endpoint will generate a django user for the |
| 41 | new device. The device is identified by a uuid, and authenticated with a token. |
| 42 | We generate the uuid here as this makes it easier to deal with collisions. |
| 43 | """ |
| 44 | device = Device() |
| 45 | user = User.objects.create_user("device_"+str(device.uuid), '', None) |
| 46 | permission = Permission.objects.get(name='Can add crashreport') |
| 47 | user.user_permissions.add(permission) |
| 48 | user.save() |
| 49 | device.user = user |
| 50 | device.token = Token.objects.create(user=user).key |
| 51 | device.save() |
| 52 | return Response({'uuid':device.uuid, 'token': device.token}) |