base context for wrappers updated

This commit is contained in:
2025-01-17 20:45:41 +03:00
parent 628f6bd483
commit d6785ed36f
20 changed files with 225 additions and 196 deletions

View File

@@ -15,7 +15,9 @@ from ApiValidations.Custom.token_objects import CompanyToken
from ApiValidations.Request.authentication import (
Login,
EmployeeSelectionValidation,
OccupantSelectionValidation, OccupantSelection, EmployeeSelection,
OccupantSelectionValidation,
OccupantSelection,
EmployeeSelection,
)
from ErrorHandlers import HTTPExceptionApi
from Schemas.company.company import Companies
@@ -39,10 +41,7 @@ from .models import (
if TYPE_CHECKING:
from fastapi import Request
from ApiServices.Token.token_handler import (
OccupantTokenObject,
EmployeeTokenObject
)
from ApiServices.Token.token_handler import OccupantTokenObject, EmployeeTokenObject
# Type aliases for common types
TokenDictType = Union["EmployeeTokenObject", "OccupantTokenObject"]
@@ -116,7 +115,7 @@ class AuthenticationSelectEventMethods(MethodToEvent):
error_code="HTTP_400_BAD_REQUEST",
lang=token_dict.lang,
loc=get_line_number_for_error(),
sys_msg="Company not found in token"
sys_msg="Company not found in token",
)
selected_company = Companies.filter_one(
Companies.uu_id == data.company_uu_id,
@@ -127,7 +126,7 @@ class AuthenticationSelectEventMethods(MethodToEvent):
error_code="HTTP_400_BAD_REQUEST",
lang=token_dict.lang,
loc=get_line_number_for_error(),
sys_msg="Company not found in token"
sys_msg="Company not found in token",
)
# Get department IDs for the company
@@ -142,12 +141,17 @@ class AuthenticationSelectEventMethods(MethodToEvent):
# Get duties IDs for the company
duties_ids = [
duty.id
for duty in Duties.filter_all(Duties.company_id == selected_company.id, db=db_session).data
for duty in Duties.filter_all(
Duties.company_id == selected_company.id, db=db_session
).data
]
# Get staff IDs
staff_ids = [
staff.id for staff in Staff.filter_all(Staff.duties_id.in_(duties_ids), db=db_session).data
staff.id
for staff in Staff.filter_all(
Staff.duties_id.in_(duties_ids), db=db_session
).data
]
# Get employee
@@ -162,7 +166,7 @@ class AuthenticationSelectEventMethods(MethodToEvent):
error_code="HTTP_400_BAD_REQUEST",
lang=token_dict.lang,
loc=get_line_number_for_error(),
sys_msg="Employee not found in token"
sys_msg="Employee not found in token",
)
# Get reachable events
@@ -173,7 +177,9 @@ class AuthenticationSelectEventMethods(MethodToEvent):
# Get staff and duties
staff = Staff.filter_one(Staff.id == employee.staff_id, db=db_session).data
duties = Duties.filter_one(Duties.id == staff.duties_id, db=db_session).data
department = Departments.filter_one(Departments.id == duties.department_id, db=db_session).data
department = Departments.filter_one(
Departments.id == duties.department_id, db=db_session
).data
# Get bulk duty
bulk_id = Duty.filter_by_one(system=True, duty_code="BULK", db=db_session).data
@@ -199,12 +205,17 @@ class AuthenticationSelectEventMethods(MethodToEvent):
employee_uu_id=employee.uu_id.__str__(),
reachable_event_list_id=reachable_event_list_id,
)
try: # Update Redis
update_token = TokenService.update_token_at_redis(request=request, add_payload=company_token)
try: # Update Redis
update_token = TokenService.update_token_at_redis(
request=request, add_payload=company_token
)
return update_token
except Exception as e:
raise HTTPExceptionApi(
error_code="", lang="en", loc=get_line_number_for_error(), sys_msg=f"{e}"
error_code="",
lang="en",
loc=get_line_number_for_error(),
sys_msg=f"{e}",
)
@classmethod

View File

