-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_improved.py
More file actions
453 lines (351 loc) · 14.2 KB
/
Copy pathapp_improved.py
File metadata and controls
453 lines (351 loc) · 14.2 KB
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
"""
Improved Flask Application with Bug Fixes and Optimizations
IMPROVEMENTS:
- Added input validation for quantities
- Made discount codes case-insensitive
- Used helper function instead of linear search
- Added email format validation
- Made email checking case-insensitive
- Added better error handling
- Removed redundant code
"""
from flask import Flask, render_template, request, redirect, url_for, flash, jsonify, session
from models_improved import Book, Cart, User, Order, PaymentGateway, EmailService
import uuid
import re
app = Flask(__name__)
app.secret_key = 'your_secret_key'
# Configuration for load testing
app.config['TESTING'] = True
app.config['WTF_CSRF_ENABLED'] = False # Disable CSRF for load testing
app.config['SECRET_KEY'] = 'load-testing-secret-key'
app.config['SESSION_COOKIE_SECURE'] = False
app.config['SESSION_COOKIE_HTTPONLY'] = False
# Global storage
users = {}
orders = {}
# Create demo user
demo_user = User("demo@bookstore.com", "demo123", "Demo User", "123 Demo Street, Demo City, DC 12345")
users["demo@bookstore.com"] = demo_user
# Cart instance
cart = Cart()
# Books list
BOOKS = [
Book("The Great Gatsby", "Fiction", 10.99, "/images/books/the_great_gatsby.jpg"),
Book("1984", "Dystopia", 8.99, "/images/books/1984.jpg"),
Book("I Ching", "Traditional", 18.99, "/images/books/I-Ching.jpg"),
Book("Moby Dick", "Adventure", 12.49, "/images/books/moby_dick.jpg")
]
def get_book_by_title(title):
"""Helper function to find a book by title"""
return next((book for book in BOOKS if book.title == title), None)
def get_current_user():
"""Helper function to get current logged-in user"""
if 'user_email' in session:
return users.get(session['user_email'])
return None
def is_valid_email(email):
"""
Validate email format
IMPROVEMENT: Added email validation
"""
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(pattern, email) is not None
def normalize_email(email):
"""
Normalize email to lowercase for consistent comparison
IMPROVEMENT: Prevents duplicate accounts with different cases
"""
return email.lower().strip()
def login_required(f):
"""Decorator to require login for certain routes"""
from functools import wraps
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user_email' not in session:
flash('Please log in to access this page.', 'error')
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function
@app.route('/')
def index():
current_user = get_current_user()
return render_template('index.html', books=BOOKS, cart=cart, current_user=current_user)
@app.route('/add-to-cart', methods=['POST'])
def add_to_cart():
"""
Add book to cart with improved validation
IMPROVEMENTS:
- Added try-except for quantity conversion
- Uses helper function instead of linear search
- Validates quantity is positive
"""
book_title = request.form.get('title')
# IMPROVED: Added error handling for quantity conversion
try:
quantity = int(request.form.get('quantity', 1))
except (ValueError, TypeError):
flash('Invalid quantity. Please enter a valid number.', 'error')
return redirect(url_for('index'))
# IMPROVED: Validate positive quantity
if quantity <= 0:
flash('Quantity must be greater than 0.', 'error')
return redirect(url_for('index'))
# IMPROVED: Validate quantity is reasonable (e.g., not more than 100)
if quantity > 100:
flash('Quantity cannot exceed 100 items.', 'error')
return redirect(url_for('index'))
# IMPROVED: Use helper function instead of manual loop
book = get_book_by_title(book_title)
if book:
try:
cart.add_book(book, quantity)
flash(f'Added {quantity} "{book.title}" to cart!', 'success')
except ValueError as e:
flash(str(e), 'error')
else:
flash('Book not found!', 'error')
return redirect(url_for('index'))
@app.route('/remove-from-cart', methods=['POST'])
def remove_from_cart():
book_title = request.form.get('title')
cart.remove_book(book_title)
flash(f'Removed "{book_title}" from cart!', 'success')
return redirect(url_for('view_cart'))
@app.route('/update-cart', methods=['POST'])
def update_cart():
"""
Update cart quantity with improved validation
IMPROVEMENTS:
- Added try-except for quantity conversion
- Better handling of zero/negative quantities
"""
book_title = request.form.get('title')
# IMPROVED: Added error handling
try:
quantity = int(request.form.get('quantity', 1))
except (ValueError, TypeError):
flash('Invalid quantity. Please enter a valid number.', 'error')
return redirect(url_for('view_cart'))
# IMPROVED: Validate quantity range
if quantity > 100:
flash('Quantity cannot exceed 100 items.', 'error')
return redirect(url_for('view_cart'))
cart.update_quantity(book_title, quantity)
if quantity <= 0:
flash(f'Removed "{book_title}" from cart!', 'success')
else:
flash(f'Updated "{book_title}" quantity to {quantity}!', 'success')
return redirect(url_for('view_cart'))
@app.route('/cart')
def view_cart():
current_user = get_current_user()
return render_template('cart.html', cart=cart, current_user=current_user)
@app.route('/clear-cart', methods=['POST'])
def clear_cart():
cart.clear()
flash('Cart cleared!', 'success')
return redirect(url_for('view_cart'))
@app.route('/checkout')
def checkout():
if cart.is_empty():
flash('Your cart is empty!', 'error')
return redirect(url_for('index'))
current_user = get_current_user()
total_price = cart.get_total_price()
return render_template('checkout.html', cart=cart, total_price=total_price, current_user=current_user)
@app.route('/process-checkout', methods=['POST'])
def process_checkout():
"""
Process checkout with improvements
IMPROVEMENTS:
- Case-insensitive discount codes
- Better validation
- Sanitized inputs
"""
if cart.is_empty():
flash('Your cart is empty!', 'error')
return redirect(url_for('index'))
# Get form data
shipping_info = {
'name': request.form.get('name', '').strip(),
'email': request.form.get('email', '').strip(),
'address': request.form.get('address', '').strip(),
'city': request.form.get('city', '').strip(),
'zip_code': request.form.get('zip_code', '').strip()
}
payment_info = {
'payment_method': request.form.get('payment_method'),
'card_number': request.form.get('card_number', '').replace(' ', '').replace('-', ''),
'expiry_date': request.form.get('expiry_date', '').strip(),
'cvv': request.form.get('cvv', '').strip()
}
discount_code = request.form.get('discount_code', '').strip()
# Validate required fields
required_fields = ['name', 'email', 'address', 'city', 'zip_code']
for field in required_fields:
if not shipping_info.get(field):
flash(f'Please fill in the {field.replace("_", " ")} field', 'error')
return redirect(url_for('checkout'))
# IMPROVED: Validate email format
if not is_valid_email(shipping_info['email']):
flash('Please enter a valid email address', 'error')
return redirect(url_for('checkout'))
# Validate payment info
if payment_info['payment_method'] == 'credit_card':
if not payment_info.get('card_number') or not payment_info.get('expiry_date') or not payment_info.get('cvv'):
flash('Please fill in all credit card details', 'error')
return redirect(url_for('checkout'))
# Calculate total with discount
total_amount = cart.get_total_price()
discount_applied = 0
# IMPROVED: Case-insensitive discount codes
discount_code_upper = discount_code.upper()
if discount_code_upper == 'SAVE10':
discount_applied = total_amount * 0.10
total_amount -= discount_applied
flash(f'Discount applied! You saved ${discount_applied:.2f}', 'success')
elif discount_code_upper == 'WELCOME20':
discount_applied = total_amount * 0.20
total_amount -= discount_applied
flash(f'Welcome discount applied! You saved ${discount_applied:.2f}', 'success')
elif discount_code:
flash('Invalid discount code', 'error')
# Process payment
payment_result = PaymentGateway.process_payment(payment_info)
if not payment_result['success']:
flash(payment_result['message'], 'error')
return redirect(url_for('checkout'))
# Create order
order_id = str(uuid.uuid4())[:8].upper()
order = Order(
order_id=order_id,
user_email=shipping_info['email'],
items=cart.get_items(),
shipping_info=shipping_info,
payment_info={
'method': payment_info['payment_method'],
'transaction_id': payment_result['transaction_id']
},
total_amount=total_amount
)
# Store order
orders[order_id] = order
# Add order to user if logged in
current_user = get_current_user()
if current_user:
current_user.add_order(order)
# Send confirmation email
EmailService.send_order_confirmation(shipping_info['email'], order)
# Clear cart
cart.clear()
# Store order in session
session['last_order_id'] = order_id
flash('Payment successful! Your order has been confirmed.', 'success')
return redirect(url_for('order_confirmation', order_id=order_id))
@app.route('/order-confirmation/<order_id>')
def order_confirmation(order_id):
"""Display order confirmation page"""
order = orders.get(order_id)
if not order:
flash('Order not found', 'error')
return redirect(url_for('index'))
current_user = get_current_user()
return render_template('order_confirmation.html', order=order, current_user=current_user)
@app.route('/register', methods=['GET', 'POST'])
def register():
"""
User registration with improvements
IMPROVEMENTS:
- Email format validation
- Case-insensitive email checking
- Better input sanitization
"""
if request.method == 'POST':
email = request.form.get('email', '').strip()
password = request.form.get('password', '').strip()
name = request.form.get('name', '').strip()
address = request.form.get('address', '').strip()
# Validate required fields
if not email or not password or not name:
flash('Please fill in all required fields', 'error')
return render_template('register.html')
# IMPROVED: Validate email format
if not is_valid_email(email):
flash('Please enter a valid email address', 'error')
return render_template('register.html')
# IMPROVED: Normalize email for case-insensitive checking
normalized_email = normalize_email(email)
# IMPROVED: Check for existing email case-insensitively
if any(normalize_email(user_email) == normalized_email for user_email in users.keys()):
flash('An account with this email already exists', 'error')
return render_template('register.html')
# IMPROVED: Validate password strength
if len(password) < 6:
flash('Password must be at least 6 characters long', 'error')
return render_template('register.html')
# Create new user with normalized email
user = User(normalized_email, password, name, address)
users[normalized_email] = user
# Log in the user
session['user_email'] = normalized_email
flash('Account created successfully! You are now logged in.', 'success')
return redirect(url_for('index'))
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
"""
User login with improvements
IMPROVEMENTS:
- Case-insensitive email lookup
"""
if request.method == 'POST':
email = request.form.get('email', '').strip()
password = request.form.get('password', '').strip()
# IMPROVED: Normalize email for case-insensitive lookup
normalized_email = normalize_email(email)
# IMPROVED: Find user by normalized email
user = None
for user_email, user_obj in users.items():
if normalize_email(user_email) == normalized_email:
user = user_obj
break
if user and user.password == password:
session['user_email'] = user.email
flash('Logged in successfully!', 'success')
return redirect(url_for('index'))
else:
flash('Invalid email or password', 'error')
return render_template('login.html')
@app.route('/logout')
def logout():
"""User logout"""
session.pop('user_email', None)
flash('Logged out successfully!', 'success')
return redirect(url_for('index'))
@app.route('/account')
@login_required
def account():
"""User account page"""
current_user = get_current_user()
return render_template('account.html', current_user=current_user)
@app.route('/update-profile', methods=['POST'])
@login_required
def update_profile():
"""Update user profile"""
current_user = get_current_user()
current_user.name = request.form.get('name', current_user.name).strip()
current_user.address = request.form.get('address', current_user.address).strip()
new_password = request.form.get('new_password', '').strip()
if new_password:
# IMPROVED: Validate password strength
if len(new_password) < 6:
flash('Password must be at least 6 characters long', 'error')
return redirect(url_for('account'))
current_user.password = new_password
flash('Password updated successfully!', 'success')
else:
flash('Profile updated successfully!', 'success')
return redirect(url_for('account'))
if __name__ == '__main__':
app.run(debug=True, port=8080, host='0.0.0.0')