-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
379 lines (283 loc) · 11.1 KB
/
server.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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
from http.server import BaseHTTPRequestHandler, HTTPServer
import sys
from urllib.parse import urlparse, parse_qs
import json
from classes_db import ClassesDB
from http import cookies
from passlib.hash import bcrypt
from session_store import SessionStores
SESSION_STORE = SessionStores()
class MyRequestHandler(BaseHTTPRequestHandler):
def end_headers(self):
self.send_cookie()
self.send_header("Access-Control-Allow-Origin", self.headers["Origin"])
self.send_header("Access-Control-Allow-Credentials", "true")
BaseHTTPRequestHandler.end_headers(self)
#goal: load cookie into self.cookie
def load_cookie(self):
if "Cookie" in self.headers:
self.cookie = cookies.SimpleCookie(self.headers["Cookie"])
else:
self.cookie = cookies.SimpleCookie()
def send_cookie(self):
for morsel in self.cookie.values():
self.send_header("set-cookie", morsel.OutputString())
#goal: load session into self.session
def load_session(self):
self.load_cookie()
#if session ID in the cookie
if "sessionId" in self.cookie:
sessionId = self.cookie["sessionId"].value
#if session ID exists in the session store.
#save the session for use later.(data_member)
self.session = SESSION_STORE.getSession(sessionId)
#otherwise, if session ID not in the session store
if self.session == None:
#create new session
sessionId = SESSION_STORE.createSession()
self.session = SESSION_STORE.getSession(sessionId)
#set the new session ID into the cookie.
self.cookie["sessionId"] = sessionId
#otherwise if session ID is NOT in the cookie
else:
sessionId = SESSION_STORE.createSession()
self.session = SESSION_STORE.getSession(sessionId)
self.cookie["sessionId"] = sessionId
#either load session data based on session ID in cookie
#OR create a new session and session ID and cookie.
#SUDO CODE.
#1. if session ID in the cookie.
#if session ID exists in the session store.
#save the session for use later.(data_member)
#otherwise, if session ID not in the session store
#create a new session
#set the new session ID into the cookie.
#otherwise, if session Id is NOT in the cookie.
#create a new session
#set the new session ID into the cookie.
def handleNotFound(self):
self.send_response(404)
self.send_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write(bytes("The class was not Found", "utf-8"))
def do_OPTIONS(self):
self.load_session()
self.send_response(200)
self.send_header("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "Content-Type")
self.end_headers()
def loggedIn(self):
if "userId" in self.session:
return True
else:
return False
def handleClassList(self):
if self.loggedIn():
self.send_response(200)
#headers
self.send_header("Content-Type", "application/json")
self.end_headers()
db = ClassesDB()
classes = db.getAllClasses()
self.wfile.write(bytes(json.dumps(classes), "utf-8"))
else:
self.handle401()
def handleClassCreate(self):
if self.loggedIn():
length = self.headers["Content-length"]
body = self.rfile.read(int(length)).decode("utf-8")
print("The text body:", body)
parsed_body = parse_qs(body)
print("the parsed body:", parsed_body)
#saving the class
clas = parsed_body["clas"][0]
major = parsed_body["major"][0]
professor = parsed_body["professor"][0]
location = parsed_body["location"][0]
rating = parsed_body["rating"][0]
#sending the values to the data base
db = ClassesDB()
db.createClass(clas, major, professor, location, rating)
self.send_response(201)
self.end_headers()
else:
self.handle401()
def handleClassDelete(self,id):
#if "userdId" not in self.session:
# self.send_response(401)
# return
#return
#if the user is not logged in:
# self.handle401()
# return
if self.loggedIn():
db = ClassesDB()
clas = db.getClass(id)
if clas == None:
self.handleNotFound()
else:
self.send_response(200)
#headers
self.send_header("Content-type", "application/json")
self.end_headers()
db.deleteClass(id)
self.wfile.write(bytes(json.dumps(clas), "utf-8"))
else:
self.handle401()
def handleClassRetrieve(self, id):
db = ClassesDB()
clas = db.getClass(id)
if clas == None:
self.handleNotFound()
else:
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
self.wfile.write(bytes(json.dumps(clas), "utf-8"))
def handleClassUpdate(self):
parts = self.path.split("/")
class_id = parts[2]
db = ClassesDB()
clas = db.getClass(class_id)
if clas != None:
#responding to the client
self.send_response(200)
self.send_header("Content-type", "application/json")
#self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
self.wfile.write(bytes(json.dumps(clas), "utf-8"))
length = self.headers["Content-length"]
#reading the body to a string
body = self.rfile.read(int(length)).decode("utf-8")
print("Body: ", body)
#print the body as a string
parsed_body = parse_qs(body)
print("parsed body", parsed_body)
clas = parsed_body["clas"][0]
major = parsed_body["major"][0]
professor = parsed_body["professor"][0]
location = parsed_body["location"][0]
rating = parsed_body["rating"][0]
db.updateClass(clas,major,professor,location,rating,class_id)
self.send_response(200)
#self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
else:
self.handleNotFound()
def do_DELETE(self):
self.load_session()
parts = self.path.split('/')[1:]
collection = parts[0]
if len(parts) > 1:
id = parts[1]
else:
id = None
if collection == "classes":
if id == None:
self.handleClassList()
else:
self.handleClassDelete(id)
else:
self.handleNotFound()
def do_GET(self):
self.load_session()
parts = self.path.split('/')[1:]
collection = parts[0]
if len(parts) > 1:
id = parts[1]
else:
id = None
if collection == "classes":
if id == None:
self.handleClassList()
else:
self.handleClassRetrieve(id)
else:
self.handleNotFound()
def do_POST(self):
self.load_session()
#create action
path = self.path.split('?')
print(path[0])
print("Path: ", self.path)
if path[0] == "/classes":
self.handleClassCreate()
elif path[0] == "/users":
self.handleUserCreate()
elif path[0] == "/sessions":
self.handleSessionCreate()
else:
self.handleNotFound()
def do_PUT(self):
self.load_session()
if self.path.split('/')[1:]:
self.handleClassUpdate()
else:
self.handleNotFound()
def handleSessionCreate(self):
length = self.headers["Content-length"] #gets the length
body = self.rfile.read(int(length)).decode("utf-8")
parsed_body = parse_qs(body)
print("this is the parsed body: ", parsed_body)
email = parsed_body["email"][0]
password = parsed_body["password"][0]
db = ClassesDB()
user = db.getUserByEmail(email) #getting the user by its email
#checking if the email exists
if user == False:
self.handle401()
else:
encrypass = db.getPassword(email) #encrypting the password
if bcrypt.verify(password, encrypass):
self.session["userId"] = email
self.send_response(201)
self.end_headers()
self.wfile.write(bytes("Created", "utf-8"))
else:
self.handle401()
self.wfile.write(bytes("Invalid login info", "utf-8"))
def handleUserCreate(self):
length = self.headers["Content-length"]
body = self.rfile.read(int(length)).decode("utf-8")
parsed_body = parse_qs(body)
print("This is the parsed body: ", parsed_body)
#saving the user
firstName = parsed_body["fname"][0]
lastName = parsed_body["lname"][0]
email = parsed_body["email"][0]
password = parsed_body["password"][0]
#password encrypt
encryptedPassword = bcrypt.hash(password)
db = ClassesDB()
user = db.getUserByEmail(email)
#checking if user exists
print("Checking prior to see if user exists")
if user == False:
db.createUser(firstName, lastName, email, encryptedPassword)
self.send_response(201)
self.end_headers()
self.wfile.write(bytes("User created", "utf-8"))
else:
self.send_response(422)
self.end_headers()
self.wfile.write(bytes("Email already exists", "utf-8"))
def handle401(self):
self.send_response(401)
self.end_headers()
def run():
db = ClassesDB()
db.createClassTable()
db.createUsersTable()
db = None #disconnect
port = 8080
if len(sys.argv) > 1:
port = int(sys.argv[1])
listen = ("0.0.0.0", port)
server = HTTPServer(listen, MyRequestHandler)
print("Server listening on", "{}:{}".format(*listen))
server.serve_forever()
#listen = ('localhost', 8080)
#server = HTTPServer(listen, MyRequestHandler)
#print("Listening...")
#server.serve_forever()
run()