validation services added

This commit is contained in:
2025-01-30 12:13:35 +03:00
parent 9276740e0e
commit 822e4155a1
24 changed files with 279 additions and 708 deletions

View File

@@ -1,23 +1,25 @@
from Events.Engine.abstract_class import Event
from ApiLayers.LanguageModels.Request import (
LoginRequestLanguageModel,
)
from typing import Any
from fastapi import Request
from models import TemplateResponseModels, TemplateRequestModels
from function_handlers import TemplateFunctions
from Events.Engine.abstract_class import Event
from .models import ValidationsPydantic
from .function_handlers import RetrieveValidation
# Auth Login
template_event = Event(
name="authentication_login_super_user_event",
key="a5d2d0d1-3e9b-4b0f-8c7d-6d4a4b4c4d4e",
request_validator=TemplateRequestModels.TemplateRequestModelX,
language_models=[LoginRequestLanguageModel],
response_validation_static="LOGIN_SUCCESS",
description="Login super user",
validation_event = Event(
name="validation_event",
key="02b5a596-14ba-4361-90d7-c6755727c63f",
request_validator=ValidationsPydantic,
language_models=[],
response_validation_static=None,
description="Get Validations by event function code",
)
template_event.endpoint_callable = (
TemplateFunctions.template_example_function()
)
def get_validation_by_event_function_code(request: Request, data: Any):
return RetrieveValidation.retrieve_validation(data=data)
validation_event.endpoint_callable = get_validation_by_event_function_code

View File

@@ -1,14 +1,16 @@
from Events.Engine.abstract_class import CategoryCluster
from info import template_page_info
from .validation import ValidationEventMethods
TemplateCluster = CategoryCluster(
name="TemplateCluster",
tags=["template"],
prefix="/template",
description="Template cluster",
pageinfo=template_page_info,
endpoints={},
ValidationsCluster = CategoryCluster(
name="ValidationsCluster",
tags=["Validations"],
prefix="/validations",
description="Validations cluster",
endpoints={
"ValidationEventMethods": ValidationEventMethods,
},
include_in_schema=True,
sub_category=[],
)

View File

@@ -1,21 +1,103 @@
from typing import Any, Union
"""
Validation function handlers
"""
from typing import Dict, Any
from fastapi import Request
from Events.base_request_model import TokenDictType, BaseRouteModel
from ApiLayers.AllConfigs.Redis.configs import RedisValidationKeysAction, RedisCategoryKeys
from Services.Redis.Actions.actions import RedisActions
from Events.base_request_model import BaseRouteModel
from config import ValidationsConfig
class Handlers:
"""Class for handling authentication functions"""
class ValidateBase:
@classmethod # Requires no auth context
def handle_function(cls, **kwargs):
"""Handle function with kwargs"""
return
redis_key: str = f"{RedisCategoryKeys.METHOD_FUNCTION_CODES}:*:"
def __init__(self, url: str, reachable_codes: list):
self.url = url
self.reachable_codes = reachable_codes
@property
def function_codes(self):
redis_function_codes= RedisActions.get_json(
list_keys=[f"{self.redis_key}{self.url}"]
)
if redis_function_codes.status:
return redis_function_codes.first
raise ValueError("Function code not found")
@property
def intersection(self):
intersection = list(set(self.function_codes).intersection(set(self.reachable_codes)))
if not len(intersection) == 1:
raise ValueError("Users reachable function codes does not match or match more than one.")
return intersection[0]
class TemplateFunctions(BaseRouteModel):
"""Class for handling authentication functions"""
class RedisHeaderRetrieve(ValidateBase):
redis_key: str = RedisValidationKeysAction.dynamic_header_request_key
@property
def header(self):
"""
Headers: Headers which is merged with response model && language models of event
"""
redis_header= RedisActions.get_json(list_keys=[f"{self.redis_key}:{self.intersection}"])
if redis_header.status:
return redis_header.first
raise ValueError("Header not found")
class RedisValidationRetrieve(ValidateBase):
redis_key: str = RedisValidationKeysAction.dynamic_validation_key
@property
def validation(self):
"""
Validation: Validation of event which is merged with response model && language models of event
"""
redis_validation = RedisActions.get_json(list_keys=[f"{self.redis_key}:{self.intersection}"])
if redis_validation.status:
return redis_validation.first
raise ValueError("Header not found")
class ValidationsBoth(RedisHeaderRetrieve, RedisValidationRetrieve):
@property
def both(self) -> Dict[str, Any]:
"""
Headers: Headers which is merged with response model && language models of event
Validation: Validation of event which is merged with response model && language models of event
"""
return {"headers": self.header, "validation": self.validation}
class RetrieveValidation(BaseRouteModel):
@classmethod
def template_example_function(cls):
return
def retrieve_validation(cls, data: Any):
"""
Retrieve validation by event function code
"""
if getattr(data, 'asked_field', "") not in ValidationsConfig.SUPPORTED_VALIDATIONS:
raise ValueError(f"Invalid asked field please retry with valid fields {ValidationsConfig.SUPPORTED_VALIDATIONS}")
reachable_codes = []
if cls.context_retriever.token.is_employee:
reachable_codes = cls.context_retriever.token.selected_company.reachable_event_codes
elif cls.context_retriever.token.is_occupant:
reachable_codes = cls.context_retriever.token.selected_occupant.reachable_event_codes
validate_dict = dict(url=data.url, reachable_code=reachable_codes)
if data.asked_field == "all":
return ValidationsBoth(**validate_dict).both
elif data.asked_field == "headers":
return RedisHeaderRetrieve(**validate_dict).header
elif data.asked_field == "validation":
return RedisValidationRetrieve(**validate_dict).validation

View File

@@ -1,25 +1,10 @@
"""
Validation records request and response models.
"""
from typing import TYPE_CHECKING, Dict, Any
from pydantic import BaseModel, Field, RootModel
from typing import Optional
from pydantic import BaseModel
class ValidationsPydantic(BaseModel):
class_model: str
reachable_event_code: str
lang: str
class InsertValidationRecordRequestModel:
pass
class UpdateValidationRecordRequestModel:
pass
class ListOptionsValidationRecordRequestModel:
pass
event_code: str
asked_field: Optional[str] = "all"

View File

@@ -1,146 +1,40 @@
"""
Validation request models.
template related API endpoints.
"""
from typing import TYPE_CHECKING, Dict, Any
from typing import Any, Dict
from fastapi import Request
from ApiEvents.abstract_class import MethodToEvent
from ApiLibrary.common.line_number import get_line_number_for_error
from ApiValidations.Custom.validation_response import ValidationModel, ValidationParser
from Events.Engine.abstract_class import MethodToEvent
from Events.base_request_model import EndpointBaseRequestModel, ContextRetrievers
from ApiLayers.Middleware.auth_middleware import MiddlewareModule
from ErrorHandlers.Exceptions.api_exc import HTTPExceptionApi
from .models import ValidationsPydantic
from .api_events import validation_event
from .function_handlers import RetrieveValidation
class AllModelsImport:
@classmethod
def import_all_models(cls):
from ApiEvents.events.account.account_records import (
AccountListEventMethod,
AccountUpdateEventMethod,
AccountCreateEventMethod,
)
from ApiEvents.events.address.address import (
AddressListEventMethod,
AddressUpdateEventMethod,
AddressCreateEventMethod,
AddressSearchEventMethod,
)
return dict(
AccountListEventMethod=AccountListEventMethod,
AccountUpdateEventMethod=AccountUpdateEventMethod,
AccountCreateEventMethod=AccountCreateEventMethod,
AddressListEventMethod=AddressListEventMethod,
AddressUpdateEventMethod=AddressUpdateEventMethod,
AddressCreateEventMethod=AddressCreateEventMethod,
AddressSearchEventMethod=AddressSearchEventMethod,
)
ValidationEventMethods = MethodToEvent(
name="ValidationEventMethods",
events={validation_event.key: validation_event},
headers=[],
errors=[],
url="/validations",
method="POST",
decorators_list=[MiddlewareModule.auth_required],
summary="Get Validations by event function code",
description="Get Validations by event function code by All, Header, Validation & request url",
)
class ValidationsBoth(MethodToEvent):
@classmethod
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)
if not return_single_model:
raise HTTPExceptionApi(
error_code="",
lang="en",
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
)
language_model_all = return_single_model.retrieve_language_parameters(
function_code=event.reachable_event_code, language=event.lang
)
language_model = language_model_all.get("language_model", None)
language_models = language_model_all.get("language_models", None)
validation = ValidationModel(response_model, language_model, language_models)
"""
Headers: Headers which is merged with response model && language models of event
Validation: Validation of event which is merged with response model && language models of event
"""
return {
"headers": validation.headers,
"validation": validation.validation,
# "language_models": language_model_all,
}
def authentication_login_with_domain_and_creds_endpoint(
request: Request, data: EndpointBaseRequestModel
) -> Dict[str, Any]:
function = ValidationEventMethods.retrieve_event(event_function_code=f"{validation_event.key}")
data = function.REQUEST_VALIDATOR(**data.data)
RetrieveValidation.context_retriever = ContextRetrievers(func=authentication_login_with_domain_and_creds_endpoint)
return function.endpoint_callable(request=request, data=data)
class ValidationsValidations(MethodToEvent):
@classmethod
def retrieve_validations(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)
if not return_single_model:
raise HTTPExceptionApi(
error_code="",
lang="en",
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
)
language_model_all = return_single_model.retrieve_language_parameters(
function_code=event.reachable_event_code, language=event.lang
)
language_model = language_model_all.get("language_model", None)
language_models = language_model_all.get("language_models", None)
validation = ValidationModel(response_model, language_model, language_models)
"""
Headers: Headers which is merged with response model && language models of event
Validation: Validation of event which is merged with response model && language models of event
"""
return {
"validation": validation.validation,
# "headers": validation.headers,
# "language_models": language_model_all,
}
class ValidationsHeaders(MethodToEvent):
@classmethod
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)
if not return_single_model:
raise HTTPExceptionApi(
error_code="",
lang="en",
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
)
language_model_all = return_single_model.retrieve_language_parameters(
function_code=event.reachable_event_code, language=event.lang
)
language_model = language_model_all.get("language_model", None)
language_models = language_model_all.get("language_models", None)
validation = ValidationModel(response_model, language_model, language_models)
"""
Headers: Headers which is merged with response model && language models of event
Validation: Validation of event which is merged with response model && language models of event
"""
return {
"headers": validation.headers,
# "validation": validation.validation,
# "language_models": language_model_all,
}
ValidationEventMethods.endpoint_callable = (
authentication_login_with_domain_and_creds_endpoint
)