예제 #1
0
 def setUp(self):
     user = User.objects.create(email="*****@*****.**").id
     self.devices = [
         {
             'id': '1234123412341234',
             'name': 'GPS tracker #1',
             'owner': user
         },
         {
             'id': '1234567812345678',
             'name': 'GPS tracker #2',
             'owner': user
         },
         {
             'id': '8765432187654321',
             'name': 'GPS tracker #3',
             'owner': user
         },
         {
             'id': '8765432112345678',
             'name': 'GPS tracker #4',
             'owner': user
         },
     ]
     for device in self.devices:
         serializer = DeviceSerializer(data=device)
         self.assertTrue(serializer.is_valid())
         serializer.save()
예제 #2
0
파일: views.py 프로젝트: rajansg/RPi-HAUS
    def post(self, request, format=None):

        # print("\nRequest == " + str(dir(request)))

        # print(request.user.id)

        device = self.get_device_object(request)

        requestdata = copy(request.DATA)

        requestdata['user'] = request.user.id

        device_serializer = DeviceSerializer(device, data=requestdata)

        # print "\nrequest.DATA == " + str(request.DATA)

        # print(device_serializer.is_valid())

        # print device_serializer.attributes()

        if device_serializer.is_valid():
            device_serializer.save()
            device = self.get_device_object(request)

            # Assuming atoms value is a list of atom names
            # atom_names = request.DATA['atoms']
            # print (str("atom_names == " + str(atom_names)))
            # for atom_name in atom_names:
            # print atom_name
            # atom = self.get_atom_object(atom_name, device)
            # print("atom == " + str(atom))
            # atom_data = {'name': atom_name, 'device': device.pk}
            # print("atom_data == " + str(atom_data))
            # atom_serializer = AtomSerializer(atom, data=atom_data)
            # print("atom_serializer == " + str(dir(atom_serializer)))

            # for each_dirname in dir(atom_serializer):
            #    print str(each_dirname) + ": " + (str(getattr(atom_serializer, each_dirname)))

            # if atom_serializer.is_valid():
            # print("atom_serializer.is_valid == True")
            # atom_serializer.save()

            if device_serializer.was_created is True:
                # If a Device was actually created in the serializer, we need
                # to give the User a DevicePermission as well.
                # This should NOT be done in views.py -- it's in models.py,
                # and accomplished by adding a create() method to the
                # Device class, which is called in serializers.py in lieu of
                # calling the Device class outright.
                return Response(device_serializer.data,
                                status=status.HTTP_201_CREATED)
            elif device_serializer.was_created is False:
                return Response(device_serializer.data,
                                status=status.HTTP_202_ACCEPTED)
        return Response(device_serializer.errors,
                        status=status.HTTP_400_BAD_REQUEST)
예제 #3
0
 def setUp(self):
     user = User.objects.create(email="*****@*****.**").id
     device_id = '1234123412341234'
     device_name = 'GPS tracker #1'
     serializer = DeviceSerializer(data={
         'id': device_id,
         'name': device_name,
         'owner': user
     })
     self.assertTrue(serializer.is_valid())
     serializer.save()
     self.entries = [
         {
             'latitude': 52.678123,
             'longitude': 47.563214,
             'datetime': '12/25/2019T10:00:00Z',
             'device': device_id
         },
         {
             'latitude': 51.678123,
             'longitude': 47.563214,
             'datetime': '12/25/2019T10:30:00Z',
             'device': device_id
         },
         {
             'latitude': 55.547825,
             'longitude': 46.123874,
             'datetime': '12/25/2019T11:00:00Z',
             'device': device_id
         },
     ]
     for entry in self.entries:
         serializer = EntrySerializer(data=entry)
         self.assertTrue(serializer.is_valid())
         serializer.save()
