new api service and logic implemented
This commit is contained in:
9
Events/AllEvents/authentication/__init__.py
Normal file
9
Events/AllEvents/authentication/__init__.py
Normal file
@@ -0,0 +1,9 @@
|
||||
"""
|
||||
Authentication package initialization.
|
||||
"""
|
||||
|
||||
from .auth import AUTH_CONFIG
|
||||
|
||||
__all__ = [
|
||||
"AUTH_CONFIG",
|
||||
]
|
||||
154
Events/AllEvents/authentication/auth/api_events.py
Normal file
154
Events/AllEvents/authentication/auth/api_events.py
Normal file
@@ -0,0 +1,154 @@
|
||||
from uuid import UUID
|
||||
from Events.Engine.abstract_class import Event
|
||||
|
||||
from .models import (
|
||||
LoginSuperUserRequestModel,
|
||||
LoginSuperUserResponseModel,
|
||||
SelectCompanyOrOccupantTypeSuperUserRequestModel,
|
||||
SelectCompanyOrOccupantTypeSuperUserResponseModel,
|
||||
EmployeeSelectionSuperUserRequestModel,
|
||||
EmployeeSelectionSuperUserResponseModel,
|
||||
OccupantSelectionSuperUserRequestModel,
|
||||
OccupantSelectionSuperUserResponseModel,
|
||||
)
|
||||
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,
|
||||
authentication_create_password,
|
||||
authentication_disconnect_user,
|
||||
authentication_logout_user,
|
||||
authentication_refresher_token,
|
||||
authentication_forgot_password,
|
||||
authentication_reset_password,
|
||||
authentication_download_avatar,
|
||||
)
|
||||
|
||||
|
||||
# Auth Login
|
||||
authentication_login_super_user_event = Event(
|
||||
key=UUID("a5d2d0d1-3e9b-4b0f-8c7d-6d4a4b4c4d4e"),
|
||||
request_validator=LoginSuperUserRequestModel,
|
||||
response_validator=LoginSuperUserResponseModel,
|
||||
description="Login super user",
|
||||
)
|
||||
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"),
|
||||
request_validator=SelectCompanyOrOccupantTypeSuperUserRequestModel,
|
||||
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_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"),
|
||||
request_validator=None, # TODO: Add request 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"),
|
||||
request_validator=None, # TODO: Add request validator
|
||||
response_validator=None, # TODO: Add response validator
|
||||
description="Refresh user information",
|
||||
)
|
||||
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"),
|
||||
request_validator=None, # TODO: Add request 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"),
|
||||
request_validator=None, # TODO: Add request 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"),
|
||||
request_validator=None, # TODO: Add request 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"),
|
||||
request_validator=None, # TODO: Add request 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"),
|
||||
request_validator=None, # TODO: Add request 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"),
|
||||
request_validator=None, # TODO: Add request 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"),
|
||||
request_validator=None, # TODO: Add request 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"),
|
||||
request_validator=None, # TODO: Add request validator
|
||||
response_validator=None, # TODO: Add response validator
|
||||
description="Download user avatar and profile info",
|
||||
)
|
||||
authentication_download_avatar_event.endpoint_callable = authentication_download_avatar
|
||||
168
Events/AllEvents/authentication/auth/auth.py
Normal file
168
Events/AllEvents/authentication/auth/auth.py
Normal file
@@ -0,0 +1,168 @@
|
||||
"""
|
||||
Authentication related API endpoints.
|
||||
"""
|
||||
|
||||
from typing import Union
|
||||
|
||||
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 .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,
|
||||
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,
|
||||
)
|
||||
|
||||
|
||||
# Type aliases for common types
|
||||
TokenDictType = Union["EmployeeTokenObject", "OccupantTokenObject"]
|
||||
|
||||
|
||||
AuthenticationLoginEventMethods = MethodToEvent(
|
||||
events=[authentication_login_super_user_event],
|
||||
headers=[],
|
||||
errors=[],
|
||||
url="/authentication/login",
|
||||
method="POST",
|
||||
summary="Login via domain and access key : [email] | [phone]",
|
||||
description="Login to the system via domain, access key : [email] | [phone]",
|
||||
)
|
||||
|
||||
|
||||
AuthenticationSelectEventMethods = MethodToEvent(
|
||||
events=[
|
||||
authentication_select_company_or_occupant_type_super_user_event,
|
||||
authentication_employee_selection_super_user_event,
|
||||
authentication_occupant_selection_super_user_event
|
||||
],
|
||||
headers=[],
|
||||
errors=[],
|
||||
url="/authentication/select",
|
||||
method="POST",
|
||||
summary="Select company or occupant type",
|
||||
description="Select company or occupant type",
|
||||
)
|
||||
|
||||
|
||||
AuthenticationCheckTokenEventMethods = MethodToEvent(
|
||||
events=[authentication_check_token_event],
|
||||
headers=[],
|
||||
errors=[],
|
||||
url="/authentication/check-token",
|
||||
method="POST",
|
||||
summary="Check if token is valid",
|
||||
description="Check if access token is valid for user",
|
||||
)
|
||||
|
||||
|
||||
AuthenticationRefreshEventMethods = MethodToEvent(
|
||||
events=[authentication_refresh_user_info_event],
|
||||
headers=[],
|
||||
errors=[],
|
||||
url="/authentication/refresh",
|
||||
method="POST",
|
||||
summary="Refresh user info",
|
||||
description="Refresh user info using access token",
|
||||
)
|
||||
|
||||
|
||||
AuthenticationChangePasswordEventMethods = MethodToEvent(
|
||||
events=[authentication_change_password_event],
|
||||
headers=[],
|
||||
errors=[],
|
||||
url="/authentication/change-password",
|
||||
method="POST",
|
||||
summary="Change password",
|
||||
description="Change password with access token",
|
||||
)
|
||||
|
||||
|
||||
AuthenticationCreatePasswordEventMethods = MethodToEvent(
|
||||
events=[authentication_create_password_event],
|
||||
headers=[],
|
||||
errors=[],
|
||||
url="/authentication/create-password",
|
||||
method="POST",
|
||||
summary="Create password",
|
||||
description="Create password with password reset token requested via email",
|
||||
)
|
||||
|
||||
|
||||
AuthenticationDisconnectUserEventMethods = MethodToEvent(
|
||||
events=[authentication_disconnect_user_event],
|
||||
headers=[],
|
||||
errors=[],
|
||||
url="/authentication/disconnect",
|
||||
method="POST",
|
||||
summary="Disconnect all sessions",
|
||||
description="Disconnect all sessions of user in access token",
|
||||
)
|
||||
|
||||
|
||||
AuthenticationLogoutEventMethods = MethodToEvent(
|
||||
events=[authentication_logout_user_event],
|
||||
headers=[],
|
||||
errors=[],
|
||||
url="/authentication/logout",
|
||||
method="POST",
|
||||
summary="Logout user",
|
||||
description="Logout only single session of user which domain is provided",
|
||||
)
|
||||
|
||||
|
||||
AuthenticationRefreshTokenEventMethods = MethodToEvent(
|
||||
events=[authentication_refresher_token_event],
|
||||
headers=[],
|
||||
errors=[],
|
||||
url="/authentication/refresh-token",
|
||||
method="POST",
|
||||
summary="Refresh token",
|
||||
description="Refresh access token with refresher token",
|
||||
)
|
||||
|
||||
|
||||
AuthenticationForgotPasswordEventMethods = MethodToEvent(
|
||||
events=[authentication_forgot_password_event],
|
||||
headers=[],
|
||||
errors=[],
|
||||
url="/authentication/forgot-password",
|
||||
method="POST",
|
||||
summary="Request password reset",
|
||||
description="Send an email to user for a valid password reset token",
|
||||
)
|
||||
|
||||
|
||||
AuthenticationResetPasswordEventMethods = MethodToEvent(
|
||||
events=[authentication_reset_password_event],
|
||||
headers=[],
|
||||
errors=[],
|
||||
url="/authentication/reset-password",
|
||||
method="POST",
|
||||
summary="Reset password",
|
||||
description="Reset user password",
|
||||
)
|
||||
|
||||
|
||||
AuthenticationDownloadAvatarEventMethods = MethodToEvent(
|
||||
events=[authentication_download_avatar_event],
|
||||
headers=[],
|
||||
errors=[],
|
||||
url="/authentication/download-avatar",
|
||||
method="POST",
|
||||
summary="Download avatar",
|
||||
description="Download avatar icon and profile info of user",
|
||||
)
|
||||
41
Events/AllEvents/authentication/auth/cluster.py
Normal file
41
Events/AllEvents/authentication/auth/cluster.py
Normal file
@@ -0,0 +1,41 @@
|
||||
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(
|
||||
tags=["authentication"],
|
||||
prefix="/authentication",
|
||||
description="Authentication cluster",
|
||||
pageinfo=authentication_page_info,
|
||||
endpoints=[
|
||||
AuthenticationLoginEventMethods,
|
||||
AuthenticationLogoutEventMethods,
|
||||
AuthenticationRefreshTokenEventMethods,
|
||||
AuthenticationForgotPasswordEventMethods,
|
||||
AuthenticationChangePasswordEventMethods,
|
||||
AuthenticationCheckTokenEventMethods,
|
||||
AuthenticationCreatePasswordEventMethods,
|
||||
AuthenticationDisconnectUserEventMethods,
|
||||
AuthenticationDownloadAvatarEventMethods,
|
||||
AuthenticationResetPasswordEventMethods,
|
||||
AuthenticationRefreshEventMethods,
|
||||
AuthenticationSelectEventMethods,
|
||||
],
|
||||
include_in_schema=True,
|
||||
sub_category=[],
|
||||
)
|
||||
481
Events/AllEvents/authentication/auth/function_handlers.py
Normal file
481
Events/AllEvents/authentication/auth/function_handlers.py
Normal file
@@ -0,0 +1,481 @@
|
||||
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 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
|
||||
from ApiLayers.ApiValidations.Custom.token_objects import CompanyToken, OccupantToken
|
||||
from ApiLayers.ErrorHandlers import HTTPExceptionApi
|
||||
from ApiLayers.Schemas import (
|
||||
BuildLivingSpace,
|
||||
BuildParts,
|
||||
RelationshipEmployee2Build,
|
||||
Companies,
|
||||
Departments,
|
||||
Duties,
|
||||
Duty,
|
||||
Staff,
|
||||
Employees,
|
||||
Event2Employee,
|
||||
Event2Occupant,
|
||||
OccupantTypes,
|
||||
Users
|
||||
)
|
||||
from ApiLayers.ApiServices.Token.token_handler import OccupantTokenObject, EmployeeTokenObject
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from fastapi import Request
|
||||
|
||||
|
||||
# Type aliases for common types
|
||||
TokenDictType = Union["EmployeeTokenObject", "OccupantTokenObject"]
|
||||
|
||||
|
||||
def authentication_login_with_domain_and_creds(request: Request, data: Any):
|
||||
"""
|
||||
Authenticate user with domain and credentials.
|
||||
|
||||
Args:
|
||||
request: FastAPI request object
|
||||
data: Request body containing login credentials
|
||||
{
|
||||
"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)
|
||||
token = user_login_module.login_user_via_credentials(access_data=data)
|
||||
|
||||
# Return response with token and headers
|
||||
return {
|
||||
"completed": True,
|
||||
"message": "User is logged in successfully",
|
||||
"access_token": token.get("access_token"),
|
||||
"refresh_token": token.get("refresher_token"),
|
||||
"access_object": {
|
||||
"user_type": token.get("user_type"),
|
||||
"companies_list": token.get("companies_list"),
|
||||
},
|
||||
"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()
|
||||
|
||||
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.filter_one(
|
||||
Companies.uu_id == data.company_uu_id,
|
||||
db=db_session,
|
||||
).first
|
||||
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 department IDs for the company
|
||||
department_ids = [
|
||||
dept.id
|
||||
for dept in Departments.filter_all(
|
||||
Departments.company_id == selected_company.id,
|
||||
db=db_session,
|
||||
).data
|
||||
]
|
||||
|
||||
# Get duties IDs for the company
|
||||
duties_ids = [
|
||||
duty.id
|
||||
for duty in Duties.filter_all(
|
||||
Duties.company_id == selected_company.id, db=db_session
|
||||
).data
|
||||
]
|
||||
|
||||
# Get staff IDs
|
||||
staff_ids = [
|
||||
staff.id
|
||||
for staff in Staff.filter_all(
|
||||
Staff.duties_id.in_(duties_ids), db=db_session
|
||||
).data
|
||||
]
|
||||
|
||||
# Get employee
|
||||
employee = Employees.filter_one(
|
||||
Employees.people_id == token_dict.person_id,
|
||||
Employees.staff_id.in_(staff_ids),
|
||||
db=db_session,
|
||||
).first
|
||||
|
||||
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)
|
||||
reachable_event_endpoints = Event2Employee.get_event_endpoints(
|
||||
employee_id=employee.id
|
||||
)
|
||||
|
||||
# Get staff and duties
|
||||
staff = Staff.filter_one(Staff.id == employee.staff_id, db=db_session).data
|
||||
duties = Duties.filter_one(Duties.id == staff.duties_id, db=db_session).data
|
||||
department = Departments.filter_one(
|
||||
Departments.id == duties.department_id, db=db_session
|
||||
).data
|
||||
|
||||
# Get bulk duty
|
||||
bulk_id = Duty.filter_by_one(system=True, duty_code="BULK", db=db_session).data
|
||||
bulk_duty_id = Duties.filter_by_one(
|
||||
company_id=selected_company.id,
|
||||
duties_id=bulk_id.id,
|
||||
**Duties.valid_record_dict,
|
||||
db=db_session,
|
||||
).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,
|
||||
reachable_event_endpoints=reachable_event_endpoints,
|
||||
)
|
||||
try: # Update Redis
|
||||
update_token = TokenService.update_token_at_redis(
|
||||
request=request, add_payload=company_token
|
||||
)
|
||||
return update_token
|
||||
except Exception as e:
|
||||
raise HTTPExceptionApi(
|
||||
error_code="",
|
||||
lang="en",
|
||||
loc=get_line_number_for_error(),
|
||||
sys_msg=f"{e}",
|
||||
)
|
||||
|
||||
|
||||
@AuthMiddlewareModule.auth_required
|
||||
def handle_occupant_selection(request: Request, data: Any, token_dict: TokenDictType):
|
||||
"""Handle occupant type selection"""
|
||||
db = BuildLivingSpace.new_session()
|
||||
# Get selected occupant type
|
||||
selected_build_living_space = 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
|
||||
)
|
||||
reachable_event_endpoints = Event2Occupant.get_event_endpoints(
|
||||
build_living_space_id=selected_build_living_space.id
|
||||
)
|
||||
|
||||
occupant_type = OccupantTypes.filter_one(
|
||||
OccupantTypes.id == selected_build_living_space.occupant_type_id,
|
||||
db=db,
|
||||
system=True,
|
||||
).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,
|
||||
reachable_event_endpoints=reachable_event_endpoints,
|
||||
)
|
||||
|
||||
try: # Update Redis
|
||||
update_token = TokenService.update_token_at_redis(
|
||||
request=request, add_payload=occupant_token
|
||||
)
|
||||
return update_token
|
||||
except Exception as e:
|
||||
raise HTTPExceptionApi(
|
||||
error_code="",
|
||||
lang="en",
|
||||
loc=get_line_number_for_error(),
|
||||
sys_msg=f"{e}",
|
||||
)
|
||||
|
||||
|
||||
@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)
|
||||
elif token_dict.is_occupant:
|
||||
return cls._handle_occupant_selection(data, token_dict, request)
|
||||
|
||||
|
||||
@AuthMiddlewareModule.auth_required
|
||||
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):
|
||||
# return ResponseHandler.success("Access Token is valid")
|
||||
# except HTTPException:
|
||||
# return ResponseHandler.unauthorized("Access Token is NOT valid")
|
||||
return
|
||||
|
||||
|
||||
@AuthMiddlewareModule.auth_required
|
||||
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)
|
||||
# if not access_token:
|
||||
# return ResponseHandler.unauthorized()
|
||||
|
||||
# found_user = Users.filter_one(Users.uu_id == token_dict.user_uu_id).data
|
||||
# if not found_user:
|
||||
# return ResponseHandler.not_found("User not found")
|
||||
# user_token = UsersTokens.filter_one(
|
||||
# UsersTokens.domain == found_user.domain_name,
|
||||
# UsersTokens.user_id == found_user.id,
|
||||
# UsersTokens.token_type == "RememberMe",
|
||||
# ).data
|
||||
# response_data = {
|
||||
# "access_token": access_token,
|
||||
# "refresh_token": getattr(user_token, "token", None),
|
||||
# "user": found_user.get_dict(),
|
||||
# }
|
||||
# return ResponseHandler.success(
|
||||
# "User info refreshed successfully",
|
||||
# data=response_data,
|
||||
# )
|
||||
# except Exception as e:
|
||||
# return ResponseHandler.error(str(e))
|
||||
return
|
||||
|
||||
|
||||
@AuthMiddlewareModule.auth_required
|
||||
def authentication_change_password(request: "Request", token_dict: TokenDictType, data: Any):
|
||||
"""Change password with access token"""
|
||||
# try:
|
||||
# if not isinstance(token_dict, EmployeeTokenObject):
|
||||
# return ResponseHandler.unauthorized("Only employees can change password")
|
||||
|
||||
# found_user = Users.filter_one(Users.uu_id == token_dict.user_uu_id).data
|
||||
# if not found_user:
|
||||
# return ResponseHandler.not_found("User not found")
|
||||
|
||||
# if not found_user.check_password(data.old_password):
|
||||
# return ResponseHandler.unauthorized("Old password is incorrect")
|
||||
|
||||
# found_user.set_password(data.new_password)
|
||||
# return ResponseHandler.success("Password changed successfully")
|
||||
# except Exception as e:
|
||||
# return ResponseHandler.error(str(e))
|
||||
return
|
||||
|
||||
|
||||
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")
|
||||
# if found_user := Users.filter_one(Users.password_token == data.password_token).data:
|
||||
# found_user.create_password(found_user=found_user, password=data.password)
|
||||
# found_user.password_token = ""
|
||||
# found_user.save()
|
||||
# return ResponseHandler.success("Password is created successfully", data=found_user.get_dict())
|
||||
# return ResponseHandler.not_found("Record not found")
|
||||
return
|
||||
|
||||
|
||||
@AuthMiddlewareModule.auth_required
|
||||
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:
|
||||
# return ResponseHandler.not_found("User not found")
|
||||
# if already_tokens := RedisActions.get_object_via_user_uu_id(user_id=str(found_user.uu_id)):
|
||||
# for key, token_user in already_tokens.items():
|
||||
# RedisActions.delete(key)
|
||||
# selected_user = Users.filter_one(Users.uu_id == token_user.get("uu_id")).data
|
||||
# selected_user.remove_refresher_token(domain=data.domain, disconnect=True)
|
||||
# return ResponseHandler.success("All sessions are disconnected", data=selected_user.get_dict())
|
||||
# return ResponseHandler.not_found("Invalid data")
|
||||
return
|
||||
|
||||
|
||||
def authentication_logout_user(request: "Request", data: Any, token_dict: TokenDictType):
|
||||
"""Logout only single session of user which domain is provided"""
|
||||
# token_user = None
|
||||
# if already_tokens := RedisActions.get_object_via_access_key(request=request):
|
||||
# for key in already_tokens:
|
||||
# token_user = RedisActions.get_json(key)
|
||||
# if token_user.get("domain") == data.domain:
|
||||
# RedisActions.delete(key)
|
||||
# selected_user = Users.filter_one(Users.uu_id == token_user.get("uu_id")).data
|
||||
# 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")
|
||||
return
|
||||
|
||||
|
||||
@AuthMiddlewareModule.auth_required
|
||||
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,
|
||||
# domain=data.domain,
|
||||
# **UsersTokens.valid_record_dict,
|
||||
# ).data
|
||||
# if not token_refresher:
|
||||
# return ResponseHandler.not_found("Invalid data")
|
||||
# if found_user := Users.filter_one(Users.id == token_refresher.user_id).data:
|
||||
# access_key = AuthActions.save_access_token_to_redis(
|
||||
# request=request, found_user=found_user, domain=data.domain
|
||||
# )
|
||||
# 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(system_arrow.now())
|
||||
# response_data = {
|
||||
# "access_token": access_key,
|
||||
# "refresh_token": data.refresh_token,
|
||||
# }
|
||||
# return ResponseHandler.success("User is logged in successfully via refresher token", data=response_data)
|
||||
# return ResponseHandler.not_found("Invalid data")
|
||||
return
|
||||
|
||||
|
||||
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)
|
||||
# forgot_link = ApiStatic.forgot_link(forgot_key=forgot_key)
|
||||
# send_email_completed = 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:
|
||||
# raise HTTPException(status_code=400, detail="Email can not be sent. Try again later")
|
||||
# found_user.password_token = forgot_key
|
||||
# found_user.password_token_is_valid = str(system_arrow.shift(days=1))
|
||||
# found_user.save()
|
||||
# return ResponseHandler.success("Password is change link is sent to your email or phone", data={})
|
||||
return
|
||||
|
||||
|
||||
@AuthMiddlewareModule.auth_required
|
||||
def authentication_reset_password(request: "Request", data: Any):
|
||||
"""Reset password with forgot password token"""
|
||||
# from sqlalchemy import or_
|
||||
# found_user = Users.query.filter(
|
||||
# or_(
|
||||
# Users.email == str(data.access_key).lower(),
|
||||
# Users.phone_number == str(data.access_key).replace(" ", ""),
|
||||
# ),
|
||||
# ).first()
|
||||
# if not found_user:
|
||||
# raise HTTPException(
|
||||
# status_code=status.HTTP_400_BAD_REQUEST,
|
||||
# detail="Given access key or domain is not matching with the any user record.",
|
||||
# )
|
||||
# reset_password_token = found_user.reset_password_token(found_user=found_user)
|
||||
# send_email_completed = send_email(
|
||||
# subject=f"Dear {found_user.user_tag}, a password reset request has been received.",
|
||||
# receivers=[str(found_user.email)],
|
||||
# html=change_your_password_template(
|
||||
# user_name=found_user.user_tag,
|
||||
# forgot_link=ApiStatic.forgot_link(forgot_key=reset_password_token),
|
||||
# ),
|
||||
# )
|
||||
# if not send_email_completed:
|
||||
# raise found_user.raise_http_exception(status_code=400, message="Email can not be sent. Try again later")
|
||||
# return ResponseHandler.success("Password change link is sent to your email or phone", data=found_user.get_dict())
|
||||
return
|
||||
|
||||
|
||||
@AuthMiddlewareModule.auth_required
|
||||
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)))
|
||||
# expired_int = (system_arrow.now() - system_arrow.get(str(found_user.expiry_ends))).days
|
||||
# user_info = {
|
||||
# "lang": token_dict.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_str": expired_starts,
|
||||
# "expired_int": int(expired_int),
|
||||
# }
|
||||
# return ResponseHandler.success("Avatar and profile is shared via user credentials", data=user_info)
|
||||
# return ResponseHandler.not_found("Invalid data")
|
||||
return
|
||||
13
Events/AllEvents/authentication/auth/info.py
Normal file
13
Events/AllEvents/authentication/auth/info.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from Events.Engine.abstract_class import PageInfo
|
||||
|
||||
|
||||
authentication_page_info = PageInfo(
|
||||
name="Authentication",
|
||||
title={"en": "Authentication"},
|
||||
description={"en": "Authentication"},
|
||||
icon="",
|
||||
parent="",
|
||||
url="",
|
||||
)
|
||||
|
||||
|
||||
34
Events/AllEvents/authentication/auth/models.py
Normal file
34
Events/AllEvents/authentication/auth/models.py
Normal file
@@ -0,0 +1,34 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class LoginSuperUserRequestModel(BaseModel):
|
||||
pass
|
||||
|
||||
|
||||
class LoginSuperUserResponseModel(BaseModel):
|
||||
pass
|
||||
|
||||
|
||||
class SelectCompanyOrOccupantTypeSuperUserRequestModel(BaseModel):
|
||||
pass
|
||||
|
||||
|
||||
class SelectCompanyOrOccupantTypeSuperUserResponseModel(BaseModel):
|
||||
pass
|
||||
|
||||
|
||||
class EmployeeSelectionSuperUserRequestModel(BaseModel):
|
||||
pass
|
||||
|
||||
|
||||
class EmployeeSelectionSuperUserResponseModel(BaseModel):
|
||||
pass
|
||||
|
||||
|
||||
class OccupantSelectionSuperUserRequestModel(BaseModel):
|
||||
pass
|
||||
|
||||
|
||||
class OccupantSelectionSuperUserResponseModel(BaseModel):
|
||||
pass
|
||||
|
||||
Reference in New Issue
Block a user