-
Notifications
You must be signed in to change notification settings - Fork 0
/
multiuser_blog.py
456 lines (409 loc) · 15.3 KB
/
multiuser_blog.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
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import webapp2
import jinja2
from google.appengine.ext import db
import time
from blog import Blog
from user import User
from comment import Comment
from utils import make_secure_val, check_secure_val, valid_username, \
valid_email, valid_password, login_required
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
class AppHandler(webapp2.RequestHandler):
""" Wrapper class to the Google App Engine Request Handler."""
def write(self, *args, **kwargs):
"""Wrapper for response.out.write()"""
return self.response.out.write(*args, **kwargs)
def render_str(self, template, **params):
""" renders a template with the params"""
t = JINJA_ENVIRONMENT.get_template(template)
return t.render(params)
def render(self, template, **kwargs):
"""displays the template on the browser"""
self.write(self.render_str(template, **kwargs))
def render_dict(self, template, d):
"""renders a template with the dictionary"""
t = JINJA_ENVIRONMENT.get_template(template)
return self.write(t.render(d))
def set_cookie(self, name, val):
"""Sets a cookie 'user_id' with the userid and val"""
cookie_val = make_secure_val(val)
self.response.headers.add_header(
'Set-Cookie',
'%s=%s; Path=/' % (name, cookie_val))
def read_cookie(self, name):
"""Return the cookie val if it exists and passes validation"""
cookie_val = self.request.cookies.get(name)
if cookie_val:
return check_secure_val(cookie_val)
def login(self, user):
"""
Creates a cookie called user_id and sets the val to the user_id|hash
"""
self.set_cookie('user_id', str(user.key().id()))
def logout(self):
"""
Sets the value of the cookie user_id to none.
"""
self.response.headers.add_header('Set-Cookie',
'user_id=; Path=/')
def initialize(self, *args, **kwargs):
"""
Checks to see if user_id cookie is present or not.
"""
webapp2.RequestHandler.initialize(self, *args, **kwargs)
user_id = self.read_cookie('user_id')
if user_id and User.by_id(int(user_id)):
self.user_id = int(user_id)
else:
self.user_id = None
class NewBlogPage(AppHandler):
"""
Handler to create a new blog page
"""
@login_required
def get(self):
self.render('newblog.html')
@login_required
def post(self):
title = self.request.get('subject')
text = self.request.get('content')
if title and text:
# both title and text are required
blog = Blog(title=title, body=text, user_id=self.user_id)
blog_id = blog.put().id()
self.redirect("/blog/%d" % blog_id)
else:
error = 'Both fields are required.'
self.render('newblog.html', error=error, title=title,
text=text)
class BlogEntryPage(AppHandler):
"""
Handler to display a particular blog entry.
"""
def get(self, post_id):
# post_id is the blog id
blog = Blog.get_by_id(int(post_id))
if blog:
# Fetch all comments that are tied to the blog.
comments = Comment.by_blog(post_id)
self.render('blogpost.html', blog=blog, user_id=self.user_id,
comments=comments)
else:
self.redirect('/blog/permissionerror/')
class EditBlogPage(AppHandler):
"""
Handler to display/process the form to edit a blog entry.
"""
@login_required
def get(self, post_id):
blog = Blog.by_id(int(post_id))
if blog:
# only the blog author can edit it
if blog.user_id == self.user_id:
self.render('editblog.html', blog=blog)
else:
error = 'Only the Blog owner can edit this blog post.'
comments = Comment.by_blog(post_id)
self.render('blogpost.html', blog=blog, error=error,
user_id=self.user_id, comments=comments)
else:
# Invalid blog - display error page
self.render('permissionerror.html')
@login_required
def post(self, post_id):
title = self.request.get('subject')
text = self.request.get('content')
if title and text:
blog = Blog.by_id(int(post_id))
if blog:
# only the blog author can edit it
if blog.user_id == self.user_id:
blog.title = title
blog.body = text
blog.put()
self.redirect("/blog/%d" % int(post_id))
else:
error = "You don't have permission to edit this blog."
self.render('permissionerror.html', error=error)
else:
self.render('permissionerror.html')
else:
error = 'Both fields are required.'
self.render('editblog.html', error=error, title=title,
text=text)
class DeleteBlogPage(AppHandler):
"""
Handler to delete a blog entry.
"""
@login_required
def post(self, post_id):
blog = Blog.by_id(int(post_id))
if blog:
# Only the blog author can delete the blog
if blog.user_id == self.user_id:
db.delete(blog.key())
# Adding a sleep of 1 second here
# Observation - the database takes a while to reflect the
# change
time.sleep(1)
self.redirect('/blog')
else:
error = 'Only the Blog owner can delete this blog post.'
comments = Comment.by_blog(post_id)
self.render('blogpost.html', blog=blog, error=error,
user_id=self.user_id, comments=comments)
else:
self.render('permissionerror.html')
class ToggleLike(AppHandler):
"""
Handler to like/unlike a blog entry.
"""
@login_required
def post(self, post_id):
user_id = self.user_id
blog = Blog.by_id(int(post_id))
if blog:
# Blog author can't like their own posts.
if blog.user_id == user_id:
error = "You can't like your own posts."
comments = Comment.by_blog(post_id)
self.render('blogpost.html', blog=blog, error=error,
user_id=user_id, comments=comments)
else:
if user_id in blog.liked:
blog.liked.remove(user_id)
blog.put()
else:
blog.liked.append(user_id)
blog.put()
self.redirect('/blog/%d' % int(post_id))
else:
self.render('permissionerror.html')
class AddComment(AppHandler):
"""
Handler to add comments to a blog.
"""
@login_required
def post(self, post_id):
blog = Blog.by_id(int(post_id))
text = self.request.get('text')
if blog:
if not text:
comment_error = "Can't post empty comment."
comments = Comment.by_blog(post_id)
self.render('blogpost.html', blog=blog,
add_comment_error=comment_error,
user_id=self.user_id, comments=comments)
else:
comment = Comment(blog_id=int(post_id),
user_id=self.user_id,
text=text)
comment.put()
# Adding a sleep of 1 second here
# Observation - the database takes a while to reflect the
# change
time.sleep(1)
self.redirect('/blog/%d' % int(post_id))
else:
self.render('permissionerror.html')
class DeleteComment(AppHandler):
"""
Handler to delete a comment.
"""
@login_required
def post(self, post_id):
# post_id is the comment id.
comment = Comment.by_id(int(post_id))
if comment:
blog_id = comment.blog_id
blog = Blog.by_id(blog_id)
# Only the commentor can delete the comment.
if comment.user_id == self.user_id:
db.delete(comment.key())
time.sleep(1)
self.redirect('/blog/%d' % blog_id)
else:
comment_error = """Only the Commenter
can delete this comment."""
comments = Comment.by_blog(blog_id)
self.render('blogpost.html', blog=blog,
user_id=self.user_id,
comments=comments,
comment_error_id=int(post_id),
comment_error=comment_error)
else:
self.render('permissionerror.html',
error="Comment doesn't exist")
class EditComment(AppHandler):
"""
Blog Handler to delete a comment.
"""
@login_required
def get(self, post_id):
comment = Comment.by_id(int(post_id))
if comment:
# Only the commentor can edit the comment.
if comment.user_id == self.user_id:
self.render('editcomment.html', comment=comment)
else:
comment_error = """Only the Commenter
can edit this comment."""
blog_id = comment.blog_id
blog = Blog.by_id(blog_id)
comments = Comment.by_blog(blog_id)
self.render('blogpost.html', blog=blog,
user_id=self.user_id,
comments=comments,
comment_error_id=int(post_id),
comment_error=comment_error)
else:
self.render('permissionerror.html',
error="Comment doesn't exist")
@login_required
def post(self, post_id):
text = self.request.get('content')
if text:
comment = Comment.by_id(int(post_id))
if comment:
# Only the commentor can edit the comment.
if comment.user_id == self.user_id:
comment.text = text
comment.put()
time.sleep(1)
self.redirect("/blog/%d" % comment.blog_id)
else:
error = "You don't have permissions to edit this comment"
self.render('permissionerror.html',
error=error)
else:
self.render('permissionerror.html',
error="Comment doesn't exist")
else:
error = "Comment cannot be blank."
self.render('editcomment.html', error=error)
class BlogPage(AppHandler):
"""
Handler that displays the main blog page.
Only the 10 latest blogs are displayed.
"""
def get(self):
# fetch the 10 latest blog entries.
blogs = Blog.all().order('-created').run(limit=10)
self.render('blog.html', blogs=blogs)
class Register(AppHandler):
"""
Handler that displays/processes the Registration form.
"""
def process_form(self, post_data):
"""
Utility function to process the form and generate errors.
"""
username = post_data[0]
password = post_data[1]
verify = post_data[2]
email = post_data[3]
errors = {}
if not username or not valid_username(username):
errors['username_error'] = "That's not a valid username."
if not password or not valid_password(password):
errors['password_error'] = "That wasn't a valid password."
else:
if not verify or verify != password:
errors['verify_error'] = "Your passwords didn't match."
if email and not valid_email(email):
errors['email_error'] = "That's not a valid email."
if errors:
errors['email'] = email
errors['username'] = username
return errors
def get(self):
self.render('register.html')
def post(self):
data = [self.request.get('username'), self.request.get('password'),
self.request.get('verify'), self.request.get('email')]
errors = self.process_form(data)
if errors:
self.render_dict('register.html', errors)
else:
user_exists = User.by_name(data[0])
if user_exists:
errors['username_error'] = "Username exists."
self.render_dict('register.html', errors)
else:
user = User.register(data[0], data[1], data[3])
# add new user to the database.
user.put()
# create cookie for the user
self.login(user)
self.redirect('/blog/welcome')
class Login(AppHandler):
"""
Handler that displays/processes the login form.
"""
def get(self):
self.render('login.html')
def post(self):
username = self.request.get('username')
password = self.request.get('password')
user = User.login(username, password)
if user:
self.login(user)
self.redirect('/blog/welcome')
else:
error = 'Invalid username and/or password.'
self.render('login.html', error=error, username=username)
class Logout(AppHandler):
"""
Handler to logout a user and delete the cookie.
"""
def get(self):
self.logout()
self.redirect('/blog/login')
class Welcome(AppHandler):
"""
Handler to display the welcome page after a user logs in.
"""
@login_required
def get(self):
user = User.by_id(self.user_id)
self.render('welcome.html', username=user.username)
class PermissionErr(AppHandler):
"""
Handler to show an error page.
"""
def get(self):
self.render('permissionerror.html')
# URL to handler mapping
app = webapp2.WSGIApplication([
(r'/blog/?', BlogPage),
(r'/blog/newpost/?', NewBlogPage),
(r'/blog/(\d+)/?', BlogEntryPage),
(r'/blog/(\d+)/edit/?', EditBlogPage),
(r'/blog/(\d+)/delete/?', DeleteBlogPage),
(r'/blog/(\d+)/togglelike/?', ToggleLike),
(r'/blog/(\d+)/addcomment/?', AddComment),
(r'/blog/comment/(\d+)/delete/?', DeleteComment),
(r'/blog/comment/(\d+)/edit/?', EditComment),
(r'/blog/signup/?', Register),
(r'/blog/login/?', Login),
(r'/blog/logout/?', Logout),
(r'/blog/welcome/?', Welcome),
(r'/blog/permissionerror/?', PermissionErr),
], debug=True)