2# +==== BEGIN CatFeeder =================+
5# ...............)..(.')
7# ...............\(__)|
8# Inspired by Joan Stark
9# source https://www.asciiart.eu/
14# CREATION DATE: 11-10-2025
15# LAST Modified: 22:47:49 14-01-2026
17# This is the backend server in charge of making the actual website work.
19# COPYRIGHT: (c) Cat Feeder
20# PURPOSE: File containing boilerplate functions that could be used by the server in it's endpoints_initialised for checking incoming data.
22# +==== END CatFeeder =================+
25from typing
import Union, Dict, Any, Optional
26from fastapi
import Request, UploadFile
27from display_tty
import Disp, initialise_logger
29from .non_web
import BoilerplateNonHTTP
30from ..utils
import constants
as CONST
31from ..core
import FinalSingleton
32from ..core.runtime_manager
import RuntimeManager, RI
40 disp: Disp = initialise_logger(__qualname__,
False)
42 def __init__(self, error: int = 84, success: int = 0, debug: bool =
False) ->
None:
44 self.
disp.update_disp_debug(debug)
45 self.
disp.log_debug(
"Initialising...")
57 self.
disp.log_debug(
"Initialised")
61 This is a function that will check if the token is correct or not.
63 request (Request): _description_: The request object
66 bool: _description_: True if the token is correct, False otherwise
68 title =
"token_correct"
70 f
"request = {request}", title
74 f
"token = {token}", title
83 self.
disp.log_error(
"BoilerplateNonHttp is missing")
84 raise RuntimeError(
"Token validation service unavailable")
89 This is a function that will check if the user is logged in or not.
91 request (Request): _description_: The request object
94 bool: _description_: True if the user is logged in, False otherwise
98 f
"request = {request}", title
100 self.
disp.log_warning(
101 "This function is the same as token_correct, please call token correct instead",
108 Insert the user data into the database.
110 user_data (dict[str, any]): _description_: The user data to insert into the database
113 int: _description_: The status of the operation
115 title =
"_insert_login_into_database"
116 if len(user_data) != 3:
118 "The user data is not in the correct format !", title
122 f
"user_data = {user_data}", title
128 f
"stringed_datetime = {user_data}", title
131 CONST.TAB_CONNECTIONS
133 if isinstance(table_columns, int):
135 table_columns = CONST.clean_list(
137 CONST.TABLE_COLUMNS_TO_IGNORE,
141 f
"table_columns = {table_columns}", title
143 status = self.
database_link.insert_or_update_data_into_table(
146 columns=table_columns
150 "Data not inserted successfully !", title
154 "Data inserted successfully.", title
160 Attempt to log the user in based on the provided credentials and the database.
163 email (str): _description_: The email of the account
166 Dict[str, Any]: _description_: The response status
167 {'status':Union[success, error], 'token':Union['some_token', '']}
169 title =
"log_user_in"
170 data = {
'status': self.
success,
'token':
''}
176 self.
disp.log_error(
"BoilerplateNonHttp is missing")
177 raise RuntimeError(
"Token validation service unavailable")
178 self.
disp.log_debug(f
"e-mail = {email}", title)
186 if isinstance(usr_id, int):
187 data[
'status'] = self.
error
189 self.
disp.log_debug(f
"usr_id = {usr_id}", title)
191 CONST.UA_TOKEN_LIFESPAN
194 uid = str(int(usr_id[0][0]))
195 self.
disp.log_debug(f
"uid = {uid}", title)
196 except (ValueError, IndexError):
197 data[
'status'] = self.
error
199 usr_data = [token, uid, lifespan]
200 self.
disp.log_debug(f
"usr_data = {usr_data}", title)
202 data[
'token'] = token
203 self.
disp.log_debug(f
"Response data: {data}", title)
208 Return the token if it is present.
211 request (Request): _description_: the request header created by the endpoint caller.
214 Union[str, None]: _description_: If the token is present, a string is returned, otherwise, it is None.
216 mtoken: Union[str,
None] = request.get(CONST.REQUEST_TOKEN_KEY)
217 mbearer: Union[str,
None] = request.get(CONST.REQUEST_BEARER_KEY)
218 token: Union[str,
None] = request.headers.get(CONST.REQUEST_TOKEN_KEY)
219 bearer: Union[str,
None] = request.headers.get(
220 CONST.REQUEST_BEARER_KEY
222 msg = f
"mtoken = {mtoken}, mbearer = {mbearer}"
223 msg += f
", token = {token}, bearer = {bearer}"
224 self.
disp.log_debug(msg,
"get_token_if_present")
225 if token
is None and bearer
is None and token
is None and bearer
is None:
227 if mbearer
is not None and mbearer.startswith(
'Bearer '):
228 return mbearer.split(
" ")[1]
229 if bearer
is not None and bearer.startswith(
'Bearer '):
230 return bearer.split(
" ")[1]
231 if token
is not None:
235 async def get_body(self, request: Request) -> Dict[str, Any]:
237 Get the body of a request, whether it's JSON or form data.
239 request (Request): The incoming request object.
242 Dict[str, Any]: Parsed request body in dictionary format.
244 body: Dict[str, Any] = {}
247 body = await request.json()
250 form = await request.form()
253 files = await request.form()
256 for file_key, file_value
in files.items():
257 if isinstance(file_value, UploadFile):
258 body[
"_files"][file_key] = {
259 "filename": file_value.filename,
260 "content_type": file_value.content_type,
261 "content": await file_value.read()
263 except Exception
as form_error:
264 msg = f
"Failed to parse request body: {str(form_error)}"
265 body = {
"error": msg}
269 """Retrieve the type of the request body if present.
270 Get the content type of the request body.
272 request (Request): The incoming request object.
274 Optional[str]: The content type of the request body, or None if not present.
276 body_type = request.headers.get(
"content-type",
None)
277 self.
disp.log_debug(f
"Body type: {body_type}")
280 def log_user_out(self, token: str =
"") -> Union[Dict[str, Any], bool]:
282 Attempt to log the user out based on the provided token.
285 token (str): _description_: The token of the account
288 Dict[str, Any]: _description_: The response status
289 {'status':Union[success, error], 'msg':'message'}
291 title =
"log_user_out"
292 data = {
'status': self.
error,
'msg':
"You are not logged in !"}
294 data[
"msg"] =
"No token provided !"
298 CONST.TAB_CONNECTIONS,
300 where=f
"token={token}",
303 if isinstance(login_table, int):
305 if len(login_table) != 1:
307 self.
disp.log_debug(f
"login_table = {login_table}", title)
309 CONST.TAB_CONNECTIONS,
313 data[
"msg"] =
"Data not removed successfully !"
314 self.
disp.log_error(data[
"msg"], title)
317 data[
"msg"] =
"You have successfully logged out."
Optional[BoilerplateNonHTTP] boilerplate_non_http_initialised
RuntimeManager runtime_manager
bool token_correct(self, Request request)
Dict[str, Any] get_body(self, Request request)
Union[str, None] get_token_if_present(self, Request request)
Dict[str, Any] log_user_in(self, str email='')
None __init__(self, int error=84, int success=0, bool debug=False)
Union[Dict[str, Any], bool] log_user_out(self, str token="")
bool logged_in(self, Request request)
Optional[str] get_body_type(self, Request request)
int _insert_login_into_database(self, dict[str, Any] user_data)