-
Notifications
You must be signed in to change notification settings - Fork 2
/
MyShareApi.py3
1813 lines (1474 loc) · 86.8 KB
/
MyShareApi.py3
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# --------------------------------------------------------------------------
# Hosts an API for the MyShare Stock Market and Portfolio Management Service
# Hosts all MyShare webpages
#
# Author: Vlad Litvak
# Email: [email protected]
# Version: 4.2.8
# Since: 08.27.2020
# --------------------------------------------------------------------------
from flask import Flask, Response, render_template
from flask_restful import Api, Resource, reqparse
from passlib.hash import sha256_crypt
from yahoo_fin import stock_info
import yfinance
import secrets
import sqlite3
import re
import json
import yagmail
ADMIN_EMAIL_ADDRESS = ""
ADMIN_EMAIL_PASSWORD = ""
SQLITE_DATABASE = "database/MyShare.db"
MAX_USER_ID = 1000000000000
MAX_ID = 1000000000000000
HTTP_OK = 200
HTTP_BAD_REQUEST = 400
HTTP_FORBIDDEN = 403
HTTP_CONFLICT = 409
HTTP_INTERNAL_SERVER_ERROR = 500
AUTHENTICATION_FAILED = 1000
OWNERSHIP_AUTHENTICATION_FAILED = 1001
TOO_MANY_AUTHENTICATION_ATTEMPTS = 1002
BOUGHT_SOLD_DISCREPANCY = 2000
MISSING_REQUIRED_PARAMS = 10000
MISSING_ID_PARAM = 10001
MISSING_PASSWORD_PARAM = 10002
MISSING_NEW_PASSWORD_PARAM = 10003
MISSING_RESET_CODE_PARAM = 10004
MISSING_USERNAME_PARAM = 10005
MISSING_EMAIL_PARAM = 10006
MISSING_FIRST_NAME_PARAM = 10007
MISSING_LAST_NAME_PARAM = 10008
MISSING_SYMBOL_PARAM = 10009
MISSING_SHARES_PARAM = 10010
MISSING_BUY_PRICE_PARAM = 10011
MISSING_BUY_DATE_PARAM = 10012
MISSING_SELL_PRICE_PARAM = 10013
MISSING_SELL_DATE_PARAM = 10014
MISSING_LOT_ID_PARAM = 10015
MISSING_SELL_LOT_ID_PARAM = 10016
INVALID_PASSWORD_PARAM = 20002
INVALID_NEW_PASSWORD_PARAM = 20003
INVALID_USERNAME_PARAM = 20005
INVALID_EMAIL_PARAM = 20006
INVALID_FIRST_NAME_PARAM = 20007
INVALID_LAST_NAME_PARAM = 20008
INVALID_SYMBOL_PARAM = 20009
INVALID_SHARES_PARAM = 20010
INVALID_BUY_PRICE_PARAM = 20011
INVALID_BUY_DATE_PARAM = 20012
INVALID_SELL_PRICE_PARAM = 20013
INVALID_SELL_DATE_PARAM = 20014
USERNAME_ALREADY_TAKEN = 30005
EMAIL_ALREADY_TAKEN = 30006
# email must be in valid format ([email protected]) and can't be longer than 100 characters
emailRegex = '^(?=.{1,100}$)[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
def checkEmailFormat(email):
return re.search(emailRegex, email)
# username can only contain letters, numbers, periods and underscores and must be 6-25 characters long
usernameRegex = '^(?=.{6,25}$)[a-zA-Z0-9._]+$'
def checkUsernameFormat(username):
return re.search(usernameRegex, username)
# password must be between 8 and 50 characters
def checkPasswordFormat(password):
return len(password) >= 8 and len(password) <= 50
# name can't be longer than 25 characters and can only contain letters, periods, and spaces
nameRegex = '^(?=.{1,25}$)[a-zA-Z.( )]+$'
def checkNameFormat(name):
return re.search(nameRegex, name)
# must be a positive integer or a positive float with exactly one or two digits after the decimal
dollarRegex = '^\d+\.\d\d$|^\d+\.\d$|^\d+$'
def checkDollarFormat(dollar):
return re.search(dollarRegex, dollar)
# must be a valid date in the format YYYY-MM-DD
dateRegex = '^\d\d\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$'
def checkDateFormat(date):
return re.search(dateRegex, date)
# must be a positive integer
intRegex = '^\d+$'
def checkIntFormat(integer):
return re.search(intRegex, integer)
# must be 1 to 5 letters
symbolRegex = '^(?=.{1,5}$)[a-zA-Z]+$'
def checkSymbolFormat(symbol):
return re.search(symbolRegex, symbol)
def executeDatabaseQuery(query):
connection = sqlite3.connect(SQLITE_DATABASE)
cursor = connection.cursor()
results = cursor.execute(query).fetchall()
connection.commit()
connection.close()
return results
def executeDatabaseUpdate(statement):
connection = sqlite3.connect(SQLITE_DATABASE)
cursor = connection.cursor()
cursor.execute("PRAGMA foreign_keys = ON;")
cursor.execute(statement)
connection.commit()
connection.close()
return cursor
def usernameAvailable(username):
if not checkUsernameFormat(username):
return False
query = "SELECT COUNT(*) FROM Users WHERE Username = '{}';".format(username)
result = executeDatabaseQuery(query)
return result[0][0] == 0
def userOwnsUsername(id, username):
query = "SELECT COUNT(*) FROM Users WHERE ID = {} AND Username = '{}';".format(id, username);
result = executeDatabaseQuery(query)
return result[0][0] != 0
def emailAvailable(email):
if not checkEmailFormat(email):
return False
query = "SELECT COUNT(*) FROM Users WHERE Email = '{}';".format(email)
result = executeDatabaseQuery(query)
return result[0][0] == 0
def userOwnsEmail(id, email):
query = "SELECT COUNT(*) FROM Users WHERE ID = {} AND Email = '{}';".format(id, email);
result = executeDatabaseQuery(query)
return result[0][0] != 0
def matchIdAndPassword(id, password):
if not checkIntFormat(id):
return False
query = "SELECT Password FROM Users WHERE ID = '{}';".format(id)
result = executeDatabaseQuery(query)
if result == []:
return False
return sha256_crypt.verify(password, result[0][0])
def symbolHeldByUser(symbol, userId):
if not symbolExists(symbol):
return False
query = "SELECT COUNT(*) FROM Holdings WHERE User = {} AND Symbol = '{}' AND SellLotID IS NULL;".format(userId, symbol)
result = executeDatabaseQuery(query)
return result[0][0] != 0
def lotOwnedByUser(lotId, userId):
if not checkIntFormat(lotId) or not checkIntFormat(userId):
return False
query = "SELECT COUNT(*) FROM Holdings WHERE LotID = {} AND User = {};".format(lotId, userId)
result = executeDatabaseQuery(query)
return result[0][0] != 0
def lotHeldByUser(lotId, userId):
if not checkIntFormat(lotId) or not checkIntFormat(userId):
return False
query = "SELECT COUNT(*) FROM Holdings WHERE LotID = {} AND User = {} AND SellLotID IS NULL;".format(lotId, userId)
result = executeDatabaseQuery(query)
return result[0][0] != 0
def lotSoldByUser(sellLotId, userId):
if not checkIntFormat(sellLotId) or not checkIntFormat(userId):
return False
query = "SELECT COUNT(*) FROM Holdings WHERE SellLotID = {} AND User = {};".format(sellLotId, userId)
result = executeDatabaseQuery(query)
return result[0][0] != 0
def shareHeldByUser(shareId, userId):
if not checkIntFormat(shareId) or not checkIntFormat(userId):
return False
query = "SELECT COUNT(*) FROM Holdings WHERE ShareId = {} AND User = {} AND SellLotID IS NULL;".format(shareId, userId)
result = executeDatabaseQuery(query)
return result[0][0] != 0
def shareSoldByUser(shareId, userId):
if not checkIntFormat(shareId) or not checkIntFormat(userId):
return False
query = "SELECT COUNT(*) FROM Holdings WHERE ShareID = {} AND User = {} AND SellLotID IS NOT NULL;".format(shareId, userId)
result = executeDatabaseQuery(query)
return result[0][0] != 0
def symbolExists(symbol):
if not checkSymbolFormat(symbol):
return False
try:
price = stock_info.get_live_price(symbol)
info = yfinance.Ticker(symbol)
info.info.update({ "currentPrice" : price })
except:
return False
return True
def createUserId():
while True:
id = secrets.randbelow(MAX_USER_ID)
query = "SELECT COUNT(*) FROM Users WHERE ID = {};".format(id)
result = executeDatabaseQuery(query)
if result[0][0] == 0:
return id
def createShareId():
while True:
id = secrets.randbelow(MAX_ID)
query = "SELECT COUNT(*) FROM Holdings WHERE ID = {};".format(id)
result = executeDatabaseQuery(query)
if result[0][0] == 0:
return id
def createShareIds(numberOfShares):
shareIds = []
for i in range(numberOfShares):
ShareIdUnique = False
while not ShareIdUnique:
shareId = secrets.randbelow(MAX_ID)
query = "SELECT COUNT(*) FROM Holdings WHERE ShareID = {};".format(shareId)
result = executeDatabaseQuery(query)
if result[0][0] == 0 and shareId not in shareIds:
shareIds.append(shareId)
ShareIdUnique = True
return shareIds
def createLotId():
while True:
id = secrets.randbelow(MAX_ID)
query = "SELECT COUNT(*) FROM Holdings WHERE LotID = {};".format(id)
result = executeDatabaseQuery(query)
if result[0][0] == 0:
return id
def createSellLotId():
while True:
id = secrets.randbelow(MAX_ID)
query = "SELECT COUNT(*) FROM Holdings WHERE SellLotID = {};".format(id)
result = executeDatabaseQuery(query)
if result[0][0] == 0:
return id
def createPasswordResetEmail(firstName, username, resetCode):
return """
<!DOCTYPE html>
<html xmlns="http:https://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins">
<body style="background-color:#191919;font-size:16px;font-family:'Poppins', 'Helvetica Neue', sans-serif;">
<div style="background-color:#464646;background:linear-gradient(0deg, #232323 0%, #5A5A5A 100%);Margin:0px auto;max-width:600px;">
<div style="color:#24A292;font-size:25px;width:40%;margin-left:30%;">
<a href="http:https://localhost:1817/myshare/home" style="text-decoration:none;">
<div style="width:100%;background-color: #353535;background: linear-gradient(0deg, #1D1D1D 0%, #353535 100%);color:#24A292;font-size:25px;text-align:center;padding-top:10px;padding-bottom:10px;border:2px solid #24A292;border-radius:10px;cursor:pointer;">MyShare</div>
</a>
</div>
<div style="width:90%;margin-left:5%;border-bottom:2px solid #24A292;">
<div style="color:#C4C4C4;width:90%;margin-left:5%;margin-bottom:15px;font-size:18px;font-weight:bolder;">Hi {},</div>
<div style="color:#FFFDFD;width:90%;margin-left:5%;">You have requested to reset your MyShare password. If this was not you, please ignore this email.</div>
</div>
<div style="width:90%;margin-left:5%;border-bottom:2px solid #24A292;">
<div style="color:#FFFDFD;width:90%;margin-left:5%;margin-bottom:5px;">Here is the information you will need to reset your password:</div>
<div style="color:#C4C4C4;width:90%;margin-left:5%;">Username: <span style="color:#FFFDFD;font-weight:bolder;">{}</span><br><span>Password Reset Code: </span><span style="font-weight:bolder;color:#FF3200">{}</span></div>
</div>
<div style="width:36%;margin-left:32%;">
<a href="http:https://localhost:1817/myshare/recover-password" style="text-decoration:none;">
<div style="width:100%;margin-bottom:10px;padding-top:10px;padding-bottom:10px;background-color:#24A292;background:linear-gradient(90deg, #24A292 0%, #247da2 100%);color:#FFFDFD;border-radius:45px;text-align:center;cursor:pointer;">Reset Password</div>
</a>
</div>
</div>
</body>
</html>
""".format(firstName, username, resetCode)
# /myshare/info
class Info(Resource):
# get general information of a symbol including current price, previous close, name, business summary, etc.
#
# param : "symbol" the symbol whose info will be returned (required)
def get(self):
parser = reqparse.RequestParser()
parser.add_argument("symbol")
params = parser.parse_args()
if params["symbol"] is None:
return Response(json.dumps({ "error" : MISSING_SYMBOL_PARAM, "message" : "'symbol' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
try:
price = round(stock_info.get_live_price(params["symbol"]), 2)
info = yfinance.Ticker(params["symbol"])
info.info.update({ "currentPrice" : price })
return Response(json.dumps(info.info), status=HTTP_OK, mimetype="application/json")
except:
return Response(json.dumps({ "error" : INVALID_SYMBOL_PARAM, "message" : "Invalid symbol" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
# /myshare/info/price
class Price(Resource):
# get current price a symbol
#
# param : "symbol" the symbol whose price will be returned (required)
def get(self):
parser = reqparse.RequestParser()
parser.add_argument("symbol")
params = parser.parse_args()
if params["symbol"] is None:
return Response(json.dumps({ "error" : MISSING_SYMBOL_PARAM, "message" : "'symbol' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
try:
return Response(json.dumps({ "price" : round(stock_info.get_live_price(params["symbol"]), 2) }), status=HTTP_OK, mimetype="application/json")
except:
return Response(json.dumps({ "error" : INVALID_SYMBOL_PARAM, "message" : "Invalid symbol" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
# /myshare/user/id
class ID(Resource):
# get a user's id
#
# param : "username" the user's username (required)
# param : "password" the user's password (required)
def get(self):
parser = reqparse.RequestParser()
parser.add_argument("username")
parser.add_argument("password")
params = parser.parse_args()
if params["username"] is None:
return Response(json.dumps({ "error" : MISSING_USERNAME_PARAM, "message" : "'username' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if params["password"] is None:
return Response(json.dumps({ "error" : MISSING_PASSWORD_PARAM, "message" : "'password' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if not checkUsernameFormat(params["username"]) or not checkPasswordFormat(params["password"]):
return Response(json.dumps({ "id" : None }), status=HTTP_OK, mimetype="application/json")
query = "SELECT Password, ID FROM Users WHERE Username = '{}';".format(params["username"])
result = executeDatabaseQuery(query)
if result == []:
return Response(json.dumps({ "id" : None }), status=HTTP_OK, mimetype="application/json")
if sha256_crypt.verify(params["password"], result[0][0]):
return Response(json.dumps({ "id" : result[0][1] }), status=HTTP_OK, mimetype="application/json")
return Response(json.dumps({ "id" : None }), status=HTTP_OK, mimetype="application/json")
# /myshare/user/
class User(Resource):
# get a user's username, email, first name, and last name
#
# param : "id" the user's id (required)
# param : "password" the user's password (required)
def get(self):
parser = reqparse.RequestParser()
parser.add_argument("id")
parser.add_argument("password")
params = parser.parse_args()
if params["id"] is None:
return Response(json.dumps({ "error" : MISSING_ID_PARAM, "message" : "'id' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if params["password"] is None:
return Response(json.dumps({ "error" : MISSING_PASSWORD_PARAM, "message" : "'password' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if not checkIntFormat(params["id"]):
return Response(json.dumps({ "error" : AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
if not checkPasswordFormat(params["password"]):
return Response(json.dumps({ "error" : AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
query = "SELECT Password, Username, Email, FirstName, LastName FROM Users WHERE ID = {};".format(params["id"])
result = executeDatabaseQuery(query)
if result == []:
return Response(json.dumps({ "error" : AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
if sha256_crypt.verify(params["password"], result[0][0]):
return Response(json.dumps({ "username" : result[0][1], "email" : result[0][2], "firstName" : result[0][3], "lastName" : result[0][4] }), status=HTTP_OK, mimetype="application/json")
return Response(json.dumps({ "error" : AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
# register a user
#
# param : "username" the user's username (required)
# param : "password" the user's password (required)
# param : "email" the user's email (required)
# param : "firstName" the user's first name (required)
# param : "lastName" the user's last name (required)
def post(self):
parser = reqparse.RequestParser()
parser.add_argument("username")
parser.add_argument("password")
parser.add_argument("email")
parser.add_argument("firstName")
parser.add_argument("lastName")
params = parser.parse_args()
if params["username"] is None:
return Response(json.dumps({ "error" : MISSING_USERNAME_PARAM, "message" : "'username' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if params["password"] is None:
return Response(json.dumps({ "error" : MISSING_PASSWORD_PARAM, "message" : "'password' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if params["email"] is None:
return Response(json.dumps({ "error" : MISSING_EMAIL_PARAM, "message" : "'email' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if params["firstName"] is None:
return Response(json.dumps({ "error" : MISSING_FIRST_NAME_PARAM, "message" : "'firstName' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if params["lastName"] is None:
return Response(json.dumps({ "error" : MISSING_LAST_NAME_PARAM, "message" : "'lastName' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if not checkUsernameFormat(params["username"]):
return Response(json.dumps({ "error" : INVALID_USERNAME_PARAM, "message" : "Invalid username" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if not checkPasswordFormat(params["password"]):
return Response(json.dumps({ "error" : INVALID_PASSWORD_PARAM, "message" : "Invalid Password" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if not checkEmailFormat(params["email"]):
return Response(json.dumps({ "error" : INVALID_EMAIL_PARAM, "message" : "Invalid email" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if not checkNameFormat(params["firstName"]):
return Response(json.dumps({ "error" : INVALID_FIRST_NAME_PARAM, "message" : "Invalid first name" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if not checkNameFormat(params["lastName"]):
return Response(json.dumps({ "error" : INVALID_LAST_NAME_PARAM, "message" : "Invalid last name" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if not usernameAvailable(params["username"]):
return Response(json.dumps({ "error" : USERNAME_ALREADY_TAKEN, "message" : "Username is already taken" }), status=HTTP_FORBIDDEN, mimetype="application/json")
if not emailAvailable(params["email"]):
return Response(json.dumps({ "error" : EMAIL_ALREADY_TAKEN, "message" : "Email is already taken" }), status=HTTP_FORBIDDEN, mimetype="application/json")
id = createUserId()
password = sha256_crypt.encrypt(params["password"])
statement = "INSERT OR IGNORE INTO Users (ID, Username, Password, Email, FirstName, LastName) VALUES ({}, '{}', '{}', '{}', '{}', '{}');".format(id, params["username"], password, params["email"], params["firstName"], params["lastName"])
update = executeDatabaseUpdate(statement)
if update.rowcount == 0:
return Response(json.dumps({ "message" : "Internal Server Error" }), status=HTTP_INTERNAL_SERVER_ERROR, mimetype="application/json")
return Response(json.dumps({ "id" : id }), status=HTTP_OK, mimetype="application/json")
# edit a user's information
#
# param : "id" the user's id (required)
# param : "password" the user's password (required)
# param : "username" the user's new username (*)
# param : "newPassword" the user's new password (*)
# param : "email" the user's new email (*)
# param : "firstName" the user's new first name (*)
# param : "lastName" the user's new last name (*)
#
# (*) at least one of these parameters is required
def patch(self):
parser = reqparse.RequestParser()
parser.add_argument("id")
parser.add_argument("password")
parser.add_argument("username")
parser.add_argument("newPassword")
parser.add_argument("email")
parser.add_argument("firstName")
parser.add_argument("lastName")
params = parser.parse_args()
if params["id"] is None:
return Response(json.dumps({ "error" : MISSING_ID_PARAM, "message" : "'id' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if params["password"] is None:
return Response(json.dumps({ "error" : MISSING_PASSWORD_PARAM, "message" : "'password' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if not checkIntFormat(params["id"]):
return Response(json.dumps({ "error" : AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
if not checkPasswordFormat(params["password"]):
return Response(json.dumps({ "error" : AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
if not matchIdAndPassword(params["id"], params["password"]):
return Response(json.dumps({ "error" : AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
updates = ""
if params["username"] is not None:
if not checkUsernameFormat(params["username"]):
return Response(json.dumps({ "error" : INVALID_USERNAME_PARAM, "message" : "Invalid username" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
updates += ", Username = '{}'".format(params["username"])
if params["email"] is not None:
if not checkEmailFormat(params["email"]):
return Response(json.dumps({ "error" : INVALID_EMAIL_PARAM, "message" : "Invalid email" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
updates += ", Email = '{}'".format(params["email"])
if params["newPassword"] is not None:
if not checkPasswordFormat(params["newPassword"]):
return Response(json.dumps({ "error" : INVALID_NEW_PASSWORD_PARAM, "message" : "Invalid new password" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
updates += ", Password = '{}'".format(sha256_crypt.encrypt(params["newPassword"]))
if params["firstName"] is not None:
if not checkNameFormat(params["firstName"]):
return Response(json.dumps({ "error" : INVALID_FIRST_NAME_PARAM, "message" : "Invalid first name" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
updates += ", FirstName = '{}'".format(params["firstName"])
if params["lastName"] is not None:
if not checkNameFormat(params["lastName"]):
return Response(json.dumps({ "error" : INVALID_LAST_NAME_PARAM, "message" : "Invalid last name" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
updates += ", LastName = '{}'".format(params["lastName"])
if params["username"] is not None:
if not usernameAvailable(params["username"]) and not userOwnsUsername(params["id"], params["username"]):
return Response(json.dumps({ "error" : USERNAME_ALREADY_TAKEN, "message" : "Username is already taken" }), status=HTTP_FORBIDDEN, mimetype="application/json")
if params["email"] is not None:
if not emailAvailable(params["email"]) and not userOwnsEmail(params["id"], params["email"]):
return Response(json.dumps({ "error" : EMAIL_ALREADY_TAKEN, "message" : "Email is already taken" }), status=HTTP_FORBIDDEN, mimetype="application/json")
if len(updates) == 0:
return Response(json.dumps({ "error" : MISSING_REQUIRED_PARAMS, "message" : "'username' and/or 'newPassword' and/or 'email' and/or 'firstName' and/or 'lastName' parameter(s) required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
statement = "UPDATE Users SET {} WHERE ID = {};".format(updates[2:], params["id"])
update = executeDatabaseUpdate(statement)
if update.rowcount == 0:
return Response(json.dumps({ "message" : "Internal Server Error" }), status=HTTP_INTERNAL_SERVER_ERROR, mimetype="application/json")
query = "SELECT Username, Email, FirstName, LastName FROM Users WHERE ID = {};".format(params["id"])
result = executeDatabaseQuery(query)
if result == []:
return Response(json.dumps({ "message" : "Internal Server Error" }), status=HTTP_INTERNAL_SERVER_ERROR, mimetype="application/json")
return Response(json.dumps({ "username" : result[0][0], "email" : result[0][1], "firstName" : result[0][2], "lastName" : result[0][3] }), status=HTTP_OK, mimetype="application/json")
# remove a user and all of their data
#
# param : "id" the user's id (required)
# param : "password" the user's password (required)
def delete(self):
parser = reqparse.RequestParser()
parser.add_argument("id")
parser.add_argument("password")
params = parser.parse_args()
if params["id"] is None:
return Response(json.dumps({ "error" : MISSING_ID_PARAM, "message" : "'id' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if params["password"] is None:
return Response(json.dumps({ "error" : MISSING_PASSWORD_PARAM, "message" : "'password' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if not checkIntFormat(params["id"]):
return Response(json.dumps({ "error" : AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
if not checkPasswordFormat(params["password"]):
return Response(json.dumps({ "error" : AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
if not matchIdAndPassword(params["id"], params["password"]):
return Response(json.dumps({ "error" : AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
statement = "DELETE FROM Users WHERE ID = {};".format(params["id"])
delete = executeDatabaseUpdate(statement)
if delete.rowcount == 0:
return Response(json.dumps({ "message" : "Internal Server Error" }), status=HTTP_INTERNAL_SERVER_ERROR, mimetype="application/json")
return Response(json.dumps({ "id" : params["id"] }), status=HTTP_OK, mimetype="application/json")
# /myshare/user/holdings
class Holdings(Resource):
# get a user's holdings
#
# param : "id" the user's id (required)
# param : "password" the user's password (required)
# param : "symbol" a filter to return holdings of only a specific symbol
def get(self):
parser = reqparse.RequestParser()
parser.add_argument("id")
parser.add_argument("password")
parser.add_argument("symbol")
params = parser.parse_args()
if params["id"] is None:
return Response(json.dumps({ "error" : MISSING_ID_PARAM, "message" : "'id' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if params["password"] is None:
return Response(json.dumps({ "error" : MISSING_PASSWORD_PARAM, "message" : "'password' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if not checkIntFormat(params["id"]):
return Response(json.dumps({ "error" : AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
if not checkPasswordFormat(params["password"]):
return Response(json.dumps({ "error" : AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
if not matchIdAndPassword(params["id"], params["password"]):
return Response(json.dumps({ "error" : AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
symbolFilter = ""
if params["symbol"] is not None:
if not checkSymbolFormat(params["symbol"]) or not symbolExists(params["symbol"]):
return Response(json.dumps({ "error" : INVALID_SYMBOL_PARAM, "message" : "Invalid symbol" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if not symbolHeldByUser(params["symbol"], params["id"]):
return Response(json.dumps({ "symbol" : symbol.upper(), "shares" : 0, "currentPrice" : round(stock_info.get_live_price(symbol), 2), "avgCostPerShare" : None, "totalPrincipal" : 0.0, "marketValue" : 0.0, "valueIncrease" : 0.0, "lots" : [] }), status=HTTP_OK, mimetype="application/json")
symbolFilter = "AND Symbol = '{}'".format(params["symbol"].upper())
holdings = []
totalPrincipal = 0.0
totalValueIncrease = 0.0
symbol = None
currentPrice = None
lot = None
lots = None
shares = None
buyPrice = None
buyDate = None
symbolShares = None
symbolPrincipal = None
query = "SELECT Symbol, LotID, ShareID, BuyPrice, BuyDate FROM Holdings WHERE User = {} {}AND SellLotID IS NULL ORDER BY Symbol, BuyDate DESC, LotID;".format(params["id"], symbolFilter)
result = executeDatabaseQuery(query)
for row in result:
# for the first returned row, save the row's information
if symbol is None:
symbol = row[0]
currentPrice = round(stock_info.get_live_price(symbol), 2)
lot = int(row[1])
lots = []
shares = [int(row[2])]
buyPrice = round(float(row[3]), 2)
buyDate = row[4]
symbolShares = 1
symbolPrincipal = buyPrice
# if the symbol is different than the current symbol, add the current lot to lots,
# then add lots to holdings, then save this row's information
elif symbol != row[0]:
lots.append({ "lotId" : lot, "buyPrice" : buyPrice, "buyDate" : buyDate, "valueIncrease": round((currentPrice - buyPrice) * len(shares), 2), "shares" : len(shares), "shareIds" : shares })
info = yfinance.Ticker(symbol)
info.info.update({ "currentPrice" : currentPrice })
holdings.append({ "symbol" : symbol, "shares" : symbolShares, "avgCostPerShare" : round(symbolPrincipal / symbolShares, 2), "principal" : round(symbolPrincipal, 2), "marketValue" : round(currentPrice * symbolShares, 2), "valueIncrease" : round((currentPrice * symbolShares) - symbolPrincipal, 2), "lots" : lots, "info" : info.info })
totalValueIncrease += round((currentPrice * symbolShares) - symbolPrincipal, 2)
totalPrincipal += round(symbolPrincipal, 2)
symbol = row[0]
currentPrice = round(stock_info.get_live_price(symbol), 2)
lot = int(row[1])
lots = []
shares = [int(row[2])]
buyPrice = round(float(row[3]), 2)
buyDate = row[4]
symbolShares = 1
symbolPrincipal = buyPrice
# if only the lot is different than the current lot, add the current lot to lots,
# then save this this lot
elif lot != int(row[1]):
lots.append({ "lotId" : lot, "buyPrice" : buyPrice, "buyDate" : buyDate, "valueIncrease": round((currentPrice - buyPrice) * len(shares), 2), "shares" : len(shares), "shareIds" : shares })
lot = int(row[1])
shares = [int(row[2])]
buyPrice = round(float(row[3]), 2)
buyDate = row[4]
symbolShares += 1
symbolPrincipal += buyPrice
# otherwise, add this share to shares
else:
symbolShares += 1
symbolPrincipal += buyPrice
shares.append(int(row[2]))
# add the saved information from the last returned row to lots and holdings
if symbol is not None:
lots.append({ "lotId" : lot, "buyPrice" : buyPrice, "buyDate" : buyDate, "valueIncrease": round((currentPrice - buyPrice) * len(shares), 2), "shares" : len(shares), "shareIds" : shares })
info = yfinance.Ticker(symbol)
info.info.update({ "currentPrice" : currentPrice })
holdings.append({ "symbol" : symbol, "shares" : symbolShares, "avgCostPerShare" : round(symbolPrincipal / symbolShares, 2), "principal" : round(symbolPrincipal, 2), "marketValue" : round(currentPrice * symbolShares, 2), "valueIncrease" : round((currentPrice * symbolShares) - symbolPrincipal, 2), "lots" : lots, "info" : info.info })
totalValueIncrease += round((currentPrice * symbolShares) - symbolPrincipal, 2)
totalPrincipal += round(symbolPrincipal, 2)
if params["symbol"] is not None:
return Response(json.dumps(holdings[0]), status=HTTP_OK, mimetype="application/json")
return Response(json.dumps({ "id" : int(params["id"]), "totalPrincipal" : round(totalPrincipal, 2), "marketValue": round(totalPrincipal + totalValueIncrease, 2), "totalValueIncrease" : totalValueIncrease, "holdings" : holdings }), status=HTTP_OK, mimetype="application/json")
# /myshare/user/lots
class Lots(Resource):
# get a user's lots
#
# param : "id" the user's id (required)
# param : "password" the user's password (required)
# param : "lotId" a filter to return info of only a specific lot
def get(self):
parser = reqparse.RequestParser()
parser.add_argument("id")
parser.add_argument("password")
parser.add_argument("lotId")
params = parser.parse_args()
if params["id"] is None:
return Response(json.dumps({ "error" : MISSING_ID_PARAM, "message" : "'id' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if params["password"] is None:
return Response(json.dumps({ "error" : MISSING_PASSWORD_PARAM, "message" : "'password' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if not checkIntFormat(params["id"]):
return Response(json.dumps({ "error" : AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
if not checkPasswordFormat(params["password"]):
return Response(json.dumps({ "error" : AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
if not matchIdAndPassword(params["id"], params["password"]):
return Response(json.dumps({ "error" : AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
lotFilter = ""
if params["lotId"] is not None:
if not lotOwnedByUser(params["lotId"], params["id"]):
return Response(json.dumps({ "error" : OWNERSHIP_AUTHENTICATION_FAILED, "message" : "User does not own this lot" }), status=HTTP_FORBIDDEN, mimetype="application/json")
lotFilter = "LotID = {} AND ".format(params["lotId"])
lots = []
totalProfitFromSelling = 0.0
totalValueIncrease = 0.0
totalPrincipal = 0.0
lot = None
symbol = None
buyPrice = None
buyDate = None
currentPrice = None
sellLots = None
holding = None
sellLot = None
sold = None
profitFromSelling = None
query = "SELECT LotID, Symbol, ShareID, BuyPrice, BuyDate, SellLotID, SellPrice, SellDate FROM Holdings WHERE {}User = {} ORDER BY BuyDate DESC, LotID, SellDate DESC, SellLotID;".format(lotFilter, params["id"])
result = executeDatabaseQuery(query)
for row in result:
# for the first returned row, save the row's information
if lot is None:
lot = int(row[0])
symbol = row[1]
buyPrice = round(float(row[3]), 2)
buyDate = row[4]
currentPrice = round(stock_info.get_live_price(symbol), 2)
holding = []
sellLots = []
sold = 0
profitFromSelling = 0.0
# if this share was not sold, add it to the holdings array
if row[5] is None:
holding.append(int(row[2]))
# otherwise initialize a sell lot and add this share to its shareIds
else:
sellLot = { "sellLotId" : int(row[5]), "sellPrice" : round(float(row[6]), 2), "sellDate" : row[7], "shareIds" : [int(row[2])] }
sold += 1
# if the lot is different than the previous row, add the current lot to lots,
# then save this row's information
elif lot != row[0]:
# if there is a saved sell lot, add it to sellLots
if sellLot is not None:
sellLotShares = len(sellLot["shareIds"])
sellLotProfit = (sellLot["sellPrice"] - buyPrice) * sellLotShares
profitFromSelling += sellLotProfit
sellLot.update({ "shares" : sellLotShares, "profit" : round(sellLotProfit, 2)} )
sellLots.append(sellLot)
sharesHolding = len(holding)
valueIncrease = round((currentPrice - buyPrice) * sharesHolding, 2)
totalValueIncrease += valueIncrease
totalPrincipal += round(buyPrice * sharesHolding, 2)
totalProfitFromSelling += profitFromSelling
lots.append({ "lotId" : lot, "symbol" : symbol, "buyPrice" : buyPrice, "buyDate" : buyDate, "currentPrice" : currentPrice, "profitFromSelling" : round(profitFromSelling, 2), "holdingValueIncrease" : valueIncrease, "sharesHolding" : sharesHolding, "holding" : holding, "sharesSold" : sold, "sellLots" : sellLots })
lot = int(row[0])
symbol = row[1]
buyPrice = round(float(row[3]), 2)
buyDate = row[4]
currentPrice = round(stock_info.get_live_price(symbol), 2)
holding = []
sellLots = []
sellLot = None
sold = 0
profitFromSelling = 0.0
# if this share was not sold, add it to the holdings array
if row[5] is None:
holding.append(int(row[2]))
# otherwise initialize a sell lot and add this share to its shareIds
else:
sellLot = { "sellLotId" : int(row[5]), "sellPrice" : round(float(row[6]), 2), "sellDate" : row[7], "shareIds" : [int(row[2])] }
sold += 1
else:
# otherwise if this share was not sold add it to the holding array
if row[5] is None:
holding.append(int(row[2]))
# if there is a saved sell lot, add it to sellLots
if sellLot is not None:
sellLotShares = len(sellLot["shareIds"])
sellLotProfit = (sellLot["sellPrice"] - buyPrice) * sellLotShares
profitFromSelling += sellLotProfit
sellLot.update({ "shares" : sellLotShares, "profit" : round(sellLotProfit, 2) })
sellLots.append(sellLot)
sellLot = None
elif sellLot is not None:
# otherwise if there is a saved sell lot and this share is from another lot,
# add the current sell lot to sellLots, then initialize a sell lot and add this share to its shareIds
if sellLot["sellLotId"] != int(row[5]):
sellLotShares = len(sellLot["shareIds"])
sellLotProfit = (sellLot["sellPrice"] - buyPrice) * sellLotShares
profitFromSelling += sellLotProfit
sellLot.update({ "shares" : sellLotShares, "profit" : sellLotProfit } )
sellLots.append(sellLot)
sellLot = { "sellLotId" : int(row[5]), "sellPrice" : round(float(row[6]), 2), "sellDate" : row[7], "shareIds" : [int(row[2])] }
# otherwise if there is a saved sell lot and this share is from that lot,
# add this share to the lot's shareIds
else:
sellLot["shareIds"].append(int(row[2]))
sold += 1
# otherwise initialize a sell lot and add this share to its shareIds
else:
sellLot = { "sellLotId" : int(row[5]), "sellPrice" : round(float(row[6]), 2), "sellDate" : row[7], "shareIds" : [int(row[2])] }
sold += 1
# append the saved information from the last returned row to lots
if lot is not None:
# if there is a saved sell lot, add it to sellLots
if sellLot is not None:
sellLotShares = len(sellLot["shareIds"])
sellLotProfit = (sellLot["sellPrice"] - buyPrice) * sellLotShares
profitFromSelling += sellLotProfit
sellLot.update({ "shares" : sellLotShares, "profit" : round(sellLotProfit, 2) })
sellLots.append(sellLot)
sharesHolding = len(holding)
valueIncrease = round((currentPrice - buyPrice) * sharesHolding, 2)
totalValueIncrease += valueIncrease
totalPrincipal += round(buyPrice * sharesHolding, 2)
totalProfitFromSelling += profitFromSelling
lots.append({ "lotId" : lot, "symbol" : symbol, "buyPrice" : buyPrice, "buyDate" : buyDate, "currentPrice" : currentPrice, "profitFromSelling" : round(profitFromSelling, 2), "holdingValueIncrease" : valueIncrease, "sharesHolding" : sharesHolding, "holding" : holding, "sharesSold" : sold, "sellLots" : sellLots })
if params["lotId"] is not None:
return Response(json.dumps(lots[0]), status=HTTP_OK, mimetype="application/json")
return Response(json.dumps({ "id" : int(params["id"]), "currentPrincipal" : totalPrincipal, "totalValueIncrease" : round(totalValueIncrease, 2), "totalProfitFromSelling": round(totalProfitFromSelling, 2), "lots" : lots }), status=HTTP_OK, mimetype="application/json")
# add a new lot for a user
#
# param : "id" the user's id (required)
# param : "password" the user's password (required)
# param : "symbol" the symbol of the shares purchased (required)
# param : "shares" the number of shares purchased (required)
# param : "buyPrice" the price at which the shares were purchased (required)
# param : "buyDate" the date the lot was purchased (required)
def post(self):
parser = reqparse.RequestParser()
parser.add_argument("id")
parser.add_argument("password")
parser.add_argument("symbol")
parser.add_argument("shares")
parser.add_argument("buyPrice")
parser.add_argument("buyDate")
params = parser.parse_args()
if params["id"] is None:
return Response(json.dumps({ "error" : MISSING_ID_PARAM, "message" : "'id' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if params["password"] is None:
return Response(json.dumps({ "error" : MISSING_PASSWORD_PARAM, "message" : "'password' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if not checkIntFormat(params["id"]):
return Response(json.dumps({ "error" : AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
if not checkPasswordFormat(params["password"]):
return Response(json.dumps({ "error" : AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
if not matchIdAndPassword(params["id"], params["password"]):
return Response(json.dumps({ "error" : AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
if params["symbol"] is None:
return Response(json.dumps({ "error" : MISSING_SYMBOL_PARAM, "message" : "'symbol' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if params["shares"] is None:
return Response(json.dumps({ "error" : MISSING_SHARES_PARAM, "message" : "'shares' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if params["buyPrice"] is None:
return Response(json.dumps({ "error" : MISSING_BUY_PRICE_PARAM, "message" : "'buyPrice' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if params["buyDate"] is None:
return Response(json.dumps({ "error" : MISSING_BUY_DATE_PARAM, "message" : "'buyDate' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if not checkIntFormat(params["shares"]) or int(params["shares"]) <= 0:
return Response(json.dumps({ "error" : INVALID_SHARES_PARAM, "message" : "Invalid amount of shares" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if not checkDollarFormat(params["buyPrice"]):
return Response(json.dumps({ "error" : INVALID_BUY_PRICE_PARAM, "message" : "Invalid buy price" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if not checkDateFormat(params["buyDate"]):
return Response(json.dumps({ "error" : INVALID_BUY_DATE_PARAM, "message" : "Invalid buy date" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if not symbolExists(params["symbol"]):
return Response(json.dumps({ "error" : INVALID_SYMBOL_PARAM, "message" : "Invalid symbol" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
lotId = createLotId()
shareIds = createShareIds(int(params["shares"]))
insertValues = ""
for shareId in shareIds:
insertValues += ", ({}, {}, {}, '{}', {}, '{}')".format(shareId, lotId, params["id"], params["symbol"].upper(), params["buyPrice"], params["buyDate"])
statement = "INSERT INTO Holdings (ShareID, LotID, User, Symbol, BuyPrice, BuyDate) VALUES {};".format(insertValues[2:])
update = executeDatabaseUpdate(statement)
if update.rowcount == 0:
return Response(json.dumps({ "message" : "Internal Server Error" }), status=HTTP_INTERNAL_SERVER_ERROR, mimetype="application/json")
return Response(json.dumps({ "user" : int(params["id"]), "symbol" : params["symbol"].upper(), "shares" : int(params["shares"]), "buyPrice" : float(params["buyPrice"]), "buyDate" : params["buyDate"], "lotId" : lotId, "shareIds" : shareIds }), status=HTTP_OK, mimetype="application/json")
# edit a lot's information
#
# param : "id" the user's id (required)
# param : "password" the user's password (required)
# param : "lotId" the lot to be edited (required)
# param : "shares" the new number of shares purchased (*)
# param : "buyPrice" the new price at which the shares were bought (*)
# param : "buyDate" the new date at which the lot was purchased (*)
#
# (*) at least one of these parameters is required
def patch(self):
parser = reqparse.RequestParser()
parser.add_argument("id")
parser.add_argument("password")
parser.add_argument("lotId")
parser.add_argument("shares")
parser.add_argument("buyPrice")
parser.add_argument("buyDate")
params = parser.parse_args()
if params["id"] is None:
return Response(json.dumps({ "error": MISSING_ID_PARAM, "message" : "'id' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if params["password"] is None:
return Response(json.dumps({ "error": MISSING_PASSWORD_PARAM, "message" : "'password' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if params["lotId"] is None:
return Response(json.dumps({ "error": MISSING_LOT_ID_PARAM, "message" : "'lotId' parameter required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if params["shares"] is None and params["buyPrice"] is None and params["buyDate"] is None:
return Response(json.dumps({ "error": MISSING_REQUIRED_PARAMS, "message" : "'shares' and/or 'buyPrice' and/or 'buyDate' parameter(s) required" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
if not checkIntFormat(params["id"]):
return Response(json.dumps({ "error": AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
if not checkPasswordFormat(params["password"]):
return Response(json.dumps({ "error": AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
if not matchIdAndPassword(params["id"], params["password"]):
return Response(json.dumps({ "error": AUTHENTICATION_FAILED, "message" : "Id and password do not match" }), status=HTTP_FORBIDDEN, mimetype="application/json")
if not lotOwnedByUser(params["lotId"], params["id"]):
return Response(json.dumps({ "error": OWNERSHIP_AUTHENTICATION_FAILED, "message" : "User does not own this lot" }), status=HTTP_FORBIDDEN, mimetype="application/json")
infoChanges = ""
if params["buyPrice"] is not None:
if not checkDollarFormat(params["buyPrice"]):
return Response(json.dumps({ "error" : INVALID_BUY_PRICE_PARAM, "message" : "Invalid buy price" }), status=HTTP_BAD_REQUEST, mimetype="application/json")
infoChanges += ", BuyPrice = {}".format(params["buyPrice"])