-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
390 lines (299 loc) · 10.6 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
# test
from datetime import datetime
from os.path import isfile
from os.path import join
from markdown import markdown
from flask import *
from flask_caching import Cache
from flask_socketio import SocketIO, send
from authlib.integrations.flask_client import OAuth
import json
import markdown
from content import load_content
from firebase.article import upload_article
import g_auth
if not isfile('.env'):
print(
'WARN: Missing .env file, please add a .env file in your root directory.'
)
content = load_content("content.yml")
earlyaccess = False
ARTICLE_MIN = 2000
ARTICLE_MAX = 30000
# firebase imports (should be done after dotenv validation)
from firebase import user as fbuser
from firebase import tools as fbtools
from firebase import paginate
from firebase import search as fbsearch
from firebase import article as fbarticle
app = Flask(__name__, template_folder='src')
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['FLASK_ENV'] = 'development'
app.config['DEBUG'] = True
app.config['CACHE_TYPE'] = 'SimpleCache'
app.config['CACHE_DEFAULT_TIMEOUT'] = 1800
app.secret_key = g_auth.secret_key
sio = SocketIO(app, debug=True, threaded=True)
oauth = OAuth(app)
google = oauth.register(**g_auth.config)
CATS = {}
with open('cats.json') as f:
CATS = json.load(f)
def md_html(md_str):
return markdown(md_str)
@app.context_processor
def utility_processor():
def is_signed_in():
return fbuser.is_signed_in()
def current_pfp():
try:
return fbtools.get_doc(u'users', fbuser.current_uid())['pfp']
except Exception:
return ''
def user_elevations():
try:
return fbtools.get_doc(u'users', fbuser.current_uid())['elevation']
except Exception:
return []
def authorized(level, uid=fbuser.current_uid()):
try:
return fbtools.isauthorized(level, uid)
except Exception:
return False
def c_user():
try:
return fbtools.get_doc(u'users', fbuser.current_uid())
except Exception:
return None
def unix_time(time):
return datetime.fromtimestamp(time).strftime('%d/%m/%Y')
def cats():
return CATS
def md(m):
return markdown.markdown(m)
return dict(is_signed_in=is_signed_in,
current_pfp=current_pfp,
user_elevations=user_elevations,
authorized=authorized,
c_user=c_user,
unix_time=unix_time,
cats=cats,
md=md)
@app.route('/', methods=['GET', 'POST'])
def home():
try:
subpage = request.args.get('goto') if earlyaccess is not True else None
init_pagi = paginate.paginate('articles', 'timestamp', l=5, o='DESC')
for i in init_pagi['data'][1:]:
i['body'] = i['body'].strip().replace("\n",
"")[:150].rsplit(' ', 1)[0]
return render_template('./screens/index.html',
subpage=subpage,
h=init_pagi)
except Exception as e:
return f"Something went wrong: {e}"
@app.route('/greet')
def greet():
return dict(session)['profile']
@app.route('/login/google')
def google_auth():
google = oauth.create_client('google')
redirect_uri = url_for('authorize', _external=True)
return google.authorize_redirect(redirect_uri)
@app.route('/authorize')
def authorize():
google = oauth.create_client('google')
token = google.authorize_access_token()
resp = google.get('userinfo')
user_info = resp.json()
user = oauth.google.userinfo()
session['profile'] = user_info
session.permanent = True
fbuser.google_user_doc(user_info)
return redirect('/')
@app.route('/profile/my/logout')
def logout():
for key in list(session.keys()):
session.pop(key)
return redirect('/')
@app.route('/profile/my/delete')
def delete_user():
try:
fbuser.delete_user()
return redirect('/profile/my/logout')
except Exception:
return "Couldn't delete your account"
@app.route('/profile/me', methods=['GET', 'POST'])
def current_user_profile_redir():
try:
cuid = fbuser.current_uid()
if cuid != None:
return redirect(f'/profile/{cuid}')
return redirect('/login')
except Exception:
return redirect('/login')
@app.route('/profile')
def profile_redir():
return redirect("/profile/me")
@app.route('/user')
def user_redir():
return redirect("/profile/me")
@app.route('/account')
def account_redir():
return redirect("/profile/me")
@app.route('/me')
def me_redir():
return redirect("/profile/me")
@app.route('/profile/my')
def profile_my():
return redirect("/profile/me")
@app.route('/my')
def my_redir():
return redirect("/profile/me")
@app.route('/about')
def about():
return render_template('./screens/about.html',
about_text=content["about_text"])
@app.route('/contribute')
def contribute():
return render_template('./screens/contr.html')
@app.route('/verify')
# return redirect if uid param is not istype(int)
def verify():
uid = request.args.get('uid')
if fbuser.user_exists(uid):
return render_template('./screens/verify.html',
verification_text=content["verification_text"])
return redirect("/")
@app.route('/favicon.png')
def favicon():
return send_from_directory(join(app.root_path, 'static'),
'favicon.png',
mimetype='image/vnd.microsoft.icon')
@app.route('/write', methods=['POST', 'GET'])
def write():
if request.method == "POST":
article_title = request.form.get('title')
article_body = request.form.get('body')
article_cover = request.form.get('cover')
if (len(article_title) <= 60 and len(article_title) >= 5) or (
len(article_body) <= ARTICLE_MIN
and len(article_body) >= ARTICLE_MAX):
fbarticle.writer_upload(article_title, article_body, article_cover)
else:
return 'illegal'
if fbtools.isauthorized('W', fbuser.current_uid()):
return render_template('./screens/elevated/write.html')
return forbidden(Exception("User not authorized"))
@app.route('/legal/terms-and-conditions')
def terms():
with open('terms.md', 'r') as f:
tac = md_html(f.read())
return render_template('./screens/legal/terms-and-conditions.html',
updated="2021-09-06",
tac=tac)
@app.errorhandler(404)
def page_not_found(e):
return render_template('./err/404.html',
message=content["404_message"]), 404
@app.errorhandler(403)
def forbidden(e):
return render_template('./err/403.html',
message=content["403_message"]), 403
@app.route('/register')
def register():
return redirect(
"/?goto=register") if earlyaccess is not True else redirect('/')
@app.route('/login')
def login():
return redirect("/?goto=login") if earlyaccess is not True else redirect(
'/')
@app.route('/profile/my/edit', methods=['GET', 'POST'])
def profile_edit():
if earlyaccess is True: return redirect('/')
try:
if (fbuser.current_uid() is None or fbtools.get_doc(
u'users', fbuser.current_uid())['elevation'] == []):
return redirect('/login')
if request.method == "POST":
fbtools.update_fields(
'users',
fbuser.current_uid(),
{
# TODO: #51 add pfp post method here too
u'email_public':
request.form.get("profile-edit-email-public") == 'on',
u'bio':
request.form.get("profile-edit-bio").strip(),
u'phone':
request.form.get("profile-edit-phone").strip(),
u'location':
request.form.get("profile-edit-location").strip(),
u'name':
request.form.get("profile-edit-name").strip(),
},
)
return render_template('./screens/profile_edit.html')
except Exception:
return redirect('/login')
@app.route('/profile/<uid>')
def user_profile(uid):
try:
user_data = fbtools.get_doc(u'users', uid)
if user_data['elevation'] == []:
raise Exception()
return render_template('./screens/profile.html', user_data=user_data)
except Exception:
return render_template('./screens/profile_not_found.html')
@app.route('/article/<auid>')
def article_page(auid):
# try fetching data from the uid using fbtools and redirect to / if Exception
""" try:
article = fbtools.get_doc(u'articles', uid)
if article["is_approved"] is True:
# Article approved and published, return the content
return render_template('./screens/article.html', article=article)
else:
raise Exception("Non-approved article")
except Exception:
# Render an article not found message
return render_template('./screens/article.html', article=None) """
try:
article = fbtools.get_doc(u'articles', auid)
article['writer'] = article['writer'].get().to_dict()
return render_template('./screens/article.html', article=article)
except Exception:
return render_template('./screens/article_not_found.html')
@app.route('/profile/my/rmpfp')
def rmpfp():
try:
fbtools.update_fields(u'users', fbuser.current_uid(), {u'pfp': ''})
except Exception:
pass
return ("current user pfp reset")
@app.route('/profile/my/delete-acc')
def rmacc():
# TODO: #52 this should open up a verification page. using the button, get a post method and when method='post', call remove account function.
return ("alla")
@app.route('/api/pagi/<coll>/<sort>/q')
def api_pagi(coll, sort):
return paginate.paginate(coll, sort, **dict(request.args))
@app.route('/search/<kw>')
def search(kw):
return fbsearch.search_article(kw)
@sio.on('pagiRequest')
def pagi_request(data):
send(paginate.paginate('articles', 'timestamp', l=10, o='desc', i=data))
def start():
# fbuser.register("dmeoeom@gdgd.com", "passssword", "name")
# fbuser.login("dmeoeom@gdgd.com", "passssword")
# app.run(debug=True, threaded=True)
sio.run(app)
def uuid():
from firebase.setup import auth
try:
return auth.current_user['localId']
except Exception:
return None
if __name__ == '__main__':
start()