async def is_authenticated(authorization=Security(APIKeyHeader(name="Authorization", auto_error=False))): if not authorization: raise CustomHTTPException( status_code=status.HTTP_401_UNAUTHORIZED, content=jsonable_encoder( BaseResponseModel( info=[InfoModel( type='error', message='Unauthorized' )] ) ) ) user_details = await UsersTableManager.is_valid_token(authorization) if not user_details: raise CustomHTTPException( status_code=status.HTTP_401_UNAUTHORIZED, content=jsonable_encoder( BaseResponseModel( info=[InfoModel( type='error', message='You are not authenticated' )] ) ) ) return format_user_details(user_details)
async def validate_user_credentials(cls, username, password): query = user.select().where(user.c.username == username) record = await database.fetch_one(query) if not record: raise CustomHTTPException( status_code=status.HTTP_404_NOT_FOUND, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel(type='error', message='User not found') ]))) if not pwd_context.verify(password, record['password']): raise CustomHTTPException( status_code=status.HTTP_401_UNAUTHORIZED, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel(type='error', message='Incorrect password') ])))
def raise_exception(e): if isinstance(e, CustomHTTPException): raise e raise CustomHTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel(type='error', message='Internal server error: ' + e.args[0]) ])))
async def post_daily_reports(): try: authenticated = requests.post(f"{BL_SERVER_URL}/login", json={ 'username': '******', 'password': '******' }) if authenticated.status_code == status.HTTP_200_OK: sensors_values = await SensorsManagement.get_sensors_details() reports_list = [] for sensor in sensors_values: reports_list.append({ 'id': sensor['id'], 'parameter': sensor['parameter'], 'value': sensor['value'] }) response = requests.post( f"{BL_SERVER_URL}/reports", headers={ "Authorization": (authenticated.json())['data'][0]['token'] }, json=reports_list) authenticated = requests.post( f"{BL_SERVER_URL}/logout", headers={ "Authorization": (authenticated.json())['data'][0]['token'] }) return JSONResponse( status_code=status.HTTP_200_OK, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel(type='success', message='Daily reports created') ]))) return JSONResponse( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel(type='error', message='Internal server error') ]))) except Exception as e: raise_exception(e)
async def update_sensors_parameters(item): try: return JSONResponse( status_code=status.HTTP_200_OK, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel(type='success', message='Sensors parameters updated') ]))) except Exception as e: raise_exception(e)
async def post_alert(item: AlertModel): try: item.alert_date = datetime.utcnow() await AlertsTableManager.create_alert(item) return JSONResponse( status_code=status.HTTP_201_CREATED, content=jsonable_encoder( BaseResponseModel( info=[InfoModel(type='success', message='Alert added')]))) except Exception as e: raise_exception(e)
async def read_record(cls, table, record_id): query = table.select().where(table.c.id == record_id) record = await database.fetch_one(query) if not record: raise CustomHTTPException( status_code=status.HTTP_404_NOT_FOUND, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel(type='error', message='Item not found') ]))) return record
async def post_responsibility(item: ResponsibilityIn): try: await ResponsibilitiesTableManager.create_responsibility(item) return JSONResponse( status_code=status.HTTP_201_CREATED, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel(type='success', message='Responsibility added successfully') ]))) except Exception as e: raise_exception(e)
async def delete_profile(id: int): try: await ProfilesTableManager.delete_record(profile, id) return JSONResponse( status_code=status.HTTP_200_OK, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel(type='success', message='Profile deleted successfully') ]))) except Exception as e: raise_exception(e)
async def post_device_group(item: DevicegroupIn): try: await DevicegroupTableManager.create_device_group(item) return JSONResponse( status_code=status.HTTP_201_CREATED, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel(type='success', message='Devicegroup added successfully') ]))) except Exception as e: raise_exception(e)
async def logout(user_details: dict = Depends(is_authenticated)): try: await UsersTableManager.update_token(user_details['username']) return JSONResponse( status_code=status.HTTP_200_OK, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel(type='success', message='User logged out successfully') ]))) except Exception as e: raise_exception(e)
async def delete_responsibility(profile_id: int, group_id: int): try: await ResponsibilitiesTableManager.delete_responsibility( profile_id=profile_id, group_id=group_id) return JSONResponse( status_code=status.HTTP_200_OK, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel(type='success', message='Responsibility deleted successfully') ]))) except Exception as e: raise_exception(e)
async def post_report(items: List[ReportModel]): try: for item in items: item.report_date = datetime.utcnow() await DailyReportsTableManager.create_reports(items) return JSONResponse( status_code=status.HTTP_201_CREATED, content=jsonable_encoder( BaseResponseModel( info=[InfoModel(type='success', message='Reports added') ]))) except Exception as e: raise_exception(e)
async def delete_device_group(device_id: int, group_id: int): try: await DevicegroupTableManager.delete_device_group(device_id=device_id, group_id=group_id) return JSONResponse( status_code=status.HTTP_200_OK, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel(type='success', message='Devicegroup deleted successfully') ]))) except Exception as e: raise_exception(e)
async def post_alerts(): try: authenticated = requests.post(f"{BL_SERVER_URL}/login", json={ 'username': '******', 'password': '******' }) if authenticated.status_code == status.HTTP_200_OK: sensors_values = await SensorsManagement.get_sensors_details() for sensor in sensors_values: if (sensor['value'] - 1) < sensor['limit'] or ( sensor['value'] + 1) > sensor['limit']: response = requests.post( f"{BL_SERVER_URL}/alerts", headers={ "Authorization": (authenticated.json())['data'][0]['token'] }, json=sensor) authenticated = requests.post( f"{BL_SERVER_URL}/logout", headers={ "Authorization": (authenticated.json())['data'][0]['token'] }) return JSONResponse( status_code=status.HTTP_200_OK, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel(type='success', message='Sensors were verified') ]))) return JSONResponse( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel(type='error', message='Internal server error') ]))) except Exception as e: raise_exception(e)
async def update_record(cls, table, record_id, schema): query = table.select().where(table.c.id == record_id) record = await database.execute(query) if not record: raise CustomHTTPException( status_code=status.HTTP_404_NOT_FOUND, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel(type='error', message='Item not found') ]))) update_query = table.update().where(table.c.id == record_id).values( **schema.dict()) await database.execute(update_query) return await database.fetch_one(query)
async def delete_device(id: int, user_details: dict = Depends(is_authenticated)): try: user_device_id_list = get_user_device_id_list( await UsersTableManager.get_user_devices( user_details['id'], await is_admin(user_details['id']))) if id in user_device_id_list: await DevicesTableManager.delete_record(device, id) return JSONResponse( status_code=status.HTTP_200_OK, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel(type='success', message='Device deleted successfully') ]))) return JSONResponse( status_code=status.HTTP_403_FORBIDDEN, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel(type='error', message='Permission denied') ]))) except Exception as e: raise_exception(e)
async def delete_delegation(cls, profile_id, user_id): query = delegation.select().where( and_(delegation.c.profile_id == profile_id, delegation.c.user_id == user_id)) record = await database.execute(query) if not record: raise CustomHTTPException( status_code=status.HTTP_404_NOT_FOUND, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel(type='error', message='Item not found') ]))) delete_query = delegation.delete().where( and_(delegation.c.profile_id == profile_id, delegation.c.user_id == user_id)) return not (bool(await database.execute(delete_query)))
async def have_permission(authorization=Security( APIKeyHeader(name="Authorization", auto_error=False))): user_id = (await is_authenticated(authorization))['id'] profile_id = await ProfilesTableManager.get_profile_id_by_profilename( 'admin') user_profiles = get_user_profile_id_list( await DelegationsTableManager.read_delegations(user_id=user_id)) if (not profile_id) or (profile_id not in user_profiles): raise CustomHTTPException( status_code=status.HTTP_403_FORBIDDEN, content=jsonable_encoder( BaseResponseModel(info=[ InfoModel( type='error', message='You are not allowed to perform this action') ]))) return user_id
async def read_all_records(cls, table, filter_query=None, type_name=None, device_id_list=None): query = table.select() if device_id_list: query = query.where(table.c.id.in_(device_id_list)) if filter_query: query = query.where(table.c.name.ilike(f'%{filter_query}%')) if type_name: type_query = device_type.select().where(device_type.c.name == type_name) type_record = await database.fetch_one(type_query) if not type_record: raise CustomHTTPException( status_code=status.HTTP_404_NOT_FOUND, content=jsonable_encoder( BaseResponseModel( info=[InfoModel( type='error', message='Type not found' )] ) ) ) query = query.where(table.c.type_id == type_record['id']) return await database.fetch_all(query)