-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
422 lines (342 loc) · 10.9 KB
/
main.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
#!/usr/bin/env python
#
# Copyright 2007 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 webapp2
import jinja2
import os
import hashlib
import hmac
import random
import string
import urllib2
import json
import logging
from google.appengine.api import memcache
from valid_credentials import valid_username, valid_password, valid_email
from google.appengine.ext import db
SECRET = 'du.uyX9fE~Tb6.pp&U3D-OsmYO,Gqi$^S34tzu9'
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
autoescape = True)
def make_pw_secure_val(name,pw,salt = None):
if not salt:
salt = make_salt(5)
hash_val = hashlib.sha256(name + pw + salt).hexdigest()
return "%s|%s" % (salt,hash_val)
# returns boolean values
def check_pw_secure_val(name,pw,pw_secure_val):
salt = pw_secure_val.split('|')[0]
return pw_secure_val == make_pw_secure_val(name,pw,salt)
def make_salt(length):
salt = ''.join(random.choice(string.letters) for x in xrange(length))
return salt
def hash_str(val):
return hmac.new(SECRET, val).hexdigest()
def make_secure_val(val):
return "%s|%s" % (val,hash_str(val))
# returns the un-encrypted value
def check_secure_val(secure_val):
val = secure_val.split('|')[0]
if secure_val == make_secure_val(val):
return val
IP_URL = "http://api.ipinfodb.com/v3/ip-city/?key=8b02066bc60c1f1cf9857134f72c8c1ea5a5a6bd73760151e673bafae9b488ef&ip=%s&format=json"
def get_coords(ip):
url = IP_URL % (ip)
content = None
try:
content = urllib2.urlopen(url).read()
except URLError:
return
if content:
j = json.loads(content)
lon = j['longitude']
lat = j['latitude']
return db.GeoPt(lat, lon)
GMAPS_URL = 'http://maps.googleapis.com/maps/api/staticmap?size=600x300&sensor=false&'
def gmaps_img(points):
markers = '&'.join('markers=%s,%s' % (p.lat, p.lon)
for p in points)
return GMAPS_URL + markers
def render_str(template, **params):
t = jinja_env.get_template(template)
return t.render(params)
class Post(db.Model):
subject = db.StringProperty(required = True)
content = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
user_id = db.StringProperty(required = True)
coords = db.GeoPtProperty()
def render(self):
self._render_text = self.content.replace('\n','<br>')
self.username = User.by_id(int(self.user_id)).name
return render_str('post.html',post = self)
@classmethod
def by_id(cls,pid):
return cls.get_by_id(pid)
class User(db.Model):
name = db.StringProperty(required = True)
pw_secure_val = db.StringProperty(required = True)
email = db.StringProperty()
@classmethod
def by_id(cls,uid):
return cls.get_by_id(uid)
@classmethod
def by_name(cls,name):
return cls.all().filter('name = ',name).get()
@classmethod
def register(cls,name, pw, email):
pw_secure_val = make_pw_secure_val(name,pw)
return User(name = name,
pw_secure_val = pw_secure_val,
email = email)
@classmethod
def login(cls,name,pw):
u = cls.by_name(name)
if u and check_pw_secure_val(name,pw,u.pw_secure_val):
return u
class Feedback(db.Model):
user_id = db.StringProperty(required = True)
content = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
def render(self):
self._render_text = self.content.replace('\n','<br>')
self.username = User.by_id(int(self.user_id)).name
return render_str('feedback.html',feedback = self)
class Comment(db.Model):
user_id = db.StringProperty(required = True)
post_id = db.StringProperty(required = True)
content = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
def render(self):
self._render_text = self.content.replace('\n','<br>')
self.username = User.by_id(int(self.user_id)).name
return render_str('comment.html',comment = self)
class BaseHandler(webapp2.RequestHandler):
def write(self, *args, **kwargs):
self.response.out.write(*args, **kwargs)
def render(self, template, **kwargs):
self.write(render_str(template, **kwargs))
def set_secure_cookie(self,name,val):
cookie_val = make_secure_val(val)
self.response.headers.add_header('Set-Cookie','%s=%s ; Path=/' % (name,cookie_val))
# returns the un-encrypted value
def read_secure_cookie(self,name):
cookie_val = self.request.cookies.get(name)
return cookie_val and check_secure_val(cookie_val)
# sets the user_id cookie to point to a user
def login(self,user):
self.set_secure_cookie('user_id', str(user.key().id()))
def logout(self):
self.set_secure_cookie('user_id','')
# runs before each request and stores the current logged in
# user in self.user which is inherited to other functions
def initialize(self, *args, **kwargs):
webapp2.RequestHandler.initialize(self, *args, **kwargs)
uid = self.read_secure_cookie('user_id')
self.user = None
if uid and User.by_id(int(uid)):
self.user = User.by_id(int(uid))
class MainHandler(BaseHandler):
def get(self):
if self.user:
self.redirect('/blog')
else:
self.render('index.html')
class Signup(BaseHandler):
def get(self):
self.render('signup-form.html')
def post(self):
has_error = False
self.username = self.request.get('username')
self.password = self.request.get('password')
self.verify = self.request.get('verify')
self.password = self.request.get('password')
self.email = self.request.get('email')
msg = 'Enter a valid %s'
params = dict(username = self.username,
email = self.email)
if not valid_username(self.username):
has_error = True
params['error_username'] = msg % 'username'
if valid_password(self.password):
if self.password.lower() == 'password':
has_error = True
params['error_password'] = "Password can't be equal to 'password'"
elif self.password.lower() == self.username.lower():
has_error = True
params['error_password'] = "password can't be equal to username"
elif not self.verify == self.password:
has_error = True
params['error_verify'] = "passwords don't match"
else:
has_error = True
params['error_password'] = msg % 'password'
if self.email and (not valid_email(self.email)):
has_error = True
params['error_email'] = msg % 'email'
if has_error:
self.render('signup-form.html', **params)
else:
self.done()
class RegisterHandler(Signup):
def done(self):
u = User.by_name(self.username)
if u:
msg = 'user already exists'
self.render('signup-form.html',error_username = msg)
else:
u = User.register(self.username,self.password,self.email)
u.put()
self.login(u)
self.redirect('/welcome')
class LoginHandler(BaseHandler):
def get(self):
self.logout()
self.render('login-form.html')
def post(self):
username = self.request.get('username')
password = self.request.get('password')
u = User.login(username,password)
if u:
self.login(u)
self.redirect('/blog')
else:
msg = 'invalid login'
self.render('login-form.html',error = msg)
class LogoutHandler(BaseHandler):
def get(self):
if self.user:
self.logout()
self.render('logout.html')
else:
self.write('No user logged in')
class WelcomeHandler(BaseHandler):
def get(self):
if self.user:
self.render('welcome.html',username = self.user.name)
else:
self.redirect('/')
def top_posts(update = False):
key = 'top'
posts = memcache.get(key)
if posts is None or update:
logging.error('DB QUERY')
posts = db.GqlQuery("select * from Post order by created desc")
posts = list(posts)
memcache.set(key, posts)
return posts
class BlogHandler(BaseHandler):
def get(self):
if self.user:
posts = top_posts()
points = []
for p in posts:
if p.coords:
points.append(p.coords)
img_url = None
if points:
img_url = gmaps_img(points)
self.render('front.html',posts = posts, img_url = img_url)
else:
self.redirect('/')
class NewPost(BaseHandler):
def get(self):
if self.user:
self.render('newpost.html')
else:
self.redirect('/')
def post(self):
subject = self.request.get('subject')
content = self.request.get('content')
user_id = str(self.user.key().id())
if subject and content:
p = Post(subject = subject,content = content,user_id = user_id)
# look up user's co-ordinates from ip
# if we have co-ordinates, add them to the Art
coords = get_coords(self.request.remote_addr)
if coords:
p.coords = coords
p.put()
post_id = str(p.key().id())
top_posts(True)
self.redirect('/blog/%s' % post_id)
else:
error = "Enter both subject and content!!!"
self.render('newpost.html',error = error)
class UserPage(BaseHandler):
def get(self,user_id):
if self.user:
posts = db.GqlQuery("select * from Post WHERE user_id='%s' order by created desc" % user_id)
self.render('postbyuser.html',elements = posts, username = User.by_id(int(user_id)).name)
else:
self.redirect('/')
class PostPage(BaseHandler):
def get(self,post_id):
if self.user:
key = db.Key.from_path('Post',int(post_id))
post = db.get(key)
if not post:
self.error(404)
return
comments = db.GqlQuery("select * from Comment WHERE post_id='%s'" % post_id)
self.render('permalink.html', post = post, comments = comments)
else:
self.redirect('/')
def post(self,post_id):
user_id = str(self.user.key().id())
content = self.request.get('content')
if content:
c = Comment(user_id = user_id,post_id = post_id,content = content)
c.put()
self.redirect('/blog/%s' % post_id)
else:
self.redirect('/blog/%s' % post_id)
class FeedbackPost(BaseHandler):
def get(self):
if self.user:
self.render('newfeedback.html')
else:
self.redirect('/')
def post(self):
content = self.request.get('content')
user_id = str(self.user.key().id())
if content:
f = Feedback(user_id = user_id,content = content)
f.put()
self.redirect('/exit')
else:
error = "Enter some content!!!"
self.render('newfeedback.html',error = error)
class SeeFeedbackHandler(BaseHandler):
def get(self):
if self.user and self.user.name == 'asutosh':
feedbacks = db.GqlQuery("select * from Feedback order by created desc")
self.render('feedback-front.html',feedbacks = feedbacks)
else:
self.redirect('/')
app = webapp2.WSGIApplication([
('/', MainHandler),
('/login', LoginHandler),
('/blog', BlogHandler),
('/logout', FeedbackPost),
('/feedbacks',SeeFeedbackHandler),
('/exit',LogoutHandler),
('/signup', RegisterHandler),
('/blog/newpost', NewPost),
('/blog/([0-9]+)', PostPage),
('/user/([0-9]+)', UserPage),
('/welcome',WelcomeHandler)
], debug=True)