-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjserver.py
265 lines (215 loc) · 7.77 KB
/
jserver.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
from session_store import SessionStore
from passlib.hash import bcrypt
from logsdb import LogsDB
from http.server import BaseHTTPRequestHandler, HTTPServer
from http import cookies
#parse_qs turns incoming data into a dictionary with arrays as its values
from urllib.parse import parse_qs
import json
SESSION_STORE = SessionStore()
class MyHTTPRequestHandler(BaseHTTPRequestHandler):
def end_headers(self):
self.sendCookie()
self.send_header("Access-Control-Allow-Origin", self.headers['Origin'])
self.send_header("Access-Control-Allow-Credentials", "true")
BaseHTTPRequestHandler.end_headers(self)
def readCookie(self):
if 'Cookie' in self.headers:
self.cookie = cookies.SimpleCookie(self.headers['Cookie'])
else:
self.cookie = cookies.SimpleCookie()
def sendCookie(self):
for morsel in self.cookie.values():
self.send_header('Set-Cookie', morsel.OutputString())
def loadSessionData(self):
self.readCookie()
#TODO: implement the algorithm
if 'sessionId' in self.cookie:
sessionId = self.cookie['sessionId'].value
sessionData = SESSION_STORE.getSessionData(sessionId)
if sessionData == None:
#creates a new session with a new cookie value
sessionId = SESSION_STORE.createSession()
sessionData = SESSION_STORE.getSessionData(sessionId)
self.cookie['sessionId'] = sessionId
else:
sessionId = SESSION_STORE.createSession()
sessionData = SESSION_STORE.getSessionData(sessionId)
self.cookie['sessionId'] = sessionId
self.sessionData = sessionData
def handleNotFound(self):
self.send_response(404)
self.end_headers()
self.wfile.write(bytes("Not Found", "utf-8"))
def handle401(self):
self.send_response(401)
self.end_headers()
self.wfile.write(bytes("Not Logged In", "utf-8"))
def handleGetLogs(self):
if "userId" not in self.sessionData:
self.handle401()
return
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
db = LogsDB()
logs = db.getAllLogs()
self.wfile.write(bytes(json.dumps(logs), "utf-8"))
def handleGetOneLog(self, member_id):
if "userId" not in self.sessionData:
handle401()
return
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
db = LogsDB()
log = db.getOneLog(member_id)
self.wfile.write(bytes(json.dumps(log), "utf-8"))
def handleCreateLog(self):
if "userId" not in self.sessionData:
self.handle401()
return
length = self.headers['Content-Length']
body = self.rfile.read(int(length)).decode("utf-8")
parsed_body = parse_qs(body)
heading = parsed_body["heading"][0]
rating = parsed_body["rating"][0]
entry = parsed_body["entry"][0]
date = parsed_body["date"][0]
place = parsed_body["place"][0]
db = LogsDB()
db.insertLog(heading, rating, entry, date, place)
self.send_response(201)
self.end_headers()
def handleLogin(self):
#if "userId" not in self.sessionData:
# self.handle401()
# return
length = self.headers['Content-Length']
body = self.rfile.read(int(length)).decode("utf-8")
parsed_body = parse_qs(body)
email = parsed_body["email"][0]
password = parsed_body["password"][0]
db = LogsDB()
user = db.getOneUser(email)
if user == None:
self.send_response(401)
self.end_headers()
else:
if bcrypt.verify(password, user['password']):
self.sessionData['userId'] = user['id']
self.send_response(201)
self.end_headers()
else:
self.send_response(401)
self.end_headers()
def handleCreateUser(self):
length = self.headers['Content-Length']
body = self.rfile.read(int(length)).decode("utf-8")
parsed_body = parse_qs(body)
fname = parsed_body["f_name"][0]
lname = parsed_body["l_name"][0]
email = parsed_body["email"][0]
p = parsed_body["password"][0]
password = bcrypt.hash(p)
db = LogsDB()
user = db.getOneUser(email)
if user == None:
db.insertUser(fname, lname, email, password)
self.send_response(201)
else:
self.send_response(422)
self.end_headers()
def handleDeleteOneLog(self, member_id):
if "userId" not in self.sessionData:
self.handle401()
return
db = LogsDB()
log = db.getOneLog(member_id)
if log != None:
db.deleteOneLog(member_id)
self.send_response(200)
self.end_headers()
else:
self.handleNotFound()
def handleEditOneLog(self, member_id):
if "userId" not in self.sessionData:
self.handle401()
return
db = LogsDB()
log = db.getOneLog(member_id)
if log != None:
length = self.headers['Content-Length']
body = self.rfile.read(int(length)).decode("utf-8")
parsed_body = parse_qs(body)
heading = parsed_body["heading"][0]
rating = parsed_body["rating"][0]
entry = parsed_body["entry"][0]
date = parsed_body["date"][0]
place = parsed_body["place"][0]
db.editOneLog(member_id, heading, rating, entry, date, place)
self.send_response(200)
self.end_headers()
else:
self.handleNotFound()
def do_OPTIONS(self):
self.loadSessionData()
self.send_response(200)
self.send_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "Content-Type")
self.end_headers()
def do_GET(self):
self.loadSessionData()
parts = self.path.split('/')
collection = parts[1]
if len(parts) > 2:
member_id = parts[2]
else:
member_id = None
if collection == "logs":
if member_id:
self.handleGetOneLog(member_id)
else:
self.handleGetLogs()
else:
self.handleNotFound()
def do_POST(self):
self.loadSessionData()
if self.path == "/logs":
self.handleCreateLog()
elif self.path == "/users":
self.handleCreateUser()
elif self.path == "/sessions":
self.handleLogin()
else:
self.handleNotFound()
def do_DELETE(self):
self.loadSessionData()
parts = self.path.split('/')
collection = parts[1]
if len(parts) > 2:
member_id = parts[2]
else:
member_id = None
if collection == "logs" and member_id:
self.handleDeleteOneLog(member_id)
else:
self.handleNotFound()
def do_PUT(self):
self.loadSessionData()
parts = self.path.split('/')
collection = parts[1]
if len(parts) > 2:
member_id = parts[2]
else:
member_id = None
if collection == "logs" and member_id:
self.handleEditOneLog(member_id)
else:
self.handleNotFound()
def run():
listen = ("127.0.0.1", 8080)
server = HTTPServer(listen, MyHTTPRequestHandler)
print("Server is listening")
server.serve_forever()
run()