first commit
This commit is contained in:
71
api_services/redis/functions.py
Normal file
71
api_services/redis/functions.py
Normal file
@@ -0,0 +1,71 @@
|
||||
import json
|
||||
import typing
|
||||
|
||||
from fastapi import status
|
||||
from fastapi.exceptions import HTTPException
|
||||
|
||||
from .conn import redis_cli
|
||||
|
||||
from api_configs import Auth
|
||||
from api_objects import EmployeeTokenObject, OccupantTokenObject
|
||||
|
||||
|
||||
def get_object_via_access_key(
|
||||
request,
|
||||
) -> typing.Union[EmployeeTokenObject, OccupantTokenObject, None]:
|
||||
if not hasattr(request, "headers"):
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail=dict(
|
||||
message="Headers are not found in request. Invalid request object."
|
||||
),
|
||||
)
|
||||
if not request.headers.get(Auth.ACCESS_TOKEN_TAG):
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail=dict(message="Unauthorized user, please login..."),
|
||||
)
|
||||
already_tokens = redis_cli.scan_iter(
|
||||
match=str(request.headers.get(Auth.ACCESS_TOKEN_TAG) + ":*")
|
||||
)
|
||||
|
||||
if already_tokens := list(already_tokens):
|
||||
try:
|
||||
if redis_object := json.loads(
|
||||
redis_cli.get(already_tokens[0].decode()) or {}
|
||||
):
|
||||
if redis_object.get("user_type") == 1:
|
||||
if not redis_object.get("selected_company", None):
|
||||
redis_object["selected_company"] = None
|
||||
return EmployeeTokenObject(**redis_object)
|
||||
elif redis_object.get("user_type") == 2:
|
||||
if not redis_object.get("selected_occupant", None):
|
||||
redis_object["selected_occupant"] = None
|
||||
return OccupantTokenObject(**redis_object)
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail=dict(
|
||||
message="User type is not found in the token object. Please reach to your administrator."
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail={
|
||||
"message": "Redis Service raised an exception.",
|
||||
"error": str(e),
|
||||
},
|
||||
)
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid credentials. Please login again.",
|
||||
)
|
||||
|
||||
|
||||
def get_object_via_user_uu_id(user_id: str) -> typing.Union[list, None]:
|
||||
already_tokens = redis_cli.scan_iter(match=str("*:" + str(user_id)))
|
||||
already_tokens = list(already_tokens)
|
||||
if list(already_tokens):
|
||||
return list(already_tokens)
|
||||
return None
|
||||
Reference in New Issue
Block a user