Terarea  2
The automation project
Loading...
Searching...
No Matches
incomming.py
Go to the documentation of this file.
1"""_summary_
2 File containing boilerplate functions that could be used by the server in it's endpoints_initialised for checking incoming data.
3"""
4
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
8
9from ..components import RuntimeData, CONST
10
11
13 """_summary_
14 """
15
16 def __init__(self, runtime_data: RuntimeData, error: int = 84, success: int = 0, debug: bool = False) -> None:
17 self.debug: bool = debug
18 self.success: int = success
19 self.error: int = error
20 self.runtime_data_initialised: RuntimeData = runtime_data
21 # ------------------------ The logging function ------------------------
22 self.disp: Disp = Disp(
23 TOML_CONF,
24 FILE_DESCRIPTOR,
25 SAVE_TO_FILE,
26 FILE_NAME,
27 debug=self.debug,
28 logger=self.__class__.__name__
29 )
30
31 def token_correct(self, request: Request) -> bool:
32 """_summary_
33 This is a function that will check if the token is correct or not.
34 Args:
35 request (Request): _description_: The request object
36
37 Returns:
38 bool: _description_: True if the token is correct, False otherwise
39 """
40 title = "token_correct"
41 self.disp.log_debug(
42 f"request = {request}", title
43 )
44 token = self.get_token_if_present(request)
45 self.disp.log_debug(
46 f"token = {token}", title
47 )
48 if token is None:
49 return False
50 return self.runtime_data_initialised.boilerplate_non_http_initialised.is_token_correct(token)
51
52 def logged_in(self, request: Request) -> bool:
53 """_summary_
54 This is a function that will check if the user is logged in or not.
55 Args:
56 request (Request): _description_: The request object
57
58 Returns:
59 bool: _description_: True if the user is logged in, False otherwise
60 """
61 title = "logged_in"
62 self.disp.log_debug(
63 f"request = {request}", title
64 )
65 self.disp.log_warning(
66 "This function is the same as token_correct, please call token correct instead",
67 title
68 )
69 return self.token_correct(request)
70
71 def _insert_login_into_database(self, user_data: dict[str, any]) -> int:
72 """_summary_
73 Insert the user data into the database.
74 Args:
75 user_data (dict[str, any]): _description_: The user data to insert into the database
76
77 Returns:
78 int: _description_: The status of the operation
79 """
80 title = "_insert_login_into_database"
81 if len(user_data) != 3:
82 self.disp.log_error(
83 "The user data is not in the correct format !", title
84 )
85 return self.error
86 self.disp.log_debug(
87 f"user_data = {user_data}", title
88 )
89 user_data[-1] = self.runtime_data_initialised.database_link.datetime_to_string(
90 user_data[-1]
91 )
92 self.disp.log_debug(
93 f"stringed_datetime = {user_data}", title
94 )
95 table_columns = self.runtime_data_initialised.database_link.get_table_column_names(
96 CONST.TAB_CONNECTIONS
97 )
98 table_columns.pop(0)
99 self.disp.log_debug(
100 f"table_columns = {table_columns}", title
101 )
102 status = self.runtime_data_initialised.database_link.insert_or_update_data_into_table(
103 table="Connections",
104 data=user_data,
105 columns=table_columns
106 )
107 if status != self.success:
108 self.disp.log_error(
109 "Data not inserted successfully !", title
110 )
111 return self.error
112 self.disp.log_debug(
113 "Data inserted successfully.", title
114 )
115 return self.success
116
117 def log_user_in(self, email: str = '') -> Dict[str, Any]:
118 """_summary_
119 Attempt to log the user in based on the provided credentials and the database.
120
121 Args:
122 email (str): _description_: The email of the account
123
124 Returns:
125 Dict[str, Any]: _description_: The response status
126 {'status':Union[success, error], 'token':Union['some_token', '']}
127 """
128 title = "log_user_in"
129 data = {'status': self.success, 'token': ''}
130 self.disp.log_debug(f"e-mail = {email}", title)
131 token = self.runtime_data_initialised.boilerplate_non_http_initialised.generate_token()
132 usr_id = self.runtime_data_initialised.database_link.get_data_from_table(
133 CONST.TAB_ACCOUNTS,
134 "id",
135 f"email='{email}'",
136 beautify=False
137 )
138 if isinstance(usr_id, int):
139 data['status'] = self.error
140 return data
141 self.disp.log_debug(f"usr_id = {usr_id}", title)
142 lifespan = self.runtime_data_initialised.boilerplate_non_http_initialised.set_lifespan(
143 CONST.UA_TOKEN_LIFESPAN
144 )
145 try:
146 uid = str(int(usr_id[0][0]))
147 self.disp.log_debug(f"uid = {uid}", title)
148 except ValueError:
149 data['status'] = self.error
150 return data
151 usr_data = [token, uid, lifespan]
152 self.disp.log_debug(f"usr_data = {usr_data}", title)
153 data['status'] = self._insert_login_into_database(usr_data)
154 data['token'] = token
155 self.disp.log_debug(f"Response data: {data}", title)
156 return data
157
158 def get_token_if_present(self, request: Request) -> Union[str, None]:
159 """_summary_
160 Return the token if it is present.
161
162 Args:
163 request (Request): _description_: the request header created by the endpoint caller.
164
165 Returns:
166 Union[str, None]: _description_: If the token is present, a string is returned, otherwise, it is None.
167 """
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
173 )
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:
178 return 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:
184 return token
185 return mtoken
186
187 async def get_body(self, request: Request) -> Dict[str, Any]:
188 """
189 Get the body of a request, whether it's JSON or form data.
190 Args:
191 request (Request): The incoming request object.
192
193 Returns:
194 Dict[str, Any]: Parsed request body in dictionary format.
195 """
196 body: Dict[str, Any] = {}
197
198 try:
199 body = await request.json()
200 except Exception:
201 try:
202 form = await request.form()
203 body = dict(form)
204
205 files = await request.form()
206 body["_files"] = {}
207
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()
214 }
215 except Exception as form_error:
216 msg = f"Failed to parse request body: {str(form_error)}"
217 body = {"error": msg}
218 return body
219
220 def log_user_out(self, token: str = "") -> Dict[str, Any]:
221 """_summary_
222 Attempt to log the user out based on the provided token.
223
224 Args:
225 token (str): _description_: The token of the account
226
227 Returns:
228 Dict[str, Any]: _description_: The response status
229 {'status':Union[success, error], 'msg':'message'}
230 """
231 title = "log_user_out"
232 data = {'status': self.error, 'msg': "You are not logged in !"}
233 if token == "":
234 data["msg"] = "No token provided !"
235 return data
236
237 login_table = self.runtime_data_initialised.database_link.get_data_from_table(
238 CONST.TAB_CONNECTIONS,
239 "*",
240 where=f"token={token}",
241 beautify=False
242 )
243 if isinstance(login_table, int):
244 return False
245 if len(login_table) != 1:
246 return False
247 self.disp.log_debug(f"login_table = {login_table}", title)
248 status = self.runtime_data_initialised.database_link.remove_data_from_table(
249 CONST.TAB_CONNECTIONS,
250 f"token={token}"
251 )
252 if status != self.success:
253 data["msg"] = "Data not removed successfully !"
254 self.disp.log_error(data["msg"], title)
255 return data
256 data["status"] = self.success
257 data["msg"] = "You have successfully logged out."
258 return data
int _insert_login_into_database(self, dict[str, any] user_data)
Definition incomming.py:71
Union[str, None] get_token_if_present(self, Request request)
Definition incomming.py:158
None __init__(self, RuntimeData runtime_data, int error=84, int success=0, bool debug=False)
Definition incomming.py:16
Dict[str, Any] log_user_out(self, str token="")
Definition incomming.py:220
Dict[str, Any] get_body(self, Request request)
Definition incomming.py:187
Dict[str, Any] log_user_in(self, str email='')
Definition incomming.py:117