auth service up running
This commit is contained in:
@@ -6,16 +6,18 @@ from typing import TypeVar, Union, Dict, Any, Optional, Type
|
||||
|
||||
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
|
||||
|
||||
TokenType = TypeVar('TokenType', bound=Union[EmployeeTokenObject, OccupantTokenObject])
|
||||
TokenType = TypeVar("TokenType", bound=Union[EmployeeTokenObject, OccupantTokenObject])
|
||||
|
||||
|
||||
class ActionsSchema(ABC):
|
||||
"""Base class for defining API action schemas.
|
||||
|
||||
|
||||
This class handles endpoint registration and validation in the database.
|
||||
"""
|
||||
|
||||
def __init__(self, endpoint: str):
|
||||
"""Initialize with an API endpoint path.
|
||||
|
||||
|
||||
Args:
|
||||
endpoint: The API endpoint path (e.g. "/users/create")
|
||||
"""
|
||||
@@ -23,10 +25,10 @@ class ActionsSchema(ABC):
|
||||
|
||||
def retrieve_action_from_endpoint(self) -> Dict[str, Any]:
|
||||
"""Retrieve the endpoint registration from the database.
|
||||
|
||||
|
||||
Returns:
|
||||
Dict containing the endpoint registration data
|
||||
|
||||
|
||||
Raises:
|
||||
HTTPException: If endpoint is not found in database
|
||||
"""
|
||||
@@ -38,21 +40,22 @@ class ActionsSchema(ABC):
|
||||
"endpoint_desc": "Temporary endpoint",
|
||||
"endpoint_code": "dummy_code",
|
||||
"id": 1,
|
||||
"uu_id": "dummy_uuid"
|
||||
"uu_id": "dummy_uuid",
|
||||
}
|
||||
|
||||
|
||||
class ActionsSchemaFactory:
|
||||
"""Factory class for creating action schemas.
|
||||
|
||||
|
||||
This class validates and initializes action schemas for API endpoints.
|
||||
"""
|
||||
|
||||
def __init__(self, action: ActionsSchema):
|
||||
"""Initialize with an action schema.
|
||||
|
||||
|
||||
Args:
|
||||
action: The action schema to initialize
|
||||
|
||||
|
||||
Raises:
|
||||
HTTPException: If action initialization fails
|
||||
"""
|
||||
@@ -67,17 +70,18 @@ class ActionsSchemaFactory:
|
||||
print(f"ActionsSchemaFactory Error: {e}")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Failed to initialize action schema"
|
||||
detail="Failed to initialize action schema",
|
||||
) from e
|
||||
|
||||
|
||||
class MethodToEvent(ABC, ActionsSchemaFactory):
|
||||
"""Base class for mapping methods to API events.
|
||||
|
||||
|
||||
This class handles method registration and validation for API events.
|
||||
"""
|
||||
|
||||
action_key: Optional[str] = None
|
||||
event_type: Optional[str] = None
|
||||
event_type: Optional[str] = None
|
||||
event_description: str = ""
|
||||
event_category: str = ""
|
||||
|
||||
@@ -87,42 +91,40 @@ class MethodToEvent(ABC, ActionsSchemaFactory):
|
||||
@classmethod
|
||||
def call_event_method(cls, method_uu_id: str, *args: Any, **kwargs: Any) -> Any:
|
||||
"""Call an event method by its UUID.
|
||||
|
||||
|
||||
Args:
|
||||
method_uu_id: UUID of the method to call
|
||||
*args: Positional arguments to pass to method
|
||||
**kwargs: Keyword arguments to pass to method
|
||||
|
||||
|
||||
Returns:
|
||||
The result of the called method
|
||||
|
||||
|
||||
Raises:
|
||||
AttributeError: If method UUID is not found
|
||||
"""
|
||||
function_name = cls.__event_keys__.get(method_uu_id)
|
||||
if not function_name:
|
||||
raise AttributeError(f"No method found for UUID: {method_uu_id}")
|
||||
|
||||
|
||||
return getattr(cls, function_name)(*args, **kwargs)
|
||||
|
||||
@classmethod
|
||||
def ban_token_objects(
|
||||
cls,
|
||||
token: TokenType,
|
||||
ban_list: Type[TokenType]
|
||||
) -> None:
|
||||
def ban_token_objects(cls, token: TokenType, ban_list: Type[TokenType]) -> None:
|
||||
"""Check if a token type is banned from accessing an event.
|
||||
|
||||
|
||||
Args:
|
||||
token: The token to check
|
||||
ban_list: The token type that is banned
|
||||
|
||||
|
||||
Raises:
|
||||
HTTPException: If token type matches banned type
|
||||
"""
|
||||
if isinstance(token, ban_list):
|
||||
user_type = "employee" if isinstance(token, EmployeeTokenObject) else "occupant"
|
||||
user_type = (
|
||||
"employee" if isinstance(token, EmployeeTokenObject) else "occupant"
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_406_NOT_ACCEPTABLE,
|
||||
detail=f"No {user_type} can reach this event. A notification has been sent to admin."
|
||||
detail=f"No {user_type} can reach this event. A notification has been sent to admin.",
|
||||
)
|
||||
|
||||
@@ -54,7 +54,7 @@ class AccountRecordsListEventMethods(MethodToEvent):
|
||||
result=records,
|
||||
cls_object=AccountRecords,
|
||||
filter_attributes=list_options,
|
||||
response_model=AccountRecordResponse
|
||||
response_model=AccountRecordResponse,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
@@ -224,7 +224,9 @@ class AccountRecordsCreateEventMethods(MethodToEvent):
|
||||
)
|
||||
account_record = AccountRecords.find_or_create(**data.excluded_dump())
|
||||
return AlchemyJsonResponse(
|
||||
completed=True, message="Account record created successfully", result=account_record
|
||||
completed=True,
|
||||
message="Account record created successfully",
|
||||
result=account_record,
|
||||
)
|
||||
elif isinstance(token_dict, EmployeeTokenObject):
|
||||
# Build.pre_query = Build.select_action(
|
||||
@@ -266,7 +268,9 @@ class AccountRecordsCreateEventMethods(MethodToEvent):
|
||||
|
||||
account_record = AccountRecords.insert_one(data_dict).data
|
||||
return AlchemyJsonResponse(
|
||||
completed=True, message="Account record created successfully", result=account_record
|
||||
completed=True,
|
||||
message="Account record created successfully",
|
||||
result=account_record,
|
||||
)
|
||||
|
||||
|
||||
@@ -297,7 +301,9 @@ class AccountRecordsUpdateEventMethods(MethodToEvent):
|
||||
|
||||
account_record = AccountRecords.update_one(build_uu_id, data).data
|
||||
return AlchemyJsonResponse(
|
||||
completed=True, message="Account record updated successfully", result=account_record
|
||||
completed=True,
|
||||
message="Account record updated successfully",
|
||||
result=account_record,
|
||||
)
|
||||
|
||||
|
||||
@@ -323,7 +329,9 @@ class AccountRecordsPatchEventMethods(MethodToEvent):
|
||||
):
|
||||
account_record = AccountRecords.patch_one(build_uu_id, data).data
|
||||
return AlchemyJsonResponse(
|
||||
completed=True, message="Account record patched successfully", result=account_record
|
||||
completed=True,
|
||||
message="Account record patched successfully",
|
||||
result=account_record,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -138,16 +138,19 @@ class AddressCreateEventMethods(MethodToEvent):
|
||||
address.update(is_confirmed=True)
|
||||
address.save()
|
||||
return AlchemyJsonResponse(
|
||||
completed=True, message="Address created successfully", result=address.get_dict()
|
||||
completed=True,
|
||||
message="Address created successfully",
|
||||
result=address.get_dict(),
|
||||
)
|
||||
|
||||
|
||||
class AddressSearchEventMethods(MethodToEvent):
|
||||
"""Event methods for searching addresses.
|
||||
|
||||
|
||||
This class handles address search functionality including text search
|
||||
and filtering.
|
||||
"""
|
||||
|
||||
event_type = "SEARCH"
|
||||
event_description = "Search for addresses using text and filters"
|
||||
event_category = "Address"
|
||||
@@ -161,18 +164,15 @@ class AddressSearchEventMethods(MethodToEvent):
|
||||
|
||||
@classmethod
|
||||
def _build_order_clause(
|
||||
cls,
|
||||
filter_list: Dict[str, Any],
|
||||
schemas: List[str],
|
||||
filter_table: Any
|
||||
cls, filter_list: Dict[str, Any], schemas: List[str], filter_table: Any
|
||||
) -> Any:
|
||||
"""Build the ORDER BY clause for the query.
|
||||
|
||||
|
||||
Args:
|
||||
filter_list: Dictionary of filter options
|
||||
schemas: List of available schema fields
|
||||
filter_table: SQLAlchemy table to query
|
||||
|
||||
|
||||
Returns:
|
||||
SQLAlchemy order_by clause
|
||||
"""
|
||||
@@ -187,16 +187,20 @@ class AddressSearchEventMethods(MethodToEvent):
|
||||
|
||||
# Build order clause
|
||||
field = getattr(filter_table, filter_list.get("order_field"))
|
||||
return field.desc() if str(filter_list.get("order_type"))[0] == "d" else field.asc()
|
||||
return (
|
||||
field.desc()
|
||||
if str(filter_list.get("order_type"))[0] == "d"
|
||||
else field.asc()
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _format_record(cls, record: Any, schemas: List[str]) -> Dict[str, str]:
|
||||
"""Format a database record into a dictionary.
|
||||
|
||||
|
||||
Args:
|
||||
record: Database record to format
|
||||
schemas: List of schema fields
|
||||
|
||||
|
||||
Returns:
|
||||
Formatted record dictionary
|
||||
"""
|
||||
@@ -216,14 +220,14 @@ class AddressSearchEventMethods(MethodToEvent):
|
||||
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
|
||||
) -> JSONResponse:
|
||||
"""Search for addresses using text search and filters.
|
||||
|
||||
|
||||
Args:
|
||||
data: Search parameters including text and filters
|
||||
token_dict: Authentication token
|
||||
|
||||
|
||||
Returns:
|
||||
JSON response with search results
|
||||
|
||||
|
||||
Raises:
|
||||
HTTPException: If search fails
|
||||
"""
|
||||
@@ -236,23 +240,23 @@ class AddressSearchEventMethods(MethodToEvent):
|
||||
if not search_result:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="No addresses found matching search criteria"
|
||||
detail="No addresses found matching search criteria",
|
||||
)
|
||||
|
||||
query = search_result.get("query")
|
||||
schemas = search_result.get("schema")
|
||||
|
||||
|
||||
# Apply filters
|
||||
filter_list = data.list_options.dump()
|
||||
filter_table = AddressStreet
|
||||
|
||||
|
||||
# Build and apply order clause
|
||||
order = cls._build_order_clause(filter_list, schemas, filter_table)
|
||||
|
||||
|
||||
# Apply pagination
|
||||
page_size = int(filter_list.get("size"))
|
||||
offset = (int(filter_list.get("page")) - 1) * page_size
|
||||
|
||||
|
||||
# Execute query
|
||||
query = (
|
||||
query.order_by(order)
|
||||
@@ -270,9 +274,7 @@ class AddressSearchEventMethods(MethodToEvent):
|
||||
print(f"Address search completed in {duration:.3f}s")
|
||||
|
||||
return AlchemyJsonResponse(
|
||||
completed=True,
|
||||
message="Address search results",
|
||||
result=results
|
||||
completed=True, message="Address search results", result=results
|
||||
)
|
||||
|
||||
except HTTPException as e:
|
||||
@@ -283,7 +285,7 @@ class AddressSearchEventMethods(MethodToEvent):
|
||||
print(f"Address search error: {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Failed to search addresses"
|
||||
detail="Failed to search addresses",
|
||||
) from e
|
||||
|
||||
|
||||
@@ -321,7 +323,9 @@ class AddressUpdateEventMethods(MethodToEvent):
|
||||
updated_address = address.update(**data_dict)
|
||||
updated_address.save()
|
||||
return AlchemyJsonResponse(
|
||||
completed=True, message="Address updated successfully", result=updated_address.get_dict()
|
||||
completed=True,
|
||||
message="Address updated successfully",
|
||||
result=updated_address.get_dict(),
|
||||
)
|
||||
elif isinstance(token_dict, OccupantTokenObject):
|
||||
raise HTTPException(
|
||||
@@ -368,7 +372,9 @@ class AddressPatchEventMethods(MethodToEvent):
|
||||
|
||||
patched_address = address.patch(**data_dict)
|
||||
return AlchemyJsonResponse(
|
||||
completed=True, message="Address patched successfully", result=patched_address.get_dict()
|
||||
completed=True,
|
||||
message="Address patched successfully",
|
||||
result=patched_address.get_dict(),
|
||||
)
|
||||
|
||||
|
||||
@@ -416,7 +422,9 @@ class AddressPostCodeCreateEventMethods(MethodToEvent):
|
||||
relation_table.update(is_confirmed=True)
|
||||
relation_table.save()
|
||||
return AlchemyJsonResponse(
|
||||
completed=True, message="Post code created successfully", result=post_code.get_dict()
|
||||
completed=True,
|
||||
message="Post code created successfully",
|
||||
result=post_code.get_dict(),
|
||||
)
|
||||
|
||||
|
||||
@@ -457,7 +465,9 @@ class AddressPostCodeUpdateEventMethods(MethodToEvent):
|
||||
updated_post_code = post_code.update(**data_dict)
|
||||
updated_post_code.save()
|
||||
return AlchemyJsonResponse(
|
||||
completed=True, message="Post code updated successfully", result=updated_post_code.get_dict()
|
||||
completed=True,
|
||||
message="Post code updated successfully",
|
||||
result=updated_post_code.get_dict(),
|
||||
)
|
||||
elif isinstance(token_dict, OccupantTokenObject):
|
||||
raise HTTPException(
|
||||
|
||||
@@ -13,10 +13,21 @@ from api_configs import Auth, ApiStatic
|
||||
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
|
||||
|
||||
from databases import (
|
||||
Companies, Staff, Duties, Departments, Employees,
|
||||
BuildLivingSpace, BuildParts, Build, Duty, Event2Occupant,
|
||||
Event2Employee, Users, UsersTokens, OccupantTypes,
|
||||
RelationshipEmployee2Build
|
||||
Companies,
|
||||
Staff,
|
||||
Duties,
|
||||
Departments,
|
||||
Employees,
|
||||
BuildLivingSpace,
|
||||
BuildParts,
|
||||
Build,
|
||||
Duty,
|
||||
Event2Occupant,
|
||||
Event2Employee,
|
||||
Users,
|
||||
UsersTokens,
|
||||
OccupantTypes,
|
||||
RelationshipEmployee2Build,
|
||||
)
|
||||
|
||||
from api_services import (
|
||||
@@ -28,17 +39,23 @@ from api_services import (
|
||||
)
|
||||
|
||||
from api_validations.validations_request import (
|
||||
Login, Logout, ChangePassword, Remember,
|
||||
Forgot, CreatePassword, OccupantSelection,
|
||||
Login,
|
||||
Logout,
|
||||
ChangePassword,
|
||||
Remember,
|
||||
Forgot,
|
||||
CreatePassword,
|
||||
OccupantSelection,
|
||||
EmployeeSelection,
|
||||
)
|
||||
|
||||
from api_validations.validations_response import (
|
||||
AuthenticationLoginResponse,
|
||||
AuthenticationRefreshResponse,
|
||||
AuthenticationUserInfoResponse
|
||||
AuthenticationUserInfoResponse,
|
||||
)
|
||||
|
||||
|
||||
class AuthenticationLoginEventMethods(MethodToEvent):
|
||||
event_type = "LOGIN"
|
||||
event_description = "Login via domain and access key : [email] | [phone]"
|
||||
@@ -56,19 +73,22 @@ class AuthenticationLoginEventMethods(MethodToEvent):
|
||||
try:
|
||||
access_dict = Users.login_user_with_credentials(data=data, request=request)
|
||||
found_user = access_dict.get("user")
|
||||
|
||||
|
||||
if not found_user:
|
||||
user_logger.log_login_attempt(
|
||||
request, None, data.domain, data.access_key,
|
||||
success=False, error="Invalid credentials"
|
||||
request,
|
||||
None,
|
||||
data.domain,
|
||||
data.access_key,
|
||||
success=False,
|
||||
error="Invalid credentials",
|
||||
)
|
||||
return ResponseHandler.unauthorized("Invalid credentials")
|
||||
|
||||
user_logger.log_login_attempt(
|
||||
request, found_user.id, data.domain, data.access_key,
|
||||
success=True
|
||||
request, found_user.id, data.domain, data.access_key, success=True
|
||||
)
|
||||
|
||||
|
||||
response_data = {
|
||||
"access_token": access_dict.get("access_token"),
|
||||
"refresh_token": access_dict.get("refresher_token"),
|
||||
@@ -78,17 +98,13 @@ class AuthenticationLoginEventMethods(MethodToEvent):
|
||||
return ResponseHandler.success(
|
||||
message="User logged in successfully",
|
||||
data=response_data,
|
||||
response_model=AuthenticationLoginResponse
|
||||
response_model=AuthenticationLoginResponse,
|
||||
)
|
||||
except Exception as e:
|
||||
user_logger.log_login_attempt(
|
||||
request, None, data.domain, data.access_key,
|
||||
success=False, error=str(e)
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail=str(e)
|
||||
request, None, data.domain, data.access_key, success=False, error=str(e)
|
||||
)
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(e))
|
||||
|
||||
|
||||
class AuthenticationSelectEventMethods(MethodToEvent):
|
||||
@@ -105,14 +121,13 @@ class AuthenticationSelectEventMethods(MethodToEvent):
|
||||
|
||||
@classmethod
|
||||
def _handle_employee_selection(
|
||||
cls,
|
||||
data: EmployeeSelection,
|
||||
token_dict: EmployeeTokenObject,
|
||||
request: Request
|
||||
cls, data: EmployeeSelection, token_dict: EmployeeTokenObject, request: Request
|
||||
):
|
||||
"""Handle employee company selection"""
|
||||
if data.company_uu_id not in token_dict.companies_uu_id_list:
|
||||
return ResponseHandler.unauthorized("Company not found in user's company list")
|
||||
return ResponseHandler.unauthorized(
|
||||
"Company not found in user's company list"
|
||||
)
|
||||
|
||||
selected_company = Companies.filter_one(
|
||||
Companies.uu_id == data.company_uu_id
|
||||
@@ -122,29 +137,27 @@ class AuthenticationSelectEventMethods(MethodToEvent):
|
||||
|
||||
# Get department IDs for the company
|
||||
department_ids = [
|
||||
dept.id for dept in Departments.filter_all(
|
||||
dept.id
|
||||
for dept in Departments.filter_all(
|
||||
Departments.company_id == selected_company.id
|
||||
).data
|
||||
]
|
||||
|
||||
# Get duties IDs for the company
|
||||
duties_ids = [
|
||||
duty.id for duty in Duties.filter_all(
|
||||
Duties.company_id == selected_company.id
|
||||
).data
|
||||
duty.id
|
||||
for duty in Duties.filter_all(Duties.company_id == selected_company.id).data
|
||||
]
|
||||
|
||||
# Get staff IDs
|
||||
staff_ids = [
|
||||
staff.id for staff in Staff.filter_all(
|
||||
Staff.duties_id.in_(duties_ids)
|
||||
).data
|
||||
staff.id for staff in Staff.filter_all(Staff.duties_id.in_(duties_ids)).data
|
||||
]
|
||||
|
||||
# Get employee
|
||||
employee = Employees.filter_one(
|
||||
Employees.people_id == token_dict.person_id,
|
||||
Employees.staff_id.in_(staff_ids)
|
||||
Employees.staff_id.in_(staff_ids),
|
||||
).data
|
||||
|
||||
if not employee:
|
||||
@@ -158,16 +171,14 @@ class AuthenticationSelectEventMethods(MethodToEvent):
|
||||
# Get staff and duties
|
||||
staff = Staff.filter_one(Staff.id == employee.staff_id).data
|
||||
duties = Duties.filter_one(Duties.id == staff.duties_id).data
|
||||
department = Departments.filter_one(
|
||||
Departments.id == duties.department_id
|
||||
).data
|
||||
department = Departments.filter_one(Departments.id == duties.department_id).data
|
||||
|
||||
# Get bulk duty
|
||||
bulk_id = Duty.filter_by_one(system=True, duty_code="BULK").data
|
||||
bulk_duty_id = Duties.filter_by_one(
|
||||
company_id=selected_company.id,
|
||||
duties_id=bulk_id.id,
|
||||
**Duties.valid_record_dict
|
||||
**Duties.valid_record_dict,
|
||||
).data
|
||||
|
||||
# Create company token
|
||||
@@ -183,7 +194,7 @@ class AuthenticationSelectEventMethods(MethodToEvent):
|
||||
staff_uu_id=staff.uu_id.__str__(),
|
||||
employee_id=employee.id,
|
||||
employee_uu_id=employee.uu_id.__str__(),
|
||||
reachable_event_list_id=reachable_event_list_id
|
||||
reachable_event_list_id=reachable_event_list_id,
|
||||
)
|
||||
|
||||
# Update Redis
|
||||
@@ -192,24 +203,19 @@ class AuthenticationSelectEventMethods(MethodToEvent):
|
||||
|
||||
@classmethod
|
||||
def _handle_occupant_selection(
|
||||
cls,
|
||||
data: OccupantSelection,
|
||||
token_dict: OccupantTokenObject,
|
||||
request: Request
|
||||
cls, data: OccupantSelection, token_dict: OccupantTokenObject, request: Request
|
||||
):
|
||||
"""Handle occupant type selection"""
|
||||
# Get occupant type
|
||||
occupant_type = OccupantTypes.filter_by_one(
|
||||
system=True,
|
||||
uu_id=data.occupant_uu_id
|
||||
system=True, uu_id=data.occupant_uu_id
|
||||
).data
|
||||
if not occupant_type:
|
||||
return ResponseHandler.not_found("Occupant Type not found")
|
||||
|
||||
# Get build part
|
||||
build_part = BuildParts.filter_by_one(
|
||||
system=True,
|
||||
uu_id=data.build_part_uu_id
|
||||
system=True, uu_id=data.build_part_uu_id
|
||||
).data
|
||||
if not build_part:
|
||||
return ResponseHandler.not_found("Build Part not found")
|
||||
@@ -230,7 +236,7 @@ class AuthenticationSelectEventMethods(MethodToEvent):
|
||||
selected_occupant_type = BuildLivingSpace.filter_one(
|
||||
BuildLivingSpace.occupant_type == occupant_type.id,
|
||||
BuildLivingSpace.person_id == token_dict.person_id,
|
||||
BuildLivingSpace.build_parts_id == build_part.id
|
||||
BuildLivingSpace.build_parts_id == build_part.id,
|
||||
).data
|
||||
if not selected_occupant_type:
|
||||
return ResponseHandler.not_found("Selected occupant type not found")
|
||||
@@ -255,7 +261,7 @@ class AuthenticationSelectEventMethods(MethodToEvent):
|
||||
responsible_employee_uuid=responsible_employee.uu_id.__str__(),
|
||||
responsible_company_id=company_related.id,
|
||||
responsible_company_uuid=company_related.uu_id.__str__(),
|
||||
reachable_event_list_id=reachable_event_list_id
|
||||
reachable_event_list_id=reachable_event_list_id,
|
||||
)
|
||||
|
||||
# Update Redis
|
||||
@@ -276,13 +282,11 @@ class AuthenticationSelectEventMethods(MethodToEvent):
|
||||
elif isinstance(token_dict, OccupantTokenObject):
|
||||
return cls._handle_occupant_selection(data, token_dict, request)
|
||||
return ResponseHandler.error(
|
||||
"Invalid token type",
|
||||
status_code=status.HTTP_400_BAD_REQUEST
|
||||
"Invalid token type", status_code=status.HTTP_400_BAD_REQUEST
|
||||
)
|
||||
except Exception as e:
|
||||
return ResponseHandler.error(
|
||||
str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
|
||||
str(e), status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
|
||||
)
|
||||
|
||||
|
||||
@@ -331,9 +335,7 @@ class AuthenticationRefreshEventMethods(MethodToEvent):
|
||||
return ResponseHandler.unauthorized()
|
||||
|
||||
# Get user and token info
|
||||
found_user = Users.filter_one(
|
||||
Users.uu_id == token_dict.user_uu_id
|
||||
).data
|
||||
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")
|
||||
|
||||
@@ -349,12 +351,12 @@ class AuthenticationRefreshEventMethods(MethodToEvent):
|
||||
response_data = {
|
||||
"access_token": access_token,
|
||||
"refresh_token": getattr(user_token, "token", None),
|
||||
"user": found_user.get_dict()
|
||||
"user": found_user.get_dict(),
|
||||
}
|
||||
return ResponseHandler.success(
|
||||
"User info refreshed successfully",
|
||||
data=response_data,
|
||||
response_model=AuthenticationRefreshResponse
|
||||
response_model=AuthenticationRefreshResponse,
|
||||
)
|
||||
except Exception as e:
|
||||
return ResponseHandler.error(str(e))
|
||||
@@ -381,7 +383,9 @@ class AuthenticationChangePasswordEventMethods(MethodToEvent):
|
||||
):
|
||||
try:
|
||||
if not isinstance(token_dict, EmployeeTokenObject):
|
||||
return ResponseHandler.unauthorized("Only employees can change password")
|
||||
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:
|
||||
@@ -389,22 +393,27 @@ class AuthenticationChangePasswordEventMethods(MethodToEvent):
|
||||
|
||||
if not found_user.check_password(data.old_password):
|
||||
user_logger.log_password_change(
|
||||
request, found_user.id, "change",
|
||||
success=False, error="Invalid old password"
|
||||
request,
|
||||
found_user.id,
|
||||
"change",
|
||||
success=False,
|
||||
error="Invalid old password",
|
||||
)
|
||||
return ResponseHandler.unauthorized("Old password is incorrect")
|
||||
|
||||
found_user.set_password(data.new_password)
|
||||
user_logger.log_password_change(
|
||||
request, found_user.id, "change",
|
||||
success=True
|
||||
request, found_user.id, "change", success=True
|
||||
)
|
||||
|
||||
return ResponseHandler.success("Password changed successfully")
|
||||
except Exception as e:
|
||||
user_logger.log_password_change(
|
||||
request, found_user.id if found_user else None,
|
||||
"change", success=False, error=str(e)
|
||||
request,
|
||||
found_user.id if found_user else None,
|
||||
"change",
|
||||
success=False,
|
||||
error=str(e),
|
||||
)
|
||||
return ResponseHandler.error(str(e))
|
||||
|
||||
@@ -471,7 +480,9 @@ class AuthenticationDisconnectUserEventMethods(MethodToEvent):
|
||||
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)):
|
||||
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(key)
|
||||
selected_user = Users.filter_one(
|
||||
@@ -566,7 +577,7 @@ class AuthenticationRefreshTokenEventMethods(MethodToEvent):
|
||||
return ResponseHandler.success(
|
||||
"User is logged in successfully via refresher token",
|
||||
data=response_data,
|
||||
response_model=AuthenticationRefreshResponse
|
||||
response_model=AuthenticationRefreshResponse,
|
||||
)
|
||||
return ResponseHandler.not_found("Invalid data")
|
||||
|
||||
@@ -697,7 +708,7 @@ class AuthenticationDownloadAvatarEventMethods(MethodToEvent):
|
||||
return ResponseHandler.success(
|
||||
"Avatar and profile is shared via user credentials",
|
||||
data=user_info,
|
||||
response_model=AuthenticationUserInfoResponse
|
||||
response_model=AuthenticationUserInfoResponse,
|
||||
)
|
||||
return ResponseHandler.not_found("Invalid data")
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ class BuildListEventMethods(MethodToEvent):
|
||||
result=records,
|
||||
cls_object=Build,
|
||||
filter_attributes=list_options,
|
||||
response_model=BuildResponse
|
||||
response_model=BuildResponse,
|
||||
)
|
||||
|
||||
|
||||
@@ -213,7 +213,7 @@ class BuildUpdateEventMethods(MethodToEvent):
|
||||
completed=False,
|
||||
message="Building not found",
|
||||
result={},
|
||||
status_code="HTTP_404_NOT_FOUND"
|
||||
status_code="HTTP_404_NOT_FOUND",
|
||||
)
|
||||
|
||||
build.update(**data.excluded_dump())
|
||||
@@ -256,7 +256,7 @@ class BuildPatchEventMethods(MethodToEvent):
|
||||
completed=False,
|
||||
message="Building not found",
|
||||
result={},
|
||||
status_code="HTTP_404_NOT_FOUND"
|
||||
status_code="HTTP_404_NOT_FOUND",
|
||||
)
|
||||
|
||||
build.update(**data.excluded_dump())
|
||||
|
||||
@@ -51,12 +51,12 @@ class BuildAreaListEventMethods(MethodToEvent):
|
||||
BuildArea.filter_attr = list_options
|
||||
records = BuildArea.filter_all()
|
||||
return AlchemyJsonResponse(
|
||||
completed=True,
|
||||
message="Building areas listed successfully",
|
||||
completed=True,
|
||||
message="Building areas listed successfully",
|
||||
result=records,
|
||||
cls_object=BuildArea,
|
||||
filter_attributes=list_options,
|
||||
response_model=BuildResponse
|
||||
response_model=BuildResponse,
|
||||
)
|
||||
|
||||
|
||||
@@ -112,9 +112,7 @@ class BuildAreaCreateEventMethods(MethodToEvent):
|
||||
data_dict["build_uu_id"] = str(selected_build.uu_id)
|
||||
area = BuildArea.insert_one(data_dict).data
|
||||
return AlchemyJsonResponse(
|
||||
completed=True,
|
||||
message="Building area created successfully",
|
||||
result=area
|
||||
completed=True, message="Building area created successfully", result=area
|
||||
)
|
||||
|
||||
|
||||
@@ -137,9 +135,7 @@ class BuildAreaUpdateEventMethods(MethodToEvent):
|
||||
):
|
||||
area = BuildArea.update_one(build_uu_id, data).data
|
||||
return AlchemyJsonResponse(
|
||||
completed=True,
|
||||
message="Building area updated successfully",
|
||||
result=area
|
||||
completed=True, message="Building area updated successfully", result=area
|
||||
)
|
||||
|
||||
|
||||
@@ -162,9 +158,7 @@ class BuildAreaPatchEventMethods(MethodToEvent):
|
||||
):
|
||||
area = BuildArea.patch_one(build_uu_id, data).data
|
||||
return AlchemyJsonResponse(
|
||||
completed=True,
|
||||
message="Building area patched successfully",
|
||||
result=area
|
||||
completed=True, message="Building area patched successfully", result=area
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ from databases import (
|
||||
BuildParts,
|
||||
)
|
||||
|
||||
|
||||
class BuildingBuildPartsListEventMethods(MethodToEvent):
|
||||
|
||||
event_type = "SELECT"
|
||||
|
||||
@@ -59,12 +59,12 @@ class BuildSitesListEventMethods(MethodToEvent):
|
||||
BuildSites.filter_attr = list_options
|
||||
records = BuildSites.filter_all()
|
||||
return AlchemyJsonResponse(
|
||||
completed=True,
|
||||
message="Building sites listed successfully",
|
||||
completed=True,
|
||||
message="Building sites listed successfully",
|
||||
result=records,
|
||||
cls_object=BuildSites,
|
||||
filter_attributes=list_options,
|
||||
response_model=BuildSitesResponse
|
||||
response_model=BuildSitesResponse,
|
||||
)
|
||||
|
||||
|
||||
@@ -110,9 +110,7 @@ class BuildSitesCreateEventMethods(MethodToEvent):
|
||||
data_dict = data.excluded_dump()
|
||||
site = BuildSites.insert_one(data_dict).data
|
||||
return AlchemyJsonResponse(
|
||||
completed=True,
|
||||
message="Building site created successfully",
|
||||
result=site
|
||||
completed=True, message="Building site created successfully", result=site
|
||||
)
|
||||
|
||||
|
||||
@@ -135,9 +133,7 @@ class BuildSitesUpdateEventMethods(MethodToEvent):
|
||||
):
|
||||
site = BuildSites.update_one(build_uu_id, data).data
|
||||
return AlchemyJsonResponse(
|
||||
completed=True,
|
||||
message="Building site updated successfully",
|
||||
result=site
|
||||
completed=True, message="Building site updated successfully", result=site
|
||||
)
|
||||
|
||||
|
||||
@@ -160,9 +156,7 @@ class BuildSitesPatchEventMethods(MethodToEvent):
|
||||
):
|
||||
site = BuildSites.patch_one(build_uu_id, data).data
|
||||
return AlchemyJsonResponse(
|
||||
completed=True,
|
||||
message="Building site patched successfully",
|
||||
result=site
|
||||
completed=True, message="Building site patched successfully", result=site
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -16,9 +16,7 @@ class BuildTypesListEventMethods(MethodToEvent):
|
||||
__event_keys__ = {
|
||||
"5344d03c-fc47-43ec-8c44-6c2acd7e5d9f": "build_types_list",
|
||||
}
|
||||
__event_validation__ = {
|
||||
"5344d03c-fc47-43ec-8c44-6c2acd7e5d9f": BuildTypesResponse
|
||||
}
|
||||
__event_validation__ = {"5344d03c-fc47-43ec-8c44-6c2acd7e5d9f": BuildTypesResponse}
|
||||
|
||||
@classmethod
|
||||
def build_types_list(
|
||||
@@ -37,7 +35,7 @@ class BuildTypesListEventMethods(MethodToEvent):
|
||||
result=results,
|
||||
cls_object=BuildTypes,
|
||||
filter_attributes=list_options,
|
||||
response_model=BuildTypesListResponse
|
||||
response_model=BuildTypesListResponse,
|
||||
)
|
||||
elif isinstance(token_dict, OccupantTokenObject):
|
||||
return AlchemyJsonResponse(
|
||||
@@ -46,7 +44,7 @@ class BuildTypesListEventMethods(MethodToEvent):
|
||||
result=None,
|
||||
cls_object=BuildTypes,
|
||||
filter_attributes=list_options,
|
||||
response_model=BuildTypesResponse
|
||||
response_model=BuildTypesResponse,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -73,7 +73,7 @@ class BuildingLivingSpacesListEventMethods(MethodToEvent):
|
||||
return AlchemyJsonResponse(
|
||||
completed=True,
|
||||
message="Living spaces listed successfully",
|
||||
result=records
|
||||
result=records,
|
||||
)
|
||||
elif isinstance(token_dict, EmployeeTokenObject):
|
||||
build_id_list_query = Build.select_action(
|
||||
@@ -217,7 +217,7 @@ class BuildingLivingSpacesCreateEventMethods(MethodToEvent):
|
||||
return AlchemyJsonResponse(
|
||||
completed=True,
|
||||
message="Living space created successfully",
|
||||
result=created_living_space
|
||||
result=created_living_space,
|
||||
)
|
||||
|
||||
|
||||
@@ -307,7 +307,7 @@ class BuildingLivingSpacesUpdateEventMethods(MethodToEvent):
|
||||
return AlchemyJsonResponse(
|
||||
completed=True,
|
||||
message="Living space updated successfully",
|
||||
result=living_space
|
||||
result=living_space,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -108,7 +108,7 @@ class CompanyUpdateEventMethods(MethodToEvent):
|
||||
completed=False,
|
||||
message="Company not found",
|
||||
result={},
|
||||
status_code="HTTP_404_NOT_FOUND"
|
||||
status_code="HTTP_404_NOT_FOUND",
|
||||
)
|
||||
company.save()
|
||||
return AlchemyJsonResponse(
|
||||
@@ -142,7 +142,7 @@ class CompanyPatchEventMethods(MethodToEvent):
|
||||
completed=False,
|
||||
message="Company not found",
|
||||
result={},
|
||||
status_code="HTTP_404_NOT_FOUND"
|
||||
status_code="HTTP_404_NOT_FOUND",
|
||||
)
|
||||
company.save()
|
||||
return AlchemyJsonResponse(
|
||||
|
||||
@@ -4,17 +4,16 @@ from fastapi import status
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from api_validations.validations_response import PeopleListResponse
|
||||
from api_validations.validations_request import InsertPerson, UpdateUsers
|
||||
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
|
||||
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
|
||||
from ApiServices.api_handlers import AlchemyJsonResponse
|
||||
from databases import (
|
||||
People,
|
||||
Users,
|
||||
Companies,
|
||||
)
|
||||
|
||||
from api_validations.validations_request import InsertPerson, UpdateUsers
|
||||
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
|
||||
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
|
||||
from ApiServices.api_handlers import AlchemyJsonResponse
|
||||
|
||||
|
||||
class PeopleListEventMethods(MethodToEvent):
|
||||
|
||||
|
||||
Reference in New Issue
Block a user