def get_endpoint_by_leshanid(request, leshan_id): ''' Given an Endpoint leshan_id, this method fetches the Endpoint from the db and returns it. (if exists) ''' if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] # CHECK THE TOKEN if core.validate(token): endpoint = Endpoint.objects(leshan_id=leshan_id) if endpoint.count(): endpoint = endpoint.first() return http.JsonResponse(data={'endpoint_id': endpoint._id}, status=HTTPStatus.OK) else: return http.JsonResponse( data={'message': 'Endpoint does not exist.'}, status=HTTPStatus.NOT_FOUND) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def get_device_resources(request, dev_id): ''' Given a device id, this method fetches all its resources and returns them. ''' if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] if core.validate(token): device = IotConnector.objects.with_id(dev_id) res_dict = {} if device: dev_endpoints = device.endpoints for endpoint in dev_endpoints: # iterator over endpoints resources = endpoint.resources res_dict[endpoint.name] = [] for res in resources: # iterator over resources res_dict[endpoint.name].append(res.to_json()) return http.JsonResponse(data=res_dict, status=HTTPStatus.OK) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def get_all(request): """This method returns all the IoT Connector Types from the database""" if request.META.get( 'HTTP_AUTHORIZATION'): # This checks if token is passed token = request.META.get('HTTP_AUTHORIZATION').split(' ')[ 1] # 'Token adsad' -> ['Token', 'adsad'] -> 'adsad' # CHECK THE TOKEN if core.validate(token): docker_images = DeviceTypeDockerCommand.objects() images_list = [] for img in docker_images: images_list.append(img.to_json()) return http.JsonResponse(data={'images': images_list}, status=HTTPStatus.OK) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def resource_status(request, res_id): '''Given a resource id this method returns USING / DOWN / NOT_USING depending on it's status If not available -> DOWN If it's being used -> USING If it's not being used -> NOT_USING ''' if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] # CHECK THE TOKEN if core.validate(token): resource = Resource.objects.with_id(res_id) if resource: if resource.status: data = {'status': 'NOT_USING'} if ResourceUse.objects(resource=resource._id).count(): data = {'status': 'USING'} else: data = {'status': 'DOWN'} sts = HTTPStatus.OK else: sts = HTTPStatus.BAD_REQUEST data = {'message': 'Resource not found'} return http.JsonResponse(data=data, status=sts) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def get_shadow_resources(request, shdw_id): ''' Given a shadow id, this method fetches all the resources that belong to a specific shadow device. ''' if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] if core.validate(token): shadow = Shadow.objects.with_id(shdw_id) res_list = [] if shadow: shdw_devices = shadow.devices for device in shdw_devices: # iterator over devices dev_endpoints = device.endpoints for endpoint in dev_endpoints: # iterator over endpoints resources = endpoint.resources for res in resources: # iterator over resources res_list.append(res.to_json()) return http.JsonResponse(data={'resources': res_list}, status=HTTPStatus.OK) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def get_all(request): """This method returns all Applications from the database""" if request.META.get( 'HTTP_AUTHORIZATION'): # This checks if token is passed token = request.META.get('HTTP_AUTHORIZATION').split(' ')[ 1] # 'Token adsad' -> ['Token', 'adsad'] -> 'adsad' # CHECK THE TOKEN if core.validate(token): apps = Application.objects() apps_list = [] for app in apps: apps_list.append(app.to_json()) return http.JsonResponse(data={'apps': apps_list}, status=HTTPStatus.OK) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def get_app(request, app_id): """This method fetches and return a specific application""" if request.META.get( 'HTTP_AUTHORIZATION'): # This checks if token is passed token = request.META.get('HTTP_AUTHORIZATION').split(' ')[ 1] # 'Token adsad' -> ['Token', 'adsad'] -> 'adsad' # CHECK THE TOKEN if core.validate(token): app = Application.objects.with_id(app_id) if app: data = {'app': app.to_json()} sts_code = HTTPStatus.OK else: sts_code = HTTPStatus.NOT_FOUND data = {'Message': sts_code.name} return http.JsonResponse(data=data, status=sts_code) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def get_tokens_by_user_id( request, user_id): # this will validate a token (gets it from header) ''' Given an user id this method searches for it's token in the database and returns it ''' if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] if core.validate(token): user = UserData.objects(_id=user_id) if user.count(): user = user.first() token_ref = user.token token = Token.objects(_id=token_ref).first() token = token.token status = HTTPStatus.OK else: token = None status = HTTPStatus.NOT_FOUND return http.JsonResponse({'token': token}, status=status) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def get_tokens_by_shadow(request, shadow_id): ''' Given a shadow id, this method searches for it's tokens in the database and returns them ''' if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] if core.validate(token): shadow = Shadow.objects(_id=shadow_id) if shadow.count(): shadow = shadow.first() token_ids_list = shadow.tokens token_list = [] status = HTTPStatus.OK for tok in token_ids_list: token_list.append(tok._id) else: token_list = [] status = HTTPStatus.NOT_FOUND return http.JsonResponse({'tokens': token_list}, status=status) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def get_shadow_devices(request, shdw_id): ''' Given a shadow id, this method fetches the devices from the db and returns them in a JSON object with a list. ''' if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] if core.validate(token): shadow = Shadow.objects.with_id(shdw_id) if shadow: devices = shadow.devices devices_list = [] for dev in devices: devices_list.append(dev.to_json()) status = HTTPStatus.OK else: status = HTTPStatus.NOT_FOUND devices_list = None return http.JsonResponse(data={'devices': devices_list}, status=status) else: return http.JsonResponse(data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse(data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def create_shadow(request): # check token if valid later ''' This endpoint expects a dict passed in the body with the following fields: { name : text:String, description: text:String } With this information it store in the database a new Shadow Device. ''' if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] if core.validate(token): if request.POST: try: # STORE TOKEN IN DATA BASE db_shdw = Shadow() db_shdw._id = uuid.uuid4().__str__() db_shdw.description = request.POST['description'] db_shdw.name = request.POST['name'] db_shdw.save() return http.JsonResponse(data={'shadow': db_shdw.to_json()}, status=HTTPStatus.OK) except: return http.HttpResponse(content=json.dumps({'message': 'Shadow couldn\'t be created'}), status=HTTPStatus.INTERNAL_SERVER_ERROR) else: return http.HttpResponse(content=json.dumps({'message': 'Try making a post request instead.'}), status=HTTPStatus.BAD_REQUEST) else: return http.JsonResponse(data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse(data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def get_resource_use_by_epid_shdwid(request, ep_id, shdw_id): """ This method returns the usages of resources that belong to a specific endpoint and to a specific shadow device """ if request.META.get( 'HTTP_AUTHORIZATION'): # This checks if token is passed token = request.META.get('HTTP_AUTHORIZATION').split(' ')[ 1] # 'Token adsad' -> ['Token', 'adsad'] -> 'adsad' # CHECK THE TOKEN if core.validate(token): res_usages_fetched = ResourceUse.objects(endpoint=ep_id, shadow=shdw_id) res_usages_list = [] for res_usage in res_usages_fetched: jsn = res_usage.to_json() jsn = json.loads(jsn) jsn['resource_code'] = res_usage.resource.type # we add the resource code too bc we need it :D res_usages_list.append(json.dumps(jsn)) return http.JsonResponse(data={'usages': res_usages_list}, status=HTTPStatus.OK) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def delete(request, usage_id): """This method removes from de DB an usage""" if request.META.get( 'HTTP_AUTHORIZATION'): # This checks if token is passed token = request.META.get('HTTP_AUTHORIZATION').split(' ')[ 1] # 'Token adsad' -> ['Token', 'adsad'] -> 'adsad' # CHECK THE TOKEN if core.validate(token): usage = ResourceUse.objects.with_id(usage_id) if usage: usage.delete() message = "Success!" status = HTTPStatus.OK else: message = HTTPStatus.NOT_FOUND.name status = HTTPStatus.NOT_FOUND return http.JsonResponse(data={'message': message}, status=status) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def get_connector_by_type(request, d_type): """ Given a connector Type, this method searches it in the DB and returns it if found. """ if request.META.get( 'HTTP_AUTHORIZATION'): # This checks if token is passed token = request.META.get('HTTP_AUTHORIZATION').split(' ')[ 1] # 'Token adsad' -> ['Token', 'adsad'] -> 'adsad' # CHECK THE TOKEN if core.validate(token): docker_images = DeviceTypeDockerCommand.objects(type=d_type) if docker_images.count(): d_image = docker_images.first() return http.JsonResponse(status=HTTPStatus.OK, data={'image': d_image.image}) else: return http.JsonResponse( data={'message': 'This type of device is not supported.'}, status=HTTPStatus.NOT_IMPLEMENTED) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def delete_resource(request, res_id): ''' This Method deletes a the Resource related to the id given. It also ensures Database consistency updating Endpoint resources field by removing itself from it. ''' if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] if core.validate(token): resource = Resource.objects.with_id(res_id) if resource: endpoint = Endpoint.objects(resources=res_id) if endpoint: endpoint.update(pull__resources=resource) resource.delete() data = {"message": 'Success!'} sts = HTTPStatus.OK else: data = {'data': HTTPStatus.NOT_FOUND.name} sts = HTTPStatus.NOT_FOUND return http.JsonResponse(data=data, status=sts) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def store_or_update_app(request, name): ''' Given an App name, this method performs the update of the database object related to the app name (if exists) or Stores a new application. Type of message in the request body: { "interest" : "an interest" # (not a list) } ''' if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] if core.validate(token): data = request.POST app = Application.objects(name=name) # it gives back a QuerySet if app.count(): # if any app fetched, we update it app = app.first() if 'interest' in data: app.interests.append(data["interest"]) try: app.save() code_to_return = HTTPStatus.OK data_to_return = {'message': 'Success'} except: return http.HttpResponseServerError( content=json.dumps({'message': 'Error Updating'}), status=HTTPStatus.INTERNAL_SERVER_ERROR) else: # we store it instead new_app = Application() new_app._id = uuid.uuid4().__str__() new_app.name = name if 'interest' in data: new_app.interests.append(data["interest"]) new_app.save() data_to_return = {'message': 'App Stored'} code_to_return = HTTPStatus.OK return http.HttpResponse(content=json.dumps(data_to_return), status=code_to_return) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def store_type(request): ''' This method expects a dict passed in the body with the following mandatory fields: { type : text:String, image: text:String } With this information it store in the database a new IoT Connector Type. WARNING: THIS METHOD DOESN'T CHECK WHETHER THE SYSTHEM SUPPORTS OR NOT THE NEW REGISTERED TYPE. IT DOESN'T EITHER CHECKS IF THE DOCKER IMAGE EXISTS. BEFORE YOU REGISTER A NEW TYPE MAKE SURE THE SYSTEM SUPPORTS IT AND ALSO THE DOCKER IMAGE IS CREATED. ''' if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] # CHECK THE TOKEN if core.validate(token): new_connector = DeviceTypeDockerCommand() if 'type' in request.POST: new_connector.type = request.POST['type'] # If It's aleready in the database, we don't add it again if DeviceTypeDockerCommand.objects( type=request.POST['type']).count(): return http.JsonResponse( data={'message': "Type aleready registered"}, status=HTTPStatus.NOT_MODIFIED) else: return http.JsonResponse( data={'message': "Type was not passed"}, status=HTTPStatus.BAD_REQUEST) if 'image' in request.POST: new_connector.image = request.POST['image'] else: return http.JsonResponse( data={'message': "Image name was not passed"}, status=HTTPStatus.BAD_REQUEST) new_connector._id = uuid.uuid4().__str__() new_connector.save() return http.JsonResponse( data={'message': 'IoT Connector stored successfully'}, status=HTTPStatus.OK) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def get_similar_resource(request, res_code, shdw_id=None): """ Given a Resource code and a Shadow id (optional), this method tries to search for a similar resource in every shadow device or in a specific one if shadow id is passed """ if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] # CHECK THE TOKEN if core.validate(token): # we suppose it's false at beginning data_to_return = {'success': False} code_to_return = HTTPStatus.NOT_FOUND if shdw_id: # we search only in this shadow shadow = Shadow.objects.with_id(shdw_id) if shadow: data_result, \ code_to_return \ = search_res_in_shadow(shadow, int(res_code)) data_to_return.update(data_result) else: # shadow doesn't exist return http.JsonResponse( data={'message': 'Shadow does not exist.'}, status=HTTPStatus.BAD_REQUEST) else: # We search in every shadow shadows = Shadow.objects() for shadow in shadows: data_result, \ code_to_return \ = search_res_in_shadow(shadow, int(res_code)) if data_result["success"]: # if true means it's been found data_to_return.update(data_result) break return http.JsonResponse(data=data_to_return, status=code_to_return) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def device_status(request, dev_id): '''Given a device id this method returns USING / DOWN / NOT_USING depending on it's endpoints and resources status If all resources are down -> DOWN If any resource is being used -> USING If no resource is being used -> NOT_USING ''' if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] # CHECK THE TOKEN if core.validate(token): device = IotConnector.objects.with_id(dev_id) if device: # Here i got all the available endpoints of the device up_endpoints_list = [ endpoint for endpoint in device.endpoints if endpoint.available ] if up_endpoints_list: resources_list = [] for endpoint in up_endpoints_list: resources_list.extend(endpoint.resources) data = {'status': 'NOT_USING'} for resource in resources_list: if ResourceUse.objects(resource=resource._id).count(): data = {'status': 'USING'} break else: data = {'status': 'DOWN'} sts = HTTPStatus.OK else: sts = HTTPStatus.BAD_REQUEST data = {'message': 'Device not found'} return http.JsonResponse(data=data, status=sts) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def delete_device(request, dev_id): ''' It performs cascade delete from device to it's resources and also REVOKES the token, not remove. It also ensures Database consistency updating Shadow devices field by removing itself from it. ''' if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] # CHECK THE TOKEN if core.validate(token): device = IotConnector.objects.with_id(dev_id) if device: # we revoke his token device.token.revoked = True device.token.save() shadow = Shadow.objects(devices=dev_id) if shadow: shadow.update( pull__devices=device) # ensure DB consistency # we delete his endpoints endpoints = device.endpoints for ep in endpoints: resources = ep.resources # we delete all the resources of the endpoint for res in resources: res.delete() ep.delete() # we delete the device at last device.delete() return http.JsonResponse(status=200, data={'message': 'Success'}) else: return http.JsonResponse( data={'message': 'Could not remove device.'}, status=HTTPStatus.NOT_MODIFIED) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def update_endpoint(request, ep_id): '''Given an Endpoint id, this method performs the update of the database object related to the given id.''' if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] # CHECK THE TOKEN if core.validate(token): data = request.POST endpoint = Endpoint.objects.with_id( ep_id) # it gives back a QuerySet if endpoint: # if any endpoint fetched if 'event' in data: endpoint.events.append(data['event']) if 'status' in data: endpoint.available = bool(int(data['status'])) for res in endpoint.resources: res.status = bool(int(data['status'])) res.save() if 'resources' in data: for res in json.loads( data['resources'] ): # data['resources'] = [resID, ...] associated_res = Resource.objects.with_id(res) associated_res.save() endpoint.resources.append( associated_res.to_dbref()) # append endpoint ref endpoint.save() data_to_return = {'message': 'Success!'} code_to_return = HTTPStatus.OK else: # if no endpoint fetched data_to_return = {'message': 'NOT MODIFIED'} code_to_return = HTTPStatus.NOT_MODIFIED return http.JsonResponse(data=data_to_return, status=code_to_return) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def validate_token(request): # TOKEN WILL BE PASSED IN THE HEADER """This method gets the token from the header and checks if it's valid or not """ if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] if validate(token): return http.JsonResponse(status=HTTPStatus.OK, data={'message': 'Valid'}) else: revoke(token) # to ensure that expired tokens are revoked in DB return http.JsonResponse(status=HTTPStatus.UNAUTHORIZED, data={"message": 'No valid'}) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def delete_app(request, app_id): ''' This Method deletes an application from the DB by its ID ''' if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] if core.validate(token): app = Application.objects.with_id(app_id) if app: usages = ResourceUse.objects(applications=app._id) for usage in usages: usage.update(pull__applications=app) aux = ResourceUse.objects.with_id(usage._id) # if all the apps are deleted, the resource is not used anymore if not aux.applications: aux.delete() try: app.delete() code_to_return = HTTPStatus.OK data_to_return = {'message': "Success"} except: return http.HttpResponseServerError( content=json.dumps({'message': 'Error Deleting'}), status=HTTPStatus.INTERNAL_SERVER_ERROR) else: # it there's no app data_to_return = {'message': 'NOT MODIFIED'} code_to_return = HTTPStatus.NOT_MODIFIED return http.HttpResponse(content=json.dumps(data_to_return), status=code_to_return) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def update_user(request, usr_id): """Given an user id, this method updates the database object of the user.""" if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] if core.validate(token): data = request.POST usr_l = UserData.objects(_id=usr_id) # it gives back a QuerySet if usr_l.count(): # if any endpoint fetched usr = usr_l.first() if 'username' in data: usr.username = data['username'] if 'shadow' in data: associated_shadow = Shadow.objects.with_id( data['shadow'] ) # it could be None (if it's not in the db) associated_shadow.save( ) # if i don't do this i can't access to_dbref() in the next line usr.shadow.append(associated_shadow.to_dbref()) usr.save() code_to_return = HTTPStatus.OK data_to_return = {'message': 'Success'} return http.HttpResponse( content=json.dumps(data_to_return), status=code_to_return) else: # it theres no shadow data_to_return = {'message': 'NOT MODIFIED'} code_to_return = HTTPStatus.NOT_MODIFIED return http.HttpResponse(content=json.dumps(data_to_return), status=code_to_return) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def get_shadow_by_id(request, shdw_id): ''' Given a shadow device id, this method fetches the shadow device from the db and returns it. ''' if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] if core.validate(token): shadow = Shadow.objects.with_id(shdw_id) if shadow: shadow = shadow.to_json() # json as string status = HTTPStatus.OK else: status = HTTPStatus.NOT_FOUND shadow = None return http.JsonResponse({'shadow': shadow}, status=status) else: return http.JsonResponse(data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse(data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def get_similar_logic(request, res_code, operation, shdw_id=None): """ Given a Resource code, an Operation and a Shadow Id (optional), this method looks for a similar logic if it's already created. Note: It only makes sense for operation = OBSERVATION """ if request.META.get( 'HTTP_AUTHORIZATION'): # This checks if token is passed token = request.META.get('HTTP_AUTHORIZATION').split(' ')[ 1] # 'Token adsad' -> ['Token', 'adsad'] -> 'adsad' # CHECK THE TOKEN if core.validate(token): if shdw_id: # the search could be in one shadow or every shadow logic_list = ResourceUse.objects(shadow=shdw_id, operation=operation) else: logic_list = ResourceUse.objects(operation=operation) for logic in logic_list: if logic.resource.type == int(res_code): kafka_topic = logic.kafka_topic return http.JsonResponse(data={ 'kafka_topic': kafka_topic, '_id': logic._id }, status=HTTPStatus.OK) # if program reaches this point, no similar logic was found return http.JsonResponse( data={'Message': HTTPStatus.NOT_FOUND.name}, status=HTTPStatus.NOT_FOUND) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def store_endpoint(request): ''' This method expects a dict passed in the body with the following fields: { registrationId : text:String, address: text:String } With this information it store in the database the new Endpoint. ''' if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] # CHECK THE TOKEN if core.validate(token): new_endpoint = Endpoint() new_endpoint._id = uuid.uuid4().__str__() new_endpoint.leshan_id = request.POST['registrationId'] new_endpoint.address = request.POST['address'] new_endpoint.name = request.POST['name'] try: new_endpoint.save() status_to_return = HTTPStatus.OK data = {'endpoint_id': new_endpoint.pk} except: # Data-Wrong or Connection Failed return http.JsonResponse( {'message': 'Wrong data or database connection failed'}, status=HTTPStatus.BAD_REQUEST) return http.JsonResponse(data=data, status=status_to_return) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def delete_shadow(request, shdw_id): ''' This Method deletes a the shadow device related to the id given and also REVOKES the token, not remove It also ensures Database consistency updating User shadow field by removing itself from it. ''' if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] if core.validate(token): shadow = Shadow.objects.with_id(shdw_id) if shadow: shadow_tokens = shadow.tokens # Before we delete the shadow device we revoke all its tokens for tk in shadow_tokens: tk.revoked = True tk.save() user = UserData.objects(shadow=shdw_id) if user: user.update(pull__shadow=shadow) try: shadow.delete() code_to_return = HTTPStatus.OK data_to_return = {'message': 'Success'} except: return http.HttpResponseServerError(content=json.dumps({'message': 'Error Deleting'}), status=HTTPStatus.INTERNAL_SERVER_ERROR) else: # it theres no shadow data_to_return = {'message': 'NOT MODIFIED'} code_to_return = HTTPStatus.NOT_MODIFIED return http.HttpResponse(content=json.dumps(data_to_return), status=code_to_return) else: return http.JsonResponse(data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse(data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def update_shadow(request, shdw_id): '''Given a Shadow id, this method performs the update of the database object related to the id.''' if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] if core.validate(token): data = request.POST shadow = Shadow.objects.with_id(shdw_id) # it gives back a QuerySet if shadow: # if any endpoint fetched if 'name' in data: shadow.name = data['name'] if 'description' in data: shadow.description = data['description'] if 'token' in data: associated_token = Token.objects.with_id(data['token']) associated_token.save() shadow.tokens.append(associated_token.to_dbref()) # append token ref try: shadow.save() code_to_return = HTTPStatus.OK data_to_return = {'message': 'Success'} except: return http.HttpResponseServerError(content=json.dumps({'message': 'Error Updating'}), status=HTTPStatus.INTERNAL_SERVER_ERROR) else: # it theres no shadow data_to_return = {'message': 'NOT MODIFIED'} code_to_return = HTTPStatus.NOT_MODIFIED return http.HttpResponse(content=json.dumps(data_to_return), status=code_to_return) else: return http.JsonResponse(data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse(data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)
def update_resource(request, endpoint_id): ''' Given an endpoint id, this method updates all the resources' status related to it ''' if request.META.get('HTTP_AUTHORIZATION'): token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1] # CHECK THE TOKEN if core.validate(token): data = request.POST associated_endpoint = Endpoint.objects.with_id( endpoint_id) # it could be None (if it's not in the db) if associated_endpoint: resources_list = associated_endpoint.resources for r in resources_list: if 'status' in data: r.status = bool(int(data['status'])) r.save() data_to_return = {'message': 'Success!'} code_to_return = HTTPStatus.OK else: data_to_return = {'message': 'The id provided doesn\'t exist'} code_to_return = HTTPStatus.BAD_REQUEST return http.JsonResponse(data=data_to_return, status=code_to_return) else: return http.JsonResponse( data={'message': 'Token invalid or expired.'}, status=HTTPStatus.UNAUTHORIZED) else: return http.JsonResponse( data={'message': "Authentication credentials not provided"}, status=HTTPStatus.BAD_REQUEST)