validations and dockerfiles are updated
This commit is contained in:
@@ -2,32 +2,35 @@ FROM python:3.12-slim-bookworm
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE 1
|
||||
ENV PYTHONUNBUFFERED 1
|
||||
ENV PYTHONPATH=/service_app
|
||||
|
||||
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
|
||||
|
||||
COPY ApiServices/AuthService/pyproject.toml .
|
||||
|
||||
RUN uv venv
|
||||
RUN uv pip install -r pyproject.toml
|
||||
|
||||
COPY ApiServices/AuthService ./service_app
|
||||
COPY ApiServices/api_handlers ./service_app/api_handlers
|
||||
|
||||
COPY databases ./service_app/databases
|
||||
COPY api_services ./service_app/api_services
|
||||
COPY api_objects ./service_app/api_objects
|
||||
COPY api_configs ./service_app/api_configs
|
||||
COPY api_events ./service_app/api_events
|
||||
COPY api_library ./service_app/api_library
|
||||
COPY api_validations ./service_app/api_validations
|
||||
|
||||
WORKDIR /service_app
|
||||
|
||||
CMD ["uv", "run", "app.py"]
|
||||
# Create logs directory
|
||||
RUN mkdir -p /service_app/logs
|
||||
|
||||
# Old File
|
||||
#FROM python:3.10
|
||||
COPY ApiServices/AuthService/pyproject.toml .
|
||||
|
||||
#RUN pip install --upgrade pip
|
||||
#RUN pip install --no-cache-dir --upgrade -r requirements.txt
|
||||
#CMD ["python", "-m", "app"]
|
||||
RUN uv venv .venv
|
||||
RUN . .venv/bin/activate && uv pip install -r pyproject.toml
|
||||
|
||||
COPY ApiServices ./ApiServices
|
||||
COPY databases ./databases
|
||||
COPY api_services ./api_services
|
||||
COPY api_objects ./api_objects
|
||||
COPY api_configs ./api_configs
|
||||
COPY api_events ./api_events
|
||||
COPY api_library ./api_library
|
||||
COPY api_validations ./api_validations
|
||||
|
||||
WORKDIR /service_app/ApiServices/AuthService
|
||||
|
||||
# Create startup script
|
||||
RUN echo '#!/bin/bash\n\
|
||||
source /service_app/.venv/bin/activate\n\
|
||||
exec python app.py' > /service_app/start.sh && \
|
||||
chmod +x /service_app/start.sh
|
||||
|
||||
CMD ["/service_app/start.sh"]
|
||||
|
||||
@@ -1 +1,5 @@
|
||||
__all__ = []
|
||||
from .authentication.router import login_route
|
||||
|
||||
__all__ = [
|
||||
"login_route",
|
||||
]
|
||||
|
||||
131
ApiServices/AuthService/routers/authentication/router.py
Normal file
131
ApiServices/AuthService/routers/authentication/router.py
Normal file
@@ -0,0 +1,131 @@
|
||||
from typing import Union
|
||||
from fastapi.routing import APIRouter
|
||||
from fastapi.requests import Request
|
||||
|
||||
from api_validations.validations_request import (
|
||||
Login,
|
||||
Logout,
|
||||
ChangePassword,
|
||||
Remember,
|
||||
Forgot,
|
||||
CreatePassword,
|
||||
OccupantSelection,
|
||||
EmployeeSelection,
|
||||
)
|
||||
from api_events.events import (
|
||||
AuthenticationLoginEventMethod,
|
||||
AuthenticationSelectEventMethod,
|
||||
AuthenticationCheckTokenEventMethod,
|
||||
AuthenticationRefreshEventMethod,
|
||||
AuthenticationChangePasswordEventMethod,
|
||||
AuthenticationCreatePasswordEventMethod,
|
||||
AuthenticationResetPasswordEventMethod,
|
||||
AuthenticationDisconnectUserEventMethod,
|
||||
AuthenticationLogoutEventMethod,
|
||||
AuthenticationRefreshTokenEventMethod,
|
||||
AuthenticationForgotPasswordEventMethod,
|
||||
AuthenticationDownloadAvatarEventMethod,
|
||||
)
|
||||
from ApiServices.api_handlers.auth_actions.token import parse_token_object_to_dict
|
||||
|
||||
|
||||
login_route = APIRouter(prefix="/authentication", tags=["Authentication"])
|
||||
login_route.include_router(login_route, include_in_schema=True)
|
||||
|
||||
|
||||
@login_route.post(path="/select", summary="Select company or occupant type")
|
||||
def authentication_select_company_or_occupant_type(
|
||||
request: Request, data: Union[EmployeeSelection, OccupantSelection]
|
||||
):
|
||||
token_dict = parse_token_object_to_dict(request=request)
|
||||
return (
|
||||
AuthenticationSelectEventMethod.authentication_select_company_or_occupant_type(
|
||||
data=data, request=request, token_dict=token_dict
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@login_route.post(path="/login", summary="Login user with domain and password")
|
||||
def authentication_login_with_domain_and_creds(request: Request, data: Login):
|
||||
return AuthenticationLoginEventMethod.authentication_login_with_domain_and_creds(
|
||||
request=request, data=data
|
||||
)
|
||||
|
||||
|
||||
@login_route.get(path="/valid", summary="Check access token is valid")
|
||||
def authentication_check_token_is_valid(request: Request):
|
||||
return AuthenticationCheckTokenEventMethod.authentication_check_token_is_valid(
|
||||
request=request
|
||||
)
|
||||
|
||||
|
||||
@login_route.get(path="/refresh", summary="Refresh credentials with access token")
|
||||
def authentication_refresh_user_info(request: Request):
|
||||
token_dict = parse_token_object_to_dict(request=request)
|
||||
return AuthenticationRefreshEventMethod.authentication_refresh_user_info(
|
||||
request=request, token_dict=token_dict
|
||||
)
|
||||
|
||||
|
||||
@login_route.post(path="/change_password", summary="Change password with access token")
|
||||
def authentication_change_password(request: Request, data: ChangePassword):
|
||||
token_dict = parse_token_object_to_dict(request=request)
|
||||
return AuthenticationChangePasswordEventMethod.authentication_change_password(
|
||||
data=data, token_dict=token_dict
|
||||
)
|
||||
|
||||
|
||||
@login_route.post(
|
||||
path="/create_password", summary="Create password with password token"
|
||||
)
|
||||
def authentication_create_password(data: CreatePassword):
|
||||
return AuthenticationCreatePasswordEventMethod.authentication_create_password(
|
||||
data=data
|
||||
)
|
||||
|
||||
|
||||
@login_route.post(path="/reset_password", summary="Create password with password token")
|
||||
def authentication_reset_password(data: Forgot):
|
||||
return AuthenticationResetPasswordEventMethod.authentication_reset_password(
|
||||
data=data
|
||||
)
|
||||
|
||||
|
||||
@login_route.post(path="/disconnect", summary="Disconnect user with access token")
|
||||
def authentication_disconnect_user(request: Request, data: Logout):
|
||||
token_dict = parse_token_object_to_dict(request=request)
|
||||
return AuthenticationDisconnectUserEventMethod.authentication_disconnect_user(
|
||||
data=data, token_dict=token_dict
|
||||
)
|
||||
|
||||
|
||||
@login_route.post(path="/logout", summary="Logout user with access token")
|
||||
def authentication_logout_user(request: Request, data: Logout):
|
||||
token_dict = parse_token_object_to_dict(request=request)
|
||||
return AuthenticationLogoutEventMethod.authentication_logout_user(
|
||||
data=data, token_dict=token_dict
|
||||
)
|
||||
|
||||
|
||||
@login_route.post(path="/refresher", summary="Refresh token with refresh token")
|
||||
def authentication_refresher_token(request: Request, data: Remember):
|
||||
token_dict = parse_token_object_to_dict(request=request)
|
||||
return AuthenticationRefreshTokenEventMethod.authentication_refresher_token(
|
||||
data=data, request=request, token_dict=token_dict
|
||||
)
|
||||
|
||||
|
||||
@login_route.post(path="/forgot", summary="Forgot password with email or phone number")
|
||||
def authentication_forgot_password(request: Request, data: Forgot):
|
||||
# token_dict = parse_token_object_to_dict(request=request)
|
||||
return AuthenticationForgotPasswordEventMethod.authentication_forgot_password(
|
||||
data=data, request=request
|
||||
)
|
||||
|
||||
|
||||
@login_route.post(path="/avatar", summary="Get link of avatar with credentials")
|
||||
def authentication_download_avatar(request: Request):
|
||||
token_dict = parse_token_object_to_dict(request=request)
|
||||
return AuthenticationDownloadAvatarEventMethod.authentication_download_avatar(
|
||||
token_dict=token_dict
|
||||
)
|
||||
@@ -5,6 +5,9 @@ ENV PYTHONUNBUFFERED 1
|
||||
|
||||
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
|
||||
|
||||
# Create logs directory
|
||||
RUN mkdir -p /service_app/logs
|
||||
|
||||
COPY ApiServices/EventService/pyproject.toml .
|
||||
|
||||
RUN uv venv
|
||||
|
||||
@@ -5,6 +5,9 @@ ENV PYTHONUNBUFFERED 1
|
||||
|
||||
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
|
||||
|
||||
# Create logs directory
|
||||
RUN mkdir -p /service_app/logs
|
||||
|
||||
COPY ApiServices/ValidationService/pyproject.toml .
|
||||
|
||||
RUN uv venv
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
from .core_response import AlchemyJsonResponse
|
||||
|
||||
__all__ = ["AlchemyJsonResponse"]
|
||||
0
ApiServices/api_handlers/auth_actions/__init__.py
Normal file
0
ApiServices/api_handlers/auth_actions/__init__.py
Normal file
223
ApiServices/api_handlers/auth_actions/auth.py
Normal file
223
ApiServices/api_handlers/auth_actions/auth.py
Normal file
@@ -0,0 +1,223 @@
|
||||
from fastapi.exceptions import HTTPException
|
||||
from api_configs import Auth
|
||||
from api_objects import (
|
||||
OccupantTokenObject,
|
||||
EmployeeTokenObject,
|
||||
UserType,
|
||||
)
|
||||
from api_services.redis.conn import redis_cli
|
||||
from ApiServices.api_handlers.auth_actions.token import AccessObjectActions
|
||||
|
||||
|
||||
def save_access_token_to_redis(
|
||||
request, found_user, domain: str, access_token: str = None
|
||||
):
|
||||
from databases import (
|
||||
BuildLivingSpace,
|
||||
BuildParts,
|
||||
Companies,
|
||||
Duties,
|
||||
Departments,
|
||||
Duty,
|
||||
Employees,
|
||||
Staff,
|
||||
Addresses,
|
||||
OccupantTypes
|
||||
)
|
||||
|
||||
if not found_user:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=dict(message="User is not found."),
|
||||
)
|
||||
|
||||
# Check user is already logged in or has a previous session
|
||||
already_tokens = AccessObjectActions.get_object_via_user_uu_id(user_id=found_user.uu_id)
|
||||
for key, token_user in already_tokens.items():
|
||||
if token_user.get("domain", "") == domain:
|
||||
redis_cli.delete(key)
|
||||
|
||||
access_token = (
|
||||
found_user.generate_access_token() if not access_token else access_token
|
||||
)
|
||||
# Prepare the user's details to save in Redis Session
|
||||
if found_user.is_occupant: # Check if user is NOT an occupant
|
||||
living_spaces: list[BuildLivingSpace] = BuildLivingSpace.filter_all(
|
||||
BuildLivingSpace.person_id == found_user.person_id
|
||||
).data
|
||||
if not living_spaces:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=dict(
|
||||
message="NO Living Space is found. This user has no proper account set please contact the admin."
|
||||
),
|
||||
)
|
||||
occupants_selection_dict = {}
|
||||
for living_space in living_spaces:
|
||||
build_parts_selection = BuildParts.filter_all(
|
||||
BuildParts.id == living_space.build_parts_id,
|
||||
)
|
||||
if not build_parts_selection.data:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=dict(
|
||||
message="No build Part is found for the living space. Please contact the admin."
|
||||
),
|
||||
)
|
||||
build_part = build_parts_selection.get(1)
|
||||
build = build_part.buildings
|
||||
occupant_type = OccupantTypes.filter_by_one(
|
||||
id=living_space.occupant_type,
|
||||
system=True,
|
||||
).data
|
||||
if not str(build.uu_id) in occupants_selection_dict:
|
||||
occupants_selection_dict[str(build.uu_id)] = dict(
|
||||
build_uu_id=str(build.uu_id),
|
||||
build_name=build.build_name,
|
||||
build_no=build.build_no,
|
||||
occupants=[
|
||||
dict(
|
||||
part_uu_id=str(build_part.uu_id),
|
||||
part_name=build_part.part_name,
|
||||
part_level=build_part.part_level,
|
||||
uu_id=str(occupant_type.uu_id),
|
||||
description=occupant_type.occupant_description,
|
||||
code=occupant_type.occupant_code,
|
||||
)
|
||||
],
|
||||
)
|
||||
elif str(build.uu_id) in occupants_selection_dict:
|
||||
occupants_selection_dict[str(build.uu_id)]["occupants"].append(
|
||||
dict(
|
||||
part_uu_id=str(build_part.uu_id),
|
||||
part_name=build_part.part_name,
|
||||
part_level=build_part.part_level,
|
||||
uu_id=str(occupant_type.uu_id),
|
||||
description=occupant_type.occupant_description,
|
||||
code=occupant_type.occupant_code,
|
||||
)
|
||||
)
|
||||
AccessObjectActions.save_object_to_redis(
|
||||
access_token=access_token,
|
||||
model_object=OccupantTokenObject(
|
||||
domain=domain,
|
||||
user_type=UserType.occupant.value,
|
||||
user_uu_id=str(found_user.uu_id),
|
||||
credentials=found_user.credentials(),
|
||||
user_id=found_user.id,
|
||||
person_id=found_user.person_id,
|
||||
person_uu_id=str(found_user.person.uu_id),
|
||||
request=dict(request.headers),
|
||||
available_occupants=occupants_selection_dict,
|
||||
),
|
||||
)
|
||||
return dict(
|
||||
user_type=UserType.occupant.name,
|
||||
available_occupants=occupants_selection_dict,
|
||||
)
|
||||
|
||||
list_employee = Employees.filter_all(
|
||||
Employees.people_id == found_user.person_id,
|
||||
).data
|
||||
companies_uu_id_list, companies_id_list, companies_list = [], [], []
|
||||
duty_uu_id_list, duty_id_list = [], []
|
||||
for employee in list_employee:
|
||||
staff = Staff.filter_one(Staff.id == employee.staff_id).data
|
||||
if duties := Duties.filter_one(Duties.id == staff.duties_id).data:
|
||||
if duty_found := Duty.filter_by_one(id=duties.duties_id).data:
|
||||
duty_uu_id_list.append(str(duty_found.uu_id))
|
||||
duty_id_list.append(duty_found.id)
|
||||
|
||||
department = Departments.filter_one(
|
||||
Departments.id == duties.department_id,
|
||||
).data
|
||||
if company := Companies.filter_one(
|
||||
Companies.id == department.company_id,
|
||||
).data:
|
||||
companies_uu_id_list.append(str(company.uu_id))
|
||||
companies_id_list.append(company.id)
|
||||
company_address = Addresses.filter_by_one(
|
||||
id=company.official_address_id
|
||||
).data
|
||||
companies_list.append(
|
||||
dict(
|
||||
uu_id=str(company.uu_id),
|
||||
public_name=company.public_name,
|
||||
company_type=company.company_type,
|
||||
company_address=company_address,
|
||||
)
|
||||
)
|
||||
AccessObjectActions.save_object_to_redis(
|
||||
access_token=access_token,
|
||||
model_object=EmployeeTokenObject(
|
||||
domain=domain,
|
||||
user_type=UserType.employee.value,
|
||||
user_uu_id=str(found_user.uu_id),
|
||||
credentials=found_user.credentials(),
|
||||
user_id=found_user.id,
|
||||
person_id=found_user.person_id,
|
||||
person_uu_id=str(found_user.person.uu_id),
|
||||
request=dict(request.headers),
|
||||
companies_uu_id_list=companies_uu_id_list,
|
||||
companies_id_list=companies_id_list,
|
||||
duty_uu_id_list=duty_uu_id_list,
|
||||
duty_id_list=duty_id_list,
|
||||
),
|
||||
)
|
||||
return dict(
|
||||
user_type=UserType.employee.name,
|
||||
companies_list=companies_list,
|
||||
)
|
||||
|
||||
|
||||
def update_selected_to_redis(request, add_payload):
|
||||
already_tokens = AccessObjectActions.get_object_via_access_key(request=request)
|
||||
if not hasattr(request, "headers"):
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail=dict(
|
||||
message="Headers are not found in request. Invalid request object."
|
||||
),
|
||||
)
|
||||
access_token = request.headers.get(Auth.ACCESS_TOKEN_TAG)
|
||||
if already_tokens.user_type == UserType.occupant.value:
|
||||
already_tokens.selected_occupant = add_payload.model_dump()
|
||||
return AccessObjectActions.save_object_to_redis(
|
||||
access_token=access_token,
|
||||
model_object=OccupantTokenObject(**already_tokens.model_dump()),
|
||||
)
|
||||
elif already_tokens.user_type == UserType.employee.value:
|
||||
already_tokens.selected_company = add_payload.model_dump()
|
||||
return AccessObjectActions.save_object_to_redis(
|
||||
access_token=access_token,
|
||||
model_object=EmployeeTokenObject(**already_tokens.model_dump()),
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail=dict(
|
||||
message="User type is not found in the token object. Please reach to your administrator."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def update_access_token_to_redis(request, add_payload):
|
||||
already_tokens = AccessObjectActions.get_object_via_access_key(request=request)
|
||||
if not hasattr(request, "headers"):
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail=dict(
|
||||
message="Headers are not found in request. Invalid request object."
|
||||
),
|
||||
)
|
||||
payload = {**add_payload, **already_tokens}
|
||||
access_token = request.headers.get(Auth.ACCESS_TOKEN_TAG)
|
||||
if payload.get("user_type") == str(UserType.occupant.value):
|
||||
|
||||
return AccessObjectActions.save_object_to_redis(
|
||||
access_token=access_token,
|
||||
model_object=OccupantTokenObject(**payload),
|
||||
)
|
||||
return AccessObjectActions.save_object_to_redis(
|
||||
access_token=access_token,
|
||||
model_object=EmployeeTokenObject(**payload),
|
||||
)
|
||||
1
ApiServices/api_handlers/auth_actions/login.py
Normal file
1
ApiServices/api_handlers/auth_actions/login.py
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
219
ApiServices/api_handlers/auth_actions/token.py
Normal file
219
ApiServices/api_handlers/auth_actions/token.py
Normal file
@@ -0,0 +1,219 @@
|
||||
import typing
|
||||
from fastapi import HTTPException, status
|
||||
from api_objects import OccupantTokenObject, EmployeeTokenObject
|
||||
from api_services.redis.functions import RedisActions
|
||||
from api_configs import Auth
|
||||
|
||||
|
||||
class AccessObjectActions:
|
||||
|
||||
@classmethod
|
||||
def save_object_to_redis(
|
||||
cls,
|
||||
access_token,
|
||||
model_object: typing.Union[OccupantTokenObject, EmployeeTokenObject],
|
||||
expiry_minutes: int = Auth.TOKEN_EXPIRE_MINUTES_30.total_seconds() // 60
|
||||
) -> bool:
|
||||
"""Save access token object to Redis with expiry
|
||||
Args:
|
||||
access_token: The access token
|
||||
model_object: The token object to save
|
||||
expiry_minutes: Minutes until token expires (default: from Auth config)
|
||||
Returns:
|
||||
bool: True if successful
|
||||
Raises:
|
||||
HTTPException: If save fails
|
||||
"""
|
||||
try:
|
||||
RedisActions.save_object_to_redis(
|
||||
access_token=access_token,
|
||||
model_object=model_object,
|
||||
expiry_minutes=expiry_minutes
|
||||
)
|
||||
return True
|
||||
except Exception as e:
|
||||
print("Save Object to Redis Error: ", e)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail=dict(
|
||||
message="Failed to save token to Redis",
|
||||
error=str(e)
|
||||
),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get_object_via_user_uu_id(cls, user_id: str) -> typing.Union[dict, None]:
|
||||
"""Get all valid tokens for a user
|
||||
Args:
|
||||
user_id: The user UUID to search for
|
||||
Returns:
|
||||
dict: Dictionary of valid tokens for the user
|
||||
"""
|
||||
return RedisActions.get_object_via_user_uu_id(user_id)
|
||||
|
||||
@classmethod
|
||||
def access_token(cls, request) -> str:
|
||||
"""Extract and validate access token from request
|
||||
Args:
|
||||
request: The request object
|
||||
Returns:
|
||||
str: The access token
|
||||
Raises:
|
||||
HTTPException: If token is missing or invalid
|
||||
"""
|
||||
if not hasattr(request, "headers"):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail=dict(
|
||||
message="Headers not found in request"
|
||||
)
|
||||
)
|
||||
|
||||
access_token = request.headers.get(Auth.ACCESS_TOKEN_TAG)
|
||||
if not access_token:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail=dict(
|
||||
message="Unauthorized user, please login"
|
||||
),
|
||||
)
|
||||
return access_token
|
||||
|
||||
@classmethod
|
||||
def get_token_object(cls, request) -> typing.Union[OccupantTokenObject, EmployeeTokenObject]:
|
||||
"""Get and validate token object from request
|
||||
Args:
|
||||
request: The request object
|
||||
Returns:
|
||||
Union[OccupantTokenObject, EmployeeTokenObject]: The token object
|
||||
Raises:
|
||||
HTTPException: If token is invalid or expired
|
||||
"""
|
||||
try:
|
||||
return RedisActions.get_object_via_access_key(request)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail=dict(
|
||||
message=str(e)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@classmethod
|
||||
def get_object_via_access_key(
|
||||
cls, request,
|
||||
) -> typing.Union[EmployeeTokenObject, OccupantTokenObject, None]:
|
||||
from api_configs import Auth
|
||||
access_object = RedisActions.get_with_regex(
|
||||
value_regex=str(request.headers.get(Auth.ACCESS_TOKEN_TAG) + ":*")
|
||||
).data
|
||||
if access_object.get("user_type") == 1:
|
||||
if not access_object.get("selected_company", None):
|
||||
access_object["selected_company"] = None
|
||||
return EmployeeTokenObject(**access_object)
|
||||
elif access_object.get("user_type") == 2:
|
||||
if not access_object.get("selected_occupant", None):
|
||||
access_object["selected_occupant"] = None
|
||||
return OccupantTokenObject(**access_object)
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail=dict(
|
||||
message="User type is not found in the token object. Please reach to your administrator."
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def parse_token_object_to_dict(request): # from requests import Request
|
||||
import api_events.events as events
|
||||
|
||||
from databases import EndpointRestriction, Events
|
||||
from api_configs.configs import Config
|
||||
|
||||
if valid_token := AccessObjectActions.get_token_object(request=request):
|
||||
endpoint_name = str(request.url).replace(str(request.base_url), "/")
|
||||
if (
|
||||
str(endpoint_name) in Config.INSECURE_PATHS
|
||||
or str(endpoint_name) in Config.NOT_SECURE_PATHS
|
||||
):
|
||||
return valid_token
|
||||
if "update" in endpoint_name:
|
||||
endpoint_name = endpoint_name.split("update")[0] + "update"
|
||||
endpoint_active = EndpointRestriction.filter_one(
|
||||
EndpointRestriction.endpoint_name.ilike(f"%{endpoint_name}%"),
|
||||
system=True,
|
||||
).data
|
||||
|
||||
if not endpoint_active:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail=f"This endpoint {endpoint_name} is not active for this user, please contact your responsible company for further information.",
|
||||
)
|
||||
if valid_token.user_type == 1:
|
||||
if not valid_token.selected_company:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Selected company is not found in the token object.",
|
||||
)
|
||||
selected_event = Events.filter_one(
|
||||
Events.endpoint_id == endpoint_active.id,
|
||||
Events.id.in_(valid_token.selected_company.reachable_event_list_id),
|
||||
).data
|
||||
if not selected_event:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="This endpoint requires event validation. Please contact your responsible company to use this event.",
|
||||
)
|
||||
event_function_class = getattr(selected_event, "function_class", None)
|
||||
event_function_code = getattr(selected_event, "function_code", None)
|
||||
function_class = getattr(events, event_function_class, None)
|
||||
active_function = getattr(
|
||||
function_class,
|
||||
function_class.__event_keys__.get(event_function_code, None),
|
||||
None,
|
||||
)
|
||||
if not active_function:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="This endpoint requires event validation. Please contact your responsible company to use this event.",
|
||||
)
|
||||
valid_token.available_event = active_function
|
||||
return valid_token
|
||||
elif valid_token.user_type == 2:
|
||||
if not valid_token.selected_occupant:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_418_IM_A_TEAPOT,
|
||||
detail="Selected occupant is not found in the token object.",
|
||||
)
|
||||
selected_event = Events.filter_all(
|
||||
Events.endpoint_id == endpoint_active.id,
|
||||
Events.id.in_(valid_token.selected_occupant.reachable_event_list_id),
|
||||
)
|
||||
if not selected_event.data:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail=f"This endpoint {endpoint_name} requires event validation. Please contact your responsible company to use this event.",
|
||||
)
|
||||
selected_event = selected_event.data[0]
|
||||
event_function_class = getattr(selected_event, "function_class", None)
|
||||
event_function_code = getattr(selected_event, "function_code", None)
|
||||
function_class = getattr(events, event_function_class, None)
|
||||
active_function = getattr(
|
||||
function_class,
|
||||
function_class.__event_keys__.get(event_function_code, None),
|
||||
None,
|
||||
)
|
||||
if not active_function:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail=f"This endpoint {endpoint_name} requires event validation. Please contact your responsible company to use this event.",
|
||||
)
|
||||
valid_token.available_event = active_function
|
||||
return valid_token
|
||||
valid_token.available_event = None
|
||||
return valid_token
|
||||
user_type = "Company" if valid_token.user_type == 1 else "Occupant"
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail=f"Token of this user is not valid. Please login and refresh {user_type} selection.",
|
||||
)
|
||||
Reference in New Issue
Block a user