-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathapp.py
377 lines (307 loc) · 12.1 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
from flask import (
Flask, render_template, redirect, request, url_for, session, flash)
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
from datetime import datetime
import os
from translate import translate_text
if os.path.exists("env.py"):
import env
app = Flask(__name__)
# Get the environment variables from the server for the DB
app.config["MONGO_URI"] = os.environ.get("MONGO_URI")
app.secret_key = os.environ.get("SECRET_KEY")
# Configure app for debug mode if the enviornment is set for debug
# Run the app in production otherwise
if os.environ.get("DEBUG") == 'True':
app.debug = True
app.config["GOOGLE_APPLICATION_CREDENTIALS"] = os.environ.get(
"GOOGLE_APPLICATION_CREDENTIALS")
else:
app.debug = False
mongo = PyMongo(app)
# Blog data references the collection within MongoDB that holds the blog data
threadDB = mongo.db.threads
userDB = mongo.db.users
postDB = mongo.db.posts
# Landing page
@app.route("/", methods=['GET', 'POST'])
def index():
"""
Check if user who arrives on index page has a username cached
or if they're a guest user
"""
sorted_threads = threadDB.find().sort('_id', -1).limit(4)
translated_threads = list(sorted_threads)
if(session.get('user')):
user = userDB.find_one({"username": session["user"]})
for thread in translated_threads:
thread['subject'] = translate_text(
user['language'], thread['subject'])
return render_template("index.html", user=userDB.find_one(
{"username": session["user"]}), threads=translated_threads)
else:
session["user"] = "guest"
return render_template("index.html", user=userDB.find_one(
{"username": session["user"]}), threads=sorted_threads)
@app.route("/login", methods=['GET', 'POST'])
def login():
"""
Matches the form input with a DB entry and adds user to session cookies
Returns:
render template login.html
"""
if request.method == "POST":
# see if the username entered in the login form is in the database
userInfo = userDB.find_one({"username": request.form.get("username")})
# the username is in the database, now check if the password is correct
if(userInfo != None):
userName = request.form.get("username")
# password is correct, go to index page
if(userInfo["password"] == request.form.get("password")):
session["user"] = userName
flash(f'Welcome back {userName}!')
return redirect(url_for("index"))
else:
# password is incorrect, reset login form
flash("Incorrect password")
session["user"] = "guest"
return render_template("login.html", user=userDB.find_one(
{"username": session["user"]}))
else:
# there is no user with this name in the database, reset login form
flash("No user account with this name exists")
session["user"] = "guest"
return render_template("login.html", user=userDB.find_one(
{"username": session["user"]}))
return render_template("login.html", user=userDB.find_one(
{"username": session["user"]}))
@app.route("/signup", methods=['GET', 'POST'])
def signup():
"""
Signup function to add users to the database
Returns:
render signup.html
"""
if request.method == 'POST':
# Check if user and email are already in the database
user_exists = userDB.find_one({
'username': request.form.get('username').lower()
})
email_exists = userDB.find_one({'email': request.form.get('email')})
# Flash error messages and return user to signup page
if user_exists:
flash('Username already taken')
return redirect(url_for('signup'))
elif email_exists:
flash('Email already in use!')
return redirect(url_for('signup'))
# If there are no conflicts get the data from
# the form and create the user in database
else:
register = {
'username': request.form.get('username'),
'email': request.form.get('email'),
'password': request.form.get('password'),
'avatar': request.form.get('profile_img'),
'language': request.form.get('language'),
'isAdmin': False,
}
userDB.insert_one(register)
# Add user to session cookies
session['user'] = request.form.get('username')
flash(
f'Account created {request.form.get(
"username")}. Welcome aboard!',)
return redirect(url_for('index'))
return render_template('signup.html', user=userDB.find_one(
{'username': session['user']}))
@app.route('/get_all_threads')
def get_all_threads():
"""
Query the database for all threads and sort them by most recent.
Store sorted results in <sorted_threads> variable to be passed
to template render
Returns:
render_template threads.html
"""
user = userDB.find_one({'username': session['user']})
# Update the number of posts in each thread in the Database
threads = threadDB.find()
for thread in threads:
threadID = str(thread['_id'])
number_of_posts = postDB.count_documents({'subjectID': threadID})
thread['posts'] = number_of_posts
threadDB.replace_one({'_id': ObjectId(threadID)}, thread)
# Sort threads by most recent first and translate them
sorted_threads = threadDB.find().sort('_id', -1)
translated_threads = list(sorted_threads)
# Pagination
page = request.args.get('page', type=int) # page number is fed in via url
POSTS_PER_PAGE = 4
# find what post is the first post on this particular page
firstPostToList = page * POSTS_PER_PAGE
lastPostToList = firstPostToList + POSTS_PER_PAGE
# translate the thread details only for the threads that will appear on
# this particular page
translated_threads = translated_threads[firstPostToList:lastPostToList]
for thread in translated_threads:
thread['subject'] = translate_text(
user['language'], thread['subject'])
thread['content'] = translate_text(
user['language'], thread['content'])
return render_template('allthreads.html', user=user, threads=translated_threads, totalThreads=threadDB.count(), page=page)
@app.route("/thread")
def thread():
threadID = request.args.get('threadID', None)
allPostsInThread = postDB.find({'subjectID': threadID})
user = userDB.find_one({"username": session["user"]})
thread = threadDB.find_one({'_id': ObjectId(threadID)})
thread['subject'] = translate_text(user['language'], thread['subject'])
thread['content'] = translate_text(user['language'], thread['content'])
translatedPosts = list(allPostsInThread)
for t in translatedPosts:
author = userDB.find_one({'username': t['author']})
t['avatar'] = author['avatar']
t['lang'] = author['language']
for post in translatedPosts:
post['content'] = translate_text(user['language'], post['content'])
return render_template(
"thread.html", user=user, thread=thread, posts=translatedPosts)
@app.route("/logout")
def logout():
session.pop("user")
session['user'] = "guest"
return redirect(url_for("index"))
@app.route("/newthread")
def newthread():
return render_template("newthread.html")
@app.route("/add_thread_to_db", methods=["POST"])
def add_thread_to_db():
new_thread = request.form.to_dict()
new_thread['created_on'] = datetime.now()
threadDB.insert_one(new_thread)
return redirect(url_for('index'))
@app.route("/newpost")
def newpost():
threadID = request.args.get('threadID', None)
return render_template(
"newpost.html", user=session["user"], thread=threadDB.find_one(
{'_id': ObjectId(threadID)}))
@app.route("/add_post_to_db", methods=["POST"])
def add_post_to_db():
new_post = request.form.to_dict()
new_post['posted_on'] = datetime.now()
postDB.insert_one(new_post)
return redirect(url_for('thread', threadID=new_post['subjectID']))
@app.route("/delete_thread_from_db")
def delete_thread_from_db():
threadID = request.args.get("threadID", None)
threadDB.remove({"_id": ObjectId(threadID)})
return redirect(url_for("admin_posts"))
@app.route("/delete_post_from_db")
def delete_post_from_db():
postID = request.args.get("postID", None)
postDB.remove({"_id": ObjectId(postID)})
return redirect(url_for("admin_posts"))
@app.route("/privacy")
def privacy():
return render_template("privacy.html", user=userDB.find_one(
{"username": session["user"]}))
@app.route("/terms")
def terms():
return render_template("terms.html", user=userDB.find_one(
{"username": session["user"]}))
@app.errorhandler(404)
def page_not_found(e):
'''
When error 404 occurs render template for respective page,
:param e: the error that occurs
:return render_template of error_404.html
'''
return render_template(
'404.html', user=userDB.find_one(
{"username": session["user"]}), error=e), 404
@app.route("/report_thread")
def report_thread():
"""
Route adds flagged: TRUE to the thread that was reported
Returns:
redirect to get_all_threads
"""
threadID = request.args.get("threadID", None)
thread = threadDB.find_one({'_id': ObjectId(threadID)})
thread['flagged'] = 'TRUE'
threadDB.replace_one({'_id': ObjectId(threadID)}, thread)
flash(
f'The thread {thread["subject"]} has been reported to the Admin!'
)
return redirect(url_for('get_all_threads'))
@app.route("/remove_thread_flag")
def remove_thread_flag():
"""
Route for the admin to remove the flag from a thread
Returns:
redirect to admin_posts route
"""
threadID = request.args.get("threadID", None)
thread = threadDB.find_one({'_id': ObjectId(threadID)})
thread['flagged'] = 'FALSE'
threadDB.replace_one({'_id': ObjectId(threadID)}, thread)
flash(
f'The thread {thread["subject"]} has been unflagged!'
)
return redirect(url_for('admin_posts'))
@app.route("/report_post")
def report_post():
"""
Route adds flagged: TRUE to the post that was reported
Returns:
redirect to get_all_threads
"""
postID = request.args.get("postID", None)
post = postDB.find_one({'_id': ObjectId(postID)})
post['flagged'] = 'TRUE'
postDB.replace_one({'_id': ObjectId(postID)}, post)
flash(
f'The post by {post["author"]} has been reported to the Admin!'
)
return redirect(url_for('get_all_threads'))
@app.route("/remove_post_flag")
def remove_post_flag():
"""
Route for the admin to remove the flag from a post
Returns:
redirect to admin_posts route
"""
postID = request.args.get("postID", None)
post = postDB.find_one({'_id': ObjectId(postID)})
post['flagged'] = 'FALSE'
postDB.replace_one({'_id': ObjectId(postID)}, post)
flash(
f'The post by {post["author"]} has been unflagged!'
)
return redirect(url_for('admin_posts'))
# View for admins to view all posts in the database
@app.route("/admin_posts")
def admin_posts():
"""
Checks if logged used is admin and queries the database
for all the flagged threads and posts then returns them to the view
Returns:
render template admin_posts.html
"""
user = userDB.find_one({'username': session['user']})
if user['isAdmin']:
flagged_threads = threadDB.find({'flagged': 'TRUE'})
flagged_posts = postDB.find({'flagged': 'TRUE'})
return render_template("admin_posts.html", threads=flagged_threads, posts=flagged_posts, user=user)
else:
flash('You are not authorized to access this feature')
return redirect('get_all_threads')
# Set debug status based on enviornment variable
if __name__ == '__main__':
if app.debug:
app.run(debug=True)
else:
app.run(debug=False)