-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
635 lines (504 loc) · 17.9 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
from flask import Flask, render_template, url_for, redirect, request, session, flash
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import secure_filename
import json
import hashlib
import os
import random
images = []
propics = []
for root, directories, files in os.walk("static/img/post"):
for filename in files:
images.append(filename)
for root, directories, files in os.walk("static/img/profile"):
for filename in files:
propics.append(filename)
def giveme():
random.shuffle(images)
return random.choice(images)
def giveprof():
random.shuffle(propics)
return random.choice(propics)
with open("templates/config.json", "r") as c:
para = json.load(c)["para"]
app = Flask(__name__)
app.config.from_object('config')
app.secret_key = 'ThisIsAwildGameOfSurvival'
db = SQLAlchemy(app)
from model import*
def hashit(s):
z = s.encode('ascii')
return hashlib.sha256(z).hexdigest()
def isalready(s):
return s in images or s in propics
def toolong(title, content):
tl = len(title) > 80
contlis = content.split("\n")
cl = len(contlis) > 7
clt = len(content) > 600
return tl or cl or clt
def longabout(about):
return len(about) > 100
def invalid(email):
if email.count("@") != 1 or email.count(".") != 1:
return True
if " " in email:
return True
if ".com" not in email:
return True
em = email.split("@")
if len(em[0]) == 0:
return True
for x in em[0]:
a = ord(x)
if 47 < a < 58 or 64 < a < 91 or 96 < a < 123:
continue
else:
return True
ep = em[1].split(".")
if len(ep) != 2:
return True
if ep[1] != "com":
return True
if ep[0] not in ["outlook", "gmail"]:
return True
return False
def invaliduser(username):
if len(username)<1:
return True
for x in username:
if 64<ord(x)<91 or 96<ord(x)<123:
continue
else:
return True
return False
@app.errorhandler(404)
def page_not_found(e):
return redirect(url_for("error"))
@app.route('/')
def index():
posts = Posts.query.order_by(Posts.date.desc()).all()
tp = para['nofpost']
last = len(posts) // tp + (len(posts) % tp != 0)
if last == 1:
return render_template('index.html', posts=posts, prev="#", next="#")
page = request.args.get('page')
try:
page = int(page)
except(Exception):
page = 0
posts = posts[page * tp:min((page + 1) * tp, len(posts))]
prev = "?page=" + str(page - 1) if page > 0 else "#"
next = "?page=" + str(page + 1) if page < last - 1 else "#"
return render_template('index.html', posts=posts, prev=prev, next=next)
@app.route('/profile/<string:name>')
def profile(name):
edit = 0
posts = Posts.query.filter_by(
author=name).order_by(Posts.date.desc()).all()
if "user" in session:
if name == session["user"]:
edit = 1
user = Users.query.get_or_404(name)
return render_template("profile.html", user=user, edit=edit, posts=posts)
@app.route('/editprofile', methods=["GET", "POST"])
def editprofile():
if "user" not in session:
flash("You are not logged in")
return redirect("/login")
user = Users.query.get_or_404(session["user"])
if request.method == 'POST':
about = request.form['about']
github = request.form['github']
code = request.form['code']
about = about.strip(' ')
about = about.strip('\n')
if longabout(about) or "\n" in about:
flash("The about is too long")
return redirect("/editprofile")
random_check = request.form.get('random')
user.about = about
user.github = github
user.code = code
if not random_check:
try:
image = request.files['profilepic']
if isalready(image.filename):
flash('Sorry! The file name already exist')
return redirect('/editprofile')
else:
image.save(os.path.join('static/img/profile/',
secure_filename(image.filename)))
user.prof = image.filename
except Exception as e:
print(e)
else:
user.prof = giveprof()
try:
db.session.commit()
return redirect('/profile/' + user.name)
except(Exception):
return redirect('/error')
else:
return render_template("editprofile.html", user=user)
@app.route('/login', methods=['GET', 'POST'])
def login():
if "user" in session:
flash("You are already logged in")
return redirect("/")
if request.method == 'POST':
try:
user = Users.query.get_or_404(request.form['username'])
except Exception as e:
print(e)
flash("You are not signed in")
return redirect("/createaccount")
password = hashit(request.form['password'])
if password == user.password:
session["user"] = user.name
flash("Logged In successfully")
return redirect("/")
else:
flash("Wrong password")
return redirect("/login")
else:
return render_template('login.html')
@app.route('/changepassword', methods=['GET', 'POST'])
def changepassword():
if "user" not in session:
flash("You are not logged in")
return redirect("/")
user = Users.query.get_or_404(session["user"])
if request.method == 'POST':
prevpass = hashit(request.form['oldpassword'])
newpassword = hashit(request.form['newpassword'])
if prevpass == user.password:
user.password = newpassword
try:
db.session.commit()
flash("Password updated! shh, Don't tell anyone")
return redirect("/profile/"+user.name)
except(Exception):
return redirect("/error")
else:
flash("Wrong current password")
return redirect("/changepassword")
else:
return render_template('changepassword.html')
@app.route('/deleteaccount', methods=['GET', 'POST'])
def deleteaccount():
if "user" not in session:
flash("You are not logged in")
return redirect("/login")
if request.method == 'POST':
user = Users.query.get_or_404(session["user"])
password = hashit(request.form['password'])
if password == user.password:
try:
posts = Posts.query.filter_by(author=session["user"]).all()
for post in posts:
db.session.delete(post)
db.session.delete(user)
db.session.commit()
session.pop("user", None)
except(Exception):
return redirect("/error")
flash("Account deleted")
return redirect("/")
else:
flash("Wrong password")
return redirect("/deleteaccount")
else:
return render_template('deleteaccount.html')
@app.route('/logout')
def logout():
if "user" in session:
session.pop("user", None)
flash("Logged out successfully")
else:
flash("You are not logged in")
return redirect("/")
@app.route('/createaccount', methods=['GET', 'POST'])
def createaccount():
if "user" in session:
flash("You are already logged in")
return redirect("/")
if request.method == 'POST':
try:
username = request.form['username']
user = Users.query.get_or_404(username)
flash("Username already exist")
return render_template('createaccount.html')
except (Exception):
email = request.form['email']
user = Users.query.filter_by(email=email).all()
if len(user):
flash("Email address already exist")
return render_template('createaccount.html')
if invalid(email):
flash("Invalid email address")
return render_template('createaccount.html')
if invaliduser(username):
flash("Only Letters are allowed in User name")
return render_template('createaccount.html')
password = hashit(request.form['password'])
newuser = Users(name=username, email=email, password=password)
try:
db.session.add(newuser)
db.session.commit()
except(Exception):
return redirect("/error")
session["user"] = username
flash("You are now signed in")
return redirect("/")
if password == user.password:
session["user"] = user.name
flash("Logged In successfully")
return redirect("/")
else:
flash("Wrong password")
return redirect("/login")
else:
return render_template('createaccount.html')
@app.route('/editor')
def editor():
if "user" not in session or session["user"] != "blue":
flash("You are not authorized visit this page")
return redirect("/")
games = Games.query.all()
return render_template('editor.html', games=games)
@app.route('/deletegame/<string:id>', methods=['GET', 'POST'])
def deletegame(id):
if "user" not in session or session["user"] != "blue":
flash("You are not authorized visit this page")
return redirect("/")
game = Games.query.get_or_404(id)
if request.method == 'POST':
try:
try:
os.remove(os.path.join(
'static/img/games/', game.nick + '.png'))
os.remove(os.path.join(
'static/js/games/', game.nick + '.js'))
except(Exception):
return redirect('/error')
db.session.delete(game)
db.session.commit()
return redirect('/editor')
except(Exception):
return redirect('/error')
else:
return render_template('deletegame.html', game=game)
@app.route('/editor/<string:id>', methods=['GET', 'POST'])
def editgame(id):
if "user" not in session or session["user"] != "blue":
flash("You are not authorized visit this page")
return redirect("/")
game = Games.query.get_or_404(id)
if request.method == 'POST':
try:
os.remove(os.path.join(
'static/img/games/', game.nick + '.png'))
os.remove(os.path.join('static/js/games/', game.nick + '.js'))
except(Exception):
return redirect('/error')
game.name = request.form['name']
game.nick = request.form['nick']
game.dis = request.form['discrip']
image = request.files['imagefile']
jsfile = request.files['jsfile']
image.save(os.path.join('static/img/games/',
secure_filename(image.filename)))
jsfile.save(os.path.join('static/js/games/',
secure_filename(jsfile.filename)))
try:
db.session.commit()
return redirect('/play')
except(Exception):
return redirect('/error')
else:
return render_template('editgame.html', game=game)
@app.route('/edit/<string:id>', methods=['GET', 'POST'])
def editblog(id):
if "user" not in session:
flash("You are not logged in !")
return redirect('/login')
post = Posts.query.get_or_404(id)
if post.author != session["user"]:
flash("You can't edit someone else post")
return redirect("/")
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
content = content.strip(' ')
content = content.strip('\n')
title = title.strip(' ')
if toolong(title, content):
flash("The title or post is too long")
return redirect("/edit/" + str(id))
post.title = title
post.content = content
try:
db.session.commit()
return redirect('/')
except(Exception):
return redirect('/error')
return render_template('editblog.html', post=post)
@app.route('/delete/<string:id>', methods=['GET', 'POST'])
def delete(id):
if "user" not in session:
flash("You are not logged in !")
return redirect('/login')
post = Posts.query.get_or_404(id)
if post.author != session["user"]:
flash("You can't delete someone else post")
return redirect("/")
if request.method == 'POST':
try:
db.session.delete(post)
db.session.commit()
return redirect('/')
except(Exception):
return redirect('/error')
return render_template('delete.html', post=post)
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/add', methods=['GET', 'POST'])
def addvideo():
if "user" not in session or session["user"] != "blue":
flash("You are not authorized visit this page")
return redirect("/")
if request.method == 'POST':
title = request.form['title']
link = request.form['link']
newvideo = Videos(
title=title, link="https://www.youtube.com/embed/" + link)
try:
db.session.add(newvideo)
db.session.commit()
return redirect('/video')
except(Exception):
return redirect('/error')
else:
return render_template('addvideo.html')
@app.route('/video')
def video():
videos = Videos.query.order_by(Videos.id.desc()).all()
return render_template('video.html', videos=videos)
@app.route('/editvideo')
def editvideo():
if "user" not in session or session["user"] != "blue":
flash("You are not authorized visit this page")
return redirect("/")
videos = Videos.query.order_by(Videos.id.desc()).all()
return render_template('editvideo.html', videos=videos)
@app.route('/deletevideo/<string:id>', methods=['GET', 'POST'])
def deletevideo(id):
if "user" not in session or session["user"] != "blue":
flash("You are not authorized visit this page")
return redirect("/")
video = Videos.query.get_or_404(id)
if request.method == 'POST':
try:
db.session.delete(video)
db.session.commit()
return redirect('/editvideo')
except(Exception):
return redirect('/error')
else:
return render_template('deletevideo.html', video=video)
@app.route('/play')
def menu():
games = Games.query.all()
return render_template('play.html', games=games)
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if "user" not in session or session["user"] != "blue":
flash("You are not authorized visit this page")
return redirect("/")
if request.method == 'POST':
name = request.form['name']
nick = request.form['nick']
dis = request.form['discrip']
try:
image = request.files['imagefile']
jsfile = request.files['jsfile']
image.save(os.path.join('static/img/games/',
secure_filename(image.filename)))
jsfile.save(os.path.join('static/js/games/',
secure_filename(jsfile.filename)))
newgame = Games(name=name, nick=nick, dis=dis)
db.session.add(newgame)
db.session.commit()
return redirect('/play')
except Exception as error:
print(error)
return redirect('/error')
else:
return render_template('upload.html')
@app.route('/error')
def error():
return render_template('404.html')
@app.route('/post', methods=['GET', 'POST'])
def post():
if "user" not in session:
flash("You are not logged in !")
return redirect('/login')
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
content = content.strip(' ')
content = content.strip('\n')
title = title.strip(' ')
if toolong(title, content):
flash("The title or post is too long")
return redirect("/post")
random_check = request.form.get('random')
if not random_check:
try:
image = request.files['postimage']
if isalready(image.filename):
flash('Sorry! The file name already exist')
return redirect('/post')
else:
image.save(os.path.join('static/img/post/',
secure_filename(image.filename)))
except(Exception):
return redirect('/error')
newpost = Posts(title=title, content=content,
image=image.filename, author=session["user"])
else:
newpost = Posts(title=title, content=content,
image=giveme(), author=session["user"])
try:
db.session.add(newpost)
db.session.commit()
return redirect('/')
except(Exception):
return redirect('/error')
else:
return render_template('/postblog.html')
@app.route('/admin/')
def admin():
if "user" not in session or session["user"] != "blue":
flash("You are not authorized visit this page")
return redirect("/")
else:
return render_template('admin.html')
@app.route('/play/<int:id>')
def play(id):
game = Games.query.get_or_404(id)
return render_template('games/playgame.html', game=game)
@app.route('/play/full/<int:id>')
def playfull(id):
game = Games.query.get_or_404(id)
return render_template('games/fullsc.html', game=game)
@app.route("/js/<string:file>")
def index_js(file):
with open("static/js/" + file, "r") as f:
data = f.read()
return data
if __name__ == '__main__':
db.create_all()
app.run(debug=True)