· 4 years ago · Mar 13, 2021, 03:44 PM
1from colorama import Fore
2
3# region for encryption
4from cryptography.fernet import Fernet
5from cryptography.hazmat.backends import default_backend
6from cryptography.hazmat.primitives import hashes
7from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
8# endregion
9
10# region db (original idea)
11import mysql.connector
12
13from sqlalchemy.ext.automap import automap_base
14from sqlalchemy import create_engine, MetaData, Column, String, Table
15from sqlalchemy.orm import Session
16
17# endregion
18
19# region firebase connection
20# import firebase_admin
21# from firebase_admin import credentials
22# endregion
23
24# region flask
25from flask import *
26# endregion
27
28from os import system, name # clear the screen
29import base64 # for encryption
30import string # generating api and other random strings
31import random # generating api and other random strings
32import json # using the data from mobile app
33import os # for generating new salt for each incoming and out going data
34# import socket
35
36# import os # might delete
37import datetime
38from datetime import timedelta
39import colorama
40import cryptography # not sure why it's showing that it's not being used
41
42# region debugging in terminals
43colorama.init(autoreset=True)
44RED = Fore.RED
45# endregion
46
47# initiate the flask web framework
48app = Flask(__name__)
49
50# information for copywritten
51__creator__ = "Pombo Technologies"
52__version__ = 0.002
53
54# region connection
55try:
56 # 10.87.107.19 (66.228.52.158)
57 host_ip = "66.228.52.158"
58 db_user = "username"
59 db_psw = "Asdf@1234"
60 db_name = "Flow"
61 Port = 3306
62
63 """
64 user='myuser',
65 password='mypassword',
66 host='localhost',
67 port='3306',
68 database='mydb'
69 """
70 mydb = mysql.connector.connect(
71 user=db_user,
72 password=db_psw,
73 host=host_ip,
74 port=Port,
75 database=db_name
76 # ,
77 # auth_plugin="mysql_native_password"
78 )
79
80except Exception as e:
81 print(f"{Fore.GREEN} * error: {str(e)}")
82# endregion
83
84
85def get_user_login(username):
86 try:
87 mycursor = mydb.cursor()
88
89 sql = f"SELECT * FROM `users` WHERE `user-name` = '{username}'"
90 mycursor.execute(sql)
91
92 # true = user exist
93 # false = user does not exist
94 if mydb.commit():
95 if mycursor.fetchone():
96 return True
97 else:
98 return False
99
100 else:
101 print("error with getting the information from the database")
102
103 except Exception as e:
104 print(f"{RED} error {str(e)}")
105
106
107def insertNewUser(userEmail, password, date, apiKey):
108 # inserting new users via email and password
109 try:
110 mycursor = mydb.cursor()
111
112 sql = "INSERT INTO `users`(`user-name`, `email`, `password`, `user-preference`, `date-created`, `api-key`) VALUES (%s, %s, %s, %s, %s, %s)"
113 val = (userEmail, userEmail, password, "", date, "")
114 mycursor.execute(sql, val)
115
116 if get_user_login(userEmail) == False:
117 if mydb.commit():
118 return True
119 else:
120 return False
121
122 except Exception as e:
123 print(f"{RED} * error: {str(e)}")
124
125
126def all(): # debugging purposes
127 try:
128 mycursor = mydb.cursor()
129
130 sql = "SELECT * FROM `users`"
131 mycursor.execute(sql)
132
133 myresult = mycursor.fetchall()
134
135 if mydb.commit():
136 for x in myresult:
137 print(x)
138
139 return True
140 else:
141 return False
142
143 except Exception as e:
144 print(f"{RED} * error: {str(e)}")
145
146
147# region global variables
148# for encrypting into bytes
149FORMAT = "utf-8"
150
151# for generating the keys
152# os.urandom(16)
153# endregion
154
155
156@app.route('/api/createuser', methods=['POST', 'GET'])
157def createUSR(): # creating an user via post method
158 try:
159 data = json.loads(request.data) # load incoming data
160
161 print(f"{Fore.GREEN} {data}")
162
163 print(data['password'])
164
165 # making sense of incoming json data
166 userEmail = data['email']
167 user_psw = data['password']
168
169 # region data
170 userEmail = str(userEmail).strip()
171 user_psw = str(user_psw).strip()
172
173 # encryption
174 user_password = encrypt(user_psw)
175
176 date = get_Date() # setting the date of the creation of account
177
178 # for accessing this api. 20 is long enough i think
179 # api_key = genAPIKey(20)
180
181 # insertNewUser(userEmail, user_password, date, api_key)
182
183 if insertNewUser(userEmail, user_password, date, ""):
184 return json.dumps(
185 {
186 "Server:": "Data received",
187 }
188 )
189
190 else:
191 return json.dumps(
192 {
193 "server:": "Data received not inserted"
194 }
195 )
196
197 # endregion
198
199 except Exception as e:
200 log(str(e)) # logging any known errors.
201 print(f"{RED} error: {str(e)}")
202
203
204@app.route('/')
205def func_name():
206 return "<h1>Testing done. check the db</h1>"
207
208
209# region usefull functions
210
211
212def RecoverAccountEmail(email): # using emails
213 pass
214
215
216def get_encryption_key(msg): # generate encryption key to encrypt lol
217 try:
218 # stripping any white spaces
219 password_provided = str(msg).strip()
220
221 # encoding into a byte
222 password = password_provided.encode(FORMAT)
223
224 # salt used to encrypt
225 # salt = b"\xb9\x1f|}'S\xa1\x96\xeb\x154\x04\x88\xf3\xdf\x05"
226 salt = os.urandom(32)
227
228 # generating said key
229 kdf = PBKDF2HMAC(
230 algorithm=hashes.SHA256(),
231 length=32,
232 salt=salt,
233 iterations=100000,
234 backend=default_backend()
235 )
236
237 # encrypt it?
238 key = base64.urlsafe_b64encode(kdf.derive(password))
239
240 return key # this is the key that'll be used for encryption
241
242 except Exception as e:
243 print(f"Error: {str(e)}")
244
245
246def encrypt(data): # encrypt
247 try:
248 # encrypt data
249 fernet = Fernet(
250 get_encryption_key(
251 data.encode(FORMAT)
252 )
253 )
254 return fernet.encrypt(
255 data.encode(FORMAT)
256 )
257 except Exception as e:
258 print(f"error: {str(e)}")
259
260
261def decrypt(data): # decrypt
262 try:
263 # decrypt data
264 fernet = Fernet(
265 get_encryption_key(
266 data
267 )
268 )
269 return fernet.decrypt(
270 data
271 )
272 except Exception as e:
273 print(f"error: {str(e)}")
274
275
276def get_time(): # get full 12 hour time
277 x = datetime.datetime.now()
278
279 hour = x.strftime("%I") # hour
280 min = x.strftime("%M") # minute
281 AMPM = x.strftime("%p") # am / pm
282
283 return f"{hour} : {min} : {AMPM}"
284
285
286def get_Date(): # get full date
287 return datetime.datetime.now().strftime("%x")
288
289
290def log(msg): # writing a .txt file with the errors in a list
291 # make this into an excel file or something more readable and user friendly
292 """
293 log number being written.
294 get the date and time
295 and showing the log
296 """
297 f = open("./err_log/log.txt", "a")
298 f.write(
299 f"\n________________________________\n" +
300 f" log id: {rnd(1000000)} \n" +
301 f"________________________________\n" +
302 f" date: {get_Date()} \n" +
303 f"________________________________\n" +
304 f" time: {get_time()} \n" +
305 f"________________________________\n" +
306 f" error log: {msg} \n" +
307 f"________________________________\n"
308 )
309 f.close()
310
311 print(f"{RED}Error logged into log.txt........")
312
313
314def genAPIKey(N): # generating the random api key and saving it with each user
315 return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
316
317
318def rnd(last): # random number generator for choosing 1
319 return random.randint(1, last)
320
321
322def cls():
323 # for windows
324 if name == 'nt':
325 _ = system('cls')
326
327 # for mac and linux(here, os.name is 'posix')
328 else:
329 _ = system('clear')
330
331# endregion
332
333
334def run(): # do not delete this!!!
335 try:
336 # , host='0.0.0.0'
337 # all()
338 app.run(threaded=True, host="0.0.0.0", debug=True)
339 except Exception as e:
340 log(str(e)) # logging any known errors.
341 # print(f" * error: {str(e)}")
342
343# endregion
344
345
346if __name__ == '__main__': # the start of the api
347 run()
348