latest version of apis event and cahce ablitites added

This commit is contained in:
2025-02-10 11:41:38 +03:00
parent e832ec7603
commit 26f601f01a
396 changed files with 34981 additions and 2 deletions

View File

@@ -0,0 +1,9 @@
"""
Authentication package initialization.
"""
from .auth.cluster import AuthCluster
__all__ = [
"AuthCluster",
]

View File

@@ -0,0 +1,200 @@
from Events.Engine.abstract_class import Event
from ApiLayers.LanguageModels.Request import (
LoginRequestLanguageModel,
SelectRequestLanguageModel,
)
from .models import AuthenticationRequestModels, AuthenticationResponseModels
from .function_handlers import AuthenticationFunctions
# Auth Login
authentication_login_super_user_event = Event(
name="authentication_login_super_user_event",
key="a5d2d0d1-3e9b-4b0f-8c7d-6d4a4b4c4d4e",
request_validator=AuthenticationRequestModels.LoginSuperUserRequestModel,
language_models=[LoginRequestLanguageModel],
statics="LOGIN_SUCCESS",
description="Login super user",
)
authentication_login_super_user_event.endpoint_callable = (
AuthenticationFunctions.authentication_login_with_domain_and_creds
)
# Auth Select Company or Occupant Type
authentication_select_super_user_event = Event(
name="authentication_select_super_user_event",
key="f951ae1a-7950-4eab-ae2d-5bd9c2d21173",
request_validator=AuthenticationRequestModels.SelectCompanyOrOccupantTypeSuperUserRequestModel,
language_models=[SelectRequestLanguageModel],
statics="LOGIN_SELECT",
description="Select company or occupant type super user",
)
authentication_select_super_user_event.endpoint_callable = (
AuthenticationFunctions.authentication_select_company_or_occupant_type
)
# Check Token Validity
authentication_check_token_event = Event(
name="authentication_check_token_event",
key="b6e3d1e2-4f9c-5c1g-9d8e-7e5f6f5e5d5f",
request_validator=None, # TODO: Add request validator
language_models=[],
# response_validator=None, # TODO: Add response validator
description="Check if token is valid",
)
authentication_check_token_event.endpoint_callable = (
AuthenticationFunctions.authentication_check_token_is_valid
)
# Refresh User Info
authentication_refresh_user_info_event = Event(
name="authentication_refresh_user_info_event",
key="c7f4e2f3-5g0d-6d2h-0e9f-8f6g7g6f6e6g",
request_validator=None, # TODO: Add request validator
language_models=[],
# response_validator=None, # TODO: Add response validator
description="Refresh user information",
)
authentication_refresh_user_info_event.endpoint_callable = (
AuthenticationFunctions.authentication_access_token_user_info
)
# Change Password
authentication_change_password_event = Event(
name="authentication_change_password_event",
key="d8g5f3g4-6h1e-7e3i-1f0g-9g7h8h7g7f7h",
request_validator=None, # TODO: Add request validator
language_models=[],
# response_validator=None, # TODO: Add response validator
description="Change user password",
)
authentication_change_password_event.endpoint_callable = (
AuthenticationFunctions.authentication_change_password
)
# Create Password
authentication_create_password_event = Event(
name="authentication_create_password_event",
key="e9h6g4h5-7i2f-8f4j-2g1h-0h8i9i8h8g8i",
request_validator=None, # TODO: Add request validator
language_models=[],
# response_validator=None, # TODO: Add response validator
description="Create new password",
)
authentication_create_password_event.endpoint_callable = (
AuthenticationFunctions.authentication_create_password
)
# Disconnect User
authentication_disconnect_user_event = Event(
name="authentication_disconnect_user_event",
key="f0i7h5i6-8j3g-9g5k-3h2i-1i9j0j9i9h9j",
request_validator=None, # TODO: Add request validator
language_models=[],
# response_validator=None, # TODO: Add response validator
description="Disconnect all user sessions",
)
authentication_disconnect_user_event.endpoint_callable = (
AuthenticationFunctions.authentication_disconnect_user
)
# Logout User
authentication_logout_user_event = Event(
name="authentication_logout_user_event",
key="g1j8i6j7-9k4h-0h6l-4i3j-2j0k1k0j0i0k",
request_validator=AuthenticationRequestModels.LogoutRequestModel,
language_models=[],
# response_validator=None, # TODO: Add response validator
description="Logout user session",
)
authentication_logout_user_event.endpoint_callable = (
AuthenticationFunctions.authentication_logout_user
)
# Refresh Token
authentication_refresher_token_event = Event(
name="authentication_refresher_token_event",
key="h2k9j7k8-0l5i-1i7m-5j4k-3k1l2l1k1j1l",
request_validator=AuthenticationRequestModels.RefresherRequestModel, # TODO: Add request validator
language_models=[],
# response_validator=None,
description="Refresh authentication token",
)
authentication_refresher_token_event.endpoint_callable = (
AuthenticationFunctions.authentication_refresher_token
)
# Forgot Password
authentication_forgot_password_event = Event(
name="authentication_forgot_password_event",
key="i3l0k8l9-1m6j-2j8n-6k5l-4l2m3m2l2k2m",
request_validator=None, # TODO: Add request validator
language_models=[],
# response_validator=None, # TODO: Add response validator
description="Request password reset",
)
authentication_forgot_password_event.endpoint_callable = (
AuthenticationFunctions.authentication_forgot_password
)
# Reset Password
authentication_reset_password_event = Event(
name="authentication_reset_password_event",
key="j4m1l9m0-2n7k-3k9o-7l6m-5m3n4n3m3l3n",
request_validator=None, # TODO: Add request validator
language_models=[],
# response_validator=None, # TODO: Add response validator
description="Reset user password",
)
authentication_reset_password_event.endpoint_callable = (
AuthenticationFunctions.authentication_reset_password
)
# Download Avatar
authentication_download_avatar_event = Event(
name="authentication_download_avatar_event",
key="k5n2m0n1-3o8l-4l0p-8m7n-6n4o5o4n4m4o",
request_validator=None, # TODO: Add request validator
language_models=[],
# response_validator=None, # TODO: Add response validator
description="Download user avatar and profile info",
)
authentication_download_avatar_event.endpoint_callable = (
AuthenticationFunctions.authentication_download_avatar
)

