-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
261 lines (212 loc) · 7.84 KB
/
main.py
File metadata and controls
261 lines (212 loc) · 7.84 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
import os
import sqlite3
import requests
from pymongo import MongoClient
from dotenv import load_dotenv
from flask import Flask, render_template, jsonify, abort, redirect, url_for, session, request, flash, request
from werkzeug.security import generate_password_hash, check_password_hash
from sqlite_db import init_db, log_event
from sqlite_db import get_recent_events
app = Flask(__name__)
load_dotenv()
init_db()
app.secret_key = os.getenv("FLASK_SECRET_KEY")
client = MongoClient(os.getenv("MONGODB_URI"))
db = client[os.getenv("MONGODB_DB", "minecraft_store")]
DB_PATH = os.getenv("SQLITE_DB_PATH", "app.db")
packs_collection = db["packs"]
users_collection = db["users"]
@app.route("/")
def home():
packs = list(packs_collection.find({}, {"_id": 0}))
return render_template("landing.html", packs=packs)
@app.route("/api/packs")
def api_packs():
packs = list(packs_collection.find({}, {"_id": 0}))
return jsonify(packs)
@app.route("/api/library")
def api_library():
user = get_current_user()
if not user:
return jsonify({"error": "unauthorized"}), 401
ids = user.get("library_ids", [])
packs = list(packs_collection.find(
{"id": {"$in": ids}},
{"_id": 0}
))
return jsonify(packs)
@app.route("/pack/<pack_id>")
def pack_detail(pack_id):
pack = packs_collection.find_one({"id": pack_id}, {"_id": 0})
log_event("pack_view", user_email=session.get("user_email"), pack_id=pack_id)
if not pack:
abort(404)
return render_template("pack_detail.html", pack=pack)
@app.route("/library/add/<pack_id>")
def add_to_library(pack_id):
user = get_current_user()
if not user:
return redirect(url_for("login"))
pack = packs_collection.find_one({"id": pack_id}, {"_id": 0})
if not pack:
abort(404)
users_collection.update_one(
{"email": user["email"]},
{"$addToSet": {"library_ids": pack_id}}
)
log_event("library_add", user_email=user["email"], pack_id=pack_id)
return redirect(url_for("library"))
@app.route("/library")
def library():
user = get_current_user()
if not user:
return redirect(url_for("login"))
user_library_ids = user.get("library_ids", [])
if not user_library_ids:
return render_template("library.html", packs=[])
packs = list(packs_collection.find({}, {"_id": 0}))
user_library_packs = []
for pack in packs:
pack_id = pack["id"]
if pack_id in user_library_ids:
user_library_packs.append(pack)
packs_by_id = {}
for pack in user_library_packs:
pack_id = pack["id"]
packs_by_id[pack_id] = pack
ordered_packs = []
for pack_id in user_library_ids:
if pack_id in packs_by_id:
ordered_packs.append(packs_by_id[pack_id])
return render_template("library.html", packs=ordered_packs)
@app.route('/library/remove/<pack_id>')
def remove_from_library(pack_id):
user = get_current_user()
if not user:
return redirect(url_for("login"))
users_collection.update_one(
{"email": user["email"]},
{"$pull": {"library_ids": pack_id}}
)
log_event("library_remove", user_email=user["email"], pack_id=pack_id)
return redirect(url_for("library"))
@app.route('/register', methods=['GET', 'POST'])
def register_user():
if request.method == "POST":
email = request.form.get("email", "").strip().lower()
password = request.form.get("password", "")
if not email or not password:
flash("Email and password are required.", "danger")
return redirect(url_for("register"))
existing_user = users_collection.find_one({"email": email})
if existing_user:
flash("That is email already exists. Please log in.", "warning")
return redirect(url_for("login"))
password_hash = generate_password_hash(password)
users_collection.insert_one({
"email": email,
"password_hash": password_hash,
"library_ids": []
})
session["user_email"] = email
flash("Account created! Thank you for registering.", "success")
return redirect(url_for("home"))
return render_template("register.html")
@app.route('/login', methods=["GET", "POST"])
def login():
if request.method == "POST":
email = request.form.get("email", "")
password = request.form.get("password", "")
user = users_collection.find_one({"email": email})
if not user or not check_password_hash(user["password_hash"], password):
flash("Invalid email or password. Please try again", "danger")
return redirect(url_for("login"))
session["user_email"] = email
log_event("login", user_email=email)
flash("Logged in successfully.", "success")
return redirect(url_for("home"))
return render_template("login.html")
@app.route("/logout")
def logout():
email = session.get("user_email")
session.pop("user_email", None)
log_event("logout", user_email=email)
flash("Logged out.", "info")
return redirect(url_for("home"))
def get_current_user():
email = session.get("user_email")
if not email:
return None
return users_collection.find_one({"email": email}, {"_id": 0})
@app.context_processor
def add_user():
return {"current_user_email": session.get("user_email")}
@app.route("/admin/logs")
def admin_log():
if not session.get("user_email"):
return redirect(url_for("login"))
db_connection = sqlite3.connect(DB_PATH)
db_connection.row_factory = sqlite3.Row
rows = db_connection.execute(
"""
SELECT ts_utc, user_email, action, pack_id, meta
FROM event_log
ORDER BY id DESC
LIMIT 100
"""
).fetchall()
db_connection.close()
return render_template("admin_logs.html", logs=rows)
@app.route("/library/checkout/<pack_id>")
def library_checkout(pack_id):
user = get_current_user()
if not user:
return redirect(url_for("login"))
user_library_ids = user.get("library_ids", [])
if pack_id not in user_library_ids:
flash("That pack isn’t in your library.", "warning")
return redirect(url_for("library"))
pack = packs_collection.find_one({"id": pack_id}, {"_id": 0})
if not pack:
abort(404)
return render_template("checkout.html", pack=pack)
@app.route("/library/checkout/<pack_id>/confirm", methods=["POST"])
def library_checkout_confirm(pack_id):
user = get_current_user()
if not user:
return redirect(url_for("login"))
user_library_ids = user.get("library_ids", [])
if pack_id not in user_library_ids:
flash("That pack isn’t in your library.", "warning")
return redirect(url_for("library"))
pack = packs_collection.find_one({"id": pack_id}, {"_id": 0})
if not pack:
abort(404)
users_collection.update_one(
{"email": user["email"]},
{"$pull": {"library_ids": pack_id}}
)
log_event("purchase_simulated", user_email=user["email"], pack_id=pack_id)
send_confirmation_email(user["email"], pack)
flash(f"Checkout completed: {pack['name']}", "success")
return redirect(url_for("library"))
def send_confirmation_email(to_email: str, pack: dict):
url = os.getenv("EMAIL_FUNCTION_URL")
if not url:
return
payload = {
"to_email": to_email,
"subject": f"Confirmation: {pack['name']}",
"content": f"""
<h2>Purchase confirmed (simulated)</h2>
<p>You checked out <b>{pack['name']}</b>.</p>
<p>Pack ID: {pack.get('id','')}</p>
<p style="color:#666;">Coursework demo: no real payment taken.</p>
"""
}
try:
requests.post(url, json=payload, timeout=5)
except Exception as error:
print("Email failed:", error)
if __name__ == "__main__":
app.run(debug=True)