-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
527 lines (431 loc) · 18.5 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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
##################### Library Imports #####################
from logging import warning
from flask import Flask, request, jsonify, abort,render_template,render_template_string, redirect, url_for,session
from random import randrange
from requests_oauthlib import OAuth2Session
import json
import requests
import os
from configparser import ConfigParser
from proxy import *
import warnings
# -- ADINT Final Project
# -- Made by: Diogo Ferreira and Rafael Cordeiro
# ----------------------------------------
# --------------SERVER--------------------
# ----------------------------------------
URL_DB_user_hist = "http://localhost:8000/"
URL_DB_user = "http://localhost:8001/"
URL_DB_gates_hist = "http://localhost:8002/gate/occurrences/"
URL_DB_gates = "http://localhost:8003/gate/"
# This information is obtained upon registration of a new GitHub OAuth
# application here: https://github.com/settings/applications/new
client_id = "570015174623402"
client_secret = "uKU28VqDtiTGm1j51+FkjFwxOiBqMjU4DEVBeWyrzHZ+7VhdWcfQc+A1oaYmow2QMKDa/bsoQb6Gvf+/MD0eHw=="
authorization_base_url = 'https://fenix.tecnico.ulisboa.pt/oauth/userdialog'
token_url = 'https://fenix.tecnico.ulisboa.pt/oauth/access_token'
type_user = 'user'
ADMIN = []
#get admins info from config file
def getAdmin(file):
data = ConfigParser()
data.read(os.path.dirname(os.path.realpath(__file__)) + file)
return json.loads(data.get('IstGate','Admin'))
#convert int to char to create alphanumeric sequence
def int2char(n):
return chr(65+n-43*(n//26))
#returns alphanumeric sequence with lenght n
def randalph(n):
code=""
for i in range(n):
code+=int2char(randrange(36))
return code
#returns HTML for table page
def teste_table(dicList,err):
table = """{% extends 'layout.html' %}
{% block content %}
<body>
<h3> List of Gates</h3>"""
if not err:
table += draw_table(dicList)
else:
table += "Empty Table Received"
table += "</body>\n{% endblock %}"
return table
#returns HTML for table
def draw_table(d):
t = """<table border="1" class="dataframe Attendance">"""
k = list(d[0].keys())
t+= "<tr>"
for i in k:
t+= "<td>"+i+"</td>"
t+= "</tr>\n"
for i in d:
t+= "<tr>"
for j in k:
t+= "<td>"+str(i[j])+"</td>"
t+= "</tr>\n"
t += "</table>\n"
return t
#Flask
app = Flask(__name__)
#------------------------------------------GATE--------------------------
@app.route("/")
def index():
return render_template("index.html")
@app.route("/gate")
def gate():
return render_template("gauthe.html")
@app.route("/gateAuth")
def gateAuth():
data = request.args
try:
int(data.get('gateID'))
data.get('gateSecret')
except:
return render_template("badinput.html"), 400
res = checkgates(data.get('gateID'),data.get('gateSecret'))
if res["Valid"]=='1':
session["gateID"] = data.get('gateID')
session["gateSecret"] = data.get('gateSecret')
return redirect(url_for('.gateQR',gateID = str(data.get('gateID'))))
else:
return render_template("badlogin.html"), 401
# Gate Display
@app.route("/gateQR/<path:gateID>")
def gateQR(gateID):
try:
session["gateID"]
except:
return render_template("badinput.html"), 400
if session["gateID"] == gateID:
return app.send_static_file("qrcode.html")
return render_template("badlogin.html"), 401
# QR Code Validation
@app.route("/gate_scan",methods=["GET","POST"])
def gate_scan():
data = request.get_json()
try:
data['qr']
session["gateID"]
except:
abort(400)
try:
user = requests.get(URL_DB_user+"user/bycode",json={'code': data['qr']}).json()["userID"]
except:
aux = newGateOcco(session["gateID"],"CLOSED")
if aux == 2:
warnings.warn('The Backup DATABASE could not Update')
if aux == 3:
warnings.warn('The Main DATABASE could not Update')
if aux == 0:
warnings.warn('Both DATABASES could not Update')
return jsonify({'open': 0}), 201
try:
aux = requests.post(URL_DB_user_hist+"user/occurrences/newOccurrence",json={'user':str(user),'gate_id': session["gateID"]},allow_redirects=True).json()
except:
return render_template("ServerShutDown.html",db = "User Occurrences Database Server"),404
if aux["StatusCode"] == "1":
aux = newGateOcco(session["gateID"],"OPEN")
if aux == 2:
warnings.warn('The Backup DATABASE could not Update')
if aux == 3:
warnings.warn('The Main DATABASE could not Update')
if aux == 0:
warnings.warn('Both DATABASES could not Update')
aux = updateAct(session["gateID"])
if aux == 2:
warnings.warn('The Backup DATABASE could not Update')
if aux == 3:
warnings.warn('The Main DATABASE could not Update')
if aux == 0:
warnings.warn('Both DATABASES could not Update')
return jsonify({'open': 1}), 201
else:
aux = newGateOcco(session["gateID"],"CLOSED")
if aux == 2:
warnings.warn('The Backup DATABASE could not Update')
if aux == 3:
warnings.warn('The Main DATABASE could not Update')
if aux == 0:
warnings.warn('Both DATABASES could not Update')
return jsonify({'open': 0}), 201
#--------------------------------------------USER------------------------------------------------------------
@app.route("/user")
def user():
return redirect(url_for('.demo'))
# QR code generation
@app.route("/user/code/<path:istID>")
def UserQR(istID):
try:
session["token"]
except:
return render_template("badinput.html"), 400
flag = 1
if request.environ["HTTP_REFERER"] ==('http://localhost:5000/user/code/'+istID):
flag = 0
try:
aux = requests.get(URL_DB_user+"user/check",json={'istID':istID,'token':session["token"]},allow_redirects=True)
except:
return render_template("ServerShutDown.html",db = "User Database Server"), 404
if aux.json()['StatusCode'] == '1':
if flag :
session["usercode"] = randalph(10)
Update_Status = requests.post(URL_DB_user+"/user/"+istID+"/updateCode",json={'istID':istID,'token':session["token"],'secret':session["usercode"]},allow_redirects=True)
if Update_Status.json()['StatusCode'] == '2':
return render_template("badlogin.html"), 401
# Check if the seecret is correct with the user that is being addressed
return render_template("qrgen.html", code=session["usercode"], istID = istID), 201
else:
return render_template("badlogin.html"), 401
#User History
@app.route("/user/code/<path:istID>/history")
def user_history(istID):
try:
session["token"]
except:
return render_template("badinput.html"), 400
# Check if the token is correct with the user that is being addressed
try:
aux = requests.get(URL_DB_user+"user/check",json={'istID':istID,'token':session["token"]},allow_redirects=True)
except:
return render_template("ServerShutDown.html",db = "User Database Server"), 404
if aux.json()['StatusCode'] == '2':
return render_template("badlogin.html"), 401
return render_template("table.html", istID = istID)
# returns a list of occurrences
@app.route("/User_reg")
def table_users():
try:
aux = requests.get(URL_DB_user+"user/check",json={'istID':session["userID"],'token':session["token"]},allow_redirects=True)
except:
return jsonify([]), 404
if aux.json()['StatusCode'] == '2':
return jsonify([]), 401
try:
list = requests.get(URL_DB_user_hist+"user/occurrences/"+ session["userID"]+"/history",allow_redirects=True).json()
except:
return jsonify([]), 404
return list
#-------------------------------------------------------------AUTH-------------------------------------------
@app.route("/user/authentified/<path:istID>")
def userAuth(istID):
try:
session["token"]
except:
return render_template("badinput.html"), 400
try:
aux = requests.get(URL_DB_user+"user/check",json={'istID':istID,'token':session["token"]},allow_redirects=True)
except:
return render_template("ServerShutDown.html",db = "User Database Server"), 404
if aux.json()['StatusCode'] == "2":
return render_template("badlogin.html"), 401
if int(istID) in ADMIN:
return redirect(url_for('.ClientIndex',istID = istID))
else:
return redirect(url_for('.userIndex',istID = istID))
# User Interface
@app.route("/user/<path:istID>")
def userIndex(istID):
try:
int(istID)
session["token"]
except:
return render_template("badinput.html"), 400
try:
aux = requests.get(URL_DB_user+"user/check",json={'istID':istID,'token':session['token']},allow_redirects=True)
except:
return render_template("ServerShutDown.html",db = "User Database Server"), 404
if aux.json()['StatusCode'] == '1':
return render_template("IndexUser.html",istID = istID)
else:
return render_template("badlogin.html"), 401
#-----------------------------------------------ADMIN----------------------------------------------------------
# Admin Interface
@app.route("/Admin")
def AdminHome():
return redirect(url_for('.demo'))
# Admin Interface
@app.route("/Admin/<path:istID>")
def AdminIndex(istID):
try:
int(istID)
session["token"]
except:
return render_template("badinput.html"), 400
if int(istID) in ADMIN:
try:
aux = requests.get(URL_DB_user+"user/check",json={'istID':istID,'token':session['token']},allow_redirects=True)
except:
return render_template("ServerShutDown.html",db = "User Database Server"), 404
if aux.json()['StatusCode'] == '1':
return render_template("indexAdmin.html",istID = istID)
else:
return render_template("badlogin.html"), 401
return render_template("notadmin.html"), 401
# Client Interface
@app.route("/<path:istID>")
def ClientIndex(istID):
try:
int(istID)
session["token"]
except:
return render_template("badinput.html"), 400
if int(istID) in ADMIN:
try:
aux = requests.get(URL_DB_user+"user/check",json={'istID':istID,'token':session['token']},allow_redirects=True)
except:
return render_template("ServerShutDown.html",db = "User Database Server"), 404
if aux.json()['StatusCode'] == '1':
return render_template("ClientIndex.html",istID = istID)
else:
return render_template("badlogin.html"), 401
return render_template("notadmin.html"), 401
# List the Active Gates
@app.route("/Admin/<path:istID>/Gates")
def AdminGates(istID):
try:
int(istID)
session["token"]
except:
return render_template("badinput.html"), 400
try:
aux = requests.get(URL_DB_user+"user/check",json={'istID':istID,'token':session['token']},allow_redirects=True)
except:
return render_template("ServerShutDown.html",db = "User Database Server"), 404
if aux.json()['StatusCode'] == '1':
if int(istID) in ADMIN:
Gates_list=listgates()
if Gates_list["StatusCode"] == '1' and Gates_list["Gates"]:
return render_template_string(teste_table(Gates_list["Gates"],0),istID = istID)
else:
return render_template_string(teste_table([],1),istID = istID)
return render_template("notadmin.html"), 401
else:
return render_template("badlogin.html"), 401
# List the Gates History
@app.route("/Admin/<path:istID>/GatesHistory")
def AdminGatesHist(istID):
try:
int(istID)
session["token"]
except:
return render_template("badinput.html"), 400
try:
aux = requests.get(URL_DB_user+"user/check",json={'istID':istID,'token':session['token']},allow_redirects=True)
except:
return render_template("ServerShutDown.html",db = "User Database Server"), 404
if aux.json()['StatusCode'] == '1':
if int(istID) in ADMIN:
l = gateshistory()
if l["history"]:
return render_template_string(teste_table(l["history"],0),istID = istID)
else:
return render_template_string(teste_table([],1),istID = istID)
return render_template("notadmin.html"), 401
else:
return render_template("badlogin.html"), 401
# List the Gates History
@app.route("/Admin/<path:istID>/GatesHistory/<path:gateID>")
def AdminGateHist(istID, gateID):
try:
int(istID)
session["token"]
except:
return render_template("badinput.html"), 400
try:
aux = requests.get(URL_DB_user+"user/check",json={'istID':istID,'token':session['token']},allow_redirects=True)
except:
return render_template("ServerShutDown.html",db = "User Database Server"), 404
if aux.json()['StatusCode'] == '1':
if int(istID) in ADMIN:
l = gateshistorybyID(gateID)
if l["history"]:
return render_template_string(teste_table(l["history"],0),istID = istID)
else:
return render_template_string(teste_table([],1),istID = istID)
return render_template("notadmin.html"), 401
else:
return render_template("badlogin.html"), 401
# Add a new gate
@app.route("/Admin/<path:istID>/newGate",methods = ['POST','GET'])
def AdminNewGate(istID):
try:
int(istID)
session["token"]
except:
return render_template("badinput.html"), 400
try:
check = requests.get(URL_DB_user+"user/check",json={'istID':istID,'token':session["token"]},allow_redirects=True)
except:
return render_template("ServerShutDown.html",db = "User Database Server"), 404
if check.json()['StatusCode'] == '1':
if int(istID) in ADMIN:
if request.method == 'POST':
data = request.form
try:
data["gateID"]
data["gateLocation"]
except:
return render_template("showCreated.html",message='Input information may be missing!',istID = istID)
if not (data["gateID"] and data["gateID"].isdigit()):
if not data["gateLocation"]:
return render_template("showCreated.html",message='ID and Location were not correctly placed!',istID = istID)
return render_template("showCreated.html",message='ID was not correctly placed (must be an integer)!',istID = istID)
elif not data["gateLocation"]:
return render_template("showCreated.html",message='Location was not correctly placed (must not be empty)!',istID = istID)
aux = creategates(data["gateID"],data["gateLocation"])
if aux == '2':
warnings.warn('The Backup DATABASE could not Update')
return render_template("showCreated.html",message='The Backup DATABASE could not Update',istID = istID)
elif aux == '3':
warnings.warn('The Main DATABASE could not Update')
return render_template("showCreated.html",message='The Main DATABASE could not Update',istID = istID)
elif aux == '0':
warnings.warn('Both DATABASES could not Update')
return render_template("showCreated.html",message='Both DATABASES could not Update',istID = istID)
elif aux == '4':
return render_template("showCreated.html",message='ID was already Taken - No Gate Created!',istID = istID)
else:
new = "Gate ID: "+str(data["gateID"])+"\n, Location: "+data["gateLocation"]+"\n, Secret Number: "+str(aux)
return render_template("showCreated.html",message=new,istID = istID), 201
else:
return render_template("newGate.html",istID = istID)
return render_template("notadmin.html"), 401
else:
return render_template("badlogin.html"), 401
#--------------------------------------------------------AUTH---------------------------------------------
@app.route("/login")
def demo():
github = OAuth2Session(client_id, redirect_uri="http://localhost:5000/callback")
authorization_url, state = github.authorization_url(authorization_base_url)
# State is used to prevent CSRF, keep this for later.
session['oauth_state'] = state
return redirect(authorization_url)
# Step 2: User authorization, this happens on the provider.
@app.route("/callback", methods=["GET"])
def callback():
github = OAuth2Session(client_id, redirect_uri="http://localhost:5000/callback")
token = github.fetch_token(token_url, client_secret=client_secret,
authorization_response=request.url)
session['oauth_token'] = token
return redirect(url_for('.profile'))
# Obtain information needed of the user
@app.route("/profile", methods=["GET"])
def profile():
github = OAuth2Session(client_id, token=session['oauth_token'])
Info = jsonify(github.get('https://fenix.tecnico.ulisboa.pt/api/fenix/v1/person').json())
ist_ID = github.get('https://fenix.tecnico.ulisboa.pt/api/fenix/v1/person').json()["username"]
session["userID"] = str(ist_ID).strip('ist')
session["token"] = randalph(12)
try:
aux = requests.post(URL_DB_user + "users/newuser",json={'user_id':session["userID"],'token':session["token"],'secret_code': ""}, allow_redirects=True).json()
except:
return render_template("ServerShutDown.html",db = "User Database Server")
return redirect(url_for('.userAuth',istID=session["userID"]))
#Start server
if __name__ == "__main__":
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = "1"
ADMIN = getAdmin('/config.idk')
app.secret_key = os.urandom(24)
app.run(debug=True)