-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtool.py
341 lines (248 loc) · 10.1 KB
/
tool.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# This file exists to provide tool functions for the main python script (app.py)
import os
import json
import names
import hashlib
import binascii
import constants
import random as rm
from coolname import generate
def genbook():
'''
Generates book information
Title randomly generated from coolname
Author randomly generated from names library
ISBN is randomly generated 12 digit number
CourseID is a randomly chosen id based off of known Ids
:return: Dictionary containing a title, author, and ISBN-13
'''
title = ' '.join(generate(3)).title()
author = names.get_full_name()
# Generate ISBN with proper checksum
isbn = ''.join([str(rm.randrange(10)) for i in range(12)])
check = sum([int(i) * 3 if isbn.index(i) % 2 != 0 else int(i) for i in isbn]) % 10
digit = check if check == 0 else 10 - check
isbn += str(digit)
courseID = rm.choice(constants.courseIds)
BNumber = rm.randint(0, 200)
BPic = rm.choice(constants.sampleBoookPics)
BPrice = float(str(rm.randrange(600)) + "." + str(rm.randrange(100)).zfill(2))
BDesc = f"{title} is a{rm.choice([' great', 'n awesome', ' bad', ' lovely', 'n ok'])} book but now I am " + \
f"{rm.choice(['choosing', 'being forced'])} to sell it. The book is in " + \
f"{rm.choice(['great', 'awesome', 'bad', 'lovely', 'ok'])} condition please contact me at the email " + \
"above if interested."
return {'id': BNumber, 'title': title, 'author': author, 'isbn': isbn, 'courseID': courseID, 'BPic': BPic,
'BPrice': BPrice, 'BDesc': BDesc}
# DB setup
def db_setup(connection, cursor, filename):
""" Creates the tables of the database and inserts course data into Courses table"""
if connection is not None:
with open(filename, "r") as f:
sqlfile = f.read()
commands = sqlfile.split(";")
for c in commands:
try:
if c.strip() != "":
cursor.execute(c + ";")
except:
pass
connection.commit()
else:
print("Connection is None")
# adds a book to the database
def db_add_book(connection, cursor, book_info):
if connection is not None:
insertion_command = "INSERT INTO Books (BNumber, BTitle, BAuthor, BISBN, BCourse, BPic, BPrice, BDesc) " \
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s) "
if type(book_info) == list:
cursor.executemany(insertion_command, book_info)
else:
cursor.execute(insertion_command, book_info)
connection.commit()
else:
print("Connection is None")
# Acts as wrapper function for db_add_book to automatically inserts randomly generated books
def db_insert_random_books(connection, cursor, numberOfBooks):
if connection is not None:
book_info = [tuple(genbook().values()) for _ in range(numberOfBooks)]
db_add_book(connection, cursor, book_info)
else:
print("Connection is not None")
# fetches n books stored in the db from top to bottom
def db_get_n_books(cursor, numberOfBooks):
if cursor is not None:
cursor.execute(f"select * from books limit {numberOfBooks}")
return cursor.fetchall()
else:
print("Cursor is None")
# adds b users to the database
def db_insert_random_users(conn, numUsers):
while numUsers > 0:
username = names.get_full_name().replace(" ", "_")[:18]
password = "VerySecurePassword"
email = username + "@uwindsor.ca"
valid, _ = register(username, password, email, conn)
if valid:
numUsers -= 1
# adds a random postings to the database
def db_insert_random_posting(conn, UserID, UBooks, PostDates):
cur = conn.cursor(dictionary=True, buffered=True)
retrieval_command = "Select UBooks, PostDates from postings where UserID = %s"
cur.execute(retrieval_command, [UserID])
data = cur.fetchone()
# in case that this is the first posting by a user
# add a row in the table
if data is None:
insertion_command = "INSERT INTO Postings (UserID, UBooks, PostDates) VALUES (%s, %s, %s)"
cur.execute(insertion_command, [UserID, json.dumps([UBooks]), json.dumps([PostDates])])
# if the user posted a book already, update data
else:
pBooks, pPostingDates = json.loads(data['UBooks']), json.loads(data['PostDates'])
# updating the data to now include the new post
pBooks.append(UBooks)
pPostingDates.append(PostDates)
update_postings_command_1 = "UPDATE Postings SET UBooks = %s WHERE UserID = %s"
update_postings_command_2 = "UPDATE Postings SET PostDates = %s WHERE UserID = %s"
cur.execute(update_postings_command_1, [json.dumps(pBooks), UserID])
cur.execute(update_postings_command_2, [json.dumps(pPostingDates), UserID])
conn.commit()
cur.close()
# adds n random postings to the database
def db_insert_n_random_postings(conn, numPostings):
cur = conn.cursor(dictionary=True)
cur.execute("select UserID from users")
availableUserIds = cur.fetchall()
for _ in range(numPostings):
year = rm.randint(1900, 2019)
month = rm.randint(1, 13)
day = rm.randint(1, 30)
hour = rm.randint(0, 24)
minute = rm.randint(0, 60)
second = rm.randint(0, 59)
postdate = f"{year}-{month:02d}-{day:02d} {hour:02d}:{minute:02d}:{second:02d}"
# creating a book then adding it to the db
book = genbook()
db_add_book(conn, cur, tuple(book.values()))
# adding who posted the book to the db
UserID = rm.choice(availableUserIds)['UserID']
Ubooks = book['isbn']
db_insert_random_posting(conn, UserID, Ubooks, postdate)
conn.commit()
cur.close()
# checks if a username + password matches anything stored
def userLogin(email, password, conn):
# getting the users infomation
u = getUser("*", email, conn)
if u is None:
return None
# verifying password is the stored one
salt = u["UPassword"][:64]
if u["UPassword"] == hash_password(password, salt.encode('ascii')):
return u
return None
# given a username, their profile is retrieved
def getUser(attribute, emailOrUsername, conn):
# looking for user in DB
cur = conn.cursor(dictionary=True)
# if email give search by email
if emailOrUsername.endswith("@uwindsor.ca"):
cur.execute(f"select {attribute} from users where UEmail = '{emailOrUsername}'")
# otherwise search by username
else:
cur.execute(f"select {attribute} from users where UserID = '{emailOrUsername}'")
# Try to fetch user info from DB
u = cur.fetchone()
cur.close()
# if we found a user return user dict
if u:
if "UBooks" in u:
# turning the list of books back into a list
u["UBooks"] = json.loads(u["UBooks"])
return u
return u
# if we didn't find user with said username, return None
return None
def register(username, password, email, conn):
"""
Creates a new user and adds their information into the database
"""
# if the user has an allowed email
if isUniversityEmail(email):
if isAvailableEmail(email, conn):
if isAvailableUsername(username, conn):
# generate a user's profile
user = dict(UserID=username, UPassword=hash_password(password, None), UEmail=email,
UBooks='[]', UOtherInfo="", IsAdmin=0)
# insert user into the db
cur = conn.cursor(dictionary=True)
insertion_command = "INSERT INTO Users (UserID, UPassword, UEmail, UBooks, UOtherInfo, IsAdmin) " \
"VALUES (%s, %s, %s, %s, %s, %s)"
cur.execute(insertion_command, tuple(user.values()))
conn.commit()
user['UBooks'] = []
return True, user
else:
return False, f"Username: {username} is not available"
else:
return False, f"Email: {email} is not available"
else:
return False, f"Email: {email} is not a university of windsor email"
def hash_password(password, salt=None):
"""
convert a password into it's hashed representation
when verifying passwords a salt can be given
"""
if salt is None:
salt = hashlib.sha256(os.urandom(60)).hexdigest().encode('ascii')
hashed_password = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'), salt, 100000)
hashed_password = binascii.hexlify(hashed_password)
return (salt + hashed_password).decode('ascii')
def isAvailableEmail(email, conn):
"""
Checks if an account exists with a given email
"""
cur = conn.cursor(dictionary=True)
# Grab info for user based on email
cur.execute("select UserID from users where UEmail = %s", [email])
# Try to fetch user info from DB
u = cur.fetchone()
cur.close()
return False if u else True
def isAvailableUsername(username, conn):
"""
Checks if an account exists with a given username
"""
cur = conn.cursor(dictionary=True)
# Grab info for user based on email
cur.execute("select UserID from users where UserID = %s", [username])
# Try to fetch user info from DB
u = cur.fetchone()
cur.close()
return False if u else True
def isUniversityEmail(email):
"""
Checks if the person has a university of windsor email
"""
return email.lower().endswith('@uwindsor.ca')
# validates if a given number is a valid isbn13 number
def isValidISBN(ISBN):
if len(ISBN) != 13:
return False
ISBN = int(ISBN)
multiplier = 3
check_sum = ISBN % 10
calculated_check_sum = 0
while ISBN != 0:
ISBN = ISBN // 10
digit = ISBN % 10
calculated_check_sum += multiplier * digit
if multiplier == 3:
multiplier = 1
else:
multiplier = 3
calculated_check_sum = calculated_check_sum % 10
if calculated_check_sum != 0:
calculated_check_sum = 10 - calculated_check_sum
return calculated_check_sum == check_sum
if __name__ == '__main__':
genbook()