2 File containing boilerplate functions that could be used by the server in it's endpoints_initialised for checking incoming data.
5from typing
import Union, Dict, Any
6from fastapi
import Request, UploadFile
7from display_tty
import Disp, TOML_CONF, FILE_DESCRIPTOR, SAVE_TO_FILE, FILE_NAME
9from ..components
import RuntimeData, CONST
16 def __init__(self, runtime_data: RuntimeData, error: int = 84, success: int = 0, debug: bool =
False) ->
None:
28 logger=self.__class__.__name__
33 This is a function that will check if the token is correct or not.
35 request (Request): _description_: The request object
38 bool: _description_: True if the token is correct, False otherwise
40 title =
"token_correct"
42 f
"request = {request}", title
46 f
"token = {token}", title
54 This is a function that will check if the user is logged in or not.
56 request (Request): _description_: The request object
59 bool: _description_: True if the user is logged in, False otherwise
63 f
"request = {request}", title
65 self.
disp.log_warning(
66 "This function is the same as token_correct, please call token correct instead",
73 Insert the user data into the database.
75 user_data (dict[str, any]): _description_: The user data to insert into the database
78 int: _description_: The status of the operation
80 title =
"_insert_login_into_database"
81 if len(user_data) != 3:
83 "The user data is not in the correct format !", title
87 f
"user_data = {user_data}", title
93 f
"stringed_datetime = {user_data}", title
100 f
"table_columns = {table_columns}", title
105 columns=table_columns
109 "Data not inserted successfully !", title
113 "Data inserted successfully.", title
119 Attempt to log the user in based on the provided credentials and the database.
122 email (str): _description_: The email of the account
125 Dict[str, Any]: _description_: The response status
126 {'status':Union[success, error], 'token':Union['some_token', '']}
128 title =
"log_user_in"
129 data = {
'status': self.
success,
'token':
''}
130 self.
disp.log_debug(f
"e-mail = {email}", title)
138 if isinstance(usr_id, int):
139 data[
'status'] = self.
error
141 self.
disp.log_debug(f
"usr_id = {usr_id}", title)
143 CONST.UA_TOKEN_LIFESPAN
146 uid = str(int(usr_id[0][0]))
147 self.
disp.log_debug(f
"uid = {uid}", title)
149 data[
'status'] = self.
error
151 usr_data = [token, uid, lifespan]
152 self.
disp.log_debug(f
"usr_data = {usr_data}", title)
154 data[
'token'] = token
155 self.
disp.log_debug(f
"Response data: {data}", title)
160 Return the token if it is present.
163 request (Request): _description_: the request header created by the endpoint caller.
166 Union[str, None]: _description_: If the token is present, a string is returned, otherwise, it is None.
168 mtoken: Union[str,
None] = request.get(CONST.REQUEST_TOKEN_KEY)
169 mbearer: Union[str,
None] = request.get(CONST.REQUEST_BEARER_KEY)
170 token: Union[str,
None] = request.headers.get(CONST.REQUEST_TOKEN_KEY)
171 bearer: Union[str,
None] = request.headers.get(
172 CONST.REQUEST_BEARER_KEY
174 msg = f
"mtoken = {mtoken}, mbearer = {mbearer}"
175 msg += f
", token = {token}, bearer = {bearer}"
176 self.
disp.log_debug(msg,
"get_token_if_present")
177 if token
is None and bearer
is None and token
is None and bearer
is None:
179 if mbearer
is not None and mbearer.startswith(
'Bearer '):
180 return mbearer.split(
" ")[1]
181 if bearer
is not None and bearer.startswith(
'Bearer '):
182 return bearer.split(
" ")[1]
183 if token
is not None:
187 async def get_body(self, request: Request) -> Dict[str, Any]:
189 Get the body of a request, whether it's JSON or form data.
191 request (Request): The incoming request object.
194 Dict[str, Any]: Parsed request body in dictionary format.
196 body: Dict[str, Any] = {}
199 body = await request.json()
202 form = await request.form()
205 files = await request.form()
208 for file_key, file_value
in files.items():
209 if isinstance(file_value, UploadFile):
210 body[
"_files"][file_key] = {
211 "filename": file_value.filename,
212 "content_type": file_value.content_type,
213 "content": await file_value.read()
215 except Exception
as form_error:
216 msg = f
"Failed to parse request body: {str(form_error)}"
217 body = {
"error": msg}
222 Attempt to log the user out based on the provided token.
225 token (str): _description_: The token of the account
228 Dict[str, Any]: _description_: The response status
229 {'status':Union[success, error], 'msg':'message'}
231 title =
"log_user_out"
232 data = {
'status': self.
error,
'msg':
"You are not logged in !"}
234 data[
"msg"] =
"No token provided !"
238 CONST.TAB_CONNECTIONS,
240 where=f
"token={token}",
243 if isinstance(login_table, int):
245 if len(login_table) != 1:
247 self.
disp.log_debug(f
"login_table = {login_table}", title)
249 CONST.TAB_CONNECTIONS,
253 data[
"msg"] =
"Data not removed successfully !"
254 self.
disp.log_error(data[
"msg"], title)
257 data[
"msg"] =
"You have successfully logged out."
bool token_correct(self, Request request)
int _insert_login_into_database(self, dict[str, any] user_data)
Union[str, None] get_token_if_present(self, Request request)
RuntimeData runtime_data_initialised
None __init__(self, RuntimeData runtime_data, int error=84, int success=0, bool debug=False)
Dict[str, Any] log_user_out(self, str token="")
Dict[str, Any] get_body(self, Request request)
Dict[str, Any] log_user_in(self, str email='')
bool logged_in(self, Request request)