View File

@@ -0,0 +1,383 @@
"""
Authentication related API endpoints.
"""
from typing import Any, Dict
from fastapi import Request
from ApiLayers.Middleware import MiddlewareModule
from Events.Engine.abstract_class import MethodToEvent
from Events.base_request_model import EndpointBaseRequestModel, ContextRetrievers
from .api_events import (
authentication_login_super_user_event,
authentication_select_super_user_event,
authentication_check_token_event,
authentication_refresh_user_info_event,
authentication_change_password_event,
authentication_create_password_event,
authentication_disconnect_user_event,
authentication_logout_user_event,
authentication_refresher_token_event,
authentication_forgot_password_event,
authentication_reset_password_event,
authentication_download_avatar_event,
)
from .function_handlers import AuthenticationFunctions
AuthenticationLoginEventMethods = MethodToEvent(
name="AuthenticationLoginEventMethods",
events={
authentication_login_super_user_event.key: authentication_login_super_user_event,
},
headers=[],
errors=[],
url="/login",
method="POST",
summary="Login via domain and access key : [email] | [phone]",
description="Login to the system via domain, access key : [email] | [phone]",
)
def authentication_login_with_domain_and_creds_endpoint(
request: Request, data: EndpointBaseRequestModel
) -> Dict[str, Any]:
event_2_catch = AuthenticationLoginEventMethods.retrieve_event(
event_function_code=f"{authentication_login_super_user_event.key}"
)
data = event_2_catch.REQUEST_VALIDATOR(**data.data)
return event_2_catch.endpoint_callable(request=request, data=data)
AuthenticationLoginEventMethods.endpoint_callable = (
authentication_login_with_domain_and_creds_endpoint
)
AuthenticationSelectEventMethods = MethodToEvent(
name="AuthenticationSelectEventMethods",
events={
authentication_select_super_user_event.key: authentication_select_super_user_event,
},
decorators_list=[MiddlewareModule.auth_required],
headers=[],
errors=[],
url="/select",
method="POST",
summary="Select company or occupant type",
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.
"""
context_retriever = ContextRetrievers(
func=authentication_select_company_or_occupant_type
)
function = AuthenticationSelectEventMethods.retrieve_event(
event_function_code=f"{authentication_select_super_user_event.key}"
)
AuthenticationFunctions.context_retriever = context_retriever
data_model = None
if context_retriever.token.is_employee:
data_model = function.REQUEST_VALIDATOR.get("EmployeeSelection", None)(
**data.data
)
elif context_retriever.token.is_occupant:
data_model = function.REQUEST_VALIDATOR.get("OccupantSelection", None)(
**data.data
)
return function.endpoint_callable(data=data_model)
AuthenticationSelectEventMethods.endpoint_callable = (
authentication_select_company_or_occupant_type
)
AuthenticationCheckTokenEventMethods = MethodToEvent(
name="AuthenticationCheckTokenEventMethods",
events={authentication_check_token_event.key: authentication_check_token_event},
headers=[],
errors=[],
decorators_list=[MiddlewareModule.auth_required],
url="/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):
context_retriever = ContextRetrievers(func=authentication_check_token_is_valid)
function = AuthenticationCheckTokenEventMethods.retrieve_event(
event_function_code=f"{authentication_check_token_event.key}"
)
AuthenticationFunctions.context_retriever = context_retriever
return function.endpoint_callable()
AuthenticationCheckTokenEventMethods.endpoint_callable = (
authentication_check_token_is_valid
)
AuthenticationRefreshEventMethods = MethodToEvent(
name="AuthenticationRefreshEventMethods",
events={
authentication_refresh_user_info_event.key: authentication_refresh_user_info_event
},
headers=[],
errors=[],
decorators_list=[MiddlewareModule.auth_required],
url="/refresh",
method="POST",
summary="Refresh user info",
description="Refresh user info using access token",
)
def authentication_refresh_user_info(request: Request):
context_retriever = ContextRetrievers(func=authentication_refresh_user_info)
function = AuthenticationRefreshEventMethods.retrieve_event(
event_function_code=f"{authentication_refresh_user_info_event.key}"
)
AuthenticationFunctions.context_retriever = context_retriever
return function.endpoint_callable()
AuthenticationRefreshEventMethods.endpoint_callable = authentication_refresh_user_info
AuthenticationChangePasswordEventMethods = MethodToEvent(
name="AuthenticationChangePasswordEventMethods",
events={
authentication_change_password_event.key: authentication_change_password_event
},
headers=[],
errors=[],
decorators_list=[MiddlewareModule.auth_required],
url="/change-password",
method="POST",
summary="Change password",
description="Change password with access token",
)
def authentication_change_password_event_callable(
request: Request, data: EndpointBaseRequestModel
):
context_retriever = ContextRetrievers(
func=authentication_change_password_event_callable
)
function = AuthenticationChangePasswordEventMethods.retrieve_event(
event_function_code=f"{authentication_change_password_event.key}"
)
AuthenticationFunctions.context_retriever = context_retriever
return function.endpoint_callable(data=data)
AuthenticationChangePasswordEventMethods.endpoint_callable = (
authentication_change_password_event_callable
)
AuthenticationCreatePasswordEventMethods = MethodToEvent(
name="AuthenticationCreatePasswordEventMethods",
events={
authentication_create_password_event.key: authentication_create_password_event
},
headers=[],
errors=[],
url="/create-password",
method="POST",
summary="Create password",
description="Create password with password reset token requested via email",
)
def authentication_create_password(request: Request, data: EndpointBaseRequestModel):
context_retriever = ContextRetrievers(func=authentication_create_password)
function = AuthenticationCreatePasswordEventMethods.retrieve_event(
event_function_code=f"{authentication_create_password_event.key}"
)
AuthenticationFunctions.context_retriever = context_retriever
return function.endpoint_callable(data=data)
AuthenticationCreatePasswordEventMethods.endpoint_callable = (
authentication_create_password
)
AuthenticationDisconnectUserEventMethods = MethodToEvent(
name="AuthenticationDisconnectUserEventMethods",
events={
authentication_disconnect_user_event.key: authentication_disconnect_user_event
},
decorators_list=[MiddlewareModule.auth_required],
headers=[],
errors=[],
url="/disconnect",
method="POST",
summary="Disconnect all sessions",
description="Disconnect all sessions of user in access token",
)
def authentication_disconnect_user(request: Request):
context_retriever = ContextRetrievers(func=authentication_disconnect_user)
function = AuthenticationDisconnectUserEventMethods.retrieve_event(
event_function_code=f"{authentication_disconnect_user_event.key}"
)
AuthenticationFunctions.context_retriever = context_retriever
return function.endpoint_callable()
AuthenticationDisconnectUserEventMethods.endpoint_callable = (
authentication_disconnect_user
)
AuthenticationLogoutEventMethods = MethodToEvent(
name="AuthenticationLogoutEventMethods",
events={authentication_logout_user_event.key: authentication_logout_user_event},
headers=[],
errors=[],
decorators_list=[MiddlewareModule.auth_required],
url="/logout",
method="POST",
summary="Logout user",
description="Logout only single session of user which domain is provided",
)
def authentication_logout_user(request: Request, data: EndpointBaseRequestModel):
context_retriever = ContextRetrievers(func=authentication_logout_user)
function = AuthenticationLogoutEventMethods.retrieve_event(
event_function_code=f"{authentication_logout_user_event.key}"
)
validated_data = function.REQUEST_VALIDATOR(**data.data)
AuthenticationFunctions.context_retriever = context_retriever
return function.endpoint_callable(data=validated_data)
AuthenticationLogoutEventMethods.endpoint_callable = authentication_logout_user
AuthenticationRefreshTokenEventMethods = MethodToEvent(
name="AuthenticationRefreshTokenEventMethods",
events={
authentication_refresher_token_event.key: authentication_refresher_token_event
},
headers=[],
errors=[],
decorators_list=[],
url="/refresh-token",
method="POST",
summary="Refresh token",
description="Refresh access token with refresher token",
)
def authentication_refresher_token(request: Request, data: EndpointBaseRequestModel):
function = AuthenticationRefreshTokenEventMethods.retrieve_event(
event_function_code=f"{authentication_refresher_token_event.key}"
)
validated_data = function.REQUEST_VALIDATOR(**data.data)
return function.endpoint_callable(request=request, data=validated_data)
AuthenticationRefreshTokenEventMethods.endpoint_callable = (
authentication_refresher_token
)
AuthenticationForgotPasswordEventMethods = MethodToEvent(
name="AuthenticationForgotPasswordEventMethods",
events={
authentication_forgot_password_event.key: authentication_forgot_password_event
},
headers=[],
errors=[],
url="/forgot-password",
method="POST",
summary="Request password reset",
description="Send an email to user for a valid password reset token",
)
def authentication_forgot_password(request: Request, data: EndpointBaseRequestModel):
context_retriever = ContextRetrievers(func=authentication_forgot_password)
function = AuthenticationForgotPasswordEventMethods.retrieve_event(
event_function_code=f"{authentication_forgot_password_event.key}"
)
AuthenticationFunctions.context_retriever = context_retriever
return function.endpoint_callable(data=data)
AuthenticationForgotPasswordEventMethods.endpoint_callable = (
authentication_forgot_password
)
AuthenticationResetPasswordEventMethods = MethodToEvent(
name="AuthenticationResetPasswordEventMethods",
events={
authentication_reset_password_event.key: authentication_reset_password_event
},
headers=[],
errors=[],
decorators_list=[MiddlewareModule.auth_required],
url="/reset-password",
method="POST",
summary="Reset password",
description="Reset user password",
)
def authentication_reset_password(request: Request, data: EndpointBaseRequestModel):
context_retriever = ContextRetrievers(func=authentication_reset_password)
function = AuthenticationResetPasswordEventMethods.retrieve_event(
event_function_code=f"{authentication_reset_password_event.key}"
)
AuthenticationFunctions.context_retriever = context_retriever
return function.endpoint_callable(data=data.data)
AuthenticationResetPasswordEventMethods.endpoint_callable = (
authentication_reset_password
)
AuthenticationDownloadAvatarEventMethods = MethodToEvent(
name="AuthenticationDownloadAvatarEventMethods",
events={
authentication_download_avatar_event.key: authentication_download_avatar_event
},
headers=[],
errors=[],
decorators_list=[MiddlewareModule.auth_required],
url="/download-avatar",
method="POST",
summary="Download avatar",
description="Download avatar icon and profile info of user",
)
def authentication_download_avatar(request: Request):
context_retriever = ContextRetrievers(func=authentication_download_avatar)
function = AuthenticationDownloadAvatarEventMethods.retrieve_event(
event_function_code=f"{authentication_download_avatar_event.key}"
)
AuthenticationFunctions.context_retriever = context_retriever
return function.endpoint_callable()
AuthenticationDownloadAvatarEventMethods.endpoint_callable = (
authentication_download_avatar
)

View File

@@ -0,0 +1,42 @@
from Events.Engine.abstract_class import CategoryCluster
from .info import authentication_page_info
from .auth import (
AuthenticationLoginEventMethods,
AuthenticationLogoutEventMethods,
AuthenticationRefreshTokenEventMethods,
AuthenticationForgotPasswordEventMethods,
AuthenticationChangePasswordEventMethods,
AuthenticationCheckTokenEventMethods,
AuthenticationCreatePasswordEventMethods,
AuthenticationDisconnectUserEventMethods,
AuthenticationDownloadAvatarEventMethods,
AuthenticationResetPasswordEventMethods,
AuthenticationRefreshEventMethods,
AuthenticationSelectEventMethods,
)
AuthCluster = CategoryCluster(
name="AuthCluster",
tags=["authentication"],
prefix="/authentication",
description="Authentication cluster",
pageinfo=authentication_page_info,
endpoints={
"AuthenticationLoginEventMethods": AuthenticationLoginEventMethods,
"AuthenticationLogoutEventMethods": AuthenticationLogoutEventMethods,
"AuthenticationRefreshTokenEventMethods": AuthenticationRefreshTokenEventMethods,
"AuthenticationForgotPasswordEventMethods": AuthenticationForgotPasswordEventMethods,
"AuthenticationChangePasswordEventMethods": AuthenticationChangePasswordEventMethods,
"AuthenticationCheckTokenEventMethods": AuthenticationCheckTokenEventMethods,
"AuthenticationCreatePasswordEventMethods": AuthenticationCreatePasswordEventMethods,
"AuthenticationDisconnectUserEventMethods": AuthenticationDisconnectUserEventMethods,
"AuthenticationDownloadAvatarEventMethods": AuthenticationDownloadAvatarEventMethods,
"AuthenticationResetPasswordEventMethods": AuthenticationResetPasswordEventMethods,
"AuthenticationRefreshEventMethods": AuthenticationRefreshEventMethods,
"AuthenticationSelectEventMethods": AuthenticationSelectEventMethods,
},
include_in_schema=True,
sub_category=[],
)

View File

@@ -0,0 +1,529 @@
from typing import Any, Union
from fastapi import Request
from ApiLayers.ApiLibrary.common.line_number import get_line_number_for_error
from ApiLayers.ApiServices.Login.user_login_handler import UserLoginModule
from ApiLayers.ApiServices.Token.token_handler import TokenService
from ApiLayers.ApiValidations.Custom.token_objects import CompanyToken, OccupantToken
from ApiLayers.ApiValidations.Response.default_response import (
EndpointSuccessResponse,
EndpointNotAcceptableResponse,
EndpointBadRequestResponse,
)
from ApiLayers.ErrorHandlers import HTTPExceptionApi
from ApiLayers.Schemas import (
BuildLivingSpace,
BuildParts,
RelationshipEmployee2Build,
Companies,
Departments,
Duties,
Duty,
Staff,
Employees,
Event2Employee,
Event2Occupant,
OccupantTypes,
Users,
UsersTokens,
)
from Events.base_request_model import TokenDictType, BaseRouteModel
from Services.Redis.Actions.actions import RedisActions
from ApiLayers.AllConfigs.Redis.configs import RedisAuthKeys
class Handlers:
"""Class for handling authentication functions"""
@classmethod # Requires no auth context
def handle_employee_selection(
cls, request: Request, data: Any, token_dict: TokenDictType
):
db = Users.new_session()
if data.company_uu_id not in token_dict.companies_uu_id_list:
raise HTTPExceptionApi(
error_code="HTTP_400_BAD_REQUEST",
lang=token_dict.lang,
loc=get_line_number_for_error(),
sys_msg="Company not found in token",
)
selected_company: Companies = Companies.filter_one(
Companies.uu_id == data.company_uu_id, db=db
).data
if not selected_company:
raise HTTPExceptionApi(
error_code="HTTP_400_BAD_REQUEST",
lang=token_dict.lang,
loc=get_line_number_for_error(),
sys_msg="Company not found in token",
)
# Get duties IDs for the company
duties_ids = [
duty.id
for duty in Duties.filter_all(
Duties.company_id == selected_company.id, db=db
).data
]
# Get staff IDs
staff_ids = [
staff.id
for staff in Staff.filter_all(Staff.duties_id.in_(duties_ids), db=db).data
]
# Get employee
employee: Employees = Employees.filter_one(
Employees.people_id == token_dict.person_id,
Employees.staff_id.in_(staff_ids),
db=db,
).data
if not employee:
raise HTTPExceptionApi(
error_code="HTTP_400_BAD_REQUEST",
lang=token_dict.lang,
loc=get_line_number_for_error(),
sys_msg="Employee not found in token",
)
# Get reachable events
reachable_event_codes = Event2Employee.get_event_codes(employee_id=employee.id)
# Get staff and duties
staff = Staff.filter_one(Staff.id == employee.staff_id, db=db).data
duties = Duties.filter_one(Duties.id == staff.duties_id, db=db).data
department = Departments.filter_one(
Departments.id == duties.department_id, db=db
).data
# Get bulk duty
bulk_id = Duty.filter_by_one(system=True, duty_code="BULK", db=db).data
bulk_duty_id = Duties.filter_by_one(
company_id=selected_company.id,
duties_id=bulk_id.id,
db=db,
).data
# Create company token
company_token = CompanyToken(
company_uu_id=selected_company.uu_id.__str__(),
company_id=selected_company.id,
department_id=department.id,
department_uu_id=department.uu_id.__str__(),
duty_id=duties.id,
duty_uu_id=duties.uu_id.__str__(),
bulk_duties_id=bulk_duty_id.id,
staff_id=staff.id,
staff_uu_id=staff.uu_id.__str__(),
employee_id=employee.id,
employee_uu_id=employee.uu_id.__str__(),
reachable_event_codes=reachable_event_codes,
)
try: # Update Redis
return TokenService.update_token_at_redis(
request=request, add_payload=company_token
)
except Exception as e:
raise HTTPExceptionApi(
error_code="",
lang="en",
loc=get_line_number_for_error(),
sys_msg=f"{e}",
)
@classmethod # Requires no auth context
def handle_occupant_selection(
cls, request: Request, data: Any, token_dict: TokenDictType
):
"""Handle occupant type selection"""
db = BuildLivingSpace.new_session()
# Get selected occupant type
selected_build_living_space: BuildLivingSpace = BuildLivingSpace.filter_one(
BuildLivingSpace.uu_id == data.build_living_space_uu_id,
db=db,
).data
if not selected_build_living_space:
raise HTTPExceptionApi(
error_code="HTTP_400_BAD_REQUEST",
lang=token_dict.lang,
loc=get_line_number_for_error(),
sys_msg="Selected occupant type not found",
)
# Get reachable events
reachable_event_codes = Event2Occupant.get_event_codes(
build_living_space_id=selected_build_living_space.id
)
occupant_type = OccupantTypes.filter_one_system(
OccupantTypes.id == selected_build_living_space.occupant_type_id,
db=db,
).data
build_part = BuildParts.filter_one(
BuildParts.id == selected_build_living_space.build_parts_id,
db=db,
).data
build = BuildParts.filter_one(
BuildParts.id == build_part.build_id,
db=db,
).data
responsible_employee = Employees.filter_one(
Employees.id == build_part.responsible_employee_id,
db=db,
).data
related_company = RelationshipEmployee2Build.filter_one(
RelationshipEmployee2Build.member_id == build.id,
db=db,
).data
# Get company
company_related = Companies.filter_one(
Companies.id == related_company.company_id,
db=db,
).data
# Create occupant token
occupant_token = OccupantToken(
living_space_id=selected_build_living_space.id,
living_space_uu_id=selected_build_living_space.uu_id.__str__(),
occupant_type_id=occupant_type.id,
occupant_type_uu_id=occupant_type.uu_id.__str__(),
occupant_type=occupant_type.occupant_type,
build_id=build.id,
build_uuid=build.uu_id.__str__(),
build_part_id=build_part.id,
build_part_uuid=build_part.uu_id.__str__(),
responsible_employee_id=responsible_employee.id,
responsible_employee_uuid=responsible_employee.uu_id.__str__(),
responsible_company_id=company_related.id,
responsible_company_uuid=company_related.uu_id.__str__(),
reachable_event_codes=reachable_event_codes,
)
try: # Update Redis
return TokenService.update_token_at_redis(
request=request, add_payload=occupant_token
)
except Exception as e:
raise HTTPExceptionApi(
error_code="",
lang="en",
loc=get_line_number_for_error(),
sys_msg=f"{e}",
)
class AuthenticationFunctions(BaseRouteModel):
"""Class for handling authentication functions"""
@classmethod # Requires no auth context
def authentication_login_with_domain_and_creds(cls, request: Request, data: Any):
"""
Authenticate user with domain and credentials.
Args:
request: FastAPI request object
data: Request body containing login credentials
{
"data": {
"domain": "evyos.com.tr",
"access_key": "karatay.berkay.sup@evyos.com.tr",
"password": "string",
"remember_me": false
}
}
Returns:
SuccessResponse containing authentication token and user info
"""
# Get token from login module
user_login_module = UserLoginModule(request=request)
user_login_module.login_user_via_credentials(access_data=data)
user_login_module.language = "en"
# Return response with token and headers
return EndpointSuccessResponse(
code="LOGIN_SUCCESS", lang=user_login_module.language
).as_dict(data=user_login_module.as_dict)
@classmethod # Requires auth context
def authentication_select_company_or_occupant_type(cls, data: Any):
"""
Handle selection of company or occupant type
{"data": {"build_living_space_uu_id": ""}} | {"data": {"company_uu_id": ""}}
{
"data": {"company_uu_id": "e9869a25-ba4d-49dc-bb0d-8286343b184b"}
}
{
"data": {"build_living_space_uu_id": "e9869a25-ba4d-49dc-bb0d-8286343b184b"}
}
"""
selection_dict = dict(
request=cls.context_retriever.request,
token_dict=cls.context_retriever.token,
data=data,
)
if cls.context_retriever.token.is_employee:
if Handlers.handle_employee_selection(**selection_dict):
return EndpointSuccessResponse(
code="LOGIN_SELECT", lang=cls.context_retriever.token.lang
).as_dict(
data={"selected": data.company_uu_id, **cls.context_retriever.base}
)
elif cls.context_retriever.token.is_occupant:
if Handlers.handle_occupant_selection(**selection_dict):
return EndpointSuccessResponse(
code="LOGIN_SELECT", lang=cls.context_retriever.token.lang
).as_dict(
data={
"selected": data.build_living_space_uu_id,
**cls.context_retriever.base,
}
)
@classmethod # Requires auth context
def authentication_check_token_is_valid(cls):
"""Check if token is valid for user"""
if cls.context_retriever.token:
return EndpointSuccessResponse(
code="TOKEN_VALID", lang=cls.context_retriever.token.lang
).as_dict(data=cls.context_retriever.base)
return {
"completed": False,
"message": "Token is not valid",
}
@classmethod # Requires not auth context
def authentication_access_token_user_info(cls):
"""Refresh user info using access token"""
if cls.context_retriever.token:
db = Users.new_session()
if found_user := Users.filter_one(
Users.id == cls.context_retriever.token.user_id, db=db
).data:
return EndpointSuccessResponse(
code="USER_INFO_REFRESHED", lang=cls.context_retriever.token.lang
).as_dict(
{
"access_token": cls.context_retriever.get_token,
"user": found_user.get_dict(),
}
)
if not found_user:
return EndpointNotAcceptableResponse(
code="USER_NOT_FOUND", lang=cls.context_retriever.token.lang
).as_dict(data={})
@classmethod # Requires no auth context
def authentication_change_password(cls, data: Any):
"""Change password with access token"""
if cls.context_retriever.token:
db = Users.new_session()
if found_user := Users.filter_one(
Users.id == cls.context_retriever.token.user_id, db=db
).data:
found_user.set_password(data.new_password)
return EndpointSuccessResponse(
code="PASSWORD_CHANGED", lang=cls.context_retriever.token.lang
).as_dict(data={"user": found_user.get_dict()})
if not found_user:
return EndpointNotAcceptableResponse(
code="USER_NOT_FOUND", lang=cls.context_retriever.token.lang
).as_dict(data={})
@classmethod # Requires not auth context
def authentication_create_password(cls, data: Any):
"""Create password with password reset token requested via email"""
db = Users.new_session()
if not data.re_password == data.password:
return EndpointNotAcceptableResponse(
code="PASSWORD_NOT_MATCH", lang=cls.context_retriever.token.lang
).as_dict(data={"password": data.password, "re_password": data.re_password})
if found_user := Users.filter_one(
Users.password_token == data.password_token, db=db
).data:
found_user.create_password(found_user=found_user, password=data.password)
found_user.password_token = ""
found_user.save()
return EndpointSuccessResponse(
code="CREATED_PASSWORD", lang=cls.context_retriever.token.lang
).as_dict(data={"user": found_user.get_dict()})
@classmethod # Requires auth context
def authentication_disconnect_user(cls):
"""Disconnect all sessions of user in access token"""
db = Users.new_session()
found_user = Users.filter_one_system(
Users.id == cls.context_retriever.token.user_id, db=db
).data
if not found_user:
return EndpointNotAcceptableResponse(
code="USER_NOT_FOUND", lang=cls.context_retriever.token.lang
).as_dict(data={})
registered_tokens = UsersTokens.filter_all(
UsersTokens.user_id == cls.context_retriever.token.user_id, db=db
)
if registered_tokens.count:
registered_tokens.query.delete()
UsersTokens.save(db=db)
RedisActions.delete(
list_keys=[f"{RedisAuthKeys.AUTH}:*:{str(found_user.uu_id)}"]
)
return EndpointSuccessResponse(
code="DISCONNECTED_USER", lang=cls.context_retriever.token.lang
).as_dict(data={"user": found_user.get_dict()})
@classmethod # Requires auth context
def authentication_logout_user(cls, data: Any):
"""Logout only single session of user which domain is provided"""
db = Users.new_session()
found_user = Users.filter_one_system(
Users.id == cls.context_retriever.token.user_id, db=db
).data
if not found_user:
return EndpointNotAcceptableResponse(
code="USER_NOT_FOUND", lang=cls.context_retriever.token.lang
).as_dict(data={})
registered_tokens = UsersTokens.filter_all_system(
UsersTokens.user_id == cls.context_retriever.token.user_id,
UsersTokens.domain == cls.context_retriever.token.domain,
db=db,
)
if registered_tokens.count:
registered_tokens.query.delete()
UsersTokens.save(db=db)
TokenService.remove_token_with_domain(user=found_user, domain=data.domain)
return EndpointSuccessResponse(
code="LOGOUT_USER", lang=cls.context_retriever.token.lang
).as_dict(data={"user": found_user.get_dict()})
@classmethod # Requires not auth context
def authentication_refresher_token(cls, request: Request, data: Any):
"""
Refresh access token with refresher token
{
"data": {
"refresh_token": "string",
"domain": "string"
}
}
"""
import arrow
from ApiLayers.ApiServices.Token.token_handler import TokenService
db = UsersTokens.new_session()
token_refresher: UsersTokens = UsersTokens.filter_by_one(
token=data.refresh_token,
domain=data.domain,
db=db,
).data
language = request.headers.get("evyos-language", "tr")
if not token_refresher:
return EndpointNotAcceptableResponse(
code="REFRESHER_NOT_FOUND", lang=language
).as_dict(data={"refresh_token": data.refresh_token})
if found_user := Users.filter_one(
Users.id == token_refresher.user_id, db=db
).data:
token_created = TokenService.set_access_token_to_redis(
request=request,
user=found_user,
domain=data.domain,
remember=True,
)
found_user.last_agent = request.headers.get("User-Agent", None)
found_user.last_platform = request.headers.get("Origin", None)
found_user.last_remote_addr = getattr(
request, "remote_addr", None
) or request.headers.get("X-Forwarded-For", None)
found_user.last_seen = str(arrow.now())
response_data = {
"access_token": token_created.get("access_token"),
"refresh_token": data.refresh_token,
}
return EndpointSuccessResponse(code="TOKEN_REFRESH", lang=language).as_dict(
data=response_data
)
raise EndpointNotAcceptableResponse(
code="USER_NOT_FOUND", lang=language
).as_dict(data={})
@classmethod # Requires not auth context
def authentication_forgot_password(cls, data: Any):
"""Send an email to user for a valid password reset token"""
import arrow
from ApiLayers.ApiServices.Token.token_handler import TokenService
from ApiLayers.AllConfigs.Templates.password_templates import (
change_your_password_template,
)
from Services.Email.send_email import email_sender
from config import ApiStatic
db = Users.new_session()
request = cls.context_retriever.request
found_user: Users = Users.check_user_exits(
access_key=data.access_key, domain=data.domain
)
forgot_key = TokenService._create_access_token(access=False)
forgot_link = ApiStatic.forgot_link(forgot_key=forgot_key)
send_email_completed = email_sender.send_email(
subject=f"Dear {found_user.user_tag}, your forgot password link has been sent.",
receivers=[str(found_user.email)],
html=change_your_password_template(
user_name=found_user.user_tag, forgot_link=forgot_link
),
)
if not send_email_completed:
return EndpointBadRequestResponse(
code="EMAIL_NOT_SENT", lang=cls.context_retriever.token.lang
).as_dict(data={"email": found_user.email})
found_user.password_token = forgot_key
found_user.password_token_is_valid = str(arrow.now().shift(days=1))
found_user.save(db=db)
return EndpointSuccessResponse(
code="FORGOT_PASSWORD", lang=cls.context_retriever.token.lang
).as_dict(
data={
"user": found_user.get_dict(),
"forgot_link": forgot_link,
"token": forgot_key,
}
)
@classmethod # Requires not auth context
def authentication_reset_password(cls, data: Any):
"""Reset password with forgot password token"""
return cls.context_retriever.base
@classmethod # Requires not auth context
def authentication_download_avatar(cls):
"""Download avatar icon and profile info of user"""
import arrow
db = Users.new_session()
if found_user := Users.filter_one(
Users.id == cls.context_retriever.token.user_id, db=db
).data:
expired_starts = str(arrow.now() - arrow.get(str(found_user.expiry_ends)))
expired_int = (
arrow.now().datetime - arrow.get(str(found_user.expiry_ends)).datetime
)
user_info = {
"lang": cls.context_retriever.token.lang,
"full_name": found_user.person.full_name,
"avatar": found_user.avatar,
"remember_me": found_user.remember_me,
"expiry_ends": str(found_user.expiry_ends),
"expired_humanized": expired_starts,
"expired_day": int(expired_int.days) * -1,
}
return EndpointSuccessResponse(
code="USER_AVATAR", lang=cls.context_retriever.token.lang
).as_dict(data=user_info)
return EndpointNotAcceptableResponse(
code="USER_NOT_FOUND", lang=cls.context_retriever.token.lang
).as_dict(data={})

View File

@@ -0,0 +1,11 @@
from Events.Engine.abstract_class import PageInfo
authentication_page_info = PageInfo(
name="Authentication",
url="",
language_models={},
endpoints={},
icon="Authentication",
sub_components=[],
)

View File

@@ -0,0 +1,24 @@
from ApiLayers.ApiValidations.Request import (
Login,
EmployeeSelection,
OccupantSelection,
Logout,
CreatePassword,
ChangePassword,
Forgot,
Remember,
)
class AuthenticationRequestModels:
LoginSuperUserRequestModel = Login
SelectCompanyOrOccupantTypeSuperUserRequestModel = {
"EmployeeSelection": EmployeeSelection,
"OccupantSelection": OccupantSelection,
}
RefresherRequestModel = Remember
LogoutRequestModel = Logout
class AuthenticationResponseModels:
pass