-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
663 lines (570 loc) · 23.5 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
import os
import cloudinary.api
import cloudinary
import cloudinary.uploader
from flask import (
Flask, flash, render_template,
redirect, request, session, url_for)
from flask_pymongo import PyMongo
from flask_mail import Mail, Message
from flask_paginate import Pagination
from flask_cors import CORS
from flask_sslify import SSLify
from dotenv import load_dotenv
from bson.objectid import ObjectId
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime
if os.path.exists("env.py"):
import env
load_dotenv()
# Create instance of Flask
app = Flask(__name__)
sslify = SSLify(app)
# Enable CORS to make requests
CORS(app)
# -- MongoDB Settings -- #
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")
# -- Admin User --- #
ADMIN = 'admin'
# -- Cloudinary Settings -- #
cloudinary.config(
cloud_name=os.getenv('CLOUD_NAME'),
api_key=os.getenv('API_KEY'),
api_secret=os.getenv('API_SECRET'))
# Code Credit: https://slack-files.com/T0L30B202-F01KX8QUEJF-6a89867a18
# -- Flask Mail Settings -- #
mail_settings = {
"MAIL_SERVER": os.environ.get('MAIL_SERVER'),
"MAIL_PORT": os.environ.get('MAIL_PORT'),
"MAIL_USE_TLS": False,
"MAIL_USE_SSL": os.environ.get('MAIL_USE_SSL'),
"MAIL_USERNAME": os.environ.get('MAIL_USERNAME'),
"MAIL_PASSWORD": os.environ.get('MAIL_PASSWORD'),
"SECURITY_EMAIL_SENDER": os.environ.get("SECURITY_EMAIL_SENDER")
}
# -- Update application settings
app.config.update(mail_settings)
# -- Create instance of Flask Mail
mail = Mail(app)
# -- Create instance of PyMongo
mongo = PyMongo(app)
# Code Credit:
# https://gist.github.com/mozillazg/69fb40067ae6d80386e10e105e6803c9
# Code Credit: https://pythonhosted.org/Flask-paginate/
# -- Set Pagination for posts per page -- #
POSTS_PER_PAGE = 5
# -- Paginate Posts -- #
def paginate_posts(posts, per_page):
page = int(request.args.get('page', 1))
offset = (page - 1) * per_page
return posts[offset: offset + per_page]
# -- Paginate Search Results -- #
def paginate_search(posts, per_page):
page = int(request.args.get('page', 1))
offset = (page - 1) * per_page
return posts[offset: offset + per_page]
def paginate_args(posts, per_page):
page = int(request.args.get('page', 1))
total = len(posts)
return Pagination(page=page, per_page=per_page, total=total)
# -- Homepage --- #
@app.route("/")
@app.route("/homepage")
def homepage():
"""
Gets all post data from the database, and renders
into Homepage template. Using the pagination only
5 posts are shown per page.
"""
posts = list(mongo.db.posts.find().sort("post_date", -1))
pagination_posts = paginate_posts(posts, POSTS_PER_PAGE)
pagination = paginate_args(posts, POSTS_PER_PAGE)
page_num = request.args.get('page', 1, type=int)
return render_template("index.html", posts=pagination_posts,
pagination=pagination, page_num=page_num)
# -- Blog Post -- #
@app.route("/blog_post/<post_id>", methods=["GET"])
def blog_post(post_id):
"""
Gets blog post content from its unique Id,
and renders all its data into Blog Post template.
"""
post = mongo.db.posts.find_one({"_id": ObjectId(post_id)})
return render_template("blog_post.html", post=post)
# -- Search Posts --- #
@app.route("/search", methods=["GET", "POST"])
def search():
"""
Search function, searches the query and presents the data
into the template with Pagination. Users are able to search
for all categories, posts by user, and all the posts.
"""
query = request.form.get("query")
posts = list(mongo.db.posts.find({"$text": {"$search": query}}))
total = len(posts)
pagination_posts = paginate_posts(posts, POSTS_PER_PAGE)
pagination = paginate_args(posts, POSTS_PER_PAGE)
return render_template("index.html", posts=pagination_posts,
pagination=pagination, total=total)
# -- User Register --- #
@app.route("/register", methods=["GET", "POST"])
def register():
"""
Searches the database if user already exists,
if not user is added into the dictionary and
redirected to their own profile page.
"""
if request.method == "POST":
# Check if username already exists in db
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"))
password = request.form.get("password")
confirm_password = request.form.get("confirm_password")
if password == confirm_password:
register = {
"name": request.form.get("name").lower(),
"last_name": request.form.get("last_name").lower(),
"email": request.form.get("email").lower(),
"username": request.form.get("username").lower(),
"password": generate_password_hash(request.form.get(
"password")),
"registered": datetime.today().strftime("%d %b, %Y")
}
mongo.db.users.insert_one(register)
# Put the new user into 'session' cookie
session["user"] = request.form.get("username").lower()
flash("Registration Successful!")
# Redirect user to their Profile page
return redirect(url_for("profile", username=session["user"]))
else:
flash("Passwords do not match!", "error")
return redirect(url_for("register"))
return render_template("register.html")
# -- User Login --- #
@app.route("/login", methods=["GET", "POST"])
def login():
"""
Login function, checks if user exits in the database,
and checks if the password mathces the user input. If not,
user is redirected to the login page. If user doesnt exit
a flash message is shown. and user gets redirected.
"""
if request.method == "POST":
# Check if username exists in db
existing_user = mongo.db.users.find_one(
{"username": request.form.get("username").lower()})
if existing_user:
# Ensure hashed password matches user input
if check_password_hash(
existing_user["password"], request.form.get("password")):
session["user"] = request.form.get("username").lower()
flash("Welcome Back, {}".format(
request.form.get("username")))
return redirect(url_for(
"profile", username=session["user"]))
else:
# Invalid password match
flash("Incorrect Username and/or Password")
return redirect(url_for("login"))
else:
# Username doesn't exist
flash("Username doesn't exist!")
return redirect(url_for("login"))
return render_template("login.html")
# -- User Profile --- #
@app.route("/profile/<username>", methods=["GET", "POST"])
def profile(username):
"""
User profile, checks if user is in session, if they are,
user's username is requested from database, and profile
page with user's posts are rendered.
"""
# Check if user is in session
if session.get('user') is None:
flash('Please sign in to see your Profile')
return redirect(url_for("login"))
else:
if session["user"] == username:
# Grab the session user's username from db
username = mongo.db.users.find_one({
"username": session["user"]})["username"]
# Get all the posts by current users
posts = list(mongo.db.posts.find(
{"author": session["user"]}).sort("post_date", 1))
else:
flash('You cant see other users Profile')
return redirect(url_for("homepage"))
# Render user profile page with all their current posts
return render_template("profile.html", username=username, posts=posts)
# -- Delete Account --- #
@app.route("/delete_account/<username>")
def delete_account(username):
"""
Delete Account, checks if user is in session,
if they are, then user is removed from the database,
and session cookies are removed.
"""
# Check if user is in session
if session.get('user') is None:
flash("You need to sign in to delete your account")
return redirect(url_for("login"))
else:
# Check if username matches the session user
if session["user"] == username:
mongo.db.users.remove({"username": username})
flash("User Successfully Deleted")
session.pop("user")
return redirect(url_for("homepage"))
else:
# If session user doesnt match current user, restrict deletion
flash("You can't delete other users accounts!")
return redirect(url_for("homepage"))
# -- User Logout --- #
@app.route("/logout")
def logout():
"""
Logout, removes user from session cookies,
and redirects them to the homepage.
"""
# Remove user from session cookie
flash("You have been logged out")
session.pop("user")
return redirect(url_for("homepage"))
# -- Add Post --- #
@app.route("/add_post", methods=["GET", "POST"])
def add_post():
"""
Add post, checks if user is in session before posting,
if they are, checks if the current post title already exists
in the database, if not then post is added into the database,
image file is uploaded to cloudinary, and user is informed with a
flash message.
"""
# Check if user in session
if session.get('user') is None:
flash("Please sign in to post")
return redirect(url_for("login"))
else:
if request.method == "POST":
# Check if post already exists in db
existing_post = mongo.db.posts.find_one({
"post_title": request.form.get("post_title")})
app.logger.info('in upload route')
cloudinary.config(
cloud_name=os.getenv('CLOUD_NAME'),
api_key=os.getenv('API_KEY'),
api_secret=os.getenv('API_SECRET'))
upload_result = None
file_to_upload = request.files['post_image']
app.logger.info('%s file_to_upload', file_to_upload)
# Upload image to Cloudinary
if file_to_upload:
upload_result = cloudinary.uploader.upload(file_to_upload)
app.logger.info(upload_result)
post = {
"post_title": request.form.get("post_title"),
"post_category": request.form.get("post_category"),
"post_content": request.form.get("post_content"),
"post_image": upload_result["url"],
"post_address": request.form.get("post_address"),
"website": request.form.get("website"),
"post_date": datetime.today().strftime('%d/%m/%Y'),
"author": session["user"]
}
if existing_post:
flash("Post already exists!")
return redirect(url_for("add_post"))
mongo.db.posts.insert_one(post)
flash("You've successfully posted!")
return redirect(url_for("homepage"))
categories = mongo.db.categories.find().sort("post_category", 1)
return render_template("add_post.html", categories=categories)
# -- Edit Post --- #
@app.route("/edit_post/<post_id>", methods=["GET", "POST"])
def edit_post(post_id):
"""
Edit post, checks if user is in session, if they are, checks if
session user is the post author, or Admin user, then gets all the
current post data from the databse, and updates the post data.
"""
# Check if user in session
if session.get('user') is None:
flash("Please sign in to edit this post")
return redirect(url_for("login"))
else:
post = mongo.db.posts.find_one({"_id": ObjectId(post_id)})
author = post["author"]
# Check if the session user is the post author or Admin
if session.get('user') == author or session.get('user') == ADMIN:
if request.method == "POST":
app.logger.info('in upload route')
cloudinary.config(
cloud_name=os.getenv('CLOUD_NAME'),
api_key=os.getenv('API_KEY'),
api_secret=os.getenv('API_SECRET'))
upload_result = None
file_to_upload = request.files['post_image']
app.logger.info('%s file_to_upload', file_to_upload)
# Upload image to Cloudinary
if file_to_upload:
upload_result = cloudinary.uploader.upload(file_to_upload)
app.logger.info(upload_result)
submit = {
"post_title": request.form.get("post_title"),
"post_category": request.form.get("post_category"),
"post_content": request.form.get("post_content"),
"post_image": upload_result["url"],
"post_address": request.form.get("post_address"),
"website": request.form.get("website"),
"post_date": datetime.today().strftime('%d/%m/%Y'),
"author": session["user"]
}
mongo.db.posts.update({"_id": ObjectId(post_id)}, submit)
flash("Post Successfully Updated")
return redirect(url_for("homepage"))
post = mongo.db.posts.find_one({"_id": ObjectId(post_id)})
categories = mongo.db.categories.find().sort("post_category", 1)
return render_template("edit_post.html", post=post,
categories=categories)
else:
flash('You cant edit other users Posts!')
return redirect(url_for("homepage"))
# -- Delete Post --- #
@app.route("/delete_post/<post_id>")
def delete_post(post_id):
"""
Delete post, checks if user is in session, then checks
if user is the author of that specific post, or Admin user.
if they are, post data is removed from the database, and a
confirmation message is shown to the author.
"""
# Check if user is in session
if session.get('user') is None:
flash('Please sign in to delete your post')
return redirect(url_for("login"))
else:
post = mongo.db.posts.find_one({"_id": ObjectId(post_id)})
author = post["author"]
# Check if the session user is the post author or Admin
if session.get('user') == author or session.get('user') == ADMIN:
mongo.db.posts.remove({"_id": ObjectId(post_id)})
flash("Post Successfully Deleted")
return redirect(url_for("homepage"))
else:
flash("You cant delete other users Posts!")
return redirect(url_for("homepage"))
# -- Add Category --- #
@app.route("/add_category", methods=["GET", "POST"])
def add_category():
"""
Add category, stricted for Admin use only. Checks if
the user is in session, and has Admin credentials.
If the user has Admin credentials, checks if the current
category already exits, if not,category is added into the
database.
"""
# Check if user is in session
if session.get('user') is None:
flash('Please sign in as Admin User to perform this action')
return redirect(url_for("login"))
else:
# Check if session user is Admin
if session['user'] == ADMIN:
if request.method == "POST":
# Check if category already exists in db
existing_category = mongo.db.categories.find_one({
"post_category": request.form.get("post_category")})
category = {
"post_category": request.form.get("post_category")}
if existing_category:
flash("Category already exists")
return render_template("add_category.html")
else:
mongo.db.categories.insert_one(category)
flash("New Category Added")
return redirect(url_for("dashboard"))
return render_template("add_category.html")
else:
flash('You are not authorized to perform this operation!')
return redirect(url_for("homepage"))
# -- Delete Category --- #
@app.route("/delete_category/<category_id>")
def delete_category(category_id):
"""
Delete Category, stricted for Admin use only.
Checks if user is in session, and has Admin credentials.
If they do, selected category is removed from the database.
"""
# Check if user is in session
if session.get('user') is None:
flash('Please sign in as Admin User to perform this action')
return redirect(url_for("login"))
else:
# Check if session user is Admin
if session['user'] == ADMIN:
mongo.db.categories.remove({"_id": ObjectId(category_id)})
flash("Category deleted")
else:
flash('You are not authorized to perform this operation!')
return redirect(url_for("homepage"))
return redirect(url_for("dashboard"))
# -- Edit Category --- #
@app.route("/edit_category/<category_id>", methods=["GET", "POST"])
def edit_category(category_id):
"""
Edit Category, restricted for Admin use only. Checks if user is
in session, and has Admin credentials. If they do, the selected
category data is retrieved from the database, and updated after
submission. Success message is shown to the Admin.
"""
# Check if user is in session
if session.get('user') is None:
flash('Please sign in as Admin User to perform this action')
return redirect(url_for("login"))
else:
# Check if session user is Admin
if session['user'] == ADMIN:
if request.method == "POST":
# Check if category already exists in db
existing_category = mongo.db.categories.find_one({
"post_category": request.form.get("post_category")})
category = {
"post_category": request.form.get("post_category")}
if existing_category:
flash("Category already exists!")
return render_template("add_category.html")
submit = {
"post_category": request.form.get("post_category")
}
mongo.db.categories.update(
{"_id": ObjectId(category_id)}, submit)
flash("Category Successfully Updated")
return redirect(url_for("dashboard"))
category = mongo.db.categories.find_one(
{"_id": ObjectId(category_id)})
return render_template("edit_category.html", category=category)
else:
flash('You are not authorized to perform this operation!')
return redirect(url_for("homepage"))
# -- Admin Dashboard --- #
@app.route("/dashboard")
def dashboard():
"""
Admin Dashboard, stricted for Admin use only. Checks is user
is in session, and has Admin credentials. Gathers all the blog
data from the database. Allows Admin user to Add, Update, and
Delete all the categories, posts, and users.
"""
# Check if user is in session
if session.get('user') is None:
flash('Please sign in as Admin User to perform this action')
return redirect(url_for("login"))
else:
# Check if session user is Admin
if session['user'] == ADMIN:
categories = list(mongo.db.categories.find().sort(
"post_category", 1))
total_categories = mongo.db.categories.count()
users = list(mongo.db.users.find().sort("username", 1))
total_users = mongo.db.users.count()
posts = list(mongo.db.posts.find().sort("post_date", -1))
total_posts = mongo.db.posts.count()
else:
flash('You are not authorized to perform this operation!')
return redirect(url_for("homepage"))
return render_template("dashboard.html", categories=categories,
total_categories=total_categories,
users=users, total_users=total_users,
total_posts=total_posts, posts=posts)
# -- Delete Registered User -- #
@app.route("/delete_user/<user_id>")
def delete_user(user_id):
"""
Delete Registered users, stricted for Admin use only.
Checks if user in session, and checks if session user
is Admin. Allows Admin user to delete users from the
database.
"""
# Check if user is in session
if session.get('user') is None:
flash('Please sign in as Admin User to perform this action')
return redirect(url_for("login"))
else:
# Check if session user is Admin
if session['user'] == ADMIN:
mongo.db.users.remove({"_id": ObjectId(user_id)})
flash("User Successfully Deleted")
else:
flash('You cant delete other users accounts!')
return redirect(url_for("homepage"))
return redirect(url_for("dashboard"))
# -- Delete User Post --- #
@app.route("/delete_user_post/<post_id>")
def delete_user_post(post_id):
"""
Delete user post, stricted for Admin use only. Allows
Admin user to delete any user post data located in the database.
"""
# Check if user is in session
if session.get('user') is None:
flash('Please sign in as Admin User to perform this action')
return redirect(url_for("login"))
else:
# Check if session user is Admin
if session['user'] == ADMIN:
mongo.db.posts.remove({"_id": ObjectId(post_id)})
flash("Post Successfully Deleted")
else:
flash('You cant delete other users posts!')
return redirect(url_for("homepage"))
return redirect(url_for("dashboard"))
# -- Contact --- #
@app.route("/contact", methods=["GET", "POST"])
def contact():
"""
Contact, renders contact page template, and using
Flask Mail functionality, allows users to contact
the admin via e-mail.
"""
if request.method == "POST":
with app.app_context():
msg = Message(subject="New Email From Wonderdam Blog")
msg.recipients = [os.environ.get("MAIL_USERNAME")]
msg.sender = request.form.get("emailaddress")
name = request.form.get("name")
message = request.form.get("message")
msg.body = (f"Name: {name} \n"
f"Email: {msg.sender} \n"
f"Message: {message} \n")
mail.send(msg)
flash("Your Message Sent Successfully!")
return redirect(url_for("contact"))
return render_template("contact.html")
##################
# Error Handlers #
##################
# Code Credit: https://flask.palletsprojects.com/en/1.1.x/patterns/errorpages/
# -- 404 Error --- #
@app.errorhandler(404)
def page_not_found(e):
"""
Page Not Found error, Renders 404 error template.
"""
return render_template("404.html"), 404
# -- 500 Error --- #
@app.errorhandler(500)
def internal_server_error(e):
"""
Internal Server Error, Renders 500 error template.
"""
return render_template("500.html"), 500
if __name__ == '__main__':
app.run(host=os.environ.get("IP"),
port=int(os.environ.get("PORT")),
debug=False)