@@ -42,7 +42,11 @@ from .models import (
RememberRequestModel,
)
from ApiEvents.base_request_model import DictRequestModel, EndpointBaseRequestModel
from ApiEvents.abstract_class import RouteFactoryConfig, EndpointFactoryConfig, endpoint_wrapper
from ApiEvents.abstract_class import (
RouteFactoryConfig,
EndpointFactoryConfig,
endpoint_wrapper,
)
if TYPE_CHECKING:
from fastapi import Request
@@ -51,6 +55,7 @@ from ApiValidations.Custom.token_objects import EmployeeTokenObject, OccupantTok
# Type aliases for common types
@endpoint_wrapper("/authentication/select")
async def authentication_select_company_or_occupant_type(
request: "Request",
@@ -64,7 +69,7 @@ async def authentication_select_company_or_occupant_type(
data = EmployeeSelection(**data.data)
elif data.data.get("build_living_space_uu_id"):
data = OccupantSelection(**data.data)
if r := await AuthenticationSelectEventMethods.authentication_select_company_or_occupant_type(
if await AuthenticationSelectEventMethods.authentication_select_company_or_occupant_type(
request=request, data=data, token_dict=auth_dict
):
if isinstance(data, EmployeeSelection):
@@ -100,7 +105,6 @@ async def authentication_check_token_is_valid(
}
@endpoint_wrapper("/authentication/refresh")
async def authentication_refresh_user_info(
request: "Request",
@@ -139,6 +143,7 @@ async def authentication_create_password(
"status": "OK",
}
@endpoint_wrapper("/authentication/forgot-password")
async def authentication_forgot_password(
request: "Request",
@@ -151,6 +156,7 @@ async def authentication_forgot_password(
"status": "OK",
}
@endpoint_wrapper("/authentication/reset-password")
async def authentication_reset_password(
request: "Request",
@@ -163,6 +169,7 @@ async def authentication_reset_password(
"status": "OK",
}
@endpoint_wrapper("/authentication/disconnect")
async def authentication_disconnect_user(
request: "Request",

View File

@@ -12,15 +12,16 @@ if TYPE_CHECKING:
class TokenObjectBase(BaseModel):
"""Base model for token objects."""
user_type: str = Field(..., description="Type of user")
user_id: str = Field(..., description="User ID")
token: str = Field(..., description="Authentication token")
permissions: Dict[str, Any] = Field(default_factory=dict, description="User permissions")
permissions: Dict[str, Any] = Field(description="User permissions")
class LoginData(TypedDict):
"""Type for login data."""
domain: str
access_key: str
password: str
@@ -29,13 +30,14 @@ class LoginData(TypedDict):
class LoginRequestModel(BaseRequestModel[LoginData]):
"""Request model for login endpoint."""
model_config = ConfigDict(
json_schema_extra={
"example": {
"domain": "example.com",
"access_key": "user@example",
"password": "password",
"remember_me": False
"remember_me": False,
}
}
)
@@ -43,96 +45,90 @@ class LoginRequestModel(BaseRequestModel[LoginData]):
class LogoutData(TypedDict):
"""Type for logout data."""
token: str
class LogoutRequestModel(BaseRequestModel[LogoutData]):
"""Request model for logout endpoint."""
model_config = ConfigDict(
json_schema_extra={
"example": {
"token": "your-token-here"
}
}
json_schema_extra={"example": {"token": "your-token-here"}}
)
class RememberData(TypedDict):
"""Type for remember token data."""
remember_token: str
class RememberRequestModel(BaseRequestModel[RememberData]):
"""Request model for remember token endpoint."""
model_config = ConfigDict(
json_schema_extra={
"example": {
"remember_token": "your-remember-token-here"
}
}
json_schema_extra={"example": {"remember_token": "your-remember-token-here"}}
)
class ForgotData(TypedDict):
"""Type for forgot password data."""
email: str
domain: str
class ForgotRequestModel(BaseRequestModel[ForgotData]):
"""Request model for forgot password endpoint."""
model_config = ConfigDict(
json_schema_extra={
"example": {
"email": "user@example.com",
"domain": "example.com"
}
"example": {"email": "user@example.com", "domain": "example.com"}
}
)
class ChangePasswordData(TypedDict):
"""Type for change password data."""
old_password: str
new_password: str
class ChangePasswordRequestModel(BaseRequestModel[ChangePasswordData]):
"""Request model for change password endpoint."""
model_config = ConfigDict(
json_schema_extra={
"example": {
"old_password": "old-pass",
"new_password": "new-pass"
}
"example": {"old_password": "old-pass", "new_password": "new-pass"}
}
)
class CreatePasswordData(TypedDict):
"""Type for create password data."""
token: str
password: str
class CreatePasswordRequestModel(BaseRequestModel[CreatePasswordData]):
"""Request model for create password endpoint."""
model_config = ConfigDict(
json_schema_extra={
"example": {
"token": "password-creation-token",
"password": "new-password"
}
"example": {"token": "password-creation-token", "password": "new-password"}
}
)
class SelectionDataOccupant(BaseModel):
"""Type for selection data."""
build_living_space_uu_id: Optional[str]
class SelectionDataEmployee(BaseModel):
"""Type for selection data."""
company_uu_id: Optional[str]
company_uu_id: Optional[str]

View File

@@ -3,7 +3,11 @@ Account records endpoint configurations.
"""
from ApiEvents.abstract_class import RouteFactoryConfig, EndpointFactoryConfig, endpoint_wrapper
from ApiEvents.abstract_class import (
RouteFactoryConfig,
EndpointFactoryConfig,
endpoint_wrapper,
)
from ApiEvents.base_request_model import EndpointBaseRequestModel
from Services.PostgresDb.Models.alchemy_response import DictJsonResponse
@@ -37,7 +41,7 @@ async def address_create(request: "Request", data: EndpointBaseRequestModel):
async def address_search(request: "Request", data: EndpointBaseRequestModel):
"""Handle address search endpoint."""
auth_dict = address_search.auth
code_dict = getattr(address_search, 'func_code', {"function_code": None})
code_dict = getattr(address_search, "func_code", {"function_code": None})
return {"auth_dict": auth_dict, "code_dict": code_dict, "data": data}
@@ -69,6 +73,7 @@ async def address_update(
}
)
prefix = "/account/records"
# Account Records Router Configuration

View File

@@ -16,12 +16,13 @@ if TYPE_CHECKING:
class AddressUpdateRequest(RootModel[Dict[str, Any]]):
"""Request model for address update."""
model_config = {
"json_schema_extra": {
"example": {
"street": "123 Main St",
"city": "Example City",
"country": "Example Country"
"country": "Example Country",
}
}
}
@@ -29,6 +30,7 @@ class AddressUpdateRequest(RootModel[Dict[str, Any]]):
class AddressUpdateResponse(BaseModel):
"""Response model for address update."""
address_uu_id: str = Field(..., description="UUID of the updated address")
data: Dict[str, Any] = Field(..., description="Updated address data")
function_code: str = Field(..., description="Function code for the endpoint")
@@ -36,14 +38,17 @@ class AddressUpdateResponse(BaseModel):
class InsertAccountRecordRequestModel(BaseRequestModel["InsertAccountRecord"]):
"""Request model for inserting account records."""
pass
class UpdateAccountRecordRequestModel(BaseRequestModel["UpdateAccountRecord"]):
"""Request model for updating account records."""
pass
class ListOptionsRequestModel(BaseRequestModel["ListOptions"]):
"""Request model for list options."""
pass

View File

@@ -49,7 +49,7 @@ def endpoint_wrapper(url_of_endpoint: Optional[str] = None):
# If result is a coroutine, await it
if inspect.iscoroutine(result):
result = await result
print('result', result)
# Add endpoint to the result
if isinstance(result, dict):
result["endpoint"] = url_of_endpoint
@@ -110,11 +110,13 @@ class EndpointFactoryConfig:
# First apply auth/event middleware
if self.is_event_required:
from middleware import TokenEventMiddleware
self.endpoint_function = TokenEventMiddleware.event_required(
self.endpoint_function
)
elif self.is_auth_required:
from middleware import MiddlewareModule
self.endpoint_function = MiddlewareModule.auth_required(
self.endpoint_function
)

View File

@@ -15,6 +15,7 @@ T = TypeVar("T")
class EndpointBaseRequestModel(BaseModel):
data: dict = Field(..., description="Data to be sent with the request")
class Config:
json_schema_extra = {
"data": {
@@ -25,13 +26,17 @@ class EndpointBaseRequestModel(BaseModel):
class BaseRequestModel(RootModel[T], Generic[T]):
"""Base model for all API requests."""
model_config = ConfigDict(
json_schema_extra={"example": {"base": "example"}} # Will be populated by subclasses
json_schema_extra={
"example": {"base": "example"}
} # Will be populated by subclasses
)
class DictRequestModel(RootModel[Dict[str, Any]]):
"""Request model for endpoints that accept dictionary data."""
model_config = ConfigDict(
json_schema_extra={
"example": {
@@ -45,6 +50,7 @@ class DictRequestModel(RootModel[Dict[str, Any]]):
class SuccessResponse(BaseModel):
"""Standard success response model."""
token: str = Field(..., example="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...")
user_info: Dict[str, Any] = Field(
...,