generated from Code-Institute-Org/gitpod-full-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
360 lines (271 loc) · 10.7 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
import os
from flask import (
Flask, render_template, request, flash,
redirect, session, url_for)
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
from werkzeug.security import generate_password_hash, check_password_hash
if os.path.exists("env.py"):
import env
app = Flask(__name__)
app.config["MONGO_DBNAME"] = os.environ.get("MONGO_DBNAME")
app.config["MONGO_URI"] = os.environ.get("MONGO_URI")
app.secret_key = os.environ.get("SECRET_KEY")
mongo = PyMongo(app)
# View characters.html
@app.route("/characters")
def characters():
roles = mongo.db.roles.find().sort("character_role")
characters = list(mongo.db.characters.find().sort("_id", -1))
return render_template(
"characters.html", roles=roles, characters=characters)
# Search characters on characters.html
@app.route("/search")
def search():
query = request.args.get("query")
characters = list(mongo.db.characters.find({"$text": {"$search": query}}))
return render_template("characters.html", characters=characters)
# Create a character on create_character.html
@app.route("/create_character", methods=["GET", "POST"])
def create_character():
"""
1. Check if user exists, then render create_character.html.
2. Match user enteries on a form to db key's (See 'characters' variable).
3. Update db roles and characters collections.
"""
if session and session["user"]:
if request.method == "POST":
characters = {
"character_role": request.form.get("character_role"),
"character_name": request.form.get("character_name"),
"character_description": request.form.get(
"character_description"),
"character_bio": request.form.get("character_bio"),
"character_skills": request.form.get("character_skills"),
"created_by": session["user"]
}
mongo.db.characters.insert_one(characters)
flash("Character created.")
return redirect(url_for("characters"))
roles = mongo.db.roles.find().sort("character_role")
if session["user"]:
return render_template("create_character.html",
roles=roles)
else:
return redirect(url_for("index"))
# Edit a character on edit_character.html
@app.route("/edit_character/<characters_id>", methods=["GET", "POST"])
def edit_character(characters_id):
"""
1. Check if user exists, then render edit_character.html.
2. Match user enteries on a form to db key's (See 'edit' variable).
3. Update db roles and characters collections.
"""
if session and session["user"]:
if request.method == "POST":
edit = {
"character_role": request.form.get("character_role"),
"character_name": request.form.get("character_name"),
"character_description": request.form.get(
"character_description"),
"character_bio": request.form.get("character_bio"),
"character_skills": request.form.get("character_skills"),
"created_by": session["user"]
}
mongo.db.characters.update({"_id": ObjectId(characters_id)}, edit)
flash("Character edited.")
return redirect(url_for("characters"))
characters = mongo.db.characters.find_one(
{"_id": ObjectId(characters_id)})
username = session["user"]
roles = mongo.db.roles.find().sort("character_role")
return render_template("edit_character.html", roles=roles,
username=username, characters=characters)
else:
return redirect(url_for("index"))
# Delete a character on characters.html
@app.route("/delete_character/<characters_id>")
def delete_character(characters_id):
"""
1. Check if user exists.
2. Delete intended character using selection's ID from db.
"""
if session and session["user"]:
mongo.db.characters.remove({"_id": ObjectId(characters_id)})
flash("Character deleted")
return redirect(url_for("characters"))
else:
return redirect(url_for("index"))
# View character roles on roles.html
@app.route("/roles")
def roles():
"""
1. Check if user is Admin.
(Roles are only available to Admin.)
2. List Roles in alphabetical order.
"""
if session and session["user"] == "admin":
roles = list(mongo.db.roles.find().sort("character_role"))
return render_template("roles.html", roles=roles)
else:
return redirect(url_for("index"))
# Delete a character role on edit_role.html
@app.route("/delete_role/<role_id>")
def delete_role(role_id):
"""
1. Check if user is Admin.
(Role deletions are only available to Admin.)
2. Get ID of role to be deleted.
3. Remove ID of role from DB.
"""
if session and session["user"] == "admin":
mongo.db.roles.remove({"_id": ObjectId(role_id)})
flash("Role deleted")
return redirect(url_for("roles"))
else:
return redirect(url_for("index"))
# Edit a character role on edit_role.html
@app.route("/edit_role/<role_id>", methods=["GET", "POST"])
def edit_role(role_id):
"""
1. Check if user is Admin.
(Role edits are only available to Admin.)
2. Get ID of role to be edited, and render edit_role.html
3. Check if new role already exists in DB. If yes, Flash and redirect.
4. Update db using the role id and the 'character's role' key.
"""
if session and session["user"] == "admin":
if request.method == "POST":
existing_role = mongo.db.roles.find_one(
{"character_role": request.form.get("character_role").lower()})
if existing_role:
flash("Role already exists")
return redirect(url_for("add_role"))
submit = {
"character_role": request.form.get("character_role")
}
mongo.db.roles.update({"_id": ObjectId(role_id)}, submit)
flash("Role Updated!")
return redirect(url_for("roles"))
role = mongo.db.roles.find_one({"_id": ObjectId(role_id)})
return render_template("edit_role.html", role=role)
else:
return redirect(url_for("index"))
# Add a character role on add_role.html
@app.route("/add_role", methods=["GET", "POST"])
def add_role():
"""
1. Check if user is Admin.
(Role additions are only available to Admin.)
2. Check if new role already exists in DB. If yes, Flash and redirect.
3. If new role is unique insert it into the roles collection in db.
"""
if session and session["user"] == "admin":
if request.method == "POST":
existing_role = mongo.db.roles.find_one(
{"character_role": request.form.get("character_role").lower()})
if existing_role:
flash("Role already exists")
return redirect(url_for("add_role"))
role = {
"character_role": request.form.get("character_role").lower()
}
mongo.db.roles.insert_one(role)
flash("New Role created")
return redirect(url_for("roles"))
return render_template("add_role.html")
else:
return redirect(url_for("index"))
# LOGIN
@app.route("/login", methods=["GET", "POST"])
def login():
"""
1. Check user entry against db to verify username and password.
2. Return identical messages whether username or password are incorrect
in case of brute force attack, and return to login.html.
3. On success welcome user and render profile page.
"""
if request.method == "POST":
existing_user = mongo.db.users.find_one(
{"username": request.form.get("username").lower()})
if existing_user:
# check username
if check_password_hash(
existing_user["password"], request.form.get("password")):
session["user"] = request.form.get("username").lower()
flash("Welcome, {}".format(
request.form.get("username").capitalize()))
return redirect(url_for(
"profile"))
else:
# Wrong Passowrd
flash("Incorrect Username and/or Password")
return redirect(url_for("login"))
else:
# Wrong Username
flash("Incorrect Username and/or Password")
return redirect(url_for("login"))
return render_template("login.html")
# REGISTER
@app.route("/register", methods=["GET", "POST"])
def register():
"""
1. Check existing usernames in db against user entry.
2. Store unique usernames in db, and hash passwords.
3. Assign successful username entry to session cookie,
which is needed to render profile.html.
"""
if request.method == "POST":
existing_user = mongo.db.users.find_one(
{"username": request.form.get("username").lower()})
if existing_user:
flash("Username already exists")
return redirect(url_for("register"))
register = {
"username": request.form.get("username").lower(),
"password": generate_password_hash(request.form.get("password"))
}
mongo.db.users.insert_one(register)
session["user"] = request.form.get("username").lower()
flash("Registration Successful")
return redirect(url_for("profile", username=session["user"]))
return render_template("register.html")
# LOG OUT
@app.route("/logout")
def logout():
flash("You've been logged out.")
session.pop("user")
return redirect(url_for("login"))
# INDEX
@app.route("/")
def index():
return render_template("index.html")
# CONTACT
@app.route("/contact")
def contact():
return render_template("contact.html")
# PROFILE
@app.route("/profile", methods=["GET", "POST"])
def profile():
"""
1. Check if user exists before rendering profile page.
2. The character list is arranged in order of most recently added.
3. The username is also used on profile.html greeting.
"""
if session and session["user"]:
characters = list(mongo.db.characters.find().sort("_id", -1))
username = session["user"]
return render_template(
"profile.html", username=username, characters=characters)
else:
return redirect(url_for("index"))
# ERROR HANDLER
@app.errorhandler(404)
def page_not_found(e):
""" Returns a 404.html on 404 errors """
return render_template('404.html'), 404
if __name__ == "__main__":
app.run(
host=os.environ.get("IP"),
port=int(os.environ.get("PORT")),
debug=False)