-
Notifications
You must be signed in to change notification settings - Fork 8
/
app.py
564 lines (493 loc) · 19.3 KB
/
app.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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
from flask import Flask, render_template, request,redirect,session,jsonify,flash,url_for;
import sqlite3
from cas import CASClient
from urllib.parse import quote_plus
from cryptography.fernet import Fernet
import os
from functools import cmp_to_key
SECRET_KEY = os.getenv('SECRET_KEY',os.urandom(24))
CAS_SERVER_URL = os.getenv('CAS_SERVER_URL', 'https://login.iiit.ac.in/cas/')
SERVICE_URL = os.getenv('SERVICE_URL', 'http://localhost:5000/Get_Auth')
REDIRECT_URL = os.getenv('REDIRECT_URL', 'http://localhost:5000/Get_Auth')
app = Flask(__name__)
app.secret_key = SECRET_KEY
cas_client = CASClient(
version=3,
service_url=f"{SERVICE_URL}?next={quote_plus(REDIRECT_URL)}",
server_url=CAS_SERVER_URL,
)
# Database Setup
conn = sqlite3.connect('cabmates.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS Login (
Fname TEXT,
Lname TEXT,
Email TEXT,
RollNo TEXT,
Uid TEXT PRIMARY KEY,
Batch TEXT,
Gender TEXT,
PhoneNo TEXT
)
''')
cursor.execute('''CREATE TABLE IF NOT EXISTS fromCampus (BookingID INTEGER PRIMARY KEY AUTOINCREMENT, Uid TEXT, DateTime DATETIME, Station TEXT)''')
cursor.execute('''CREATE TABLE IF NOT EXISTS toCampus (BookingID INTEGER PRIMARY KEY AUTOINCREMENT, Uid TEXT, DateTime DATETIME, Station TEXT)''')
# Database Setup End
def compare_datetime(entry1, entry2):
if entry1[2] < entry2[2]:
return -1
elif entry1[2] > entry2[2]:
return 1
else:
return 0
def sort_by_datetime(entries):
entries.sort(key=cmp_to_key(compare_datetime))
return entries
@app.route('/')
def LogIn():
return render_template('LogIn.html')
@app.route('/Get_Auth', methods=['POST', 'GET'])
def Get_Auth():
if request.method == 'POST':
cas_login_url = cas_client.get_login_url()
return redirect(cas_login_url)
else:
ticket = request.args.get('ticket')
if ticket:
user, attributes, pgtiou = cas_client.verify_ticket(ticket)
if user:
roll = attributes['RollNo']
email = attributes['E-Mail']
first_name = attributes['FirstName']
last_name = attributes['LastName']
uid = attributes['uid']
batch = ''
gender = ''
conn = sqlite3.connect('cabmates.db')
cursor = conn.cursor()
try:
cursor.execute( '''
SELECT * FROM Login WHERE Uid = ?
''', (uid,))
entry=cursor.fetchone()
conn.commit()
conn.close()
if entry:
with open('key.key', 'rb') as file:
key = file.read()
fernet = Fernet(key)
token = fernet.encrypt(uid.encode())
session['token'] = token
return redirect('/index')
else:
message='User not found! Please Sign Up.'
return render_template('SignUp.html',roll=roll, email=email, first_name=first_name, last_name=last_name, uid=uid, message=message)
except:
message='Error with database. Please try again'
return render_template('LogIn.html', message=message)
else:
message='Error with CAS. Please try again'
return render_template('LogIn.html', message=message)
else:
message='Error with CAS. Please try again'
return render_template('LogIn.html', message=message)
@app.route('/Get_userData',methods=['POST', 'GET'])
def Get_userData():
if request.method == 'POST':
fname = request.form['fname']
lname = request.form['lname']
email = request.form['email']
roll = request.form['roll']
uid = request.form['uid']
gender = request.form['gender']
batch = request.form['batch']
PhoneNo = request.form['PhoneNo']
conn = sqlite3.connect('cabmates.db')
cursor = conn.cursor()
try:
print(fname)
print(lname)
print(email)
print(roll)
print(uid)
print(gender)
print(batch)
print(PhoneNo)
cursor.execute('''
INSERT INTO Login (Fname, Lname, Email, RollNo, Uid, Batch, Gender, PhoneNo)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (fname, lname, email, roll, uid, batch, gender, PhoneNo))
print('signUp successful')
conn.commit()
conn.close()
with open('key.key', 'rb') as file:
key = file.read()
fernet = Fernet(key)
token = fernet.encrypt(uid.encode())
session['token'] = token
return redirect('/index')
except:
print('Sign Up Failed')
message='Sign Up Failed!'
return render_template('LogIn.html', message=message)
@app.route('/getDataForBooking',methods=['POST', 'GET'])
def getForFromCampus():
if request.method == 'POST':
token = session['token']
with open('key.key', 'rb') as file:
key = file.read()
fernet = Fernet(key)
uid = fernet.decrypt(token).decode()
to = request.form['station']
date = request.form['departureDate']
time = request.form['departureTime']
direction = request.form['direction']
print(to,date,time)
f = '%Y-%m-%d %H:%M:%S'
date_time = date + ' ' + time + ':00'
try:
conn = sqlite3.connect('cabmates.db')
cursor = conn.cursor()
if direction == 'From Campus':
cursor.execute('''INSERT INTO fromCampus (Uid, DateTime, Station) VALUES (?, ?, ?)''', (uid, date_time, to))
else:
cursor.execute('''INSERT INTO toCampus (Uid, DateTime, Station) VALUES (?, ?, ?)''', (uid, date_time, to))
print('Data inserted')
conn.commit()
conn.close()
except:
print('Data not inserted')
return redirect('/index')
else:
return redirect('/index')
@app.route('/deleteBooking', methods=['POST', 'GET'])
def delete_booking_route():
entry_id = request.form['entry_id']
direction = request.form['direction']
print(direction, entry_id)
try:
conn = sqlite3.connect('cabmates.db')
cursor = conn.cursor()
if direction == 'From Campus':
cursor.execute('''DELETE FROM fromCampus WHERE BookingID = ?''', (entry_id,))
else:
cursor.execute('''DELETE FROM toCampus WHERE BookingID = ?''', (entry_id,))
conn.commit()
conn.close()
print('Data deleted')
except:
print('Data not deleted')
return redirect('/index')
@app.route('/viewBooking', methods=['POST', 'GET'])
def view_booking():
entry_id = request.form['entry_id']
direction = request.form['direction']
token = session['token']
with open('key.key', 'rb') as file:
key = file.read()
fernet = Fernet(key)
uid = fernet.decrypt(token).decode()
print(direction, entry_id)
try:
conn = sqlite3.connect('cabmates.db')
cursor = conn.cursor()
BookingEntries = []
if direction == 'From Campus':
cursor.execute('''SELECT * FROM fromCampus WHERE BookingID = ?''', (entry_id,))
# cursor.execute('''SELECT * FROM fromCampus''')
entry = cursor.fetchone()
cursor.execute('''SELECT * FROM fromCampus WHERE Station = ?''', (entry[3],))
# cursor.execute('''SELECT * FROM fromCampus ''')
else:
cursor.execute('''SELECT * FROM toCampus WHERE BookingID = ?''', (entry_id,))
# cursor.execute('''SELECT * FROM toCampus''')
entry = cursor.fetchone()
cursor.execute('''SELECT * FROM toCampus WHERE Station = ?''', (entry[3],))
# cursor.execute('''SELECT * FROM toCampus''')
entries = cursor.fetchall()
for item in entries:
if item[1] == uid:
continue
date = item[2].split(' ')[0]
time = item[2].split(' ')[1]
uid = item[1]
cursor.execute( '''select * from Login where Uid = ?''', (item[1],))
data = cursor.fetchone()
Fname = data[0]
Lname = data[1]
Name = Fname + ' ' + Lname
Gender = data[6]
Batch = data[5]
temp_tuple = (date, time, uid, Name, Gender, Batch)
BookingEntries.append(temp_tuple)
cursor.execute('SELECT * FROM Login WHERE Uid = ?', (uid,))
user = cursor.fetchone()
conn.commit()
conn.close()
except:
print('Data not found')
return render_template('/bookingspage.html', available_options = BookingEntries, fname=user[0], lname=user[2] , entry_id=entry_id, direction=direction)
@app.route('/upcomingTravels')
def upcomingTravels():
conn = sqlite3.connect('cabmates.db')
cursor = conn.cursor()
token = session['token']
with open('key.key', 'rb') as file:
key = file.read()
fernet = Fernet(key)
uid = fernet.decrypt(token).decode()
if(session):
cursor.execute( '''
SELECT * FROM fromCampus WHERE Uid = ?
''', (uid,))
entries = cursor.fetchall()
sort_by_datetime(entries)
fromCampus_entries = []
for item in entries:
date = item[2].split(' ')[0]
time = item[2].split(' ')[1]
station = item[3]
entry_id = item[0]
temp_tuple = (date,time,station,entry_id)
fromCampus_entries.append(temp_tuple)
cursor.execute( '''
SELECT * FROM toCampus WHERE Uid = ?
''', (uid,))
entries = cursor.fetchall()
sort_by_datetime(entries)
toCampus_entries = []
for item in entries:
date = item[2].split(' ')[0]
time = item[2].split(' ')[1]
station = item[3]
entry_id = item[0]
temp_tuple = (date,time,station,entry_id)
toCampus_entries.append(temp_tuple)
cursor.execute( '''select * from Login where Uid = ?''', (uid,))
user = cursor.fetchone()
return render_template('upcomingtravels.html', fromCampus_entries = fromCampus_entries, toCampus_entries = toCampus_entries, fname=user[0],lname=user[1])
else:
return redirect('/')
@app.route('/index')
def index():
conn = sqlite3.connect('cabmates.db')
cursor = conn.cursor()
token = session['token']
with open('key.key', 'rb') as file:
key = file.read()
fernet = Fernet(key)
uid = fernet.decrypt(token).decode()
if(session):
cursor.execute( '''select * from Login where Uid = ?''', (uid,))
user = cursor.fetchone()
print('uid:',uid)
print('user:',user)
return render_template('index.html', fname=user[0],lname=user[1])
else:
return redirect('/')
@app.route('/logout_user', methods=['POST', 'GET'])
def logout_user():
session.pop('token', None)
return redirect('/')
@app.route('/viewBookingRedirect', methods=['POST', 'GET'])
def view_booking_redirect():
token = session['token']
with open('key.key', 'rb') as file:
key = file.read()
fernet = Fernet(key)
uid = fernet.decrypt(token).decode()
try:
conn = sqlite3.connect('cabmates.db')
cursor = conn.cursor()
BookingEntries = []
cursor.execute('''SELECT * FROM fromCampus''')
entries1 = cursor.fetchall()
for item in entries1:
if item[1] == uid:
continue
date = item[2].split(' ')[0]
time = item[2].split(' ')[1]
cursor.execute( '''select * from Login where Uid = ?''', (item[1],))
data = cursor.fetchone()
Fname = data[0]
Lname = data[1]
Name = Fname + ' ' + Lname
email_id=data[2]
Gender = data[6]
PhoneNo = data[7]
Batch = data[5]
station= item[3]
from_location="IIIT Campus"
temp_tuple = (date, time, uid, Name, Gender, Batch, station, from_location, email_id, PhoneNo)
BookingEntries.append(temp_tuple)
cursor.execute('''SELECT * FROM toCampus''')
entries1 = cursor.fetchall()
for item in entries1:
if item[1] == uid:
continue
date = item[2].split(' ')[0]
time = item[2].split(' ')[1]
cursor.execute( '''select * from Login where Uid = ?''', (item[1],))
data = cursor.fetchone()
Fname = data[0]
Lname = data[1]
Name = Fname + ' ' + Lname
Gender = data[6]
PhoneNo = data[7]
Batch = data[5]
email_id=data[2]
station= "IIIT Campus"
from_location=item[3]
temp_tuple = (date, time, uid, Name, Gender, Batch,station,from_location, email_id, PhoneNo)
BookingEntries.append(temp_tuple)
cursor.execute('SELECT * FROM Login WHERE Uid = ?', (uid,))
user = cursor.fetchone()
conn.commit()
conn.close()
except Exception as e:
print('An error occurred:', e)
return render_template('/bookingspage.html', available_options = BookingEntries, fname=user[0], lname=user[1])
def isTimeNotInRange(requested_time, entry_time):
for i in range(len(requested_time)):
hour = int(entry_time.split(':')[0])
timeRange = requested_time[i].split('-')
if (hour >= int(timeRange[0].split(':')[0]) and hour <= int(timeRange[1].split(':')[0])):
return False
return True
@app.route('/apply_filters', methods=['POST'])
def apply_filters():
token = session['token']
with open('key.key', 'rb') as file:
key = file.read()
fernet = Fernet(key)
uid = fernet.decrypt(token).decode()
try:
conn = sqlite3.connect('cabmates.db')
cursor = conn.cursor()
filters = request.json
requested_batch = filters.get('selectedBatch').split(",")
requested_time = filters.get('selectedTime').split(",")
requested_desti = filters.get('selectedDestination').split(",")
requested_start = filters.get('selectedStart').split(",")
requested_date = filters.get('selectedDate')
AllEntries = []
cursor.execute('''SELECT * FROM fromCampus''')
entries1 = cursor.fetchall()
for item in entries1:
if item[1] == uid:
continue
date = item[2].split(' ')[0]
time = item[2].split(' ')[1]
cursor.execute( '''select * from Login where Uid = ?''', (item[1],))
data = cursor.fetchone()
Fname = data[0]
Lname = data[1]
Name = Fname + ' ' + Lname
email_id=data[2]
Gender = data[6]
PhoneNo = data[7]
Batch = data[5]
station= item[3]
from_location="IIIT Campus"
temp_tuple = (date, time, uid, Name, Gender, Batch, station, from_location, email_id, PhoneNo)
AllEntries.append(temp_tuple)
cursor.execute('''SELECT * FROM toCampus''')
entries1 = cursor.fetchall()
for item in entries1:
if item[1] == uid:
continue
date = item[2].split(' ')[0]
time = item[2].split(' ')[1]
cursor.execute( '''select * from Login where Uid = ?''', (item[1],))
data = cursor.fetchone()
Fname = data[0]
Lname = data[1]
Name = Fname + ' ' + Lname
Gender = data[6]
PhoneNo = data[7]
Batch = data[5]
email_id=data[2]
station= "IIIT Campus"
from_location=item[3]
temp_tuple = (date, time, uid, Name, Gender, Batch,station,from_location, email_id, PhoneNo)
AllEntries.append(temp_tuple)
BookingEntries = []
for entry in AllEntries:
if (requested_batch[0] != '' and entry[5] not in requested_batch):
continue
if (requested_desti[0] != '' and entry[6] not in requested_desti):
continue
if (requested_start[0] != '' and entry[7] not in requested_start):
continue
if (requested_date != None and entry[0] != requested_date):
continue
if (requested_time[0] != '' and isTimeNotInRange(requested_time, entry[1])):
continue
BookingEntries.append(entry)
filtered_data = {'available_options': BookingEntries}
return jsonify(filtered_data)
except Exception as e:
print("Error:", e)
return jsonify({'error': str(e)}), 500
@app.route('/about')
def about():
token = session['token']
with open('key.key', 'rb') as file:
key = file.read()
fernet = Fernet(key)
uid = fernet.decrypt(token).decode()
conn = sqlite3.connect('cabmates.db')
cursor = conn.cursor()
cursor.execute('SELECT * FROM Login WHERE Uid = ?', (uid,))
user = cursor.fetchone()
conn.close()
return render_template('about.html', fname=user[0], lname=user[1])
@app.route('/editprofilepage')
def editprofilepage():
token = session['token']
with open('key.key', 'rb') as file:
key = file.read()
fernet = Fernet(key)
uid = fernet.decrypt(token).decode()
try:
conn = sqlite3.connect('cabmates.db')
cursor = conn.cursor()
cursor.execute('SELECT * FROM Login WHERE Uid = ?', (uid,))
user = cursor.fetchone()
conn.close()
return render_template('editprofilepage.html', fname=user[0], lname=user[1],user=user)
except Exception as e:
print('An error occurred:2', e)
@app.route('/update_userData', methods=['POST'])
def update_userData():
try:
gender = request.form.get('gender')
batch = request.form.get('batch')
PhoneNo = request.form.get('PhoneNo')
token = session['token']
with open('key.key', 'rb') as file:
key = file.read()
fernet = Fernet(key)
uid = fernet.decrypt(token).decode()
conn = sqlite3.connect('cabmates.db')
cursor = conn.cursor()
cursor.execute('''
UPDATE Login
SET gender = ?, batch = ?, PhoneNo = ?
WHERE Uid = ?
''', (gender, batch, PhoneNo, uid))
conn.commit()
cursor.execute('SELECT * FROM Login WHERE Uid = ?', (uid,))
user = cursor.fetchall()
conn.close()
# Redirect with a success message
return redirect(url_for('editprofilepage', update_message='success'))
except Exception as e:
print('An error occurred:', e)
return redirect(url_for('editprofilepage', update_message='error'))
if __name__ == '__main__':
key = Fernet.generate_key()
with open('key.key', 'wb') as file:
file.write(key)
app.run(debug=True)