From 5cfca7cd8831925055e0416f7cc0f677b4e28fd7 Mon Sep 17 00:00:00 2001 From: violetaperezandrade Date: Thu, 30 May 2024 00:02:58 -0300 Subject: [PATCH] refactor external services add function to retrieve token from header add user's endpoint to retrieve user id from token --- app/controller/measurements.py | 2 +- app/{service/plants.py => external/Plants.py} | 0 app/{service/users.py => external/Users.py} | 18 +++++++++++++++++ app/external/__init__.py | 0 app/main.py | 15 +++++++++++--- app/service/rabbitmq/consumer.py | 20 ++++++++++--------- 6 files changed, 42 insertions(+), 13 deletions(-) rename app/{service/plants.py => external/Plants.py} (100%) rename app/{service/users.py => external/Users.py} (67%) create mode 100644 app/external/__init__.py diff --git a/app/controller/measurements.py b/app/controller/measurements.py index daea70f..4dadf86 100644 --- a/app/controller/measurements.py +++ b/app/controller/measurements.py @@ -2,7 +2,7 @@ from fastapi.responses import JSONResponse from fastapi.encoders import jsonable_encoder from service.measurements import MeasurementsService -from service.plants import PlantsService +from external.Plants import PlantsService from schemas.measurement import MeasurementSavedSchema diff --git a/app/service/plants.py b/app/external/Plants.py similarity index 100% rename from app/service/plants.py rename to app/external/Plants.py diff --git a/app/service/users.py b/app/external/Users.py similarity index 67% rename from app/service/users.py rename to app/external/Users.py index a248490..dc68030 100644 --- a/app/service/users.py +++ b/app/external/Users.py @@ -40,3 +40,21 @@ async def get_user(user_id: int) -> Optional[UserSchema]: status_code=e.response.status_code, detail=e.response.content.decode(), ) + + @staticmethod + async def get_user_id(token: str) -> int: + try: + async with AsyncClient() as client: + response = await client.post( + USERS_SERVICE_URL + "/users/token", json={"token": token} + ) + response.raise_for_status() + user_id = response.json().get("user_id") + return user_id + + except HTTPStatusError as e: + logger.error("Error while getting user ID: " + str(e)) + raise HTTPException( + status_code=e.response.status_code, + detail=e.response.content.decode(), + ) diff --git a/app/external/__init__.py b/app/external/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/main.py b/app/main.py index 8595c3a..cc47262 100644 --- a/app/main.py +++ b/app/main.py @@ -1,10 +1,10 @@ import logging from typing import List, Literal -from fastapi import FastAPI, Depends +from fastapi import FastAPI, Depends, Header from controller.measurements import MeasurementsController from service.measurements import MeasurementsService -from service.plants import PlantsService +from external.Plants import PlantsService from repository.measurements import MeasurementsRepository from schemas.measurement import MeasurementSavedSchema from schemas.device_plant import ( @@ -26,6 +26,11 @@ logger.setLevel("DEBUG") +async def get_access_token(x_access_token: str = Header(...)): + print(f"Token: {x_access_token}") + return x_access_token + + @app.get("/") async def root(): return {"message": "measurments service"} @@ -58,8 +63,12 @@ async def update_all_in_device_plant(id_device: str, @app.get("/measurements/device-plant", response_model=List[DevicePlantSchema]) async def get_device_plant( - query_params: DevicePlantQueryParams = Depends(DevicePlantQueryParams) + query_params: DevicePlantQueryParams = Depends(DevicePlantQueryParams), + token: str = Depends(get_access_token) ): + print(f"Token: {token}") + token = token.split(" ")[1] + print(f"Token stripped: {token}") return controller.handle_get_device_plant(query_params.get_query_params()) diff --git a/app/service/rabbitmq/consumer.py b/app/service/rabbitmq/consumer.py index 119647d..a41b9ee 100644 --- a/app/service/rabbitmq/consumer.py +++ b/app/service/rabbitmq/consumer.py @@ -1,25 +1,27 @@ import asyncio import json -from ..users import UsersService -from exceptions.logger_messages import LoggerMessages import pydantic import logging -from exceptions.invalid_insertion import InvalidInsertionError -from exceptions.deviating_parameters import DeviatedParametersError -from exceptions.empty_package import EmptyPackageError -from exceptions.row_not_found import RowNotFoundError + from pydantic import ValidationError -from schemas.measurement import MeasurementReadingSchema from sqlalchemy import MetaData from sqlalchemy.orm import Session from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base +from os import environ +from firebase_admin import messaging + +from external.Users import UsersService from ..common.middleware import Middleware from database.models.measurement import Measurement from database.database import SQLAlchemyClient from resources.parser import apply_rules -from os import environ -from firebase_admin import messaging +from schemas.measurement import MeasurementReadingSchema +from exceptions.logger_messages import LoggerMessages +from exceptions.invalid_insertion import InvalidInsertionError +from exceptions.deviating_parameters import DeviatedParametersError +from exceptions.empty_package import EmptyPackageError +from exceptions.row_not_found import RowNotFoundError Base = declarative_base(