-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
676 lines (518 loc) · 21.4 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
from flask import Flask, request, jsonify
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity
from flask_cors import CORS
from flask_pymongo import PyMongo
from flask_mail import Mail, Message
import bcrypt
import uuid
import random
import string
from datetime import datetime, timedelta
from bson import ObjectId
import logging
from google.oauth2 import id_token
from google.auth.transport import requests as google_requests
app = Flask(__name__)
# MongoDB configuration
app.config['MONGO_URI'] = 'mongodb+srv://jaypanchal:[email protected]/user?retryWrites=true&w=majority&appName=Cluster0'
mongo = PyMongo(app)
# JWT configuration
app.config['JWT_SECRET_KEY'] = 'e6580f87eb7fe5378219c529bfac2ff004b3f60864a2cc3c0bac8a7a40698092'
jwt = JWTManager(app)
# Flask-Mail configuration
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = '[email protected]'
app.config['MAIL_PASSWORD'] = 'xjzi akki ibaz dmam'
app.config['MAIL_DEFAULT_SENDER'] = 'Crud Operation''[email protected]'
mail = Mail(app)
CORS(app, resources={r"/*": {"origins": "https://main--webapplicationbyjay.netlify.app"}})
@app.route('/signup', methods=['POST'])
def signup():
data = request.get_json()
username = data.get('username')
password = data.get('password')
email = data.get('email')
mobile = data.get('mobile')
users = mongo.db.users
existing_user = users.find_one({'$or': [{'email': email}, {'mobile': mobile}]})
if existing_user:
return jsonify({"msg": "User with this email or mobile number already exists"}), 400
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
verification_token = str(uuid.uuid4())
user_data = {
'username': username,
'password': hashed_password,
'email': email,
'mobile': mobile,
'verified': False,
'verification_token': verification_token
}
users.insert_one(user_data)
print("User added to MongoDB, sending email...")
# Send verification email
verification_link = f'https://deploying-14hj.onrender.com/verify/{verification_token}'
msg = Message('Verify Your Email', recipients=[email])
msg.body = f"""Hello {username},
Thank you for registering with our service.
Please verify your email address by clicking the following link:
{verification_link}
For your reference, here are your registration details:
- **Username:** {username}
- **Password:** {password}
Please keep this information safe. If you did not register for this account, please ignore this email.
Best regards,
"""
mail.send(msg)
return jsonify({"msg": "User created successfully. Please check your email for verification."}), 201
@app.route('/verify/<token>', methods=['GET'])
def verify_email(token):
users = mongo.db.users
user = users.find_one({'verification_token': token})
if not user:
return jsonify({"msg": "Invalid or expired verification token"}), 400
users.update_one({'verification_token': token}, {'$set': {'verified': True, 'verification_token': None}})
return jsonify({"msg": "Email verified successfully. You can now log in."}), 200
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
username = data.get('username')
password = data.get('password')
users = mongo.db.users
user = users.find_one({'username': username})
if not user or not bcrypt.checkpw(password.encode('utf-8'), user['password']):
return jsonify({"msg": "Invalid username or password"}), 401
if not user['verified']:
return jsonify({"msg": "Please verify your email address. Check your inbox for the verification link."}), 403
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token), 200
@app.route('/google-login', methods=['POST'])
def google_login():
data = request.get_json()
token = data.get('token')
try:
idinfo = id_token.verify_oauth2_token(token, google_requests.Request(), app.config['188656099171-j2toqn6u865c05epp4aggd8fgvm1k0oe.apps.googleusercontent.com'])
google_user_id = idinfo['sub']
email = idinfo['email']
username = idinfo.get('name', email)
users = mongo.db.users
user = users.find_one({'email': email})
if not user:
# Create a new user if not exists
user_data = {
'username': username,
'email': email,
'verified': True # Assuming Google users are verified by default
}
users.insert_one(user_data)
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token), 201
# Existing user
if not user['verified']:
return jsonify({"msg": "Please verify your email address. Check your inbox for the verification link."}), 403
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token), 200
except ValueError as e:
return jsonify({"msg": "Invalid Google token"}), 400
@app.route('/forgot-password', methods=['POST'])
def forgot_password():
data = request.get_json()
email = data.get('email')
users = mongo.db.users
user = users.find_one({'email': email})
if not user:
return jsonify({"msg": "No user found with this email address"}), 404
# Generate a 6-digit OTP
otp = ''.join(random.choices(string.digits, k=6))
otp_expiry = datetime.datetime.now() + datetime.timedelta(minutes=10) # OTP valid for 10 minutes
users.update_one({'email': email}, {'$set': {'otp': otp, 'otp_expiry': otp_expiry}})
msg = Message('Your OTP Code', recipients=[email])
msg.body = f"""Hello,
Here is your OTP code for password reset:
{otp}
This OTP is valid for 10 minutes. If you did not request this, please ignore this email.
Best regards,
"""
mail.send(msg)
return jsonify({"msg": "OTP has been sent to your email."}), 200
@app.route('/reset-password', methods=['POST'])
def reset_password():
data = request.get_json()
email = data.get('email')
otp = data.get('otp')
new_password = data.get('password')
users = mongo.db.users
user = users.find_one({'email': email})
if not user:
return jsonify({"msg": "No user found with this email address"}), 404
# Check OTP validity
if user.get('otp') != otp or datetime.datetime.now() > user.get('otp_expiry'):
return jsonify({"msg": "Invalid or expired OTP"}), 400
# Hash the new password
hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt())
users.update_one({'email': email}, {'$set': {'password': hashed_password, 'otp': None, 'otp_expiry': None}})
return jsonify({"msg": "Password has been reset successfully. You can now log in with your new password."}), 200
@app.route('/protected', methods=['GET'])
@jwt_required()
def protected():
current_user = get_jwt_identity()
return jsonify(logged_in_as=current_user), 200
@app.route('/profile', methods=['GET'])
@jwt_required()
def get_profile():
current_user = get_jwt_identity()
users = mongo.db.users
user = users.find_one({'username': current_user}, {'_id': 0, 'password': 0, 'verification_token': 0})
if user:
return jsonify(user), 200
else:
return jsonify({"msg": "User not found"}), 404
@app.route('/profile', methods=['PUT'])
@jwt_required()
def update_profile():
current_user = get_jwt_identity()
data = request.get_json()
users = mongo.db.users
update_data = {
'username': data.get('username'),
'email': data.get('email'),
'mobile': data.get('mobile')
}
# Debugging print statements
print(f"Current User: {current_user}")
print(f"Update Data: {update_data}")
result = users.update_one({'username': current_user}, {'$set': update_data})
print(f"Update Result: {result.matched_count}, {result.modified_count}")
if result.modified_count == 1:
return jsonify({"msg": "Profile updated successfully"}), 200
else:
return jsonify({"msg": "Profile update failed"}), 400
@app.route('/transaction', methods=['POST'])
@jwt_required()
def add_transaction():
data = request.get_json()
username = get_jwt_identity()
if not all([data.get('type'), data.get('amount'), data.get('category'), data.get('date')]):
return jsonify({"msg": "Transaction type, amount, category, and date are required"}), 400
transaction = {
'username': username,
'type': data.get('type'),
'amount': data.get('amount'),
'category': data.get('category'),
'date': data.get('date'),
'receipt': data.get('receipt'),
'note': data.get('note')
}
mongo.db.transactions.insert_one(transaction)
return jsonify({"msg": "Transaction added successfully"}), 201
@app.route('/transaction/<transaction_id>', methods=['PUT'])
@jwt_required()
def update_transaction(transaction_id):
data = request.get_json()
username = get_jwt_identity()
try:
transaction_id = ObjectId(transaction_id)
except Exception as e:
return jsonify({"msg": "Invalid transaction ID"}), 400
if not all([data.get('type'), data.get('amount'), data.get('category'), data.get('date')]):
return jsonify({"msg": "Transaction type, amount, category, and date are required"}), 400
update_data = {
'type': data.get('type'),
'amount': data.get('amount'),
'category': data.get('category'),
'date': data.get('date'),
'receipt': data.get('receipt'),
'note': data.get('note')
}
result = mongo.db.transactions.update_one(
{'_id': transaction_id, 'username': username},
{'$set': update_data}
)
if result.matched_count == 1:
return jsonify({"msg": "Transaction updated successfully"}), 200
else:
return jsonify({"msg": "Transaction not found"}), 404
@app.route('/transaction/<transaction_id>', methods=['DELETE'])
@jwt_required()
def delete_transaction(transaction_id):
username = get_jwt_identity()
try:
transaction_id = ObjectId(transaction_id)
except Exception as e:
return jsonify({"msg": "Invalid transaction ID"}), 400
result = mongo.db.transactions.delete_one({'_id': transaction_id, 'username': username})
if result.deleted_count == 1:
return jsonify({"msg": "Transaction deleted successfully"}), 200
else:
return jsonify({"msg": "Transaction not found"}), 404
@app.route('/transactions', methods=['GET'])
@jwt_required()
def get_transactions():
username = get_jwt_identity()
transactions = mongo.db.transactions.find({'username': username})
return jsonify([{
'id': str(txn['_id']),
'type': txn.get('type'),
'amount': txn.get('amount'),
'category': txn.get('category'),
'date': txn.get('date'),
'receipt': txn.get('receipt'),
'note': txn.get('note')
} for txn in transactions]), 200
def is_on_budget(spent, budget_amount, tolerance=0.01):
return spent <= (budget_amount + tolerance)
def get_spending_by_category(username):
transactions = mongo.db.transactions.find({'username': username})
spending_by_category = {}
for txn in transactions:
category = txn.get('category')
amount = txn.get('amount', 0)
try:
amount = float(amount)
except ValueError:
amount = 0.0 # Ensure amount is a float
if category:
# Add to existing category or initialize if not present
if category in spending_by_category:
spending_by_category[category] += amount
else:
spending_by_category[category] = amount
return spending_by_category
# Create a budget
@app.route('/budget', methods=['POST'])
@jwt_required()
def create_budget():
data = request.get_json()
username = get_jwt_identity()
if not all([data.get('category'), data.get('amount'), data.get('frequency')]):
return jsonify({"msg": "Category, amount, and frequency are required"}), 400
budget = {
'username': username,
'category': data.get('category'),
'amount': data.get('amount'),
'frequency': data.get('frequency') # Monthly or Yearly
}
mongo.db.budgets.insert_one(budget)
return jsonify({"msg": "Budget created successfully"}), 201
# Update a budget
@app.route('/budget/<budget_id>', methods=['PUT'])
@jwt_required()
def update_budget(budget_id):
data = request.get_json()
username = get_jwt_identity()
try:
budget_id = ObjectId(budget_id)
except Exception as e:
return jsonify({"msg": "Invalid budget ID"}), 400
if not all([data.get('category'), data.get('amount'), data.get('frequency')]):
return jsonify({"msg": "Category, amount, and frequency are required"}), 400
update_data = {
'category': data.get('category'),
'amount': data.get('amount'),
'frequency': data.get('frequency')
}
result = mongo.db.budgets.update_one(
{'_id': budget_id, 'username': username},
{'$set': update_data}
)
if result.matched_count == 1:
return jsonify({"msg": "Budget updated successfully"}), 200
else:
return jsonify({"msg": "Budget not found"}), 404
@app.route('/budget/<budget_id>', methods=['DELETE'])
@jwt_required()
def delete_budget(budget_id):
username = get_jwt_identity()
try:
budget_id = ObjectId(budget_id)
except Exception as e:
return jsonify({"msg": "Invalid budget ID"}), 400
result = mongo.db.budgets.delete_one({'_id': budget_id, 'username': username})
if result.deleted_count == 1:
return jsonify({"msg": "Budget deleted successfully"}), 200
else:
return jsonify({"msg": "Budget not found"}), 404
@app.route('/budgets', methods=['GET'])
@jwt_required()
def get_budgets():
try:
username = get_jwt_identity()
# Fetch budgets for the authenticated user
budgets_cursor = mongo.db.budgets.find({'username': username})
# Convert cursor to a list of dictionaries, ensuring data is serializable
budgets_list = []
for budget in budgets_cursor:
budget_data = {
'id': str(budget['_id']), # Convert ObjectId to string
'category': budget.get('category', ''), # Default to empty string if not provided
'amount': float(budget.get('amount', '0')), # Convert amount to float, default to '0'
'frequency': budget.get('frequency', 'Monthly') # Default to 'Monthly' if not provided
}
budgets_list.append(budget_data)
return jsonify(budgets_list), 200
except Exception as e:
print(f"Error in get_budgets: {str(e)}") # Log detailed error
return jsonify({"error": "An error occurred while fetching budgets."}), 500
@app.route('/budgets/track', methods=['GET'])
@jwt_required()
def track_budget():
try:
username = get_jwt_identity()
# Get spending by category
spending_by_category = get_spending_by_category(username)
# Get budgets
budgets_cursor = mongo.db.budgets.find({'username': username})
budgets_list = []
for budget in budgets_cursor:
budget_data = {
'category': budget.get('category', ''),
'amount': float(budget.get('amount', '0')),
'frequency': budget.get('frequency', 'Monthly')
}
budgets_list.append(budget_data)
notifications = []
for budget in budgets_list:
category = budget['category']
budget_amount = budget['amount']
frequency = budget['frequency']
spent = spending_by_category.get(category, 0)
# Check if spending exceeds the budget
if spent > budget_amount:
notifications.append({
'category': category,
'budget_amount': budget_amount,
'spent': spent,
'message': f"You are out of budget for {category}.",
'percentage_spent': (spent / budget_amount) * 100,
'frequency': frequency
})
elif spent == 0:
notifications.append({
'category': category,
'budget_amount': budget_amount,
'spent': spent,
'message': f"You haven't spent anything in {category} yet.",
'percentage_spent': 0,
'frequency': frequency
})
else:
notifications.append({
'category': category,
'budget_amount': budget_amount,
'spent': spent,
'message': f"You are within the budget for {category}.",
'percentage_spent': (spent / budget_amount) * 100,
'frequency': frequency
})
return jsonify(notifications), 200
except Exception as e:
print(f"Error in track_budget: {str(e)}") # Log detailed error
return jsonify({"error": "An error occurred while tracking budgets."}), 500
@app.route('/dashboard', methods=['GET'])
@jwt_required()
def dashboard_overview():
username = get_jwt_identity()
# Get total income and expense
total_income = sum(
float(txn.get('amount', 0))
for txn in mongo.db.transactions.find({'username': username, 'type': 'income'})
)
total_expense = sum(
float(txn.get('amount', 0))
for txn in mongo.db.transactions.find({'username': username, 'type': 'expense'})
)
# Get budgets
budgets = mongo.db.budgets.find({'username': username})
# Convert budgets to JSON serializable format
budgets_list = [{
'id': str(budget['_id']), # Convert ObjectId to string
'category': budget.get('category'),
'amount': float(budget.get('amount', 0)), # Convert amount to float
'frequency': budget.get('frequency')
} for budget in budgets]
# Get income data over time
income_data = mongo.db.transactions.aggregate([
{'$match': {'username': username, 'type': 'income'}},
{'$group': {
'_id': '$date',
'amount': {'$sum': '$amount'}
}},
{'$sort': {'_id': 1}}
])
income_data_list = [{'date': str(item['_id']), 'amount': float(item['amount'])} for item in income_data]
# Get expense data over time
expense_data = mongo.db.transactions.aggregate([
{'$match': {'username': username, 'type': 'expense'}},
{'$group': {
'_id': '$date',
'amount': {'$sum': '$amount'}
}},
{'$sort': {'_id': 1}}
])
expense_data_list = [{'date': str(item['_id']), 'amount': float(item['amount'])} for item in expense_data]
# Prepare the response
response = {
'total_income': total_income,
'total_expense': total_expense,
'budgets': budgets_list,
'income_data': income_data_list,
'expense_data': expense_data_list
}
return jsonify(response), 200
def filter_transactions_by_period(username, period):
today = datetime.utcnow()
start_date = None
if period == 'weekly':
start_date = today - timedelta(days=today.weekday()) # Start of the current week (Monday)
elif period == 'monthly':
start_date = today.replace(day=1) # Start of the current month
elif period == 'yearly':
start_date = today - timedelta(days=365) # 365 days ago from today
if start_date:
# Debug information
print(f"Filtering transactions from: {start_date.isoformat()}")
# Convert start_date to string format for MongoDB
start_date_str = start_date.strftime('%Y-%m-%d')
transactions = mongo.db.transactions.find({
'username': username,
'date': {'$gte': start_date_str}
})
transactions_list = list(transactions)
print(f"Number of transactions fetched: {len(transactions_list)}")
# Debug information for each transaction
for txn in transactions_list:
print(txn)
return transactions_list
else:
return []
def aggregate_transactions(transactions):
total_income = 0
total_expenses = 0
for txn in transactions:
amount_str = txn.get('amount', '0')
try:
amount = float(amount_str)
except ValueError:
amount = 0
if txn.get('type') == 'income':
total_income += amount
elif txn.get('type') == 'expense':
total_expenses += amount
print(f"Total Income: {total_income}")
print(f"Total Expenses: {total_expenses}")
return total_income, total_expenses
@app.route('/report/<period>', methods=['GET'])
@jwt_required()
def generate_report(period):
username = get_jwt_identity()
if period not in ['weekly', 'monthly', 'yearly']:
return jsonify({"msg": "Invalid period. Choose 'weekly', 'monthly', or 'yearly'"}), 400
transactions = filter_transactions_by_period(username, period)
total_income, total_expenses = aggregate_transactions(transactions)
return jsonify({
'total_income': total_income,
'total_expenses': total_expenses
}), 200
if __name__ == '__main__':
app.run(port=5000, debug=True)