redis implemntations and api setup completed
This commit is contained in:
@@ -2,8 +2,8 @@
|
||||
Authentication package initialization.
|
||||
"""
|
||||
|
||||
from .auth import AUTH_CONFIG
|
||||
from .auth.cluster import AuthCluster
|
||||
|
||||
__all__ = [
|
||||
"AUTH_CONFIG",
|
||||
"AuthCluster",
|
||||
]
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
from uuid import UUID
|
||||
from Events.Engine.abstract_class import Event
|
||||
|
||||
from .models import (
|
||||
@@ -14,8 +13,6 @@ from .models import (
|
||||
from .function_handlers import (
|
||||
authentication_login_with_domain_and_creds,
|
||||
authentication_select_company_or_occupant_type,
|
||||
handle_employee_selection,
|
||||
handle_occupant_selection,
|
||||
authentication_check_token_is_valid,
|
||||
authentication_refresh_user_info,
|
||||
authentication_change_password,
|
||||
@@ -31,124 +28,126 @@ from .function_handlers import (
|
||||
|
||||
# Auth Login
|
||||
authentication_login_super_user_event = Event(
|
||||
key=UUID("a5d2d0d1-3e9b-4b0f-8c7d-6d4a4b4c4d4e"),
|
||||
name="authentication_login_super_user_event",
|
||||
key="a5d2d0d1-3e9b-4b0f-8c7d-6d4a4b4c4d4e",
|
||||
request_validator=LoginSuperUserRequestModel,
|
||||
response_validator=LoginSuperUserResponseModel,
|
||||
# response_validator=LoginSuperUserResponseModel,
|
||||
description="Login super user",
|
||||
)
|
||||
authentication_login_super_user_event.endpoint_callable = authentication_login_with_domain_and_creds
|
||||
authentication_login_super_user_event.endpoint_callable = (
|
||||
authentication_login_with_domain_and_creds
|
||||
)
|
||||
|
||||
# Auth Select Company or Occupant Type
|
||||
authentication_select_company_or_occupant_type_super_user_event = Event(
|
||||
key=UUID("a5d2d0d1-3e9b-4b0f-8c7d-6d4a4b4c4d4e"),
|
||||
name="authentication_select_company_or_occupant_type_super_user_event",
|
||||
key="a5d2d0d1-3e9b-4b0f-8c7d-6d4a4b4c4d4e",
|
||||
request_validator=SelectCompanyOrOccupantTypeSuperUserRequestModel,
|
||||
response_validator=SelectCompanyOrOccupantTypeSuperUserResponseModel,
|
||||
# response_validator=SelectCompanyOrOccupantTypeSuperUserResponseModel,
|
||||
description="Select company or occupant type super user",
|
||||
)
|
||||
authentication_select_company_or_occupant_type_super_user_event.endpoint_callable = authentication_select_company_or_occupant_type
|
||||
|
||||
authentication_employee_selection_super_user_event = Event(
|
||||
key=UUID("a5d2d0d1-3e9b-4b0f-8c7d-6d4a4b4c4d4e"),
|
||||
request_validator=EmployeeSelectionSuperUserRequestModel,
|
||||
response_validator=EmployeeSelectionSuperUserResponseModel,
|
||||
description="Employee selection super user",
|
||||
authentication_select_company_or_occupant_type_super_user_event.endpoint_callable = (
|
||||
authentication_select_company_or_occupant_type
|
||||
)
|
||||
authentication_employee_selection_super_user_event.endpoint_callable = handle_employee_selection
|
||||
|
||||
authentication_occupant_selection_super_user_event = Event(
|
||||
key=UUID("a5d2d0d1-3e9b-4b0f-8c7d-6d4a4b4c4d4e"),
|
||||
request_validator=OccupantSelectionSuperUserRequestModel,
|
||||
response_validator=OccupantSelectionSuperUserResponseModel,
|
||||
description="Occupant selection super user",
|
||||
)
|
||||
authentication_occupant_selection_super_user_event.endpoint_callable = handle_occupant_selection
|
||||
|
||||
# Check Token Validity
|
||||
authentication_check_token_event = Event(
|
||||
key=UUID("b6e3d1e2-4f9c-5c1g-9d8e-7e5f6f5e5d5f"),
|
||||
name="authentication_check_token_event",
|
||||
key="b6e3d1e2-4f9c-5c1g-9d8e-7e5f6f5e5d5f",
|
||||
request_validator=None, # TODO: Add request validator
|
||||
response_validator=None, # TODO: Add response validator
|
||||
# response_validator=None, # TODO: Add response validator
|
||||
description="Check if token is valid",
|
||||
)
|
||||
authentication_check_token_event.endpoint_callable = authentication_check_token_is_valid
|
||||
|
||||
# Refresh User Info
|
||||
authentication_refresh_user_info_event = Event(
|
||||
key=UUID("c7f4e2f3-5g0d-6d2h-0e9f-8f6g7g6f6e6g"),
|
||||
name="authentication_refresh_user_info_event",
|
||||
key="c7f4e2f3-5g0d-6d2h-0e9f-8f6g7g6f6e6g",
|
||||
request_validator=None, # TODO: Add request validator
|
||||
response_validator=None, # TODO: Add response validator
|
||||
# response_validator=None, # TODO: Add response validator
|
||||
description="Refresh user information",
|
||||
)
|
||||
authentication_refresh_user_info_event.endpoint_callable = authentication_refresh_user_info
|
||||
authentication_refresh_user_info_event.endpoint_callable = (
|
||||
authentication_refresh_user_info
|
||||
)
|
||||
|
||||
# Change Password
|
||||
authentication_change_password_event = Event(
|
||||
key=UUID("d8g5f3g4-6h1e-7e3i-1f0g-9g7h8h7g7f7h"),
|
||||
name="authentication_change_password_event",
|
||||
key="d8g5f3g4-6h1e-7e3i-1f0g-9g7h8h7g7f7h",
|
||||
request_validator=None, # TODO: Add request validator
|
||||
response_validator=None, # TODO: Add response validator
|
||||
# response_validator=None, # TODO: Add response validator
|
||||
description="Change user password",
|
||||
)
|
||||
authentication_change_password_event.endpoint_callable = authentication_change_password
|
||||
|
||||
# Create Password
|
||||
authentication_create_password_event = Event(
|
||||
key=UUID("e9h6g4h5-7i2f-8f4j-2g1h-0h8i9i8h8g8i"),
|
||||
name="authentication_create_password_event",
|
||||
key="e9h6g4h5-7i2f-8f4j-2g1h-0h8i9i8h8g8i",
|
||||
request_validator=None, # TODO: Add request validator
|
||||
response_validator=None, # TODO: Add response validator
|
||||
# response_validator=None, # TODO: Add response validator
|
||||
description="Create new password",
|
||||
)
|
||||
authentication_create_password_event.endpoint_callable = authentication_create_password
|
||||
|
||||
# Disconnect User
|
||||
authentication_disconnect_user_event = Event(
|
||||
key=UUID("f0i7h5i6-8j3g-9g5k-3h2i-1i9j0j9i9h9j"),
|
||||
name="authentication_disconnect_user_event",
|
||||
key="f0i7h5i6-8j3g-9g5k-3h2i-1i9j0j9i9h9j",
|
||||
request_validator=None, # TODO: Add request validator
|
||||
response_validator=None, # TODO: Add response validator
|
||||
# response_validator=None, # TODO: Add response validator
|
||||
description="Disconnect all user sessions",
|
||||
)
|
||||
authentication_disconnect_user_event.endpoint_callable = authentication_disconnect_user
|
||||
|
||||
# Logout User
|
||||
authentication_logout_user_event = Event(
|
||||
key=UUID("g1j8i6j7-9k4h-0h6l-4i3j-2j0k1k0j0i0k"),
|
||||
name="authentication_logout_user_event",
|
||||
key="g1j8i6j7-9k4h-0h6l-4i3j-2j0k1k0j0i0k",
|
||||
request_validator=None, # TODO: Add request validator
|
||||
response_validator=None, # TODO: Add response validator
|
||||
# response_validator=None, # TODO: Add response validator
|
||||
description="Logout user session",
|
||||
)
|
||||
authentication_logout_user_event.endpoint_callable = authentication_logout_user
|
||||
|
||||
# Refresh Token
|
||||
authentication_refresher_token_event = Event(
|
||||
key=UUID("h2k9j7k8-0l5i-1i7m-5j4k-3k1l2l1k1j1l"),
|
||||
name="authentication_refresher_token_event",
|
||||
key="h2k9j7k8-0l5i-1i7m-5j4k-3k1l2l1k1j1l",
|
||||
request_validator=None, # TODO: Add request validator
|
||||
response_validator=None, # TODO: Add response validator
|
||||
# response_validator=None, # TODO: Add response validator
|
||||
description="Refresh authentication token",
|
||||
)
|
||||
authentication_refresher_token_event.endpoint_callable = authentication_refresher_token
|
||||
|
||||
# Forgot Password
|
||||
authentication_forgot_password_event = Event(
|
||||
key=UUID("i3l0k8l9-1m6j-2j8n-6k5l-4l2m3m2l2k2m"),
|
||||
name="authentication_forgot_password_event",
|
||||
key="i3l0k8l9-1m6j-2j8n-6k5l-4l2m3m2l2k2m",
|
||||
request_validator=None, # TODO: Add request validator
|
||||
response_validator=None, # TODO: Add response validator
|
||||
# response_validator=None, # TODO: Add response validator
|
||||
description="Request password reset",
|
||||
)
|
||||
authentication_forgot_password_event.endpoint_callable = authentication_forgot_password
|
||||
|
||||
# Reset Password
|
||||
authentication_reset_password_event = Event(
|
||||
key=UUID("j4m1l9m0-2n7k-3k9o-7l6m-5m3n4n3m3l3n"),
|
||||
name="authentication_reset_password_event",
|
||||
key="j4m1l9m0-2n7k-3k9o-7l6m-5m3n4n3m3l3n",
|
||||
request_validator=None, # TODO: Add request validator
|
||||
response_validator=None, # TODO: Add response validator
|
||||
# response_validator=None, # TODO: Add response validator
|
||||
description="Reset user password",
|
||||
)
|
||||
authentication_reset_password_event.endpoint_callable = authentication_reset_password
|
||||
|
||||
# Download Avatar
|
||||
authentication_download_avatar_event = Event(
|
||||
key=UUID("k5n2m0n1-3o8l-4l0p-8m7n-6n4o5o4n4m4o"),
|
||||
name="authentication_download_avatar_event",
|
||||
key="k5n2m0n1-3o8l-4l0p-8m7n-6n4o5o4n4m4o",
|
||||
request_validator=None, # TODO: Add request validator
|
||||
response_validator=None, # TODO: Add response validator
|
||||
# response_validator=None, # TODO: Add response validator
|
||||
description="Download user avatar and profile info",
|
||||
)
|
||||
authentication_download_avatar_event.endpoint_callable = authentication_download_avatar
|
||||
|
||||
@@ -2,19 +2,17 @@
|
||||
Authentication related API endpoints.
|
||||
"""
|
||||
|
||||
from typing import Union
|
||||
from typing import Union, Any, Dict
|
||||
|
||||
from ApiLayers.Middleware import MiddlewareModule, TokenEventMiddleware
|
||||
from ApiLayers.ApiValidations.Request import EmployeeSelection, OccupantSelection
|
||||
|
||||
from Events.Engine.abstract_class import MethodToEvent
|
||||
from Events.base_request_model import SuccessResponse
|
||||
|
||||
from ApiLayers.ApiLibrary.common.line_number import get_line_number_for_error
|
||||
from ApiLayers.ApiServices.Token.token_handler import OccupantTokenObject, EmployeeTokenObject
|
||||
from Events.base_request_model import EndpointBaseRequestModel
|
||||
|
||||
from .api_events import (
|
||||
authentication_login_super_user_event,
|
||||
authentication_select_company_or_occupant_type_super_user_event,
|
||||
authentication_employee_selection_super_user_event,
|
||||
authentication_occupant_selection_super_user_event,
|
||||
authentication_check_token_event,
|
||||
authentication_refresh_user_info_event,
|
||||
authentication_change_password_event,
|
||||
@@ -27,13 +25,18 @@ from .api_events import (
|
||||
authentication_download_avatar_event,
|
||||
)
|
||||
|
||||
from fastapi import Request
|
||||
|
||||
|
||||
# Type aliases for common types
|
||||
TokenDictType = Union["EmployeeTokenObject", "OccupantTokenObject"]
|
||||
|
||||
|
||||
AuthenticationLoginEventMethods = MethodToEvent(
|
||||
events=[authentication_login_super_user_event],
|
||||
name="AuthenticationLoginEventMethods",
|
||||
events={
|
||||
authentication_login_super_user_event.key: authentication_login_super_user_event,
|
||||
},
|
||||
headers=[],
|
||||
errors=[],
|
||||
url="/authentication/login",
|
||||
@@ -42,13 +45,24 @@ AuthenticationLoginEventMethods = MethodToEvent(
|
||||
description="Login to the system via domain, access key : [email] | [phone]",
|
||||
)
|
||||
|
||||
def authentication_login_with_domain_and_creds(
|
||||
request: Request,
|
||||
data: EndpointBaseRequestModel,
|
||||
) -> Dict[str, Any]:
|
||||
function = AuthenticationLoginEventMethods.retrieve_event(
|
||||
event_function_code=f"{authentication_login_super_user_event.key}"
|
||||
)
|
||||
return function.endpoint_callable(request=request, data=data)
|
||||
|
||||
|
||||
AuthenticationLoginEventMethods.endpoint_callable = authentication_login_with_domain_and_creds
|
||||
|
||||
AuthenticationSelectEventMethods = MethodToEvent(
|
||||
events=[
|
||||
authentication_select_company_or_occupant_type_super_user_event,
|
||||
authentication_employee_selection_super_user_event,
|
||||
authentication_occupant_selection_super_user_event
|
||||
],
|
||||
name="AuthenticationSelectEventMethods",
|
||||
events={
|
||||
authentication_select_company_or_occupant_type_super_user_event.key: authentication_select_company_or_occupant_type_super_user_event,
|
||||
},
|
||||
decorators_list=[MiddlewareModule.auth_required],
|
||||
headers=[],
|
||||
errors=[],
|
||||
url="/authentication/select",
|
||||
@@ -57,22 +71,53 @@ AuthenticationSelectEventMethods = MethodToEvent(
|
||||
description="Select company or occupant type",
|
||||
)
|
||||
|
||||
def authentication_select_company_or_occupant_type(
|
||||
request: Request,
|
||||
data: EndpointBaseRequestModel,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Select company or occupant type.
|
||||
"""
|
||||
auth_dict = authentication_select_company_or_occupant_type.auth
|
||||
function = AuthenticationSelectEventMethods.retrieve_event(
|
||||
event_function_code=f"{authentication_select_company_or_occupant_type_super_user_event.key}"
|
||||
)
|
||||
return function.endpoint_callable(request=request, data=data, token_dict=auth_dict)
|
||||
|
||||
|
||||
AuthenticationSelectEventMethods.endpoint_callable = authentication_select_company_or_occupant_type
|
||||
|
||||
AuthenticationCheckTokenEventMethods = MethodToEvent(
|
||||
events=[authentication_check_token_event],
|
||||
name="AuthenticationCheckTokenEventMethods",
|
||||
events={
|
||||
authentication_check_token_event.key: authentication_check_token_event
|
||||
},
|
||||
headers=[],
|
||||
errors=[],
|
||||
decorators_list=[MiddlewareModule.auth_required],
|
||||
url="/authentication/check-token",
|
||||
method="POST",
|
||||
summary="Check if token is valid",
|
||||
description="Check if access token is valid for user",
|
||||
)
|
||||
|
||||
def authentication_check_token_is_valid(request: Request):
|
||||
function = AuthenticationCheckTokenEventMethods.retrieve_event(
|
||||
event_function_code=f"{authentication_check_token_event.key}"
|
||||
)
|
||||
return function.endpoint_callable(request=request)
|
||||
|
||||
|
||||
AuthenticationCheckTokenEventMethods.endpoint_callable = authentication_check_token_is_valid
|
||||
|
||||
AuthenticationRefreshEventMethods = MethodToEvent(
|
||||
events=[authentication_refresh_user_info_event],
|
||||
name="AuthenticationRefreshEventMethods",
|
||||
events={
|
||||
authentication_refresh_user_info_event.key: authentication_refresh_user_info_event
|
||||
},
|
||||
headers=[],
|
||||
errors=[],
|
||||
decorators_list=[MiddlewareModule.auth_required],
|
||||
url="/authentication/refresh",
|
||||
method="POST",
|
||||
summary="Refresh user info",
|
||||
@@ -80,19 +125,45 @@ AuthenticationRefreshEventMethods = MethodToEvent(
|
||||
)
|
||||
|
||||
|
||||
def authentication_refresh_user_info(request: Request):
|
||||
token_dict = authentication_refresh_user_info.auth
|
||||
function = AuthenticationRefreshEventMethods.retrieve_event(
|
||||
event_function_code=f"{authentication_refresh_user_info_event.key}"
|
||||
)
|
||||
return function.endpoint_callable(request=request, token_dict=token_dict)
|
||||
|
||||
|
||||
AuthenticationRefreshEventMethods.endpoint_callable = authentication_refresh_user_info
|
||||
|
||||
AuthenticationChangePasswordEventMethods = MethodToEvent(
|
||||
events=[authentication_change_password_event],
|
||||
name="AuthenticationChangePasswordEventMethods",
|
||||
events={
|
||||
authentication_change_password_event.key: authentication_change_password_event
|
||||
},
|
||||
headers=[],
|
||||
errors=[],
|
||||
decorators_list=[MiddlewareModule.auth_required],
|
||||
url="/authentication/change-password",
|
||||
method="POST",
|
||||
summary="Change password",
|
||||
description="Change password with access token",
|
||||
)
|
||||
|
||||
def authentication_change_password_event_callable(request: Request, data: EndpointBaseRequestModel):
|
||||
token_dict = authentication_change_password_event_callable.auth
|
||||
function = AuthenticationChangePasswordEventMethods.retrieve_event(
|
||||
event_function_code=f"{authentication_change_password_event.key}"
|
||||
)
|
||||
return function.endpoint_callable(data=data, token_dict=token_dict)
|
||||
|
||||
|
||||
AuthenticationChangePasswordEventMethods.endpoint_callable = authentication_change_password_event_callable
|
||||
|
||||
AuthenticationCreatePasswordEventMethods = MethodToEvent(
|
||||
events=[authentication_create_password_event],
|
||||
name="AuthenticationCreatePasswordEventMethods",
|
||||
events={
|
||||
authentication_create_password_event: authentication_create_password_event
|
||||
},
|
||||
headers=[],
|
||||
errors=[],
|
||||
url="/authentication/create-password",
|
||||
@@ -101,9 +172,21 @@ AuthenticationCreatePasswordEventMethods = MethodToEvent(
|
||||
description="Create password with password reset token requested via email",
|
||||
)
|
||||
|
||||
def authentication_create_password(data: EndpointBaseRequestModel):
|
||||
function = AuthenticationCreatePasswordEventMethods.retrieve_event(
|
||||
event_function_code=f"{authentication_create_password_event.key}"
|
||||
)
|
||||
return function.endpoint_callable(data=data)
|
||||
|
||||
|
||||
AuthenticationCreatePasswordEventMethods.endpoint_callable = authentication_create_password
|
||||
|
||||
AuthenticationDisconnectUserEventMethods = MethodToEvent(
|
||||
events=[authentication_disconnect_user_event],
|
||||
name="AuthenticationDisconnectUserEventMethods",
|
||||
events={
|
||||
authentication_disconnect_user_event.key: authentication_disconnect_user_event
|
||||
},
|
||||
decorators_list=[MiddlewareModule.auth_required],
|
||||
headers=[],
|
||||
errors=[],
|
||||
url="/authentication/disconnect",
|
||||
@@ -112,9 +195,19 @@ AuthenticationDisconnectUserEventMethods = MethodToEvent(
|
||||
description="Disconnect all sessions of user in access token",
|
||||
)
|
||||
|
||||
def authentication_disconnect_user(request: Request, data: EndpointBaseRequestModel):
|
||||
token_dict = authentication_disconnect_user.auth
|
||||
function = AuthenticationDisconnectUserEventMethods.retrieve_event(
|
||||
event_function_code=f"{authentication_disconnect_user_event.key}"
|
||||
)
|
||||
return function.endpoint_callable(data=data, token_dict=token_dict)
|
||||
|
||||
|
||||
AuthenticationLogoutEventMethods = MethodToEvent(
|
||||
events=[authentication_logout_user_event],
|
||||
name="AuthenticationLogoutEventMethods",
|
||||
events={
|
||||
authentication_logout_user_event.key: authentication_logout_user_event
|
||||
},
|
||||
headers=[],
|
||||
errors=[],
|
||||
url="/authentication/logout",
|
||||
@@ -123,20 +216,51 @@ AuthenticationLogoutEventMethods = MethodToEvent(
|
||||
description="Logout only single session of user which domain is provided",
|
||||
)
|
||||
|
||||
@TokenEventMiddleware.event_required
|
||||
def authentication_logout_user(request: Request, data: EndpointBaseRequestModel):
|
||||
function = AuthenticationLogoutEventMethods.retrieve_event(
|
||||
event_function_code=f"{authentication_logout_user_event.key}"
|
||||
)
|
||||
print('authentication_logout_user', dict(
|
||||
auth=getattr(authentication_logout_user, "auth", None),
|
||||
func_code=getattr(authentication_logout_user, "func_code", None),
|
||||
))
|
||||
function.endpoint_callable.auth = getattr(authentication_logout_user, "auth", None)
|
||||
function.endpoint_callable.func_code = getattr(authentication_logout_user, "func_code", None)
|
||||
return function.endpoint_callable(request=request, data=data)
|
||||
|
||||
|
||||
AuthenticationLogoutEventMethods.endpoint_callable = authentication_logout_user
|
||||
|
||||
AuthenticationRefreshTokenEventMethods = MethodToEvent(
|
||||
events=[authentication_refresher_token_event],
|
||||
name="AuthenticationRefreshTokenEventMethods",
|
||||
events={
|
||||
authentication_refresher_token_event.key: authentication_refresher_token_event
|
||||
},
|
||||
headers=[],
|
||||
errors=[],
|
||||
decorators_list=[MiddlewareModule.auth_required, ],
|
||||
url="/authentication/refresh-token",
|
||||
method="POST",
|
||||
summary="Refresh token",
|
||||
description="Refresh access token with refresher token",
|
||||
)
|
||||
|
||||
def authentication_refresher_token(request: Request, data: EndpointBaseRequestModel):
|
||||
token_dict = authentication_refresher_token.auth
|
||||
function = AuthenticationRefreshTokenEventMethods.retrieve_event(
|
||||
event_function_code=f"{authentication_refresher_token_event.key}"
|
||||
)
|
||||
return function.endpoint_callable(data=data, request=request, token_dict=token_dict)
|
||||
|
||||
AuthenticationRefreshTokenEventMethods.endpoint_callable = authentication_refresher_token
|
||||
|
||||
|
||||
AuthenticationForgotPasswordEventMethods = MethodToEvent(
|
||||
events=[authentication_forgot_password_event],
|
||||
name="AuthenticationForgotPasswordEventMethods",
|
||||
events={
|
||||
authentication_forgot_password_event.key: authentication_forgot_password_event
|
||||
},
|
||||
headers=[],
|
||||
errors=[],
|
||||
url="/authentication/forgot-password",
|
||||
@@ -146,10 +270,25 @@ AuthenticationForgotPasswordEventMethods = MethodToEvent(
|
||||
)
|
||||
|
||||
|
||||
def authentication_forgot_password(request: Request, data: EndpointBaseRequestModel):
|
||||
token_dict = authentication_forgot_password.auth
|
||||
function = AuthenticationForgotPasswordEventMethods.retrieve_event(
|
||||
event_function_code=f"{authentication_forgot_password_event.key}"
|
||||
)
|
||||
return function.endpoint_callable(data=data, token_dict=token_dict)
|
||||
|
||||
|
||||
AuthenticationForgotPasswordEventMethods.endpoint_callable = authentication_forgot_password
|
||||
|
||||
|
||||
AuthenticationResetPasswordEventMethods = MethodToEvent(
|
||||
events=[authentication_reset_password_event],
|
||||
name="AuthenticationResetPasswordEventMethods",
|
||||
events={
|
||||
authentication_reset_password_event.key: authentication_reset_password_event
|
||||
},
|
||||
headers=[],
|
||||
errors=[],
|
||||
decorators_list=[MiddlewareModule.auth_required],
|
||||
url="/authentication/reset-password",
|
||||
method="POST",
|
||||
summary="Reset password",
|
||||
@@ -157,12 +296,38 @@ AuthenticationResetPasswordEventMethods = MethodToEvent(
|
||||
)
|
||||
|
||||
|
||||
def authentication_reset_password(data: EndpointBaseRequestModel):
|
||||
# token_dict = authentication_reset_password.auth
|
||||
function = AuthenticationResetPasswordEventMethods.retrieve_event(
|
||||
event_function_code=f"{authentication_reset_password_event.key}"
|
||||
)
|
||||
return function.endpoint_callable(data=data)
|
||||
|
||||
|
||||
AuthenticationResetPasswordEventMethods.endpoint_callable = authentication_reset_password
|
||||
|
||||
AuthenticationDownloadAvatarEventMethods = MethodToEvent(
|
||||
events=[authentication_download_avatar_event],
|
||||
name="AuthenticationDownloadAvatarEventMethods",
|
||||
events={
|
||||
authentication_download_avatar_event.key: authentication_download_avatar_event
|
||||
},
|
||||
headers=[],
|
||||
errors=[],
|
||||
decorators_list=[],
|
||||
url="/authentication/download-avatar",
|
||||
method="POST",
|
||||
summary="Download avatar",
|
||||
description="Download avatar icon and profile info of user",
|
||||
)
|
||||
|
||||
|
||||
@MiddlewareModule.auth_required
|
||||
def authentication_download_avatar(request: Request):
|
||||
token_dict = authentication_download_avatar.auth
|
||||
function = AuthenticationDownloadAvatarEventMethods.retrieve_event(
|
||||
event_function_code=f"{authentication_download_avatar_event.key}"
|
||||
)
|
||||
return function.endpoint_callable(token_dict=token_dict)
|
||||
|
||||
|
||||
AuthenticationDownloadAvatarEventMethods.endpoint_callable = authentication_download_avatar
|
||||
|
||||
@@ -18,6 +18,7 @@ from .auth import (
|
||||
|
||||
|
||||
AuthCluster = CategoryCluster(
|
||||
name="AuthCluster",
|
||||
tags=["authentication"],
|
||||
prefix="/authentication",
|
||||
description="Authentication cluster",
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
from typing import Any, TYPE_CHECKING, Union
|
||||
|
||||
from Events.base_request_model import TokenDictType
|
||||
from Events.Engine.abstract_class import MethodToEvent
|
||||
from Events.base_request_model import SuccessResponse
|
||||
from typing import Any, TYPE_CHECKING, Union, Dict
|
||||
|
||||
from ApiLayers.ApiLibrary.common.line_number import get_line_number_for_error
|
||||
from ApiLayers.ApiLibrary.date_time_actions.date_functions import DateTimeLocal
|
||||
from ApiLayers.ApiServices.middleware.auth_middleware import AuthMiddlewareModule
|
||||
|
||||
from ApiLayers.ApiServices.Login.user_login_handler import UserLoginModule
|
||||
from ApiLayers.ApiServices.Token.token_handler import TokenService
|
||||
@@ -17,20 +11,17 @@ from ApiLayers.Schemas import (
|
||||
BuildParts,
|
||||
RelationshipEmployee2Build,
|
||||
Companies,
|
||||
Departments,
|
||||
Duties,
|
||||
Departments,
|
||||
Duties,
|
||||
Duty,
|
||||
Staff,
|
||||
Employees,
|
||||
Event2Employee,
|
||||
Event2Occupant,
|
||||
OccupantTypes,
|
||||
Users
|
||||
Users,
|
||||
)
|
||||
from ApiLayers.ApiServices.Token.token_handler import OccupantTokenObject, EmployeeTokenObject
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from fastapi import Request
|
||||
from fastapi import Request
|
||||
|
||||
|
||||
# Type aliases for common types
|
||||
@@ -70,7 +61,7 @@ def authentication_login_with_domain_and_creds(request: Request, data: Any):
|
||||
"user": token.get("user"),
|
||||
}
|
||||
|
||||
@AuthMiddlewareModule.auth_required
|
||||
|
||||
def handle_employee_selection(request: Request, data: Any, token_dict: TokenDictType):
|
||||
Users.set_user_define_properties(token=token_dict)
|
||||
db_session = Users.new_session()
|
||||
@@ -185,7 +176,6 @@ def handle_employee_selection(request: Request, data: Any, token_dict: TokenDict
|
||||
)
|
||||
|
||||
|
||||
@AuthMiddlewareModule.auth_required
|
||||
def handle_occupant_selection(request: Request, data: Any, token_dict: TokenDictType):
|
||||
"""Handle occupant type selection"""
|
||||
db = BuildLivingSpace.new_session()
|
||||
@@ -270,17 +260,20 @@ def handle_occupant_selection(request: Request, data: Any, token_dict: TokenDict
|
||||
)
|
||||
|
||||
|
||||
@AuthMiddlewareModule.auth_required
|
||||
def authentication_select_company_or_occupant_type(request: Request, data: Any, token_dict: TokenDictType):
|
||||
"""Handle selection of company or occupant type"""
|
||||
if token_dict.is_employee:
|
||||
return cls._handle_employee_selection(data, token_dict, request)
|
||||
if handle_employee_selection(data, token_dict, request):
|
||||
return {"selected_occupant": None, "selected_company": data.company_uu_id}
|
||||
elif token_dict.is_occupant:
|
||||
return cls._handle_occupant_selection(data, token_dict, request)
|
||||
if handle_occupant_selection(data, token_dict, request):
|
||||
return {
|
||||
"selected_company": None, "selected_occupant": data.build_living_space_uu_id,
|
||||
}
|
||||
return {"completed": False, "selected_company": None, "selected_occupant": None}
|
||||
|
||||
|
||||
@AuthMiddlewareModule.auth_required
|
||||
def authentication_check_token_is_valid(request: "Request", data: Any):
|
||||
def authentication_check_token_is_valid(request: Request, data: Any):
|
||||
"""Check if token is valid for user"""
|
||||
# try:
|
||||
# if RedisActions.get_object_via_access_key(request=request):
|
||||
@@ -290,8 +283,7 @@ def authentication_check_token_is_valid(request: "Request", data: Any):
|
||||
return
|
||||
|
||||
|
||||
@AuthMiddlewareModule.auth_required
|
||||
def authentication_refresh_user_info(request: "Request", token_dict: TokenDictType, data: Any):
|
||||
def authentication_refresh_user_info(request: Request, token_dict: TokenDictType, data: Any):
|
||||
"""Refresh user info using access token"""
|
||||
# try:
|
||||
# access_token = request.headers.get(Auth.ACCESS_TOKEN_TAG)
|
||||
@@ -320,8 +312,7 @@ def authentication_refresh_user_info(request: "Request", token_dict: TokenDictTy
|
||||
return
|
||||
|
||||
|
||||
@AuthMiddlewareModule.auth_required
|
||||
def authentication_change_password(request: "Request", token_dict: TokenDictType, data: Any):
|
||||
def authentication_change_password(request: Request, token_dict: TokenDictType, data: Any):
|
||||
"""Change password with access token"""
|
||||
# try:
|
||||
# if not isinstance(token_dict, EmployeeTokenObject):
|
||||
@@ -341,7 +332,7 @@ def authentication_change_password(request: "Request", token_dict: TokenDictType
|
||||
return
|
||||
|
||||
|
||||
def authentication_create_password(request: "Request", data: Any):
|
||||
def authentication_create_password(request: Request, data: Any):
|
||||
"""Create password with password reset token requested via email"""
|
||||
# if not data.re_password == data.password:
|
||||
# raise HTTPException(status_code=status.HTTP_406_NOT_ACCEPTABLE, detail="Password must match")
|
||||
@@ -354,8 +345,7 @@ def authentication_create_password(request: "Request", data: Any):
|
||||
return
|
||||
|
||||
|
||||
@AuthMiddlewareModule.auth_required
|
||||
def authentication_disconnect_user(request: "Request", token_dict: TokenDictType, data: Any):
|
||||
def authentication_disconnect_user(request: Request, token_dict: TokenDictType, data: Any):
|
||||
"""Disconnect all sessions of user in access token"""
|
||||
# found_user = Users.filter_one(Users.uu_id == token_dict.user_uu_id).data
|
||||
# if not found_user:
|
||||
@@ -370,7 +360,7 @@ def authentication_disconnect_user(request: "Request", token_dict: TokenDictType
|
||||
return
|
||||
|
||||
|
||||
def authentication_logout_user(request: "Request", data: Any, token_dict: TokenDictType):
|
||||
def authentication_logout_user(request: Request, data: Any):
|
||||
"""Logout only single session of user which domain is provided"""
|
||||
# token_user = None
|
||||
# if already_tokens := RedisActions.get_object_via_access_key(request=request):
|
||||
@@ -382,11 +372,14 @@ def authentication_logout_user(request: "Request", data: Any, token_dict: TokenD
|
||||
# selected_user.remove_refresher_token(domain=data.domain)
|
||||
# return ResponseHandler.success("Session is logged out", data=token_user)
|
||||
# return ResponseHandler.not_found("Logout is not successfully completed")
|
||||
token_dict = authentication_logout_user.auth
|
||||
print('token_dict', token_dict)
|
||||
func_code = authentication_logout_user.func_code
|
||||
print('func_code', func_code)
|
||||
return
|
||||
|
||||
|
||||
@AuthMiddlewareModule.auth_required
|
||||
def authentication_refresher_token(request: "Request", token_dict: TokenDictType, data: Any):
|
||||
def authentication_refresher_token(request: Request, token_dict: TokenDictType, data: Any):
|
||||
"""Refresh access token with refresher token"""
|
||||
# token_refresher = UsersTokens.filter_by_one(
|
||||
# token=data.refresh_token,
|
||||
@@ -412,7 +405,7 @@ def authentication_refresher_token(request: "Request", token_dict: TokenDictType
|
||||
return
|
||||
|
||||
|
||||
def authentication_forgot_password(request: "Request", data: Any):
|
||||
def authentication_forgot_password(request: Request, data: Any):
|
||||
"""Send an email to user for a valid password reset token"""
|
||||
# found_user: Users = Users.check_user_exits(access_key=data.access_key, domain=data.domain)
|
||||
# forgot_key = AuthActions.save_access_token_to_redis(request=request, found_user=found_user, domain=data.domain)
|
||||
@@ -431,8 +424,7 @@ def authentication_forgot_password(request: "Request", data: Any):
|
||||
return
|
||||
|
||||
|
||||
@AuthMiddlewareModule.auth_required
|
||||
def authentication_reset_password(request: "Request", data: Any):
|
||||
def authentication_reset_password(request: Request, data: Any):
|
||||
"""Reset password with forgot password token"""
|
||||
# from sqlalchemy import or_
|
||||
# found_user = Users.query.filter(
|
||||
@@ -461,8 +453,7 @@ def authentication_reset_password(request: "Request", data: Any):
|
||||
return
|
||||
|
||||
|
||||
@AuthMiddlewareModule.auth_required
|
||||
def authentication_download_avatar(request: "Request", data: Any, token_dict: TokenDictType):
|
||||
def authentication_download_avatar(request: Request, data: Any, token_dict: TokenDictType):
|
||||
"""Download avatar icon and profile info of user"""
|
||||
# if found_user := Users.filter_one(Users.id == token_dict.user_id).data:
|
||||
# expired_starts = str(system_arrow.now() - system_arrow.get(str(found_user.expiry_ends)))
|
||||
|
||||
@@ -9,5 +9,3 @@ authentication_page_info = PageInfo(
|
||||
parent="",
|
||||
url="",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -31,4 +31,3 @@ class OccupantSelectionSuperUserRequestModel(BaseModel):
|
||||
|
||||
class OccupantSelectionSuperUserResponseModel(BaseModel):
|
||||
pass
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
Events package initialization.
|
||||
"""
|
||||
|
||||
|
||||
__all__ = [
|
||||
]
|
||||
|
||||
6
Events/AllEvents/events_file.py
Normal file
6
Events/AllEvents/events_file.py
Normal file
@@ -0,0 +1,6 @@
|
||||
import Events.AllEvents.authentication as auths_events
|
||||
import Events.AllEvents.events as events_events
|
||||
import Events.AllEvents.validations as validations_events
|
||||
|
||||
|
||||
events_list = (auths_events, events_events, validations_events)
|
||||
@@ -27,6 +27,7 @@ class AllModelsImport:
|
||||
AddressCreateEventMethod,
|
||||
AddressSearchEventMethod,
|
||||
)
|
||||
|
||||
return dict(
|
||||
AccountListEventMethod=AccountListEventMethod,
|
||||
AccountUpdateEventMethod=AccountUpdateEventMethod,
|
||||
@@ -41,7 +42,9 @@ class AllModelsImport:
|
||||
class ValidationsBoth(MethodToEvent):
|
||||
|
||||
@classmethod
|
||||
def retrieve_both_validations_and_headers(cls, event: ValidationsPydantic) -> Dict[str, Any]:
|
||||
def retrieve_both_validations_and_headers(
|
||||
cls, event: ValidationsPydantic
|
||||
) -> Dict[str, Any]:
|
||||
EVENT_MODELS = AllModelsImport.import_all_models()
|
||||
return_single_model = EVENT_MODELS.get(event.class_model, None)
|
||||
# event_class_validation = getattr(return_single_model, "__event_validation__", None)
|
||||
@@ -52,7 +55,9 @@ class ValidationsBoth(MethodToEvent):
|
||||
loc=get_line_number_for_error(),
|
||||
sys_msg="Validation code not found",
|
||||
)
|
||||
response_model = return_single_model.retrieve_event_response_model(event.reachable_event_code)
|
||||
response_model = return_single_model.retrieve_event_response_model(
|
||||
event.reachable_event_code
|
||||
)
|
||||
language_model_all = return_single_model.retrieve_language_parameters(
|
||||
function_code=event.reachable_event_code, language=event.lang
|
||||
)
|
||||
@@ -85,7 +90,9 @@ class ValidationsValidations(MethodToEvent):
|
||||
loc=get_line_number_for_error(),
|
||||
sys_msg="Validation code not found",
|
||||
)
|
||||
response_model = return_single_model.retrieve_event_response_model(event.reachable_event_code)
|
||||
response_model = return_single_model.retrieve_event_response_model(
|
||||
event.reachable_event_code
|
||||
)
|
||||
language_model_all = return_single_model.retrieve_language_parameters(
|
||||
function_code=event.reachable_event_code, language=event.lang
|
||||
)
|
||||
@@ -107,8 +114,7 @@ class ValidationsValidations(MethodToEvent):
|
||||
class ValidationsHeaders(MethodToEvent):
|
||||
|
||||
@classmethod
|
||||
def retrieve_headers(cls, event: ValidationsPydantic
|
||||
) -> Dict[str, Any]:
|
||||
def retrieve_headers(cls, event: ValidationsPydantic) -> Dict[str, Any]:
|
||||
EVENT_MODELS = AllModelsImport.import_all_models()
|
||||
return_single_model = EVENT_MODELS.get(event.class_model, None)
|
||||
# event_class_validation = getattr(return_single_model, "__event_validation__", None)
|
||||
@@ -119,7 +125,9 @@ class ValidationsHeaders(MethodToEvent):
|
||||
loc=get_line_number_for_error(),
|
||||
sys_msg="Validation code not found",
|
||||
)
|
||||
response_model = return_single_model.retrieve_event_response_model(event.reachable_event_code)
|
||||
response_model = return_single_model.retrieve_event_response_model(
|
||||
event.reachable_event_code
|
||||
)
|
||||
language_model_all = return_single_model.retrieve_language_parameters(
|
||||
function_code=event.reachable_event_code, language=event.lang
|
||||
)
|
||||
|
||||
@@ -7,15 +7,16 @@ making common utilities and base classes available for all API services.
|
||||
from .abstract_class import (
|
||||
MethodToEvent,
|
||||
PageInfo,
|
||||
ClusterToMethod,
|
||||
CategoryCluster,
|
||||
Event,
|
||||
)
|
||||
|
||||
# from .base_request_model import BaseRequestModel, DictRequestModel
|
||||
|
||||
# Re-export commonly used classes
|
||||
__all__ = [
|
||||
"MethodToEvent",
|
||||
"PageInfo",
|
||||
"ClusterToMethod",
|
||||
"CategoryCluster",
|
||||
"Event",
|
||||
]
|
||||
|
||||
@@ -1,153 +1,8 @@
|
||||
from typing import Any, ClassVar, Dict, List, Optional
|
||||
from abc import abstractmethod
|
||||
from typing import Any, Dict, List, Optional, Callable
|
||||
from uuid import UUID
|
||||
|
||||
from .pageinfo import PageInfo
|
||||
|
||||
|
||||
class Event:
|
||||
|
||||
KEY_: str # static string uuid.uuid4().__str__()
|
||||
RESPONSE_VALIDATOR: ClassVar["PydanticModel"]
|
||||
REQUEST_VALIDATOR: ClassVar["PydanticModel"]
|
||||
DESCRIPTION: str
|
||||
EXTRA_OPTIONS: Optional[Dict[str, Any]] = None
|
||||
|
||||
def __init__(
|
||||
self, key: UUID, request_validator: "PydanticModel", response_validator: "PydanticModel",
|
||||
description: str, extra_options: Optional[Dict[str, Any]] = None
|
||||
) -> None:
|
||||
self.KEY_ = key
|
||||
self.REQUEST_VALIDATOR = request_validator
|
||||
self.RESPONSE_VALIDATOR = response_validator
|
||||
self.DESCRIPTION = description
|
||||
self.EXTRA_OPTIONS = extra_options
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return f"This is an event of {self.__class__.__name__}. Description: {self.DESCRIPTION}"
|
||||
|
||||
@property
|
||||
def key(self):
|
||||
return str(self.KEY_)
|
||||
|
||||
@abstractmethod
|
||||
def endpoint_callable(request: "Request", data: Any):
|
||||
"""
|
||||
return cls.retrieve_event(event_function_code).retrieve_callable(token_dict, data)
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class MethodToEvent:
|
||||
"""
|
||||
for all endpoint callable
|
||||
def endpoint_callable(request: Request, data: PydanticModel):
|
||||
return cls.retrieve_event(event_function_code).retrieve_callable(token_dict, data)
|
||||
"""
|
||||
EVENTS: list[Event]
|
||||
HEADER_LANGUAGE_MODELS: list[Dict] # [Table.__language_model__ | Dict[__language_model__]]
|
||||
ERRORS_LANGUAGE_MODELS: Optional[list[Dict]] # [Dict[ErrorCode][lang]]
|
||||
|
||||
URL: str
|
||||
METHOD: str
|
||||
SUMMARY: str
|
||||
DESCRIPTION: str
|
||||
EXTRA_OPTIONS: Optional[Dict[str, Any]] = None
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
events: list[Event],
|
||||
headers: list[Dict],
|
||||
url: str,
|
||||
method: str,
|
||||
summary: str,
|
||||
description: str,
|
||||
errors: Optional[list[Dict]] = None,
|
||||
extra_options: Optional[Dict[str, Any]] = None,
|
||||
):
|
||||
self.EVENTS = events
|
||||
self.URL = url
|
||||
self.METHOD = method
|
||||
self.SUMMARY = summary
|
||||
self.DESCRIPTION = description
|
||||
self.HEADER_LANGUAGE_MODELS = headers
|
||||
self.ERRORS_LANGUAGE_MODELS = errors
|
||||
self.EXTRA_OPTIONS = extra_options
|
||||
|
||||
def retrieve_all_event_keys():
|
||||
"""
|
||||
self.EVENTS.iter()
|
||||
[FUNCTION_CODE]
|
||||
"""
|
||||
pass
|
||||
|
||||
def retrieve_event(event_function_code: str):
|
||||
if list_found := [event for event in self.EVENTS if str(event.key) == event_function_code]:
|
||||
return list_found[0]
|
||||
raise ValueError(f"Event with function code {event_function_code} not found")
|
||||
|
||||
def retrieve_redis_value() -> Dict:
|
||||
"""
|
||||
Key(f"METHOD_FUNCTION_CODES:{ClusterToMethod}:MethodEvent:Endpoint") : Value([FUNCTION_CODE, ...])
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class CategoryCluster:
|
||||
|
||||
TAGS: list
|
||||
PREFIX: str
|
||||
PAGEINFO: PageInfo
|
||||
DESCRIPTION: str
|
||||
ENDPOINTS: list = [MethodToEvent]
|
||||
SUBCATEGORY: Optional[List["CategoryCluster"]] = []
|
||||
INCLUDE_IN_SCHEMA: Optional[bool] = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tags: list,
|
||||
prefix: str,
|
||||
description: str,
|
||||
pageinfo: PageInfo,
|
||||
endpoints: list,
|
||||
sub_category: list = [],
|
||||
include_in_schema: Optional[bool] = True,
|
||||
):
|
||||
self.TAGS = tags
|
||||
self.PREFIX = prefix
|
||||
self.PAGEINFO = pageinfo
|
||||
self.DESCRIPTION = description
|
||||
self.ENDPOINTS = endpoints or []
|
||||
self.SUBCATEGORY = sub_category or []
|
||||
self.INCLUDE_IN_SCHEMA = include_in_schema
|
||||
|
||||
|
||||
def retrieve_all_function_codes():
|
||||
"""
|
||||
[FUNCTION_CODE, ...]
|
||||
self.ENDPOINTS -> iter()
|
||||
"""
|
||||
pass
|
||||
|
||||
def retrieve_page_info():
|
||||
"""
|
||||
PAGE_INFO:ClusterToMethod = {
|
||||
"PageInfo": {...}
|
||||
"subCategory": PAGE_INFO:ClusterToMethod
|
||||
}
|
||||
PAGE_INFO:ClusterToMethod = {
|
||||
"PageInfo": {...}
|
||||
"subCategory": PAGE_INFO:ClusterToMethod
|
||||
}
|
||||
"""
|
||||
pass
|
||||
|
||||
def retrieve_redis_value() -> Dict:
|
||||
"""
|
||||
Key(CLUSTER_FUNCTION_CODES:ClusterToMethod) : Value(PAGE_INFO, [FUNCTION_CODE, ...])
|
||||
"""
|
||||
pass
|
||||
from ApiLayers.AllConfigs.Redis.configs import RedisCategoryKeys
|
||||
|
||||
|
||||
class PageInfo:
|
||||
@@ -155,7 +10,7 @@ class PageInfo:
|
||||
NAME: str
|
||||
BUTTON_NAME: str
|
||||
PAGE_URL: str
|
||||
PAGEINFO: "PageInfo"
|
||||
PAGEINFO: Dict[str, Any]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -173,4 +28,195 @@ class PageInfo:
|
||||
self.PARENT = parent
|
||||
|
||||
|
||||
class Event:
|
||||
|
||||
KEY_: str # static string uuid.uuid4().__str__()
|
||||
RESPONSE_VALIDATOR: Optional[Any]
|
||||
REQUEST_VALIDATOR: Optional[Any]
|
||||
DESCRIPTION: str
|
||||
EXTRA_OPTIONS: Optional[Dict[str, Any]] = None
|
||||
endpoint_callable: Any
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
key: str | UUID,
|
||||
description: str,
|
||||
request_validator: Optional[Any] = None,
|
||||
response_validator: Optional[Any] = None,
|
||||
extra_options: Optional[Dict[str, Any]] = None,
|
||||
) -> None:
|
||||
self.NAME = name
|
||||
self.KEY_ = key
|
||||
self.REQUEST_VALIDATOR = request_validator
|
||||
self.RESPONSE_VALIDATOR = response_validator
|
||||
self.DESCRIPTION = description
|
||||
self.EXTRA_OPTIONS = extra_options
|
||||
|
||||
@property
|
||||
def description(self):
|
||||
return f"This is an event of {self.name}. Description: {self.DESCRIPTION}"
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self.NAME
|
||||
|
||||
@property
|
||||
def key(self):
|
||||
return str(self.KEY_)
|
||||
|
||||
@abstractmethod
|
||||
def endpoint_callable(self, **kwargs) -> Any:
|
||||
"""
|
||||
Retrieves the endpoint function based on the event key.
|
||||
"""
|
||||
return self.endpoint_callable(**kwargs)
|
||||
|
||||
|
||||
class MethodToEvent:
|
||||
"""
|
||||
for all endpoint callable
|
||||
def endpoint_callable(request: Request, data: PydanticModel):
|
||||
return cls.retrieve_event(event_function_code).retrieve_callable(token_dict, data)
|
||||
[Table.__language_model__ | Dict[__language_model__]]
|
||||
[Dict[ErrorCode][lang]]
|
||||
|
||||
"""
|
||||
|
||||
EVENTS: dict[str, Event]
|
||||
HEADER_LANGUAGE_MODELS: list[Dict]
|
||||
ERRORS_LANGUAGE_MODELS: Optional[list[Dict]]
|
||||
URL: str
|
||||
METHOD: str
|
||||
SUMMARY: str
|
||||
DESCRIPTION: str
|
||||
DECORATORS_LIST: Optional[Callable] = []
|
||||
EXTRA_OPTIONS: Optional[Dict[str, Any]] = None
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
events: dict[str, Event],
|
||||
headers: list[Dict],
|
||||
url: str,
|
||||
method: str,
|
||||
summary: str,
|
||||
description: str,
|
||||
decorators_list: Optional[List[Callable]] = None,
|
||||
errors: Optional[list[Dict]] = None,
|
||||
extra_options: Optional[Dict[str, Any]] = None,
|
||||
):
|
||||
self.EVENTS = events
|
||||
self.URL = url
|
||||
self.METHOD = method
|
||||
self.SUMMARY = summary
|
||||
self.NAME = name
|
||||
self.DESCRIPTION = description
|
||||
self.DECORATORS_LIST = decorators_list
|
||||
self.HEADER_LANGUAGE_MODELS = headers
|
||||
self.ERRORS_LANGUAGE_MODELS = errors
|
||||
self.EXTRA_OPTIONS = extra_options
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self.NAME
|
||||
|
||||
def retrieve_all_event_keys(self):
|
||||
"""
|
||||
Retrieves all event keys from the events list.
|
||||
"""
|
||||
return [str(event_key) for event_key in self.EVENTS.keys()]
|
||||
|
||||
def retrieve_event(self, event_function_code: str) -> Event:
|
||||
"""
|
||||
Retrieves the event object from the events list based on the event function code.
|
||||
"""
|
||||
if found_event := self.EVENTS.get(event_function_code, None):
|
||||
return found_event
|
||||
raise ValueError(f"Event with function code {event_function_code} not found")
|
||||
|
||||
def retrieve_redis_value(self, cluster_name: str) -> Dict:
|
||||
"""
|
||||
Key("METHOD_FUNCTION_CODES:{ClusterToMethod}:MethodEvent:Endpoint") : Value([FUNCTION_CODE, ...])
|
||||
"""
|
||||
redis_key = f"{RedisCategoryKeys.METHOD_FUNCTION_CODES}:{cluster_name}:{self.name}:{self.URL}"
|
||||
return {redis_key: self.retrieve_all_event_keys()}
|
||||
|
||||
@staticmethod
|
||||
def endpoint_callable(**kwargs):
|
||||
"""
|
||||
return cls.retrieve_event(event_function_code).retrieve_callable(token_dict, data)
|
||||
"""
|
||||
raise NotImplementedError("Endpoint callable method is not implemented")
|
||||
|
||||
|
||||
class CategoryCluster:
|
||||
|
||||
TAGS: list
|
||||
PREFIX: str
|
||||
PAGEINFO: PageInfo
|
||||
DESCRIPTION: str
|
||||
ENDPOINTS: list[MethodToEvent] # [MethodToEvent, ...]
|
||||
SUBCATEGORY: Optional[List["CategoryCluster"]] # [CategoryCluster, ...]
|
||||
INCLUDE_IN_SCHEMA: Optional[bool] = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
tags: list,
|
||||
prefix: str,
|
||||
description: str,
|
||||
pageinfo: PageInfo,
|
||||
endpoints: list[MethodToEvent],
|
||||
sub_category: list,
|
||||
include_in_schema: Optional[bool] = True,
|
||||
):
|
||||
self.NAME = name
|
||||
self.TAGS = tags
|
||||
self.PREFIX = prefix
|
||||
self.PAGEINFO = pageinfo
|
||||
self.DESCRIPTION = description
|
||||
self.ENDPOINTS = endpoints or []
|
||||
self.SUBCATEGORY = sub_category or []
|
||||
self.INCLUDE_IN_SCHEMA = include_in_schema
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self.NAME
|
||||
|
||||
def get_redis_cluster_index_value(self):
|
||||
"""
|
||||
RedisCategoryKeys.CLUSTER_2_METHOD_EVENT
|
||||
Returns the class name and function codes for the class.
|
||||
"""
|
||||
dict_cluster_2_method, list_endpoints = {}, [i.name for i in self.ENDPOINTS]
|
||||
for endpoint_name in list_endpoints:
|
||||
dict_cluster_2_method[endpoint_name] = self.name
|
||||
dict_cluster_2_method[self.name] = list_endpoints
|
||||
return dict_cluster_2_method
|
||||
|
||||
def retrieve_all_function_codes(self):
|
||||
"""
|
||||
Retrieves all function codes by iterating over the events list.
|
||||
"""
|
||||
all_function_codes = []
|
||||
for event_method in self.ENDPOINTS:
|
||||
all_function_codes.extend([str(event_key) for event_key in event_method.EVENTS.keys()])
|
||||
return all_function_codes
|
||||
|
||||
def retrieve_redis_value(self) -> Dict:
|
||||
"""
|
||||
Create Redis Key and Value from function codes
|
||||
Key(CLUSTER_FUNCTION_CODES:ClusterToMethod) : Value(PAGE_INFO, [FUNCTION_CODE, ...])
|
||||
"""
|
||||
return {
|
||||
f"{RedisCategoryKeys.CLUSTER_FUNCTION_CODES}:{self.name}": self.retrieve_all_function_codes()
|
||||
}
|
||||
|
||||
def retrieve_page_info(self):
|
||||
"""
|
||||
PAGE_INFO:ClusterToMethod = {"PageInfo": {...}, "subCategory": PAGE_INFO:ClusterToMethod}
|
||||
"""
|
||||
raise NotImplementedError(
|
||||
"CategoryCluster retrieve_page_info() method is not implemented"
|
||||
)
|
||||
|
||||
42
Events/Engine/set_defaults/category_cluster_models.py
Normal file
42
Events/Engine/set_defaults/category_cluster_models.py
Normal file
@@ -0,0 +1,42 @@
|
||||
from Events.Engine import CategoryCluster
|
||||
|
||||
|
||||
class CategoryBulk:
|
||||
|
||||
def __init__(self, category_cluster: CategoryCluster = None, name: str = ""):
|
||||
self.category_cluster = category_cluster
|
||||
self.name = name
|
||||
|
||||
|
||||
class CategoryClusterController:
|
||||
|
||||
imports_dict: list[CategoryBulk] = []
|
||||
|
||||
@property
|
||||
def imports(self):
|
||||
return self.imports_dict
|
||||
|
||||
@classmethod
|
||||
def import_all_category_clusters(cls, category_clusters):
|
||||
"""
|
||||
Imports all category clusters from the given list
|
||||
{ "category_cluster_name": "category_cluster_module" }
|
||||
"""
|
||||
if not hasattr(category_clusters, "__all__"):
|
||||
raise ValueError(f"Given module {str(category_clusters)} does not have __all__ attribute")
|
||||
for iter_module in [str(item) for item in category_clusters.__all__]:
|
||||
# CategoryCluster which represent api routers for each category
|
||||
cls.imports_dict.append(
|
||||
CategoryBulk(
|
||||
category_cluster=getattr(category_clusters, iter_module, None),
|
||||
name=iter_module
|
||||
))
|
||||
|
||||
@classmethod
|
||||
def as_dict(cls):
|
||||
to_dict = {}
|
||||
for cluster in cls.imports_dict:
|
||||
to_dict[cluster.name] = cluster.category_cluster
|
||||
return to_dict
|
||||
|
||||
cluster_controller = CategoryClusterController()
|
||||
84
Events/Engine/set_defaults/prepare_redis_items.py
Normal file
84
Events/Engine/set_defaults/prepare_redis_items.py
Normal file
@@ -0,0 +1,84 @@
|
||||
from ApiLayers.AllConfigs.Redis.configs import RedisCategoryKeys
|
||||
|
||||
|
||||
class PrepareRedisItems:
|
||||
|
||||
MENU_FIRST_LAYER_KEY: str = RedisCategoryKeys.MENU_FIRST_LAYER
|
||||
MENU_FIRST_LAYER_VALUE: set[str] = set()
|
||||
CLUSTER_INDEX_KEY: str = RedisCategoryKeys.CLUSTER_INDEX
|
||||
CLUSTER_INDEX_VALUE: dict = {}
|
||||
CLUSTER_FUNCTION_CODES_KEY: str = RedisCategoryKeys.CLUSTER_FUNCTION_CODES
|
||||
CLUSTER_FUNCTION_CODES_VALUE: dict = {}
|
||||
METHOD_FUNCTION_CODES_KEY: str = RedisCategoryKeys.METHOD_FUNCTION_CODES
|
||||
METHOD_FUNCTION_CODES_VALUE: dict = {}
|
||||
ENDPOINT2CLASS_KEY: str = RedisCategoryKeys.ENDPOINT2CLASS
|
||||
ENDPOINT2CLASS_VALUE: dict = {}
|
||||
|
||||
@property
|
||||
def as_dict(self):
|
||||
return {
|
||||
self.MENU_FIRST_LAYER_KEY: list(self.MENU_FIRST_LAYER_VALUE),
|
||||
self.CLUSTER_INDEX_KEY: self.CLUSTER_INDEX_VALUE,
|
||||
self.CLUSTER_FUNCTION_CODES_KEY: self.CLUSTER_FUNCTION_CODES_VALUE,
|
||||
self.METHOD_FUNCTION_CODES_KEY: self.METHOD_FUNCTION_CODES_VALUE,
|
||||
self.ENDPOINT2CLASS_KEY: self.ENDPOINT2CLASS_VALUE,
|
||||
}
|
||||
|
||||
|
||||
class DecoratorModule:
|
||||
|
||||
@staticmethod
|
||||
def get_all_decorators(func):
|
||||
"""
|
||||
Get all decorators of a function, excluding the original function itself.
|
||||
Returns a list of decorator functions in the order they were applied.
|
||||
"""
|
||||
decorators = []
|
||||
current_func = func
|
||||
original_qualname = getattr(func, '__qualname__', '')
|
||||
|
||||
while hasattr(current_func, '__wrapped__'):
|
||||
if hasattr(current_func, '__closure__') and current_func.__closure__:
|
||||
for cell in current_func.__closure__:
|
||||
decorator = cell.cell_contents
|
||||
# Only add if it's a callable and not the original function
|
||||
if callable(decorator) and getattr(decorator, '__qualname__', '') != original_qualname:
|
||||
decorators.append(decorator)
|
||||
current_func = current_func.__wrapped__
|
||||
return list(dict.fromkeys(decorators)) # Remove duplicates while preserving order
|
||||
|
||||
@staticmethod
|
||||
def get_actual_decorators(method_endpoint):
|
||||
original_qualname = getattr(method_endpoint.endpoint_callable, '__qualname__', '')
|
||||
actual_decorators = [
|
||||
d for d in method_endpoint.DECORATORS_LIST or []
|
||||
if callable(d) and getattr(d, '__qualname__', '') != original_qualname
|
||||
]
|
||||
return actual_decorators
|
||||
|
||||
@classmethod
|
||||
def apply_decorators(cls, method_endpoint):
|
||||
# Get the original function and its qualname
|
||||
function_callable = method_endpoint.endpoint_callable
|
||||
# Filter out the original function and apply decorators
|
||||
actual_decorators = cls.get_actual_decorators(method_endpoint)
|
||||
|
||||
# Apply decorators in reverse order (to match @ syntax behavior)
|
||||
for decorator in reversed(actual_decorators):
|
||||
try:
|
||||
function_callable = decorator(function_callable)
|
||||
except Exception as e:
|
||||
print(f"Warning: Failed to apply decorator {decorator.__qualname__}: {str(e)}")
|
||||
|
||||
method_endpoint.endpoint_callable = function_callable
|
||||
|
||||
# Get the final list of applied decorators (for debugging)
|
||||
applied_decorators = cls.get_all_decorators(method_endpoint.endpoint_callable)
|
||||
applied_decorators_qualname = [getattr(d, '__qualname__', str(d)) for d in applied_decorators]
|
||||
if applied_decorators:
|
||||
print(f"Applied decorators for {method_endpoint.name}:", applied_decorators_qualname)
|
||||
return applied_decorators_qualname
|
||||
|
||||
@classmethod
|
||||
def list_qualname(cls, method_endpoint_list):
|
||||
return [getattr(method_endpoint, '__qualname__', '') for method_endpoint in method_endpoint_list]
|
||||
@@ -1,2 +1,16 @@
|
||||
from Events.AllEvents.events_file import events_list
|
||||
from .category_cluster_models import cluster_controller
|
||||
|
||||
|
||||
def get_cluster_controller_group():
|
||||
for cluster in events_list:
|
||||
cluster_controller.import_all_category_clusters(cluster)
|
||||
return cluster_controller
|
||||
|
||||
"""
|
||||
prepare_routing = PrepareRouting(cluster_controller_group=cluster_controller)
|
||||
prepare_events = PrepareEvents(cluster_controller_group=cluster_controller)
|
||||
set_items_2_redis = SetItems2Redis(prepare_events=prepare_events)
|
||||
print(set_items_2_redis)
|
||||
print(prepare_routing)
|
||||
"""
|
||||
|
||||
@@ -1,7 +1,171 @@
|
||||
import AllEvents.auth as auths_events
|
||||
import AllEvents.events as events_events
|
||||
import AllEvents.validations as validations_events
|
||||
from typing import Any
|
||||
|
||||
from ApiLayers.ApiServices.Cluster.create_router import (
|
||||
CreateRouterFromCluster,
|
||||
CreateEndpointFromCluster
|
||||
)
|
||||
from Events.Engine.abstract_class import CategoryCluster
|
||||
from Services.Redis.Actions.actions import RedisActions
|
||||
from Services.Redis.Models.cluster import RedisList
|
||||
|
||||
from .prepare_redis_items import DecoratorModule, PrepareRedisItems
|
||||
from .category_cluster_models import CategoryClusterController
|
||||
|
||||
|
||||
for event in [*auths_events.__all__, *events_events.__all__, *validations_events.__all__]:
|
||||
print(event)
|
||||
class PrepareRouting(DecoratorModule):
|
||||
|
||||
__routers_list: list[Any] = list()
|
||||
__endpoints_list: list[Any] = list()
|
||||
__safe_endpoint_list: list[Any] = list()
|
||||
|
||||
def __init__(self, cluster_controller_group: CategoryClusterController):
|
||||
self.cluster_controller_group = cluster_controller_group
|
||||
self.prepare_needs()
|
||||
|
||||
def __str__(self):
|
||||
return f"\nPrepared Routing:\n\n{self.routers}\n\n{self.endpoints}\n\n{self.safe_endpoints}\n"
|
||||
|
||||
@property
|
||||
def routers(self):
|
||||
return self.__routers_list
|
||||
|
||||
@property
|
||||
def endpoints(self):
|
||||
return self.__endpoints_list
|
||||
|
||||
@property
|
||||
def safe_endpoints(self):
|
||||
return self.__safe_endpoint_list
|
||||
|
||||
def create_endpoints(self, cluster: CategoryCluster, created_router):
|
||||
for method_endpoint in list(cluster.ENDPOINTS):
|
||||
# Filter out the original function and apply decorators
|
||||
applied_decorators_qualname = self.apply_decorators(method_endpoint)
|
||||
# Register the endpoint with FastAPI router
|
||||
create_endpoint = CreateEndpointFromCluster(
|
||||
router=created_router, method_endpoint=method_endpoint
|
||||
)
|
||||
created_router = create_endpoint.router
|
||||
if "MiddlewareModule" in applied_decorators_qualname:
|
||||
self.__safe_endpoint_list.append(method_endpoint)
|
||||
self.__endpoints_list.append(method_endpoint)
|
||||
|
||||
def create_router(self, cluster: CategoryCluster):
|
||||
### Create Router Parameters create router for each cluster
|
||||
created_router = CreateRouterFromCluster(
|
||||
prefix=cluster.PREFIX,
|
||||
tags=cluster.TAGS,
|
||||
include_in_schema=cluster.INCLUDE_IN_SCHEMA,
|
||||
)
|
||||
self.__routers_list.append(created_router.router)
|
||||
return created_router.router
|
||||
|
||||
def prepare_needs(self):
|
||||
# @Pages iterate(ClusterToMethod)
|
||||
for cluster_control in self.cluster_controller_group.imports:
|
||||
cluster = cluster_control.category_cluster
|
||||
created_router = self.create_router(cluster)
|
||||
self.create_endpoints(cluster, created_router)
|
||||
|
||||
|
||||
class PrepareEvents(DecoratorModule):
|
||||
|
||||
def __init__(self, cluster_controller_group: CategoryClusterController):
|
||||
self.cluster_controller_group = cluster_controller_group
|
||||
self.valid_redis_items: PrepareRedisItems = PrepareRedisItems()
|
||||
self.prepare_needs()
|
||||
|
||||
def prepare_needs(self):
|
||||
# @Pages iterate(ClusterToMethod)
|
||||
for cluster_control in self.cluster_controller_group.imports:
|
||||
cluster = cluster_control.category_cluster
|
||||
### Create Redis Parameters
|
||||
# [SAVE]REDIS => MENU_FIRST_LAYER = [ClusterToMethod, ...]
|
||||
self.valid_redis_items.MENU_FIRST_LAYER_VALUE.add(cluster.name)
|
||||
# [SAVE]REDIS => CLUSTER_INDEX = {ClusterToMethod: [MethodEvent, ...], "MethodEvent": "ClusterToMethod"}
|
||||
self.valid_redis_items.CLUSTER_INDEX_VALUE.update(cluster.get_redis_cluster_index_value())
|
||||
# [SAVE]REDIS => CLUSTER_FUNCTION_CODES = {"ClusterToMethod"} : [FUNCTION_CODE, ...]}
|
||||
self.valid_redis_items.CLUSTER_FUNCTION_CODES_VALUE = {
|
||||
f"{self.valid_redis_items.CLUSTER_FUNCTION_CODES_KEY}:{cluster.name}" : tuple(cluster.retrieve_all_function_codes())
|
||||
}
|
||||
|
||||
for method_endpoint in list(cluster.ENDPOINTS):
|
||||
# [SAVE]REDIS => ENDPOINT2CLASS = {MethodEvent: Endpoint("/.../.../..."), ...}
|
||||
self.valid_redis_items.ENDPOINT2CLASS_VALUE.update(
|
||||
{f"{cluster.name}:{method_endpoint.name}": method_endpoint.URL}
|
||||
)
|
||||
self.valid_redis_items.ENDPOINT2CLASS_VALUE.update(
|
||||
{method_endpoint.URL :f"{cluster.name}:{method_endpoint.name}"}
|
||||
)
|
||||
# [SAVE]REDIS => METHOD_FUNCTION_CODES:MethodEvent:Endpoint = [FUNCTION_CODE, ...]
|
||||
self.valid_redis_items.METHOD_FUNCTION_CODES_VALUE.update(
|
||||
method_endpoint.retrieve_redis_value(cluster_name=cluster.name)
|
||||
)
|
||||
|
||||
|
||||
class SetItems2Redis:
|
||||
|
||||
std_out: str = ""
|
||||
|
||||
def __init__(self, prepare_events: PrepareEvents):
|
||||
self.prepare_events = prepare_events
|
||||
self.set_items()
|
||||
|
||||
def __str__(self):
|
||||
self.std_out = f"\nSetItems2Redis:\n\n{self.std_out}"
|
||||
return self.std_out
|
||||
|
||||
def set_items(self):
|
||||
from ApiLayers.AllConfigs.Redis.configs import RedisCategoryKeys
|
||||
dict_prep = self.prepare_events.valid_redis_items.as_dict
|
||||
RedisActions.delete(
|
||||
list_keys=[
|
||||
f"{RedisCategoryKeys.MENU_FIRST_LAYER}:*",
|
||||
f"{RedisCategoryKeys.CLUSTER_INDEX}:*",
|
||||
f"{RedisCategoryKeys.CLUSTER_FUNCTION_CODES}:*",
|
||||
f"{RedisCategoryKeys.METHOD_FUNCTION_CODES}:*"
|
||||
f"{RedisCategoryKeys.ENDPOINT2CLASS}:*",
|
||||
]
|
||||
)
|
||||
|
||||
# Save MENU_FIRST_LAYER to Redis
|
||||
redis_list = RedisList(redis_key=RedisCategoryKeys.MENU_FIRST_LAYER)
|
||||
RedisActions.set_json(
|
||||
list_keys=redis_list.to_list(), value=dict_prep.get(RedisCategoryKeys.MENU_FIRST_LAYER)
|
||||
)
|
||||
self.std_out = f"{RedisCategoryKeys.MENU_FIRST_LAYER}: {dict_prep.get(RedisCategoryKeys.MENU_FIRST_LAYER)}\n"
|
||||
|
||||
# Save CLUSTER_INDEX to Redis
|
||||
redis_list = RedisList(redis_key=RedisCategoryKeys.CLUSTER_INDEX)
|
||||
RedisActions.set_json(
|
||||
list_keys=redis_list.to_list(), value=dict_prep.get(RedisCategoryKeys.CLUSTER_INDEX)
|
||||
)
|
||||
self.std_out += f"\n{RedisCategoryKeys.CLUSTER_INDEX}: {dict_prep.get(RedisCategoryKeys.CLUSTER_INDEX)}\n"
|
||||
|
||||
# Save CLUSTER_FUNCTION_CODES to Redis by iterating over the dict
|
||||
for redis_key, redis_value in dict_prep.get(RedisCategoryKeys.CLUSTER_FUNCTION_CODES).items():
|
||||
redis_list = RedisList(redis_key=redis_key)
|
||||
RedisActions.set_json(
|
||||
list_keys=redis_list.to_list(), value=list(redis_value)
|
||||
)
|
||||
self.std_out += f"\n{RedisCategoryKeys.CLUSTER_FUNCTION_CODES}: {dict_prep.get(RedisCategoryKeys.CLUSTER_FUNCTION_CODES)}\n"
|
||||
|
||||
# Save METHOD_FUNCTION_CODES to Redis by iterating over the dict
|
||||
for redis_key, redis_value in dict_prep.get(RedisCategoryKeys.METHOD_FUNCTION_CODES).items():
|
||||
redis_list = RedisList(redis_key=redis_key)
|
||||
RedisActions.set_json(
|
||||
list_keys=redis_list.to_list(), value=list(redis_value)
|
||||
)
|
||||
self.std_out += f"\n{RedisCategoryKeys.METHOD_FUNCTION_CODES}: {dict_prep.get(RedisCategoryKeys.METHOD_FUNCTION_CODES)}\n"
|
||||
|
||||
# Save ENDPOINT2CLASS to Redis by iterating over the dict
|
||||
for redis_key, redis_value in dict_prep.get(RedisCategoryKeys.ENDPOINT2CLASS).items():
|
||||
redis_list = RedisList(redis_key=f"{RedisCategoryKeys.ENDPOINT2CLASS}:{redis_key}\n")
|
||||
RedisActions.set_json(
|
||||
list_keys=redis_list.to_list(), value=redis_value
|
||||
)
|
||||
self.std_out += f"\n{RedisCategoryKeys.ENDPOINT2CLASS}: {dict_prep.get(RedisCategoryKeys.ENDPOINT2CLASS)}\n"
|
||||
|
||||
RedisActions.set_json(
|
||||
list_keys=[f"{RedisCategoryKeys.REBUILD}:*"], value=False
|
||||
)
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
|
||||
class ClusterToMethod:
|
||||
|
||||
TAGS: list = ["Tag or Router"]
|
||||
PREFIX: str = "/..."
|
||||
PAGEINFO: PageInfo
|
||||
ENDPOINTS: list = [MethodEvent, ...]
|
||||
SUBCATEGORY: List[ClassVar[Any]] = [ClusterToMethod, ...]
|
||||
|
||||
def retrieve_all_function_codes():
|
||||
"""
|
||||
[FUNCTION_CODE, ...]
|
||||
self.ENDPOINTS -> iter()
|
||||
"""
|
||||
pass
|
||||
|
||||
def retrieve_page_info():
|
||||
"""
|
||||
PAGE_INFO:ClusterToMethod = {
|
||||
"PageInfo": {...}
|
||||
"subCategory": PAGE_INFO:ClusterToMethod
|
||||
}
|
||||
PAGE_INFO:ClusterToMethod = {
|
||||
"PageInfo": {...}
|
||||
"subCategory": PAGE_INFO:ClusterToMethod
|
||||
}
|
||||
"""
|
||||
pass
|
||||
|
||||
def retrieve_redis_value() -> Dict:
|
||||
"""
|
||||
Key(CLUSTER_FUNCTION_CODES:ClusterToMethod) : Value(PAGE_INFO, [FUNCTION_CODE, ...])
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,919 +0,0 @@
|
||||
"""
|
||||
Abstract base classes for API route and event handling.
|
||||
|
||||
This module provides core abstractions for route configuration and factory,
|
||||
with support for authentication and event handling.
|
||||
"""
|
||||
import uuid
|
||||
import inspect
|
||||
|
||||
from typing import (
|
||||
Tuple,
|
||||
TypeVar,
|
||||
Optional,
|
||||
Callable,
|
||||
Dict,
|
||||
Any,
|
||||
List,
|
||||
Type,
|
||||
ClassVar,
|
||||
Union,
|
||||
Set,
|
||||
)
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from pydantic import BaseModel
|
||||
from fastapi import Request, Depends, APIRouter
|
||||
from functools import wraps
|
||||
|
||||
from ApiLayers.ApiLibrary.common.line_number import get_line_number_for_error
|
||||
from ApiLayers.ErrorHandlers.Exceptions.api_exc import HTTPExceptionApi
|
||||
from ApiLayers.Schemas.rules.rules import EndpointRestriction
|
||||
|
||||
|
||||
ResponseModel = TypeVar("ResponseModel", bound=BaseModel)
|
||||
|
||||
|
||||
def endpoint_wrapper(url_of_endpoint: Optional[str] = None):
|
||||
"""Create a wrapper for endpoints that stores url_of_endpoint in closure.
|
||||
|
||||
Args:
|
||||
url_of_endpoint: Optional URL path for the endpoint
|
||||
"""
|
||||
|
||||
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
||||
@wraps(func)
|
||||
async def wrapper(
|
||||
*args: Any, **kwargs: Any
|
||||
) -> Union[Dict[str, Any], BaseModel]:
|
||||
# Handle both async and sync functions
|
||||
if inspect.iscoroutinefunction(func):
|
||||
result = await func(*args, **kwargs)
|
||||
else:
|
||||
result = func(*args, **kwargs)
|
||||
|
||||
# If result is a coroutine, await it
|
||||
if inspect.iscoroutine(result):
|
||||
result = await result
|
||||
|
||||
# Add endpoint to the result
|
||||
if isinstance(result, dict):
|
||||
result["endpoint"] = url_of_endpoint
|
||||
return result
|
||||
elif isinstance(result, BaseModel):
|
||||
# Convert Pydantic model to dict and add endpoint
|
||||
result_dict = result.model_dump()
|
||||
result_dict["endpoint"] = url_of_endpoint
|
||||
return result_dict
|
||||
return result
|
||||
|
||||
wrapper.url_of_endpoint = url_of_endpoint
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
@dataclass
|
||||
class EndpointFactoryConfig:
|
||||
"""Configuration class for API endpoints.
|
||||
|
||||
Attributes:
|
||||
url_of_endpoint: Full URL path for this endpoint
|
||||
endpoint: URL path for this endpoint
|
||||
method: HTTP method (GET, POST, etc.)
|
||||
summary: Short description for API documentation
|
||||
description: Detailed description for API documentation
|
||||
endpoint_function: Function to handle the endpoint
|
||||
is_auth_required: Whether authentication is required
|
||||
response_model: Optional response model for OpenAPI schema
|
||||
request_model: Optional request model for OpenAPI schema
|
||||
is_event_required: Whether event handling is required
|
||||
extra_options: Additional endpoint options
|
||||
"""
|
||||
|
||||
url_prefix: str
|
||||
url_endpoint: str
|
||||
url_of_endpoint: str
|
||||
endpoint: str
|
||||
method: str
|
||||
summary: str
|
||||
description: str
|
||||
endpoint_function: Callable[..., Any] # Now accepts any parameters and return type
|
||||
response_model: Optional[type] = None
|
||||
request_model: Optional[type] = None
|
||||
is_auth_required: bool = True
|
||||
is_event_required: bool = False
|
||||
extra_options: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
def __post_init__(self):
|
||||
"""Post initialization hook.
|
||||
|
||||
Wraps endpoint function with appropriate middleware based on configuration:
|
||||
- If auth and event required -> wrap with TokenEventMiddleware
|
||||
- If only event required -> wrap with EventMiddleware
|
||||
- If only auth required -> wrap with MiddlewareModule.auth_required
|
||||
"""
|
||||
# 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
|
||||
)
|
||||
|
||||
# Then wrap with endpoint_wrapper to store url_of_endpoint
|
||||
self.endpoint_function = endpoint_wrapper(self.url_of_endpoint)(
|
||||
self.endpoint_function
|
||||
)
|
||||
|
||||
|
||||
class RouteFactoryConfig:
|
||||
"""Configuration class for API route factories.
|
||||
|
||||
Attributes:
|
||||
name: Route name
|
||||
tags: List of tags for API documentation
|
||||
prefix: URL prefix for all endpoints in this route
|
||||
include_in_schema: Whether to include in OpenAPI schema
|
||||
endpoints: List of endpoint configurations
|
||||
extra_options: Additional route options
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
tags: List[str],
|
||||
prefix: str,
|
||||
include_in_schema: bool = True,
|
||||
endpoints: List[EndpointFactoryConfig] = None,
|
||||
extra_options: Dict[str, Any] = None,
|
||||
):
|
||||
self.name = name
|
||||
self.tags = tags
|
||||
self.prefix = prefix
|
||||
self.include_in_schema = include_in_schema
|
||||
self.endpoints = endpoints or []
|
||||
self.extra_options = extra_options or {}
|
||||
|
||||
def __post_init__(self):
|
||||
"""Validate and normalize configuration after initialization."""
|
||||
if self.endpoints is None:
|
||||
self.endpoints = []
|
||||
if self.extra_options is None:
|
||||
self.extra_options = {}
|
||||
|
||||
def as_dict(self) -> Dict[str, Any]:
|
||||
"""Convert configuration to dictionary format."""
|
||||
return {
|
||||
"name": self.name,
|
||||
"tags": self.tags,
|
||||
"prefix": self.prefix,
|
||||
"include_in_schema": self.include_in_schema,
|
||||
"endpoints": [endpoint.__dict__ for endpoint in self.endpoints],
|
||||
"extra_options": self.extra_options,
|
||||
}
|
||||
|
||||
|
||||
class MethodToEvent:
|
||||
"""Base class for mapping methods to API events with type safety and endpoint configuration.
|
||||
|
||||
This class provides a framework for handling API events with proper
|
||||
type checking for tokens and response models, as well as managing
|
||||
endpoint configurations and frontend page structure.
|
||||
|
||||
Type Parameters:
|
||||
TokenType: Type of authentication token
|
||||
ResponseModel: Type of response model
|
||||
|
||||
Class Variables:
|
||||
action_key: Unique identifier for the action
|
||||
event_type: Type of event (e.g., 'query', 'command')
|
||||
event_description: Human-readable description of the event
|
||||
event_category: Category for grouping related events
|
||||
__event_keys__: Mapping of UUIDs to event names
|
||||
__event_validation__: Validation rules for events
|
||||
__endpoint_config__: API endpoint configuration
|
||||
__page_info__: Frontend page configuration
|
||||
"""
|
||||
|
||||
action_key: ClassVar[Optional[str]] = None
|
||||
event_type: ClassVar[Optional[str]] = None
|
||||
event_description: ClassVar[str] = ""
|
||||
event_category: ClassVar[str] = ""
|
||||
__event_keys__: ClassVar[Dict[str, str]] = {}
|
||||
__event_validation__: Dict[str, Tuple[Type, Union[List, tuple]]] = {}
|
||||
__endpoint_config__: ClassVar[Dict[str, Dict[str, Any]]] = {
|
||||
"endpoints": {}, # Mapping of event UUIDs to endpoint configs
|
||||
"router_prefix": "", # Router prefix for all endpoints in this class
|
||||
"tags": [], # OpenAPI tags
|
||||
}
|
||||
__page_info__: ClassVar[Dict[str, Any]] = {
|
||||
"name": "", # Page name (e.g., "AccountPage")
|
||||
"title": {"tr": "", "en": ""}, # Multi-language titles
|
||||
"icon": "", # Icon name
|
||||
"url": "", # Frontend route
|
||||
"component": None, # Optional component name
|
||||
"parent": None, # Parent page name if this is a subpage
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def register_endpoint(
|
||||
cls,
|
||||
event_uuid: str,
|
||||
path: str,
|
||||
method: str = "POST",
|
||||
response_model: Optional[Type] = None,
|
||||
**kwargs
|
||||
) -> None:
|
||||
"""Register an API endpoint configuration for an event.
|
||||
|
||||
Args:
|
||||
event_uuid: UUID of the event
|
||||
path: Endpoint path (will be prefixed with router_prefix)
|
||||
method: HTTP method (default: POST)
|
||||
response_model: Pydantic model for response
|
||||
**kwargs: Additional FastAPI endpoint parameters
|
||||
"""
|
||||
if event_uuid not in cls.__event_keys__:
|
||||
raise ValueError(f"Event UUID {event_uuid} not found in {cls.__name__}")
|
||||
|
||||
cls.__endpoint_config__["endpoints"][event_uuid] = {
|
||||
"path": path,
|
||||
"method": method,
|
||||
"response_model": response_model,
|
||||
**kwargs
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def configure_router(cls, prefix: str, tags: List[str]) -> None:
|
||||
"""Configure the API router settings.
|
||||
|
||||
Args:
|
||||
prefix: Router prefix for all endpoints
|
||||
tags: OpenAPI tags for documentation
|
||||
"""
|
||||
cls.__endpoint_config__["router_prefix"] = prefix
|
||||
cls.__endpoint_config__["tags"] = tags
|
||||
|
||||
@classmethod
|
||||
def configure_page(
|
||||
cls,
|
||||
name: str,
|
||||
title: Dict[str, str],
|
||||
icon: str,
|
||||
url: str,
|
||||
component: Optional[str] = None,
|
||||
parent: Optional[str] = None
|
||||
) -> None:
|
||||
"""Configure the frontend page information.
|
||||
|
||||
Args:
|
||||
name: Page name
|
||||
title: Multi-language titles (must include 'tr' and 'en')
|
||||
icon: Icon name
|
||||
url: Frontend route
|
||||
component: Optional component name
|
||||
parent: Parent page name for subpages
|
||||
"""
|
||||
required_langs = {"tr", "en"}
|
||||
if not all(lang in title for lang in required_langs):
|
||||
raise ValueError(f"Title must contain all required languages: {required_langs}")
|
||||
|
||||
cls.__page_info__.update({
|
||||
"name": name,
|
||||
"title": title,
|
||||
"icon": icon,
|
||||
"url": url,
|
||||
"component": component,
|
||||
"parent": parent
|
||||
})
|
||||
|
||||
@classmethod
|
||||
def get_endpoint_config(cls) -> Dict[str, Any]:
|
||||
"""Get the complete endpoint configuration."""
|
||||
return cls.__endpoint_config__
|
||||
|
||||
@classmethod
|
||||
def get_page_info(cls) -> Dict[str, Any]:
|
||||
"""Get the frontend page configuration."""
|
||||
return cls.__page_info__
|
||||
|
||||
@classmethod
|
||||
def has_available_events(cls, user_permission_uuids: Set[str]) -> bool:
|
||||
"""Check if any events are available based on user permissions."""
|
||||
return bool(set(cls.__event_keys__.keys()) & user_permission_uuids)
|
||||
|
||||
@classmethod
|
||||
def get_page_info_with_permissions(
|
||||
cls,
|
||||
user_permission_uuids: Set[str],
|
||||
include_endpoints: bool = False
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
"""Get page info if user has required permissions.
|
||||
|
||||
Args:
|
||||
user_permission_uuids: Set of UUIDs the user has permission for
|
||||
include_endpoints: Whether to include available endpoint information
|
||||
|
||||
Returns:
|
||||
Dict with page info if user has permissions, None otherwise
|
||||
"""
|
||||
# Check if user has any permissions for this page's events
|
||||
if not cls.has_available_events(user_permission_uuids):
|
||||
return None
|
||||
|
||||
# Start with basic page info
|
||||
page_info = {
|
||||
**cls.__page_info__,
|
||||
"category": cls.event_category,
|
||||
"type": cls.event_type,
|
||||
"description": cls.event_description
|
||||
}
|
||||
|
||||
# Optionally include available endpoints
|
||||
if include_endpoints:
|
||||
available_endpoints = {}
|
||||
for uuid, endpoint in cls.__endpoint_config__["endpoints"].items():
|
||||
if uuid in user_permission_uuids:
|
||||
available_endpoints[uuid] = {
|
||||
"path": f"{cls.__endpoint_config__['router_prefix']}{endpoint['path']}",
|
||||
"method": endpoint["method"],
|
||||
"event_name": cls.__event_keys__[uuid]
|
||||
}
|
||||
if available_endpoints:
|
||||
page_info["available_endpoints"] = available_endpoints
|
||||
|
||||
return page_info
|
||||
|
||||
@classmethod
|
||||
def get_events_config(cls) -> Dict[str, Any]:
|
||||
"""Get the complete configuration including events, endpoints, and page info."""
|
||||
return {
|
||||
"events": cls.__event_keys__,
|
||||
"endpoints": cls.__endpoint_config__,
|
||||
"page_info": cls.__page_info__,
|
||||
"category": cls.event_category,
|
||||
"type": cls.event_type,
|
||||
"description": cls.event_description
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def retrieve_event_response_model(cls, function_code: str) -> Any:
|
||||
"""Retrieve event validation for a specific function.
|
||||
|
||||
Args:
|
||||
function_code: Function identifier
|
||||
|
||||
Returns:
|
||||
Tuple containing response model and language models
|
||||
"""
|
||||
event_validation_list = cls.__event_validation__.get(function_code, None)
|
||||
if not event_validation_list:
|
||||
raise HTTPExceptionApi(
|
||||
error_code="",
|
||||
lang="en",
|
||||
loc=get_line_number_for_error(),
|
||||
sys_msg="Function not found",
|
||||
)
|
||||
return event_validation_list[0]
|
||||
|
||||
@classmethod
|
||||
def retrieve_event_languages(cls, function_code: str) -> Union[List, tuple]:
|
||||
"""Retrieve event description for a specific function.
|
||||
|
||||
Args:
|
||||
function_code: Function identifier
|
||||
|
||||
Returns:
|
||||
Event description
|
||||
"""
|
||||
event_keys_list = cls.__event_validation__.get(function_code, None)
|
||||
if not event_keys_list:
|
||||
raise HTTPExceptionApi(
|
||||
error_code="",
|
||||
lang="en",
|
||||
loc=get_line_number_for_error(),
|
||||
sys_msg="Function not found",
|
||||
)
|
||||
function_language_models: Union[List, tuple] = event_keys_list[1]
|
||||
if not function_language_models:
|
||||
raise HTTPExceptionApi(
|
||||
error_code="",
|
||||
lang="en",
|
||||
loc=get_line_number_for_error(),
|
||||
sys_msg="Function not found",
|
||||
)
|
||||
return function_language_models
|
||||
|
||||
@staticmethod
|
||||
def merge_models(language_model: List) -> Dict:
|
||||
merged_models = {"tr": {}, "en": {}}
|
||||
for model in language_model:
|
||||
for lang in dict(model).keys():
|
||||
if lang not in merged_models:
|
||||
merged_models[lang] = model[lang]
|
||||
else:
|
||||
merged_models[lang].update(model[lang])
|
||||
return merged_models
|
||||
|
||||
@classmethod
|
||||
def retrieve_event_function(cls, function_code: str) -> Dict[str, str]:
|
||||
"""Retrieve event parameters for a specific function.
|
||||
|
||||
Args:
|
||||
function_code: Function identifier
|
||||
|
||||
Returns:
|
||||
Dictionary of event parameters
|
||||
"""
|
||||
function_event = cls.__event_keys__[function_code]
|
||||
function_itself = getattr(cls, function_event, None)
|
||||
if not function_itself:
|
||||
raise HTTPExceptionApi(
|
||||
error_code="",
|
||||
lang="en",
|
||||
loc=get_line_number_for_error(),
|
||||
sys_msg="Function not found",
|
||||
)
|
||||
return function_itself
|
||||
|
||||
@classmethod
|
||||
def retrieve_language_parameters(
|
||||
cls, function_code: str, language: str = "tr"
|
||||
) -> Dict[str, Any]:
|
||||
"""Retrieve language-specific parameters for an event.
|
||||
|
||||
Args:
|
||||
language: Language code (e.g. 'tr', 'en')
|
||||
function_code: Function identifier
|
||||
|
||||
Returns:
|
||||
Dictionary of language-specific field mappings
|
||||
"""
|
||||
event_language_models = cls.retrieve_event_languages(function_code)
|
||||
event_response_model = cls.retrieve_event_response_model(function_code)
|
||||
event_response_model_merged = cls.merge_models(event_language_models)
|
||||
event_response_model_merged_lang = event_response_model_merged[language]
|
||||
# Map response model fields to language-specific values
|
||||
only_language_dict = {
|
||||
field: event_response_model_merged_lang[field]
|
||||
for field in event_response_model.model_fields
|
||||
if field in event_response_model_merged_lang
|
||||
}
|
||||
"""
|
||||
__event_validation__ : {"key": [A, B, C]}
|
||||
Language Model : Language Model that is model pydatnic requires
|
||||
Language Models : All language_models that is included in Langugage Models Section
|
||||
Merged Language Models : Merged with all models in list event_validation
|
||||
"""
|
||||
return {
|
||||
"language_model": only_language_dict,
|
||||
"language_models": event_response_model_merged,
|
||||
}
|
||||
|
||||
|
||||
class EventMethodRegistry:
|
||||
"""Registry for mapping event method UUIDs to categories and managing permissions."""
|
||||
|
||||
def __init__(self):
|
||||
self._uuid_map: Dict[str, Tuple[Type[MethodToEvent], str]] = {} # uuid -> (method_class, event_name)
|
||||
self._category_events: Dict[str, Set[str]] = defaultdict(set) # category -> set of uuids
|
||||
|
||||
def register_method(self, category_name: str, method_class: Type[MethodToEvent]) -> None:
|
||||
"""Register a method class with its category."""
|
||||
# Register all UUIDs from the method
|
||||
for event_uuid, event_name in method_class.__event_keys__.items():
|
||||
self._uuid_map[event_uuid] = (method_class, event_name)
|
||||
self._category_events[category_name].add(event_uuid)
|
||||
|
||||
def get_method_by_uuid(self, event_uuid: str) -> Optional[Tuple[Type[MethodToEvent], str]]:
|
||||
"""Get method class and event name by UUID."""
|
||||
return self._uuid_map.get(event_uuid)
|
||||
|
||||
def get_events_for_category(self, category_name: str) -> Set[str]:
|
||||
"""Get all event UUIDs for a category."""
|
||||
return self._category_events.get(category_name, set())
|
||||
|
||||
|
||||
class EventCategory:
|
||||
"""Base class for defining event categories similar to frontend page structure."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
title: Dict[str, str],
|
||||
icon: str,
|
||||
url: str,
|
||||
component: Optional[str] = None,
|
||||
page_info: Any = None,
|
||||
all_endpoints: Dict[str, Set[str]] = None, # category -> set of event UUIDs
|
||||
sub_categories: List = None,
|
||||
):
|
||||
self.name = name
|
||||
self.title = self._validate_title(title)
|
||||
self.icon = icon
|
||||
self.url = url
|
||||
self.component = component
|
||||
self.page_info = page_info
|
||||
self.all_endpoints = all_endpoints or {}
|
||||
self.sub_categories = self._process_subcategories(sub_categories or [])
|
||||
|
||||
def _validate_title(self, title: Dict[str, str]) -> Dict[str, str]:
|
||||
"""Validate title has required languages."""
|
||||
required_langs = {"tr", "en"}
|
||||
if not all(lang in title for lang in required_langs):
|
||||
raise ValueError(f"Title must contain all required languages: {required_langs}")
|
||||
return title
|
||||
|
||||
def _process_subcategories(self, categories: List[Union[Dict, "EventCategory"]]) -> List["EventCategory"]:
|
||||
"""Process subcategories ensuring they are all EventCategory instances."""
|
||||
processed = []
|
||||
for category in categories:
|
||||
if isinstance(category, dict):
|
||||
processed.append(EventCategory.from_dict(category))
|
||||
elif isinstance(category, EventCategory):
|
||||
processed.append(category)
|
||||
else:
|
||||
raise ValueError(f"Invalid subcategory type: {type(category)}")
|
||||
return processed
|
||||
|
||||
def has_available_events(self, user_permission_uuids: Set[str]) -> bool:
|
||||
"""Check if category has available events based on UUID intersection."""
|
||||
# Check current category's events
|
||||
return any(
|
||||
bool(events & user_permission_uuids)
|
||||
for events in self.all_endpoints.values()
|
||||
)
|
||||
|
||||
def get_menu_item(self, user_permission_uuids: Set[str]) -> Optional[Dict[str, Any]]:
|
||||
"""Get menu item if category has available events."""
|
||||
# First check if this category has available events
|
||||
if not self.has_available_events(user_permission_uuids):
|
||||
return None
|
||||
|
||||
menu_item = {
|
||||
"name": self.name,
|
||||
"title": self.title,
|
||||
"icon": self.icon,
|
||||
"url": self.url
|
||||
}
|
||||
|
||||
if self.component:
|
||||
menu_item["component"] = self.component
|
||||
|
||||
# Only process subcategories if parent has permissions
|
||||
sub_items = []
|
||||
for subcategory in self.sub_categories:
|
||||
if sub_menu := subcategory.get_menu_item(user_permission_uuids):
|
||||
sub_items.append(sub_menu)
|
||||
|
||||
if sub_items:
|
||||
menu_item["items"] = sub_items
|
||||
|
||||
return menu_item
|
||||
|
||||
def get_available_events(self, registry: EventMethodRegistry, user_permission_uuids: Set[str]) -> Dict[str, List[Dict[str, Any]]]:
|
||||
"""Get available events based on user permission UUIDs."""
|
||||
available_events = defaultdict(list)
|
||||
|
||||
# Process endpoints in current category
|
||||
category_events = self.all_endpoints.get(self.name, set())
|
||||
for event_uuid in category_events & user_permission_uuids:
|
||||
method_info = registry.get_method_by_uuid(event_uuid)
|
||||
if method_info:
|
||||
method_class, event_name = method_info
|
||||
available_events[method_class.event_type].append({
|
||||
"uuid": event_uuid,
|
||||
"name": event_name,
|
||||
"description": method_class.event_description,
|
||||
"category": method_class.event_category
|
||||
})
|
||||
|
||||
# Process subcategories recursively
|
||||
for subcategory in self.sub_categories:
|
||||
sub_events = subcategory.get_available_events(registry, user_permission_uuids)
|
||||
for event_type, events in sub_events.items():
|
||||
available_events[event_type].extend(events)
|
||||
|
||||
return dict(available_events)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict[str, Any]) -> "EventCategory":
|
||||
"""Create category from dictionary."""
|
||||
return cls(
|
||||
name=data["name"],
|
||||
title=data["title"],
|
||||
icon=data["icon"],
|
||||
url=data["url"],
|
||||
component=data.get("component"),
|
||||
page_info=data.get("pageInfo"),
|
||||
all_endpoints=data.get("allEndpoints", {}),
|
||||
sub_categories=data.get("subCategories", [])
|
||||
)
|
||||
|
||||
def to_dict(self, registry: EventMethodRegistry, user_permission_uuids: Optional[Set[str]] = None) -> Dict[str, Any]:
|
||||
"""Convert category to dictionary with optional permission filtering."""
|
||||
result = {
|
||||
"name": self.name,
|
||||
"title": self.title,
|
||||
"icon": self.icon,
|
||||
"url": self.url,
|
||||
"pageInfo": self.page_info,
|
||||
}
|
||||
|
||||
if user_permission_uuids is not None:
|
||||
# Only include endpoints and their info if user has permissions
|
||||
available_events = self.get_available_events(registry, user_permission_uuids)
|
||||
if available_events:
|
||||
result["availableEvents"] = available_events
|
||||
result["allEndpoints"] = self.all_endpoints
|
||||
else:
|
||||
# Include all endpoints if no permissions specified
|
||||
result["allEndpoints"] = self.all_endpoints
|
||||
|
||||
# Process subcategories
|
||||
subcategories = [
|
||||
sub.to_dict(registry, user_permission_uuids) for sub in self.sub_categories
|
||||
]
|
||||
# Only include subcategories that have available events
|
||||
if user_permission_uuids is None or any(
|
||||
"availableEvents" in sub for sub in subcategories
|
||||
):
|
||||
result["subCategories"] = subcategories
|
||||
|
||||
if self.component:
|
||||
result["component"] = self.component
|
||||
|
||||
return result
|
||||
|
||||
|
||||
class EventCategoryManager:
|
||||
"""Manager class for handling event categories and their relationships."""
|
||||
|
||||
def __init__(self):
|
||||
self.categories: List[EventCategory] = []
|
||||
self.registry = EventMethodRegistry()
|
||||
|
||||
def get_menu_tree(self, user_permission_uuids: Set[str]) -> List[Dict[str, Any]]:
|
||||
"""Get menu tree based on available events."""
|
||||
return [
|
||||
menu_item for category in self.categories
|
||||
if (menu_item := category.get_menu_item(user_permission_uuids))
|
||||
]
|
||||
|
||||
def register_category(self, category: EventCategory) -> None:
|
||||
"""Register a category and its endpoints in the registry."""
|
||||
self.categories.append(category)
|
||||
|
||||
def add_category(self, category: Union[EventCategory, Dict[str, Any]]) -> None:
|
||||
"""Add a new category."""
|
||||
if isinstance(category, dict):
|
||||
category = EventCategory.from_dict(category)
|
||||
self.register_category(category)
|
||||
|
||||
def add_categories(self, categories: List[Union[EventCategory, Dict[str, Any]]]) -> None:
|
||||
"""Add multiple categories at once."""
|
||||
for category in categories:
|
||||
self.add_category(category)
|
||||
|
||||
def get_category(self, name: str) -> Optional[EventCategory]:
|
||||
"""Get category by name."""
|
||||
return next((cat for cat in self.categories if cat.name == name), None)
|
||||
|
||||
def get_all_categories(self, user_permission_uuids: Optional[Set[str]] = None) -> List[Dict[str, Any]]:
|
||||
"""Get all categories as dictionary, filtered by user permissions."""
|
||||
return [cat.to_dict(self.registry, user_permission_uuids) for cat in self.categories]
|
||||
|
||||
def get_category_endpoints(self, category_name: str) -> Set[str]:
|
||||
"""Get all endpoint UUIDs for a category."""
|
||||
category = self.get_category(category_name)
|
||||
return category.all_endpoints.get(category_name, set()) if category else set()
|
||||
|
||||
def get_subcategories(self, category_name: str, user_permission_uuids: Optional[Set[str]] = None) -> List[Dict[str, Any]]:
|
||||
"""Get subcategories for a category."""
|
||||
category = self.get_category(category_name)
|
||||
if not category:
|
||||
return []
|
||||
return [sub.to_dict(self.registry, user_permission_uuids) for sub in category.sub_categories]
|
||||
|
||||
def find_category_by_url(self, url: str) -> Optional[EventCategory]:
|
||||
"""Find a category by its URL."""
|
||||
for category in self.categories:
|
||||
if category.url == url:
|
||||
return category
|
||||
for subcategory in category.sub_categories:
|
||||
if subcategory.url == url:
|
||||
return subcategory
|
||||
return None
|
||||
|
||||
|
||||
class EventMethodRegistry:
|
||||
"""Registry for all MethodToEvent classes and menu building."""
|
||||
|
||||
_instance = None
|
||||
_method_classes: Dict[str, Type[MethodToEvent]] = {}
|
||||
|
||||
def __new__(cls):
|
||||
if cls._instance is None:
|
||||
cls._instance = super().__new__(cls)
|
||||
return cls._instance
|
||||
|
||||
@classmethod
|
||||
def register_method_class(cls, method_class: Type[MethodToEvent]) -> None:
|
||||
"""Register a MethodToEvent class."""
|
||||
if not issubclass(method_class, MethodToEvent):
|
||||
raise ValueError(f"{method_class.__name__} must be a subclass of MethodToEvent")
|
||||
|
||||
page_info = method_class.get_page_info()
|
||||
cls._method_classes[page_info["name"]] = method_class
|
||||
|
||||
@classmethod
|
||||
def get_all_menu_items(
|
||||
cls,
|
||||
user_permission_uuids: Set[str],
|
||||
include_endpoints: bool = False
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""Get all menu items based on user permissions.
|
||||
|
||||
Args:
|
||||
user_permission_uuids: Set of UUIDs the user has permission for
|
||||
include_endpoints: Whether to include available endpoint information
|
||||
|
||||
Returns:
|
||||
List of menu items organized in a tree structure
|
||||
"""
|
||||
# First get all page infos
|
||||
page_infos = {}
|
||||
for method_class in cls._method_classes.values():
|
||||
if page_info := method_class.get_page_info_with_permissions(user_permission_uuids, include_endpoints):
|
||||
page_infos[page_info["name"]] = page_info
|
||||
|
||||
# Build tree structure
|
||||
menu_tree = []
|
||||
child_pages = set()
|
||||
|
||||
# First pass: identify all child pages
|
||||
for page_info in page_infos.values():
|
||||
if page_info.get("parent"):
|
||||
child_pages.add(page_info["name"])
|
||||
|
||||
# Second pass: build tree structure
|
||||
for name, page_info in page_infos.items():
|
||||
# Skip if this is a child page
|
||||
if name in child_pages:
|
||||
continue
|
||||
|
||||
# Start with this page's info
|
||||
menu_item = page_info.copy()
|
||||
|
||||
# Find and add children
|
||||
children = []
|
||||
for child_info in page_infos.values():
|
||||
if child_info.get("parent") == name:
|
||||
children.append(child_info)
|
||||
|
||||
if children:
|
||||
menu_item["items"] = sorted(
|
||||
children,
|
||||
key=lambda x: x["name"]
|
||||
)
|
||||
|
||||
menu_tree.append(menu_item)
|
||||
|
||||
return sorted(menu_tree, key=lambda x: x["name"])
|
||||
|
||||
@classmethod
|
||||
def get_available_endpoints(
|
||||
cls,
|
||||
user_permission_uuids: Set[str]
|
||||
) -> Dict[str, Dict[str, Any]]:
|
||||
"""Get all available endpoints based on user permissions.
|
||||
|
||||
Args:
|
||||
user_permission_uuids: Set of UUIDs the user has permission for
|
||||
|
||||
Returns:
|
||||
Dict mapping event UUIDs to endpoint configurations
|
||||
"""
|
||||
available_endpoints = {}
|
||||
|
||||
for method_class in cls._method_classes.values():
|
||||
if page_info := method_class.get_page_info_with_permissions(
|
||||
user_permission_uuids,
|
||||
include_endpoints=True
|
||||
):
|
||||
if endpoints := page_info.get("available_endpoints"):
|
||||
available_endpoints.update(endpoints)
|
||||
|
||||
return available_endpoints
|
||||
|
||||
|
||||
"""
|
||||
Example usage
|
||||
|
||||
# Register your MethodToEvent classes
|
||||
registry = EventMethodRegistry()
|
||||
registry.register_method_class(AccountEventMethods)
|
||||
registry.register_method_class(AccountDetailsEventMethods)
|
||||
|
||||
# Get complete menu structure
|
||||
user_permissions = {
|
||||
"uuid1",
|
||||
"uuid2",
|
||||
"uuid3"
|
||||
}
|
||||
|
||||
menu_items = registry.get_all_menu_items(user_permissions, include_endpoints=True)
|
||||
# Result:
|
||||
[
|
||||
{
|
||||
"name": "AccountPage",
|
||||
"title": {"tr": "Hesaplar", "en": "Accounts"},
|
||||
"icon": "User",
|
||||
"url": "/account",
|
||||
"category": "account",
|
||||
"type": "query",
|
||||
"description": "Account management operations",
|
||||
"available_endpoints": {
|
||||
"uuid1": {"path": "/api/account/view", "method": "GET"},
|
||||
"uuid2": {"path": "/api/account/edit", "method": "POST"}
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"name": "AccountDetailsPage",
|
||||
"title": {"tr": "Hesap Detayları", "en": "Account Details"},
|
||||
"icon": "FileText",
|
||||
"url": "/account/details",
|
||||
"parent": "AccountPage",
|
||||
"category": "account_details",
|
||||
"type": "query",
|
||||
"available_endpoints": {
|
||||
"uuid3": {"path": "/api/account/details/view", "method": "GET"}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
# Get all available endpoints
|
||||
endpoints = registry.get_available_endpoints(user_permissions)
|
||||
# Result:
|
||||
{
|
||||
"uuid1": {
|
||||
"path": "/api/account/view",
|
||||
"method": "GET",
|
||||
"event_name": "view_account"
|
||||
},
|
||||
"uuid2": {
|
||||
"path": "/api/account/edit",
|
||||
"method": "POST",
|
||||
"event_name": "edit_account"
|
||||
},
|
||||
"uuid3": {
|
||||
"path": "/api/account/details/view",
|
||||
"method": "GET",
|
||||
"event_name": "view_details"
|
||||
}
|
||||
}
|
||||
|
||||
# Get event UUIDs from MethodToEvent classes
|
||||
account_events = {uuid for uuid in AccountEventMethods.__event_keys__}
|
||||
|
||||
# Define categories with event UUIDs
|
||||
PAGES_INFO = [
|
||||
{
|
||||
"name": "AccountPage",
|
||||
"title": {"tr": "Hesaplar", "en": "Accounts"},
|
||||
"icon": "User",
|
||||
"url": "/account",
|
||||
"pageInfo": AccountPageInfo,
|
||||
"allEndpoints": {"AccountPage": account_events},
|
||||
"subCategories": [
|
||||
{
|
||||
"name": "AccountDetailsPage",
|
||||
"title": {"tr": "Hesap Detayları", "en": "Account Details"},
|
||||
"icon": "FileText",
|
||||
"url": "/account/details",
|
||||
"allEndpoints": {} # No direct endpoints, only shown if parent has permissions
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
# Initialize manager
|
||||
manager = EventCategoryManager()
|
||||
manager.add_categories(PAGES_INFO)
|
||||
|
||||
# Get menu tree based on available events
|
||||
user_permission_uuids = {
|
||||
"31f4f32f-0cd4-4995-8a6a-f9f56335848a",
|
||||
"ec98ef2c-bcd0-432d-a8f4-1822a56c33b2"
|
||||
}
|
||||
menu_tree = manager.get_menu_tree(user_permission_uuids)
|
||||
"""
|
||||
Reference in New Issue
Block a user