예제 #4
0
    def post(self, request, format=None):

        # print("\nRequest == " + str(dir(request)))

        # print(request.user.id)

        device = self.get_device_object(request)

        requestdata = copy(request.DATA)

        requestdata['user'] = request.user.id

        device_serializer = DeviceSerializer(device, data=requestdata)

        # print "\nrequest.DATA == " + str(request.DATA)

        # print(device_serializer.is_valid())

        # print device_serializer.attributes()

        if device_serializer.is_valid():
            device_serializer.save()
            device = self.get_device_object(request)

            # Assuming atoms value is a list of atom names
            # atom_names = request.DATA['atoms']
            # print (str("atom_names == " + str(atom_names)))
            # for atom_name in atom_names:
            # print atom_name
            # atom = self.get_atom_object(atom_name, device)
            # print("atom == " + str(atom))
            # atom_data = {'name': atom_name, 'device': device.pk}
            # print("atom_data == " + str(atom_data))
            # atom_serializer = AtomSerializer(atom, data=atom_data)
            # print("atom_serializer == " + str(dir(atom_serializer)))

            # for each_dirname in dir(atom_serializer):
            #    print str(each_dirname) + ": " + (str(getattr(atom_serializer, each_dirname)))

            # if atom_serializer.is_valid():
            # print("atom_serializer.is_valid == True")
            # atom_serializer.save()

            if device_serializer.was_created is True:
                # If a Device was actually created in the serializer, we need
                # to give the User a DevicePermission as well.
                # This should NOT be done in views.py -- it's in models.py,
                # and accomplished by adding a create() method to the
                # Device class, which is called in serializers.py in lieu of
                # calling the Device class outright.
                return Response(device_serializer.data, status=status.HTTP_201_CREATED)
            elif device_serializer.was_created is False:
                return Response(device_serializer.data, status=status.HTTP_202_ACCEPTED)
        return Response(device_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #5
0
    def setup(self, request, pk=None):
        try:
            device = Device.objects.get(id=pk)
        except Device.DoesNotExist:
            return Response({"detail":"Authentication credentials were not provided."}, status=403)
        
        self.check_object_permissions(request, device)

        
        request.data["token"] = generate_sha256()
        serializer = DeviceSerializer(device, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({'result':'ok'})
        return Response({"detail":"Authentication credentials were not provided."}, status=403)
예제 #6
0
파일: views.py 프로젝트: rajansg/RPi-HAUS
    def get(self, request, format=None):

        # When a Device is created a DevicePermission will also
        # be created for the User who created that Device.
        # devices_owned_by_user = Device.objects.filter(user_id=request.user.pk)

        # Adding listing of Devices a User has a DevicePermission for.
        permissions = DevicePermission.objects.filter(user=request.user.pk)

        # Each DevicePermission has a Device, and each Device has a pk:
        permitted_device_pks = [
            permission.device.pk for permission in permissions.all()
        ]

        # With the above info, we can compile a list of Device objects
        # from the database that the User has a DevicePermission for:
        devices_user_is_permitted_for = []
        for each_device_pk in permitted_device_pks:
            device_to_append = Device.objects.get(pk=each_device_pk)
            devices_user_is_permitted_for.append(device_to_append)

        device_serializer = DeviceSerializer(devices_user_is_permitted_for,
                                             many=True)

        return Response(device_serializer.data)
예제 #7
0
    def setup(self, request, pk=None):
        try:
            device = Device.objects.get(id=pk)
        except Device.DoesNotExist:
            return Response(
                {"detail": "Authentication credentials were not provided."},
                status=403)

        self.check_object_permissions(request, device)

        request.data["token"] = generate_sha256()
        serializer = DeviceSerializer(device, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({'result': 'ok'})
        return Response(
            {"detail": "Authentication credentials were not provided."},
            status=403)
예제 #8
0
파일: views.py 프로젝트: rajansg/RPi-HAUS
    def get(self, request, device_pk, format=None):
        device = self.get_device_object(device_pk)

        permission = self.get_permission_for_device(request, device)
        if not permission:
            # Break the function and 403 if the user does not have permission:
            # return HttpResponseForbidden("You do not have permission to view this device.")
            return HttpResponseForbidden()

        device_serializer = DeviceSerializer(device)
        return Response(device_serializer.data)
예제 #9
0
    def post(self, request, **kwargs):

        # Check correct arguments provided
        # Note - do not verify registrationID here as device should not exist
        if not (hasattr(request, "data") & isinstance(request.data, object)):
            return error.incorrect_arguments

        user = self.request.user

        # Check device does not already exist
        if hasattr(user, "device"):
            return errors.device_exists

        deviceData = request.data
        serializer = DeviceSerializer(data=deviceData, context={'user': user})

        if not serializer.is_valid():
            return errors.invalidData(serializer.errors)
            
        serializer.save()
        return Response({"code": "device_created", "message": "Device successfully created"}, status=status.HTTP_201_CREATED)
예제 #10
0
def getstatus(request):
    """
    Check if there is a pending request
    Android facing
    """
    if request.method != 'PUT':
        return HttpResponse(status=401)

    data = JSONParser().parse(request)

    device = handlers.getstatus(data['username'], data['password'])

    serialdevice = DeviceSerializer(device)

    return JSONResponse(serialdevice.data)
예제 #11
0
 def get(self, request, format=None):
     try:
         if request.auth == None:
             raise PermissionDenied
         queryset = Device.objects.all()
         serializer = DeviceSerializer(queryset, many=True)
         res = {'deviceList': serializer.data}
         return Response(res, status=status.HTTP_200_OK)
     except FieldDoesNotExist as error:
         return Response(
             {
                 'error': "FieldDoesNotExist ",
                 'date': datetime.now()
             },
             status=status.HTTP_400_BAD_REQUEST)
     except PermissionDenied as error:
         return Response(
             {
                 'error': "PermissionDenied",
                 'date': datetime.now()
             },
             status=status.HTTP_400_BAD_REQUEST)
예제 #12
0
def apiGetDeleteDevice( request, uid ):
	
	# Get device details
	if( request.method == "GET" ):	
		try:
		
			if( uid == "" ):
				device_data = Device.objects.all()
			else:
				device_data = get_object_or_404( Device, uid = uid )
			
		except Device.DoesNotExist:
			return Response( status = status.HTTP_404_NOT_FOUND )
			
		except ObjectDoesNotExist:
			return Response( status = status.HTTP_404_NOT_FOUND )
		
		if( request.method == "GET" ):
			serializer = DeviceSerializer( device_data, many=True )
			return Response( serializer.data )
			
	
	# Delete device
	elif( request.method == "DELETE" ):
		try:			
			# Get object with input uid
			device_del = get_object_or_404( Device, uid = uid )
			
			# Delete the object
			Device.objects.filter( uid = uid ).delete()
		
		except PermissionDenied as e:
			return Response( status = status.HTTP_401_UNAUTHORIZED )
		
		except ObjectDoesNotExist as e:
			return Response( status = status.HTTP_404_NOT_FOUND )
	 
		if( request.method == "DELETE" ):
			return Response( status = status.HTTP_202_ACCEPTED )
예제 #13
0
def apiDevice( request ):
	
	# Return list of all devices
	if( request.method == "GET" ):
		try:
			device_data = Device.objects.all()
			
		except Device.DoesNotExist:
			return Response( status = status.HTTP_404_NOT_FOUND )
		
	
		serializer = DeviceSerializer( device_data, many=True )
		return Response( serializer.data )
		
	
	# Create new device
	elif ( request.method == "POST" ):
		try:
			# Extract attributes
			payload = request.POST
		
			uid = payload["uid"]
			name = payload["name"]
			
			# Create new Device
			device_new = Device( uid = uid, name = name )
			
			Device.full_clean( device_new )
			
			device_new.save()
			
		
		except PermissionDenied as e:
			return Response( status = status.HTTP_401_UNAUTHORIZED )
		
		
	 

		return Response( status = status.HTTP_201_CREATED )
예제 #14
0
    def post(self, request, format=None):
        userprofile_serializer = UserProfileSerializer(data=request.DATA)
        reg_serializer = RegistrationSerializer(data=request.DATA)
        if 'device' in request.DATA:
            phone_serializer = DeviceSerializer(data=request.DATA['device'])
        else:
            phone_serializer = DeviceSerializer(data=request.DATA)

        errors = {}
        if userprofile_serializer.is_valid() and reg_serializer.is_valid() and phone_serializer.is_valid():
            user = reg_serializer.save()
            data = reg_serializer.data

            phone = phone_serializer.object
            phone.user = user
            phone_serializer.save()
            data.update(phone_serializer.data)

            user_profile = userprofile_serializer.object
            user_profile.user = user
            userprofile_serializer.save()
            data.update(userprofile_serializer.data)

            # trigger user activation to send welcome email
            signals.user_activated.send(sender=self.__class__,
                                        user=user,
                                        request=request)

            # return the right client
            client = Client.objects.get(pk=1)

            data.update({'client_id': client.client_id, 'client_secret': client.client_secret})

            return Response(data, status=status.HTTP_201_CREATED)

        errors.update(reg_serializer.errors)
        errors.update(phone_serializer.errors)
        errors.update(userprofile_serializer.errors)

        return Response(errors, status=status.HTTP_400_BAD_REQUEST)
예제 #15
0
 def searchDevList(self, request, pk=None):
     devices = Device.objects.filter(devTag=pk)
     serializer = DeviceSerializer(devices, many=True)
     return Response(serializer.data)
예제 #16
0
 def get(self, request):
     devices = Device.objects.filter(owner=request.user).order_by('added')
     serializer = DeviceSerializer(instance=devices, many=True)
     return Response({'devices': serializer.data})
예제 #17
0
    def save_device_data(self, request, *args, **kwargs):
        phoneserializer = DeviceSerializer(data=request.DATA)

        if phoneserializer.is_valid():
            phoneserializer.object.user = request.user
            phoneserializer.save(force_insert=True)
예제 #18
0
def get_devices(dev, many=True):
    serializer = DeviceSerializer(dev, many=many)
    return JsonResponse(serializer.data, safe=False)