generated from uwidcit/flask-starter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
604 lines (468 loc) · 21.1 KB
/
main.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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
import json
from flask_cors import CORS
from flask_login import LoginManager, current_user, login_user, login_required
from flask import Flask, request, render_template, redirect, flash, url_for
from flask_jwt import JWT, jwt_required, current_identity
from sqlalchemy.exc import IntegrityError
from datetime import timedelta
import os
from models import db, Club, Election, User, ClubMember, Candidate, ElectionBallot
def get_db_uri(scheme='sqlite://', user='', password='', host='//electoraDB.db', port='', name=''):
return scheme+'://'+user+':'+password+'@'+host+':'+port+'/'+name
def loadConfig(app):
try:
app.config.from_object('config.development')
except:
print("No config file used. Using environment variables.")
DBUSER = os.environ.get("DBUSER")
DBPASSWORD = os.environ.get("DBPASSWORD")
DBHOST = os.environ.get("DBHOST")
DBPORT = os.environ.get("DBPORT", default="8080")
DBNAME = os.environ.get("DBNAME")
DBURI = os.environ.get("DBURI")
SQLITEDB = os.environ.get("SQLITEDB", default="False")
app.config['ENV'] = os.environ.get("ENV", default="")
app.config['SQLALCHEMY_DATABASE_URI'] = get_db_uri() if SQLITEDB in {'True', 'true', 'TRUE'} else DBURI
app.config["JWT_SECRET_KEY"] = os.environ.get("JWT_SECRET_KEY")
def create_app():
app = Flask(__name__)
loadConfig(app)
CORS(app)
app.config['JWT_EXPIRATION_DELTA'] = timedelta(days = 7)
db.init_app(app)
return app
app = create_app()
app.app_context().push()
def authenticate(username, password):
try:
user = db.session.query(User).filter_by(username=username).first()
if user and user.checkPassword(password):
return user
except:
db.session.rollback()
return None
def identity(payload):
try:
return db.session.query(User).get(payload['identity'])
except:
db.session.rollback()
return None
jwt = JWT(app, authenticate, identity)
@app.route('/')
def clientApp():
return app.send_static_file('app.html')
@app.route('/favicon.ico')
def favicon():
return app.send_static_file('images/favicon.png')
@app.route('/logo.png')
def logo():
return app.send_static_file('images/logo.png')
@app.route('/api/clubs', methods=["GET"])
def getClubs():
try:
clubs = db.session.query(Club).all()
if not clubs:
return json.dumps({"error": "No clubs have been added yet!"})
else:
listOfClubs = [club.toDict() for club in clubs]
return json.dumps(listOfClubs)
except:
db.session.rollback()
return json.dumps({"error": "Unable to get clubs!"})
@app.route('/api/clubs/<clubID>/getPastElections', methods=["GET"])
def getPastElections(clubID):
try:
pastElections = Election.query.filter_by(clubID=clubID, isOpen=False).all()
if not pastElections:
return json.dumps({"error" : "Unable to get past elections for this club!"})
else:
pastElections = [election.toDict() for election in pastElections]
return json.dumps(pastElections)
except:
db.session.rollback()
return json.dumps({"error": "Unable to get past elections!"})
@app.route('/api/clubs/<clubID>', methods=["GET"])
def getClubsByID(clubID):
try:
clubID = int(clubID)
foundClub = db.session.query(Club).filter_by(clubID=clubID).first()
if not foundClub:
return json.dumps({"error" : "Club not found!"})
else:
return json.dumps(foundClub.toDict())
except:
db.session.rollback()
return json.dumps({"error": "Unable to get clubs!"})
@app.route('/api/clubs/<clubID>', methods=["POST"])
@jwt_required()
def joinClub(clubID):
try:
if not clubID:
return json.dumps({"error" : "No supplied club ID!"})
response = current_identity.joinClub(clubID)
if response:
return json.dumps({"message" : "Club joined!"})
else:
return json.dumps({"error" : "User is already a member of this club or club does not exist!"})
except:
db.session.rollback()
return json.dumps({"error": "Unable to join club!"})
@app.route('/api/myClubs', methods=["GET"])
@jwt_required()
def getMyClubs():
try:
myClubs = current_identity.myClubs()
if myClubs:
return json.dumps(myClubs)
else:
return json.dumps({"error" : "Not a member of any club!"})
except:
db.session.rollback()
return json.dumps({"error": "Unable to get clubs!"})
@app.route('/api/myClubs/<clubID>', methods=["DELETE"])
@jwt_required()
def leaveClub(clubID):
try:
if not clubID:
return json.dumps({"error" : "No supplied club ID!"})
response = current_identity.leaveClub(clubID)
if response:
return json.dumps({"message" : "Club left!"})
else:
return json.dumps({"error" : "User is not a member of this club!"})
except:
db.session.rollback()
return json.dumps({"error": "Unable to leave club!"})
@app.route('/register', methods=["POST"])
def register():
try:
regDetails = request.get_json()
if not regDetails["username"] and not regDetails["password"] and not regDetails["firstName"] and not regDetails["confirmPassword"] and not regDetails["lastName"]:
return json.dumps({"error" : "Please ensure all the data ie entered for registration"})
if len(regDetails["password"]) <= 6:
return json.dumps({"error" : "Password too short!"})
if regDetails["password"] != regDetails["confirmPassword"]:
return json.dumps({"error" : "Passwords do not match!"})
try:
newUser = User(regDetails["username"], regDetails["password"], regDetails["firstName"], regDetails["lastName"])
db.session.add(newUser)
db.session.commit()
return json.dumps({"message" : "Successfully signed up!"})
except:
db.session.rollback()
return json.dumps({"error" : "Error registering user! User may already exist!"})
except:
db.session.rollback()
return json.dumps({"error": "Unable to register!"})
@app.route('/identify', methods=["GET"])
@jwt_required()
def identify():
try:
return json.dumps({"username" : current_identity.username, "firstName" : current_identity.firstName, "lastName" : current_identity.lastName})
except:
return json.dumps({"error" : "Not logged in or session has expired!"})
#Remove before production
#@app.route('/debug/elections', methods=["GET"])
#def getElectionsDebug():
# elections = db.session.query(Election).all()
# listOfElections = [election.toDict() for election in elections]
# return json.dumps(listOfElections)
##Remove before production
#@app.route('/debug/candidates', methods=["GET"])
#def getCandidatesDebug():
# candidates = db.session.query(Candidate).all()
# listOfCandidates = [candidate.toDict() for candidate in candidates]
# return json.dumps(listOfCandidates)
@app.route('/api/elections', methods=["GET"])
@jwt_required()
def getMyElections():
try:
memberships = db.session.query(ClubMember).filter_by(id=current_identity.id).all()
if not memberships:
return json.dumps({"error" : "You have no elections or are not a member of any club!"})
allMyElections = []
for membership in memberships:
listOfMyClubElections = membership.myElections()
if listOfMyClubElections:
for clubElection in listOfMyClubElections:
allMyElections.append(clubElection)
if allMyElections:
return json.dumps(allMyElections)
else:
return json.dumps({"error" : "Unable find your elections!"})
except:
db.session.rollback()
return json.dumps({"error": "Unable to get elections!"})
@app.route('/api/elections/<electionID>', methods=["GET"])
@jwt_required()
def getElectionByID(electionID):
try:
memberships = db.session.query(ClubMember).filter_by(id=current_identity.id).all()
if not memberships:
return json.dumps({"error" : "You are not a member of this club!"})
election = db.session.query(Election).filter_by(electionID=electionID).first()
if not election:
return json.dumps({"error" : "No such election found!"})
for membership in memberships:
if election.clubID == membership.clubID:
electionDetails = election.toDict()
if electionDetails:
return json.dumps(electionDetails)
else:
return json.dumps({"error" : "Unable find election by ID!"})
except:
db.session.rollback()
return json.dumps({"error": "Unable to get election!"})
@app.route('/api/elections/<electionID>/candidates/<candidateID>', methods=["POST"])
@jwt_required()
def voteForCandidate(electionID, candidateID):
try:
elec = db.session.query(Election).filter_by(electionID=electionID).first()
if not elec:
return json.dumps({"error" : "Election cannot be found!"})
clubMembership = db.session.query(ClubMember).filter_by(clubID=elec.clubID, id=current_identity.id).first()
if not clubMembership:
return json.dumps({"error" : "User is not a member of this club!"})
elec = db.session.query(Election).filter_by(electionID=electionID).first()
if not elec:
return json.dumps({"error" : "Election cannot be found!"})
if clubMembership.castVote(candidateID):
return json.dumps({"message" : "Vote casted!"})
else:
return json.dumps({"error" : "Unable to cast vote!"})
except:
db.session.rollback()
return json.dumps({"error": "Unable to vote!"})
def validateCandidate(candidate):
if "firstName" in candidate and "lastName" in candidate:
if len(candidate["firstName"]) > 0 and len(candidate["lastName"]) > 0:
return True
return False
@app.route('/api/elections', methods=["POST"])
@jwt_required()
def createElection():
try:
electionDetails = request.get_json()
if not electionDetails or "clubID" not in electionDetails or "position" not in electionDetails or "candidates" not in electionDetails:
return json.dumps({"error" : "Not enough information provided!"})
for candidate in electionDetails["candidates"]:
if not validateCandidate(candidate):
return json.dumps({"error" : "Invalid candidate information provided!"})
clubMembership = db.session.query(ClubMember).filter_by(clubID=electionDetails["clubID"], id=current_identity.id).first()
if not clubMembership:
return json.dumps({"error" : "You are not a member of this club!"})
response = clubMembership.callElection(electionDetails["clubID"], electionDetails["position"], electionDetails["candidates"])
if response:
return json.dumps({"message" : "Election started!"})
else:
return json.dumps({"error" : "An active already exists for that position, invalid candidate information provided, or you are not a member of this club!"})
except:
db.session.rollback()
return json.dumps({"error": "Unable to create election!"})
@app.route('/api/elections/<electionID>', methods=["PUT"])
@jwt_required()
def updateElection(electionID):
try:
updateDetails = request.get_json()
if not updateDetails or not electionID:
return json.dumps({"error" : "Not enough information provided!"})
if "isOpen" in updateDetails:
if updateDetails["isOpen"] == True:
electionClub = db.session.query(Election).filter_by(electionID=electionID).first()
if not electionClub:
return json.dumps({"error" : "No election found!"})
membership = db.session.query(ClubMember).filter_by(clubID=electionClub.clubID, id=current_identity.id).first()
if not membership:
return json.dumps({"error" : "User is not a member of this club!"})
electionClub = db.session.query(Election).filter_by(electionID=electionID).first()
if not electionClub:
return json.dumps({"error" : "No election found!"})
result = membership.openElection(electionID)
if result:
return json.dumps({"message" : "Election opened!"})
else :
return json.dumps({"error" : "You do not have permission to open this election!"})
if updateDetails["isOpen"] == False:
electionClub = db.session.query(Election).filter_by(electionID=electionID).first()
if not electionClub:
return json.dumps({"error" : "No election found!"})
membership = db.session.query(ClubMember).filter_by(clubID=electionClub.clubID, id=current_identity.id).first()
if not membership:
return json.dumps({"error" : "User is not a member of this club!"})
result = membership.closeElection(electionID)
if result:
return json.dumps({"message" : "Election closed!"})
else :
return json.dumps({"error" : "You do not have permission to close this election!"})
if "position" in updateDetails:
membership = db.session.query(ClubMember).filter_by(id=current_identity.id).first()
if not membership:
return json.dumps({"error" : "You do not have permission to change the position within this election or the election is closed!"})
result = membership.changePosition(electionID, updateDetails["position"])
if result:
return json.dumps({"message" : "Election position updated!"})
else:
return json.dumps({"error" : "You do not have permission to change the position within this election or the election is closed!"})
except:
db.session.rollback()
return json.dumps({"error": "Unable to update election!"})
@app.route('/api/elections/<electionID>', methods=["DELETE"])
@jwt_required()
def deleteElection(electionID):
try:
if not electionID:
return json.dumps({"error" : "Not election ID provided!"})
electionClub = db.session.query(Election).filter_by(electionID=electionID).first()
if not electionClub:
return json.dumps({"error" : "No election found!"})
membership = db.session.query(ClubMember).filter_by(clubID=electionClub.clubID, id=current_identity.id).first()
if not membership:
return json.dumps({"error" : "User is not a member of this club!"})
electionClub = db.session.query(Election).filter_by(electionID=electionID).first()
if not electionClub:
return json.dumps({"error" : "No election found!"})
response = membership.deleteElection(electionID)
if response:
return json.dumps({"message" : "Election deleted!"})
else:
return json.dumps({"error" : "Unable to delete election!"})
except:
db.session.rollback()
return json.dumps({"error": "Unable to delete election!"})
@app.route('/api/myManagingElections', methods=["GET"])
@jwt_required()
def getMyManagingElections():
try:
memberships = db.session.query(ClubMember).filter_by(id=current_identity.id).all()
allMyManagingElections = []
for membership in memberships:
listOfMyClubElections = membership.myManagingElections()
if listOfMyClubElections:
for clubElection in listOfMyClubElections:
allMyManagingElections.append(clubElection)
if allMyManagingElections:
return json.dumps(allMyManagingElections)
else:
return json.dumps({"error" : "No managing elections for your account."})
except:
db.session.rollback()
return json.dumps({"error": "Unable to get elections!"})
@app.route('/api/myManagingElections/<electionID>', methods=["GET"])
@jwt_required()
def displayMyManagingElection(electionID):
try:
memberships = db.session.query(ClubMember).filter_by(id=current_identity.id).all()
allMyManagingElections = []
for membership in memberships:
listOfMyClubElections = membership.myManagingElections()
if listOfMyClubElections:
for clubElection in listOfMyClubElections:
allMyManagingElections.append(clubElection)
myElections = membership.myManagingElections()
currElection = None
if myElections:
for election in myElections:
for i in range(0, len(election)):
if election[i]["electionID"] == int(electionID):
currElection = election[i]
if not currElection:
return json.dumps({"error" : "You are not a member of the club that is hosting this election or the election does not exist!"})
else:
return json.dumps(currElection)
except:
db.session.rollback()
return json.dumps({"error": "Unable to get elections!"})
@app.route('/api/elections/<electionID>/candidates/<candidateID>', methods=["PUT"])
@jwt_required()
def updateCandidate(electionID, candidateID):
try:
updateDetails = request.get_json()
if "firstName" not in updateDetails and "lastName" not in updateDetails:
return json.dumps({"error" : "Incorrect candidate details provided!"})
if not validateCandidate(updateDetails):
return json.dumps({"error" : "Incorrect candidate details provided!"})
membership = db.session.query(ClubMember).filter_by(id=current_identity.id).first()
if not membership:
return json.dumps({"error" : "User does not have permission to update this candidate!"})
if membership.updateCandidate(electionID, candidateID, updateDetails):
return json.dumps({"message" : "Candidate details updated!"})
else:
return json.dumps({"error" : "Unable to update candidate!"})
except:
db.session.rollback()
return json.dumps({"error": "Unable to update candidate!"})
@app.route('/api/elections/<electionID>/candidates', methods=["GET"])
@jwt_required()
def getCandidatesDetails(electionID):
try:
election = db.session.query(Election).filter_by(electionID=electionID).first()
if not election:
return json.dumps({"error" : "Election does not exist!"})
clubMembership = db.session.query(ClubMember).filter_by(clubID=election.clubID, id=current_identity.id).first()
if not clubMembership:
return json.dumps({"error" : "User does not have permission to view this candidate."})
candidatesDetails = clubMembership.getElectionCandidatesDetails(electionID)
if candidatesDetails:
return json.dumps(candidatesDetails)
else:
return json.dumps({"error" : "No candidates found for this election."})
except:
db.session.rollback()
return json.dumps({"error": "Unable to get candidate!"})
@app.route('/api/elections/<electionID>/candidates/<candidateID>', methods=["GET"])
@jwt_required()
def getCandidateDetails(electionID, candidateID):
try:
cand = db.session.query(Candidate).filter_by(candidateID=candidateID, electionID=electionID).first()
if not cand:
return json.dumps({"error" : "No candidate found for that ID."})
election = db.session.query(Election).filter_by(electionID=electionID).first()
if not election:
return json.dumps({"error" : "No election found for that ID."})
clubMembership = db.session.query(ClubMember).filter_by(clubID=election.clubID, id=current_identity.id).first()
if not election:
return json.dumps({"error" : "No permissions to view this election."})
candidateDetails = cand.toDict()
if candidateDetails:
return json.dumps(candidateDetails)
else:
return json.dumps({"error" : "No candidate found for that ID."})
except:
db.session.rollback()
return json.dumps({"error": "Unable to get candidate!"})
@app.route('/api/elections/<electionID>/candidates', methods=["POST"])
@jwt_required()
def addCandidate(electionID):
try:
candidateDetails = request.get_json()
if "firstName" in candidateDetails and "lastName" in candidateDetails:
if not validateCandidate(candidateDetails):
return json.dumps({"error" : "Not enough information provided!"})
else:
return json.dumps({"error" : "Not enough information provided!"})
membership = db.session.query(ClubMember).filter_by(id=current_identity.id).first()
if not membership:
return json.dumps({"error" : "Unable to add candidate to election! You may not be a manager!"})
result = membership.addCandidate(electionID, candidateDetails)
if result:
return json.dumps({"message" : "Candidate has been added to election!"})
else:
return json.dumps({"error" : "Unable to add candidate to election! Candidate may already exist!"})
except:
db.session.rollback()
return json.dumps({"error": "Unable to add candidate!"})
@app.route('/api/elections/<electionID>/candidates/<candidateID>', methods=["DELETE"])
@jwt_required()
def deleteCandidate(electionID, candidateID):
try:
membership = db.session.query(ClubMember).filter_by(id=current_identity.id).first()
if not membership:
return json.dumps({"error" : "User does not have permission to update this candidate!"})
result = membership.deleteCandidate(electionID, candidateID)
if result:
return json.dumps({"message" : "Candidate has been deleted from the election!"})
else:
return json.dumps({"error" : "Unable to delete candidate from election!"})
except:
db.session.rollback()
return json.dumps({"error": "Unable to delete candidate!"})