-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes.py
154 lines (128 loc) · 6.25 KB
/
routes.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
from flask import render_template, request, redirect, url_for, session, flash
from db import get_db, hash_password
def configure_routes(app):
@app.teardown_appcontext
def teardown_db(exception):
get_db().close()
@app.route('/')
def home():
if 'username' in session:
username = session['username']
return render_template('home.html', username=username)
return render_template('home.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
hashed_password = hash_password(password) # Hash the password before checking
db = get_db()
# Intentionally vulnerable to SQL Injection in the username field
query = f"SELECT * FROM users WHERE username = '{username}' AND password = '{hashed_password}'"
print(f"Executing SQL Query: {query}") # Debug the SQL query being executed
result = db.execute(query).fetchone()
if result:
session['username'] = result[1] # Log in as the specific user returned by the query
session.pop('cart', None) # Clear the cart on new login
return redirect(url_for('home'))
else:
return render_template('error.html', message="Invalid credentials! Use SQL Injection payload in the username field.")
return render_template('login.html')
@app.route('/logout')
def logout():
session.pop('username', None)
session.pop('cart', None) # Clear the cart on logout
return redirect(url_for('home'))
@app.route('/search-user', methods=['GET', 'POST'])
def search_user():
if 'username' not in session:
flash("You need to be logged in to search for users.")
return redirect(url_for('login'))
db = get_db()
# Handle user actions
if request.method == 'POST':
if 'add_user' in request.form:
# Add new user
new_username = request.form['new_username']
new_password = request.form['new_password']
existing_user = db.execute("SELECT * FROM users WHERE username = ?", (new_username,)).fetchone()
if existing_user:
flash("User already exists!")
else:
hashed_password = hash_password(new_password)
db.execute("INSERT INTO users (username, password) VALUES (?, ?)", (new_username, hashed_password))
db.commit()
flash("User added successfully!")
elif 'delete_user' in request.form:
# Delete user
user_id = request.form.get('user_id_to_delete')
admin_user = db.execute("SELECT * FROM users WHERE id = ? AND username = 'admin'", (user_id,)).fetchone()
if admin_user:
flash("Cannot delete the admin user!")
else:
db.execute("DELETE FROM users WHERE id = ?", (user_id,))
db.commit()
flash("User deleted successfully!")
else:
# Search user by ID
user_id = request.form.get('user_id')
try:
query = f"SELECT * FROM users WHERE id = {user_id}"
print(f"Executing SQL Query: {query}")
result = db.execute(query).fetchall()
if result:
user_data = result
return render_template('search_user.html', user_data=user_data)
else:
flash("No user found with that ID!")
except Exception as e:
flash(f"An error occurred: {str(e)}")
return render_template('search_user.html')
@app.route('/products')
def products():
db = get_db()
products_list = db.execute("SELECT * FROM products").fetchall()
return render_template('products.html', products=products_list)
@app.route('/add-to-cart/<int:product_id>')
def add_to_cart(product_id):
db = get_db()
product = db.execute("SELECT * FROM products WHERE id = ?", (product_id,)).fetchone()
if not product:
flash('Product not found!')
return redirect(url_for('products'))
# Initialize cart if not present
if 'cart' not in session:
session['cart'] = []
# Convert the product tuple to a dictionary for easier access in the cart
session['cart'].append({'id': product[0], 'name': product[1], 'price': product[2]})
flash(f"{product[1]} added to cart!")
return redirect(url_for('products'))
@app.route('/cart')
def view_cart():
cart = session.get('cart', [])
total = sum(item['price'] for item in cart)
return render_template('cart.html', cart=cart, total=total)
@app.route('/checkout', methods=['POST'])
def checkout():
cart = session.get('cart', [])
total = request.form.get('total') # Vulnerable to parameter tampering
# Check if the cart is empty before proceeding to checkout
if not cart:
flash("Your cart is empty. Please add items to your cart before checking out.")
return redirect(url_for('products'))
# Save order summary for display on the success page
session['order_summary'] = cart
session['order_total'] = total
# Clear the cart after checkout
session.pop('cart', None)
# Redirect to the success page
return redirect(url_for('checkout_success'))
@app.route('/checkout-success')
def checkout_success():
order_summary = session.get('order_summary', [])
order_total = session.get('order_total', 0)
# Check if the order summary exists to prevent direct access to this page without completing checkout
if not order_summary:
flash("No order summary found. Please complete a checkout process.")
return redirect(url_for('products'))
return render_template('checkout_success.html', order_summary=order_summary, order_total=order_total)