Skip to content

Commit

Permalink
refactor external services
Browse files Browse the repository at this point in the history
add function to retrieve token from header
add user's endpoint to retrieve user id from token
  • Loading branch information
violetaperezandrade committed May 30, 2024
1 parent 5d3d21c commit 5cfca7c
Show file tree
Hide file tree
Showing 6 changed files with 42 additions and 13 deletions.
2 changes: 1 addition & 1 deletion app/controller/measurements.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
File renamed without changes.
18 changes: 18 additions & 0 deletions app/service/users.py → app/external/Users.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
)
Empty file added app/external/__init__.py
Empty file.
15 changes: 12 additions & 3 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -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 (
Expand All @@ -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"}
Expand Down Expand Up @@ -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())


Expand Down
20 changes: 11 additions & 9 deletions app/service/rabbitmq/consumer.py
Original file line number Diff line number Diff line change
@@ -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(
Expand Down

0 comments on commit 5cfca7c

Please sign in to comment.