-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
2388 lines (1982 loc) · 106 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
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
from flask import render_template, redirect, Flask, session, request, make_response, url_for
from flask_mail import Mail, Message
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
import secrets
from sqlalchemy import text
import requests
from werkzeug.utils import secure_filename
import os
import datetime
from datetime import date, timedelta
from sqlalchemy.exc import OperationalError
from flask_session import Session
from flask_talisman import Talisman
from flask_wtf import FlaskForm
from flask_wtf.csrf import CSRFProtect
from authlib.integrations.flask_client import OAuth
from authlib.integrations.base_client.errors import OAuthError
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from imhotep_files_flask import upload_file, delete_file
#define the app
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('secret_key')
app.config['SESSION_PERMANENT'] = True
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=365)
app.config['SESSION_REFRESH_EACH_REQUEST'] = True
app.config['SESSION_USE_SIGNER'] = True
app.config['SESSION_KEY_PREFIX'] = 'myapp_session:'
app.config['SESSION_COOKIE_SECURE'] = True
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_REFRESH_EACH_REQUEST'] = True # Refresh session timeout with each request
sess = Session(app)
@app.before_request
def refresh_session():
session.permanent = True # Keep the session permanent for every request
#define the mail to send the verification code and the forget password
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = '[email protected]'
app.config['MAIL_PASSWORD'] = os.getenv('MAIL_PASSWORD')
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail = Mail(app)
#connection with the database
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
#define the place to save the user photo and the allowed image formats
app.config["MAX_CONTENT_LENGTH"] = 3 * 1024 * 1024
app.config["UPLOAD_FOLDER_PHOTO"] = os.path.join(os.getcwd(), "static", "user_photo")
ALLOWED_EXTENSIONS = ("png", "jpg", "jpeg")
csrf = CSRFProtect(app)
class CSRFForm(FlaskForm):
pass
app.config.update(
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SECURE=True # Ensure cookies are only sent over HTTPS
)
# Define your CSP policy
csp = {
'default-src': "'self'",
'script-src': [
"'self'",
"https://cdn.jsdelivr.net", # Allow Bootstrap and Font Awesome
"https://cdn.tailwindcss.com", # Allow Tailwind CSS CDN
"'unsafe-inline'", # Allow inline scripts (needed for some Bootstrap features)
],
'style-src': [
"'self'",
"'unsafe-inline'", # Allow inline styles (necessary for Bootstrap)
"https://cdn.jsdelivr.net", # Allow Bootstrap CSS
"https://cdnjs.cloudflare.com" # Allow Font Awesome
],
'font-src': [
"'self'",
"https://cdnjs.cloudflare.com", # Allow Font Awesome fonts
"https://fonts.gstatic.com" # If using Google Fonts
],
'img-src': ["'self'", "data:"], # Add any other domains as necessary
'connect-src': ["'self'"], # Add any other domains for AJAX calls if necessary
}
# Set up Talisman with the CSP configuration
Talisman(app, content_security_policy=csp)
oauth = OAuth(app)
google = oauth.register(
name='google',
client_id=os.getenv("GOOGLE_CLIENT_ID"),
client_secret=os.getenv("GOOGLE_CLIENT_SECRET"),
access_token_url='https://accounts.google.com/o/oauth2/token',
access_token_params=None,
authorize_url='https://accounts.google.com/o/oauth2/auth',
authorize_params=None,
api_base_url='https://www.googleapis.com/oauth2/v1/',
userinfo_endpoint='https://openidconnect.googleapis.com/v1/userinfo', # This is only needed if using openId to fetch user info
client_kwargs={'scope': 'email profile'},
server_metadata_url='https://accounts.google.com/.well-known/openid-configuration'
)
limiter = Limiter(
get_remote_address, # This will limit based on the IP address of the requester
app=app,
default_limits=["250 per day", "75 per hour"] # Set default rate limits
)
def send_verification_mail_code(user_mail):
verification_code = secrets.token_hex(4)
msg = Message('Email Verification', sender='[email protected]', recipients=[user_mail])
msg.body = f"Your verification code is: {verification_code}"
mail.send(msg)
session["verification_code"] = verification_code
def set_currency_session(favorite_currency):
primary_api_key = os.getenv('EXCHANGE_API_KEY_PRIMARY')
data = None
try:
response = requests.get(f"https://imhotepexchangeratesapi.pythonanywhere.com/latest_rates/{primary_api_key}/{favorite_currency}")
data = response.json()
rate = data["data"]
except requests.RequestException as e:
print(f"Failed to fetch exchange rates: {e}")
return None
if rate:
session["rate"] = rate
today = datetime.datetime.now().date()
session["rate_date"] = today
session["favorite_currency"] = favorite_currency
return rate
return None
def convert_to_fav_currency(dictionary, user_id):
favorite_currency = select_favorite_currency(user_id)
today = datetime.datetime.now().date()
if session.get('rate_date') != today:
session.pop('rate', None)
session.pop('rate_expire', None)
session.pop('favorite_currency', None)
rate = set_currency_session(favorite_currency)
if not rate:
return None, favorite_currency
elif session.get('favorite_currency') != favorite_currency:
session.pop('rate', None)
session.pop('rate_expire', None)
session.pop('favorite_currency', None)
rate = set_currency_session(favorite_currency)
if not rate:
return None, favorite_currency
else:
rate = session.get('rate')
if rate == None:
try:
rate = set_currency_session(favorite_currency)
except:
return "Error"
total_favorite_currency = 0
for currency, amount in dictionary.items():
converted_amount = amount / rate[currency]
total_favorite_currency += converted_amount
return total_favorite_currency, favorite_currency
def show_networth():
user_id = session.get("user_id")
favorite_currency = select_favorite_currency(user_id)
total_db = db.session.execute(
text("SELECT currency, total FROM networth WHERE user_id = :user_id"),
{"user_id": user_id}
).fetchall()
total_db_dict = dict(total_db)
total_favorite_currency,favorite_currency = convert_to_fav_currency(total_db_dict, user_id)
return total_favorite_currency, favorite_currency
def select_currencies(user_id):
currency_db = db.session.execute(
text("SELECT currency from networth WHERE user_id = :user_id"),
{"user_id": user_id}
).fetchall()
currency_all = []
for item in currency_db:
currency_all.append(item[0])
return(currency_all)
def allowed_file(filename):
if "." in filename:
filename_check = filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
return filename_check
else:
return False
#a function that seperate the file extention form the filename by spliting it after the . and selects the index [1]
def file_ext(filename):
if "." in filename:
file_ext = filename.split('.', 1)[1].lower()
return file_ext
def select_user_data(user_id):
user_info = db.session.execute(
text("SELECT user_username, user_mail, user_photo_path FROM users WHERE user_id = :user_id"),
{"user_id": user_id}
).fetchall()[0]
user_username = user_info[0]
user_mail = user_info[1]
user_photo_path = user_info[2]
return user_username, user_mail, user_photo_path
def select_user_photo():
user_id = session.get("user_id")
user_photo_path = db.session.execute(
text("SELECT user_photo_path FROM users WHERE user_id = :user_id"),
{"user_id": user_id}
).fetchone()[0]
return user_photo_path
def select_favorite_currency(user_id):
favorite_currency = db.session.execute(
text("SELECT favorite_currency FROM users WHERE user_id = :user_id"),
{"user_id" :user_id}
).fetchone()[0]
return favorite_currency
def select_years_wishlist(user_id):
all_years_db = db.session.execute(
text("SELECT DISTINCT(year) FROM wishlist WHERE user_id = :user_id"),
{"user_id" :user_id}
).fetchall()
all_years = []
for item in all_years_db:
all_years.append(item[0])
return all_years
def wishlist_page(user_id):
today = date.today()
year = today.year
wishlist_db = db.session.execute(
text("SELECT * FROM wishlist WHERE user_id = :user_id AND year = :year ORDER BY wish_id"),
{"user_id" :user_id , "year" :year}
).fetchall()
return year, wishlist_db
def logout():
session.permanent = False
session["logged_in"] = False
session.pop('rate', None)
session.pop('rate_expire', None)
session.clear()
def security_check(user_id, check_pass):
password_db = db.session.execute(
text("SELECT user_password FROM users WHERE user_id = :user_id"),
{"user_id" :user_id}
).fetchone()[0]
if check_password_hash(password_db, check_pass):
return True
else:
return False
def save_profile_picture(picture_url, user_id):
"""Downloads and saves the user's Google profile picture to the server using the user ID."""
try:
if not os.path.exists(app.config["UPLOAD_FOLDER_PHOTO"]):
os.makedirs(app.config["UPLOAD_FOLDER_PHOTO"])
filename = f"{user_id}.jpg"
filepath = os.path.join(app.config["UPLOAD_FOLDER_PHOTO"], filename)
response = requests.get(picture_url)
if response.status_code == 200:
with open(filepath, 'wb') as f:
f.write(response.content)
return filename
else:
return None
except Exception:
return None
def trans(user_id):
from_date = request.args.get("from_date")
to_date = request.args.get("to_date")
page = int(request.args.get("page", 1)) # Default to page 1
per_page = 20 # Number of records per page
offset = (page - 1) * per_page
now = datetime.datetime.now()
first_day_current_month = now.replace(day=1)
if now.month == 12:
first_day_next_month = now.replace(year=now.year + 1, month=1, day=1)
else:
first_day_next_month = now.replace(month=now.month + 1, day=1)
if from_date is None:
from_date = first_day_current_month.date()
if to_date is None:
to_date = first_day_next_month.date()
trans_db = db.session.execute(
text("SELECT * FROM trans WHERE user_id = :user_id AND date BETWEEN :from_date AND :to_date ORDER BY date DESC LIMIT :limit OFFSET :offset"),
{"user_id": user_id, "from_date" :from_date, "to_date" :to_date, "limit": per_page, "offset": offset}
).fetchall()
# Get total count for pagination
total_count = db.session.execute(
text('''
SELECT COUNT(*) FROM trans
WHERE user_id = :user_id
AND date BETWEEN :from_date AND :to_date
'''),
{"user_id": user_id, "from_date": from_date, "to_date": to_date}
).scalar()
total_pages = (total_count + per_page - 1) // per_page # Calculate total number of pages
return trans_db, to_date,from_date, total_pages, page
'''def query_gemini(prompt, user_data):
enriched_prompt = prompt
if user_data:
enriched_prompt = f"User data: {user_data}\n{prompt}"
response = chat_session.send_message(enriched_prompt)
print(response.text)
return response.text
def get_user_data(user_id):
trans_db = db.session.execute(
text("SELECT currency, date, amount, trans_status, trans_details FROM trans WHERE user_id = :user_id"),
{"user_id":user_id}
).fetchall()
target_db = db.session.execute(
text("SELECT target, mounth, year FROM target WHERE user_id = :user_id"),
{"user_id":user_id}
).fetchall()
wishlist_db = db.session.execute(
text("SELECT currency, price, status, link, wish_details, year FROM wishlist WHERE user_id = :user_id"),
{"user_id":user_id}
).fetchall()
networth_db = db.session.execute(
text("SELECT currency, total FROM networth WHERE user_id = :user_id"),
{"user_id":user_id}
).fetchall()
print(user_id)
favorite_currency = db.session.execute(
text("SELECT favorite_currency FROM users WHERE user_id = :user_id"),
{"user_id":user_id}
).fetchone()[0]
print(favorite_currency)
user_data = {
'transactions': [{'currency': row[0], 'date': row[1].strftime('%Y-%m-%d'), 'amount': float(row[2]), 'trans_status': row[3], 'trans_details': row[4] } for row in trans_db],
'user_save_target': [{'target': row[0], 'mounth': row[1], 'year': row[2]} for row in target_db],
'wishlist': [{'currency': row[0], 'price': row[1], 'status': row[2], 'link': row[3], 'wish_details': row[4], 'year': row[5]} for row in wishlist_db],
'networth': [{'currency': row[0], 'total': row[1]} for row in networth_db],
'favorite_currency': favorite_currency,
}
return user_data'''
@app.errorhandler(404)
def page_not_found(error):
return render_template('error_handle.html', error_code = "404", error_description = "We can't find that page."), 404
@app.errorhandler(400)
def session_expired(error):
return render_template('error_handle.html', error_code = "400", error_description= "Session Expired."), 400
@app.errorhandler(429)
def request_amount_exceed(error):
return render_template('error_handle.html', error_code = "429", error_description= "You exceeded the Maximum amount of requests! Please Try Again Later"), 429
@app.errorhandler(405)
def page_not_found(error):
return render_template('error_handle.html', error_code = "405", error_description = "Method Not Allowed."), 405
@app.errorhandler(Exception)
def server_error(error):
return render_template('error_handle.html', error_code = "500", error_description = "Something went wrong."), 500
@app.errorhandler(500)
def internal_server_error(error):
return render_template('error_handle.html', error_code = "500", error_description="Something Went Wrong."), 500
@app.route("/", methods=["GET"])
def index():
return redirect("/login_page")
@app.route("/login_page", methods=["GET"])
def login_page():
if session.get("logged_in"):
return redirect("/home")
else:
return render_template("login.html", form=CSRFForm())
@app.route("/register_page", methods=["GET"])
def register_page():
return render_template("register.html", form=CSRFForm())
@app.route("/register", methods=["POST"])
def register():
user_username = (request.form.get("user_username").strip()).lower()
user_password = request.form.get("user_password")
user_mail = request.form.get("user_mail").lower()
if "@" in user_username:
error = "username should not have @"
return render_template("register.html", error=error, form=CSRFForm())
if "@" not in user_mail:
error = "mail should have @"
return render_template("register.html", error=error, form=CSRFForm())
existing_username = db.session.execute(
text("SELECT user_username FROM users WHERE LOWER(user_username) = :user_username"),
{"user_username": user_username}
).fetchall()
if existing_username:
error_existing = "Username is already in use. Please choose another one. or "
return render_template("register.html", error=error_existing, form=CSRFForm())
existing_mail = db.session.execute(
text("SELECT user_mail FROM users WHERE LOWER(user_mail) = :user_mail"),
{"user_mail": user_mail}
).fetchall()
if existing_mail:
error_existing = "Mail is already in use. Please choose another one. or "
return render_template("register.html", error=error_existing, form=CSRFForm())
try:
last_user_id = db.session.execute(
text("SELECT MAX(user_id) FROM users")
).fetchone()[0]
user_id = last_user_id + 1
except:
user_id = 1
session["user_id"] = user_id
hashed_password = generate_password_hash(user_password)
send_verification_mail_code(user_mail)
db.session.execute(
text("INSERT INTO users (user_id, user_username, user_password, user_mail, user_mail_verify, favorite_currency) VALUES (:user_id, :user_username, :user_password, :user_mail, :user_mail_verify, :favorite_currency)"),
{"user_id": user_id ,"user_username": user_username, "user_password": hashed_password, "user_mail": user_mail, "user_mail_verify": "not_verified", "favorite_currency": "USD"}
)
db.session.commit()
return render_template("mail_verify.html", user_mail=user_mail, user_username=user_username, form=CSRFForm())
@app.route("/mail_verification", methods=["POST", "GET"])
def mail_verification():
if request.method == "GET":
return render_template("mail_verify.html", form=CSRFForm())
else:
verification_code = request.form.get("verification_code").strip()
user_id = session.get("user_id")
user_mail = request.form.get("user_mail")
user_username = request.form.get("user_username")
if verification_code == session.get("verification_code"):
db.session.execute(
text("UPDATE users SET user_mail_verify = :user_mail_verify WHERE user_id = :user_id"), {"user_mail_verify" :"verified", "user_id": user_id}
)
db.session.commit()
try:
msg = Message('Email Verified', sender='[email protected]', recipients=[user_mail])
msg.body = f"Welcome {user_username} To Imhotep Finacial Manager"
mail.send(msg)
except:
"""Pass the mail send"""
success="Email verified successfully. You can now log in."
return render_template("login.html", success=success, form=CSRFForm())
else:
error="Invalid verification code."
return render_template("mail_verify.html", error=error, form=CSRFForm())
@app.route("/register_google")
def login_google():
google = oauth.create_client('google') # create the google oauth client
redirect_uri = url_for('authorize', _external=True)
return google.authorize_redirect(redirect_uri)
@app.route('/authorize')
def authorize():
google = oauth.create_client('google')
try:
# create the google oauth client
token = google.authorize_access_token()
# Access token from google (needed to get user info)
resp = google.get('userinfo')
# userinfo contains stuff u specificed in the scrope
user_info = resp.json()
user = oauth.google.userinfo()# uses openid endpoint to fetch user info
user_mail = user_info["email"]
user_username = user_mail.split('@')[0]
user_mail_verify = user_info["verified_email"]
user_photo_url = user_info["picture"]
existing_mail = db.session.execute(
text("SELECT user_mail FROM users WHERE LOWER(user_mail) = :user_mail"),
{"user_mail": user_mail}
).fetchall()
if existing_mail:
user = db.session.execute(
text("SELECT user_id FROM users WHERE LOWER(user_mail) = :user_mail"),
{"user_mail": user_mail}
).fetchone()[0]
session["logged_in"] = True
session["user_id"] = user
session.permanent = True
return redirect("/home")
session["user_mail"] = user_mail
session["user_mail_verify"] = user_mail_verify
session["user_photo_url"] = user_photo_url
existing_username = db.session.execute(
text("SELECT user_username FROM users WHERE LOWER(user_username) = :user_username"),
{"user_username": user_username}
).fetchall()
if existing_username:
#error_existing = "Username is already in use. Please choose another one."
return render_template("add_username_google_login.html", form=CSRFForm())
session["user_username"] = user_username
return render_template('add_password_google_login.html', form=CSRFForm())
except OAuthError as error:
# Catch the OAuthError and handle it
if error.error == 'access_denied':
error_message = "Google login was canceled. Please try again."
return render_template("login.html", error=error_message, form=CSRFForm())
else:
error_message = "An error occurred. Please try again."
return render_template("login.html", error=error_message, form=CSRFForm())
@app.route("/add_password_google_login", methods=["POST"])
def add_password_google_login():
user_password = request.form.get("user_password")
hashed_password = generate_password_hash(user_password)
user_username = session.get("user_username")
user_mail = session.get("user_mail")
user_mail_verify = session.get("user_mail_verify")
user_photo_url = session.get("user_photo_url")
try:
last_user_id = db.session.execute(
text("SELECT MAX(user_id) FROM users")
).fetchone()[0]
user_id = last_user_id + 1
except:
user_id = 1
if user_photo_url:
user_photo_path = save_profile_picture(user_photo_url, user_id)
db.session.execute(
text("INSERT INTO users (user_id, user_username, user_password, user_mail, user_mail_verify, favorite_currency, user_photo_path) VALUES (:user_id, :user_username, :user_password, :user_mail, :user_mail_verify, :favorite_currency, :user_photo_path)"),
{"user_id": user_id ,"user_username": user_username, "user_password": hashed_password, "user_mail": user_mail, "user_mail_verify": "verified", "favorite_currency": "USD", "user_photo_path":user_photo_path}
)
db.session.commit()
try:
msg = Message('Welcome To Imhotep Finance', sender='[email protected]', recipients=[user_mail])
msg.body = f"Welcome {user_username} To Imhotep Finacial Manager"
mail.send(msg)
except:
"""Do Nothing"""
session["logged_in"] = True
session["user_id"] = user_id
session.permanent = True
return redirect("/home")
@app.route("/add_username_google_login", methods=["POST"])
def add_username_google_login():
user_username = request.form.get("user_username")
existing_username = db.session.execute(
text("SELECT user_username FROM users WHERE LOWER(user_username) = :user_username"),
{"user_username": user_username}
).fetchall()
if existing_username:
error_existing = "Username is already in use. Please choose another one."
return render_template("add_username_google_login.html", form=CSRFForm(), error=error_existing)
session["user_username"] = user_username
return render_template('add_password_google_login.html', form=CSRFForm())
@app.route("/login", methods=["POST"])
@limiter.limit("5 per minute")
def login():
user_username_mail = (request.form.get("user_username_mail").strip()).lower()
user_password = request.form.get("user_password")
if "@" in user_username_mail:
try:
login_db = db.session.execute(
text("SELECT user_password, user_mail_verify FROM users WHERE LOWER(user_mail) = :user_mail"),
{"user_mail": user_username_mail}
).fetchall()[0]
password_db = login_db[0]
user_mail_verify = login_db[1]
if check_password_hash(password_db, user_password):
if user_mail_verify == "verified":
user = db.session.execute(
text("SELECT user_id FROM users WHERE LOWER(user_mail) = :user_mail AND user_password = :user_password"),
{"user_mail": user_username_mail, "user_password": password_db}
).fetchone()[0]
session["logged_in"] = True
session["user_id"] = user
session.permanent = True
return redirect("/home")
else:
error_verify = "Your mail isn't verified"
return render_template("login.html", error_verify=error_verify, form=CSRFForm())
else:
error = "Your username or password are incorrect!"
return render_template("login.html", error=error, form=CSRFForm())
except:
error = "Your E-mail or password are incorrect!"
return render_template("login.html", error=error, form=CSRFForm())
else:
try:
login_db = db.session.execute(
text("SELECT user_password, user_mail_verify FROM users WHERE LOWER(user_username) = :user_username"),
{"user_username": user_username_mail}
).fetchall()[0]
password_db = login_db[0]
user_mail_verify = login_db[1]
if check_password_hash(password_db, user_password):
if user_mail_verify == "verified":
user = db.session.execute(
text("SELECT user_id FROM users WHERE LOWER(user_username) = :user_username AND user_password = :user_password"),
{"user_username": user_username_mail, "user_password": password_db}
).fetchone()[0]
session["logged_in"] = True
session["user_id"] = user
session.permanent = True
return redirect("/home")
else:
error_verify = "Your mail isn't verified"
return render_template("login.html", error_verify=error_verify, form=CSRFForm())
else:
error = "Your username or password are incorrect!"
return render_template("login.html", error=error, form=CSRFForm())
except:
error = "Your username or password are incorrect!"
return render_template("login.html", error=error, form=CSRFForm())
@app.route("/manual_mail_verification", methods=["POST", "GET"])
def manual_mail_verification():
if request.method == "GET":
return render_template("manual_mail_verification.html", form=CSRFForm())
else:
user_mail = (request.form.get("user_mail").strip()).lower()
try:
mail_verify_db = db.session.execute(
text("SELECT user_id, user_mail_verify FROM users WHERE user_mail = :user_mail"), {"user_mail" : user_mail}
).fetchall()[0]
user_id = mail_verify_db[0]
mail_verify = mail_verify_db[1]
except:
error_not = "This mail isn't used on the webapp!"
return render_template("manual_mail_verification.html", error_not = error_not, form=CSRFForm())
if mail_verify == "verified":
error = "This Mail is already used and verified"
return render_template("login.html", error=error, form=CSRFForm())
else:
session["user_id"] = user_id
send_verification_mail_code(user_mail)
return render_template("mail_verify.html", form=CSRFForm())
@app.route("/forget_password",methods=["POST", "GET"])
def forget_password():
if request.method == "GET":
return render_template("forget_password.html", form=CSRFForm())
else:
user_mail = request.form.get("user_mail")
try:
db.session.execute(
text("SELECT user_mail FROM users WHERE user_mail = :user_mail"), {"user_mail" : user_mail}
).fetchall()[0]
temp_password = secrets.token_hex(4)
msg = Message('Reset Password', sender='[email protected]', recipients=[user_mail])
msg.body = f"Your temporary Password is: {temp_password}"
mail.send(msg)
hashed_password = generate_password_hash(temp_password)
db.session.execute(
text("UPDATE users SET user_password = :user_password WHERE user_mail = :user_mail"), {"user_password" :hashed_password, "user_mail": user_mail}
)
db.session.commit()
success="The Mail is sent check Your mail for your new password"
return render_template("login.html", success=success, form=CSRFForm())
except:
error = "This Email isn't saved"
return render_template("forget_password.html", error = error, form=CSRFForm())
@app.route("/logout", methods=["GET", "POST"])
def logout_route():
logout()
return redirect("/login_page")
@app.route("/home", methods=["GET"])
def home():
if not session.get("logged_in"):
return redirect("/login_page")
else:
try:
user_photo_path = select_user_photo()
except OperationalError:
error = "Welcome Back"
return render_template('error.html', error=error, form=CSRFForm())
user_id = session.get("user_id")
total_favorite_currency, favorite_currency = show_networth()
total_favorite_currency = f"{total_favorite_currency:,.2f}"
target_db = db.session.execute(
text("SELECT * FROM target WHERE user_id = :user_id"),
{"user_id": user_id}
).fetchall()
if target_db:
target_db = sorted(target_db, key=lambda x: (x[4], x[3]), reverse=True)
target = target_db[0][2]
mounth_db = int(target_db[0][3])
year_db = int(target_db[0][4])
now = datetime.datetime.now()
mounth = now.month
year = now.year
if mounth_db != mounth or year_db != year:
try:
last_target_id = db.session.execute(
text("SELECT MAX(target_id) FROM target")
).fetchone()[0]
target_id = last_target_id + 1
except:
target_id = 1
db.session.execute(
text("INSERT INTO target (target_id, user_id, target, mounth, year) VALUES (:target_id, :user_id, :target, :mounth, :year)"),
{"target_id":target_id, "user_id" :user_id, "target": target, "mounth" :mounth, "year" :year}
)
db.session.commit()
first_day_current_month = now.replace(day=1)
if now.month == 12:
first_day_next_month = now.replace(year=now.year + 1, month=1, day=1)
else:
first_day_next_month = now.replace(month=now.month + 1, day=1)
from_date = first_day_current_month.date()
to_date = first_day_next_month.date()
taregt_db_1 = db.session.execute(
text("SELECT target FROM target WHERE user_id = :user_id AND mounth = :mounth AND year = :year"),
{"user_id": user_id, "mounth": mounth, "year": year}
).fetchone()
if taregt_db_1:
target = taregt_db_1[0]
score_deposite = db.session.execute(
text("SELECT amount, currency FROM trans WHERE user_id = :user_id AND date BETWEEN :from_date AND :to_date AND trans_status = :trans_status"),
{"user_id": user_id, "from_date": from_date, "to_date": to_date, "trans_status": "deposit"}
).fetchall()
score_withdraw = db.session.execute(
text("SELECT amount, currency FROM trans WHERE user_id = :user_id AND date BETWEEN :from_date AND :to_date AND trans_status = :trans_status"),
{"user_id": user_id, "from_date": from_date, "to_date": to_date, "trans_status": "withdraw"}
).fetchall()
currency_totals_deposite = {}
for amount, currency in score_deposite:
amount = float(amount)
if currency in currency_totals_deposite:
currency_totals_deposite[currency] += amount
else:
currency_totals_deposite[currency] = amount
total_favorite_currency_deposite, favorite_currency_deposite = convert_to_fav_currency(currency_totals_deposite, user_id)
currency_totals_withdraw= {}
for amount, currency in score_withdraw:
amount = float(amount)
if currency in currency_totals_withdraw:
currency_totals_withdraw[currency] += amount
else:
currency_totals_withdraw[currency] = amount
total_favorite_currency_withdraw, favorite_currency_withdraw = convert_to_fav_currency(currency_totals_withdraw, user_id)
score = (total_favorite_currency_deposite - target) - total_favorite_currency_withdraw
if score > 0:
score_txt = "Above Target"
elif score < 0:
score_txt = "Below Target"
else:
score_txt = "On Target"
db.session.execute(
text("UPDATE target SET score = :score WHERE user_id = :user_id AND mounth = :mounth AND year = :year"),
{"user_id" :user_id, "score":score, "mounth" :mounth, "year" :year}
)
db.session.commit()
return render_template("home.html", total_favorite_currency = total_favorite_currency, favorite_currency=favorite_currency , user_photo_path=user_photo_path, score_txt=score_txt, score=score, target = target, form=CSRFForm())
else:
return render_template("home.html", total_favorite_currency = total_favorite_currency, favorite_currency=favorite_currency , user_photo_path=user_photo_path, form=CSRFForm())
@app.route("/deposit", methods=["POST", "GET"])
def deposit():
if not session.get("logged_in"):
return redirect("/login_page")
else:
try:
user_photo_path = select_user_photo()
except OperationalError:
error = "Welcome Back"
return render_template('error.html', error=error, form=CSRFForm())
total_favorite_currency, favorite_currency = show_networth()
total_favorite_currency = f"{total_favorite_currency:,.2f}"
if request.method == "GET":
return render_template("deposit.html", user_photo_path=user_photo_path, total_favorite_currency=total_favorite_currency, favorite_currency=favorite_currency, form=CSRFForm())
else:
date = request.form.get("date")
amount = float(request.form.get("amount"))
currency = request.form.get("currency")
user_id = session.get("user_id")
trans_details = request.form.get("trans_details")
if currency is None or amount is None :
error = "You have to choose the currency!"
return render_template("deposit.html", error = error,total_favorite_currency=total_favorite_currency, favorite_currency=favorite_currency, user_photo_path=user_photo_path, form=CSRFForm())
try:
last_trans_id = db.session.execute(
text("SELECT MAX(trans_id) FROM trans WHERE user_id = :user_id"),
{"user_id": user_id}
).fetchone()[0]
trans_id = last_trans_id + 1
except:
trans_id = 1
try:
last_trans_key = db.session.execute(
text("SELECT MAX(trans_key) FROM trans")
).fetchone()[0]
trans_key = last_trans_key + 1
except:
trans_key = 1
last_networth_id = db.session.execute(
text("SELECT MAX(networth_id) FROM networth")
).fetchone()[0]
if last_networth_id:
networth_id = last_networth_id + 1
else:
networth_id = 1
db.session.execute(
text("INSERT INTO trans (date, trans_key, amount, currency, user_id, trans_id, trans_status, trans_details) VALUES (:date, :trans_key, :amount, :currency, :user_id, :trans_id, :trans_status, :trans_details)"),
{"date": date,"trans_key":trans_key, "amount": amount, "currency": currency, "user_id": user_id, "trans_id": trans_id, "trans_status": "deposit", "trans_details": trans_details}
)
db.session.commit()
networth_db = db.session.execute(
text("SELECT networth_id, total FROM networth WHERE user_id = :user_id AND currency = :currency"),
{"user_id": user_id, "currency": currency}
).fetchone()
if networth_db:
networth_id = networth_db[0]
total = float(networth_db[1])
new_total = total + amount
db.session.execute(
text("UPDATE networth SET total = :total WHERE networth_id = :networth_id"),
{"total" :new_total, "networth_id": networth_id}
)
db.session.commit()
else:
db.session.execute(
text("INSERT INTO networth (networth_id, user_id , currency, total) VALUES (:networth_id, :user_id , :currency, :total)"),
{"networth_id": networth_id, "user_id": user_id, "currency": currency, "total": amount}
)
db.session.commit()
return redirect("/home")
@app.route("/withdraw", methods=["POST", "GET"])
def withdraw():
if not session.get("logged_in"):
return redirect("/login_page")
else:
try:
user_photo_path = select_user_photo()
except OperationalError:
error = "Welcome Back"
return render_template('error.html', error=error, form=CSRFForm())
total_favorite_currency, favorite_currency = show_networth()
total_favorite_currency = f"{total_favorite_currency:,.2f}"
if request.method == "GET":
user_id = session.get("user_id")
currency_all = select_currencies(user_id)
return render_template("withdraw.html", currency_all = currency_all, user_photo_path=user_photo_path, total_favorite_currency=total_favorite_currency, favorite_currency=favorite_currency, form=CSRFForm())
else:
date = request.form.get("date")
amount = float(request.form.get("amount"))
currency = request.form.get("currency")
user_id = session.get("user_id")
trans_details = request.form.get("trans_details")
trans_details_link = request.form.get("trans_details_link")
if currency == None or date == None or amount == None :
error = "You have to choose the currency!"
currency_all = select_currencies(user_id)
return render_template("withdraw.html", currency_all = currency_all, error = error, user_photo_path=user_photo_path, total_favorite_currency=total_favorite_currency, favorite_currency=favorite_currency, form=CSRFForm())
amount_of_currency = db.session.execute(
text("SELECT total FROM networth WHERE user_id = :user_id AND currency = :currency"),
{"user_id": user_id, "currency":currency}
).fetchone()[0]
if amount > amount_of_currency:
error = "This user doesn't have this amount of this currency"
currency_all = select_currencies(user_id)
return render_template("withdraw.html", currency_all = currency_all, error=error, user_photo_path=user_photo_path, total_favorite_currency=total_favorite_currency, favorite_currency=favorite_currency, form=CSRFForm())
try:
last_trans_id = db.session.execute(
text("SELECT MAX(trans_id) FROM trans WHERE user_id = :user_id"),
{"user_id": user_id}
).fetchone()[0]
trans_id = last_trans_id + 1
except:
trans_id = 1
last_trans_key = db.session.execute(
text("SELECT MAX(trans_key) FROM trans")
).fetchone()[0]
if last_trans_key: