-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblog.py
365 lines (315 loc) · 11.5 KB
/
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
import webapp2
import logging
import re
import jinja2
import os
from google.appengine.ext import db
import time
from random import randint
import cgi
import hashlib
import hmac
import urllib2
from xml.dom import minidom
import json
from datetime import datetime, timedelta
from google.appengine.api import memcache
def get_coords(ip):
page = urllib2.urlopen("http://freegeoip.net/xml/" + ip)
dom = minidom.parseString(page.read())
countryCode = dom.getElementsByTagName("CountryCode")[0].childNodes
if countryCode.length > 0:
latitude = dom.getElementsByTagName("Latitude")[0].childNodes[0].nodeValue
longitude = dom.getElementsByTagName("Longitude")[0].childNodes[0].nodeValue
return db.GeoPt(latitude, longitude)
return None
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'])
userre = re.compile(r"^([a-z0-9_\-A-Z]{3,20})");
passre = re.compile(r"^(.{3,20})");
emailre= re.compile(r"^(.{1,20}@.{1,20}\..{1,20})")
def hash_str(s):
return hmac.new("imsosecret",str(s)).hexdigest()
def make_secure_val(s):
return str(str(s)+"|"+hash_str(s))
def check_secure_val(h):
s,ha=h.split('|')
has=hash_str(s)
if ha==has:
return s
else:
return None
def make_salt():
h=""
while len(h)<25:
h=h+str(randint(0, 9))
return h
def make_pw_hash(name, pw, salt=None):
if not salt:
salt=make_salt()
hashs = hash_str(name+""+pw+""+salt)
rstring=hashs+"|"+salt
return rstring
def valid_pw(name,pw,h):
code,salt = h.split('|')
check=make_pw_hash(name,pw,salt)
logging.info("check:"+check)
if h==check:
return True
return False
def validate():
userhash = self.request.cookies.get('userid', None)
i,j = userhash.split('|')
if userhash:
if check_secure_val(userhash):
return Users.get_by_id(i).username
self.redirect('/blog/signup')
def mc_set(key, val):
mcTime=datetime.utcnow()
memcache.set(key,(val, mcTime))
return None
def mc_get(key):
if memcache.get(key):
val,mcTime = memcache.get(key)
age=(datetime.utcnow() - mcTime).total_seconds()
return (val,age)
else:
return (None,0)
def top_post(update):
post,time=mc_get('hit')
if post == None or update:
logging.info(">>> DATABASE ACCESS <<<")
posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC Limit 10" )
mc_set('hit',posts)
return mc_get('hit')
else:
logging.info(">>> CACHE HIT <<<")
return mc_get('hit')
def age_str(age):
s = 'DB accessed %s seconds ago'
age = int(age)
if age == 1:
s = s.replace('seconds', 'second')
return s % age
class Post(db.Model):
subject = db.StringProperty()
blog = db.TextProperty()
created = db.DateTimeProperty(auto_now_add=True)
coords = db.GeoPtProperty()
def as_dict(self):
time_fmt = '%c'
d = {'subject' : self.subject, 'content' : self.blog, 'created' : self.created.strftime(time_fmt)}
return d
class Users(db.Model):
username=db.StringProperty()
passhash=db.StringProperty()
email=db.StringProperty()
class MyHandler(webapp2.RequestHandler):
def write(self, *writeArgs):
self.response.write(" : ".join(writeArgs))
def render_str(self, template, **params):
tplt = JINJA_ENVIRONMENT.get_template('templates/'+template)
return tplt.render(params)
def render(self, template, **kw):
self.write(self.render_str(template, **kw))
def render_json(self, d):
json_txt = json.dumps(d)
self.response.headers['Content-Type'] = 'application/json; charset=UTF-8'
self.write(json_txt)
class MainPage(MyHandler):
def get(self, subject="", blog="", error="", update=""):
userhash=self.request.cookies.get('userid','DNE')
logging.info(userhash)
template_values={}
if not userhash=='DNE' and not userhash=='' and check_secure_val(userhash):
loggedUser = Users.get_by_id(int(check_secure_val(userhash)))
posts,mcTime = top_post(update)
mcTime=age_str(mcTime)
if self.request.url.endswith('.json'):
self.render_json([post.as_dict() for post in posts])
else:
self.render("posts.html", posts=posts, username=loggedUser.username, age=mcTime)
else:
posts,mcTime = top_post(update)
if self.request.url.endswith('.json'):
self.render_json([post.as_dict() for post in posts])
else:
self.render("posts.html", posts=posts, age=mcTime)
class EntryPage(MyHandler):
def get(self, product_id):
userhash=self.request.cookies.get('userid','DNE')
if userhash=='DNE' or userhash=='' or not check_secure_val(userhash):
self.redirect('/blog')
else:
newprod,mcTime=mc_get(product_id)
if newprod==None:
mc_set(product_id,Post.get_by_id(int(product_id)))
newprod,mcTime=mc_get(product_id)
mcTime=age_str(mcTime)
loggedUser = Users.get_by_id(int(check_secure_val(userhash)))
if self.request.url.endswith('.json'):
self.render_json([newprod.as_dict()])
else:
self.render("npst.html", post=newprod, username=loggedUser.username, age=mcTime)
class NewPage(MyHandler):
def get(self):
userhash=self.request.cookies.get('userid','DNE')
if userhash=='DNE' or userhash=='' or not check_secure_val(userhash):
self.redirect('/blog')
else:
loggedUser = Users.get_by_id(int(check_secure_val(userhash)))
self.render("newpost.html", username=loggedUser.username)
def post(self):
error=""
subject = self.request.get('subject')
blog = self.request.get('content')
ip = self.request.get('location')
userhash=self.request.cookies.get('userid','DNE')
if(len(subject)==0 or len(blog)==0):
error="Need both a subject and text!"
if userhash=='DNE' or userhash=='' or not check_secure_val(userhash):
self.redirect('/blog')
loggedUser = Users.get_by_id(int(check_secure_val(userhash)))
self.render("newpost.html",error=error)
else:
postInst = Post()
postInst.coords = get_coords(ip)
postInst.subject=subject
postInst.blog=blog
postInst.put()
time.sleep(0.2)
top_post(update=True)
self.redirect("/blog/"+str(postInst.key().id()))
class SignupPage(MyHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/html'
template_values = {"username": "","password": "", "verify":"", "email": "", "eusername":"", "everify":"", "epassword":"","eemail":""}
template = JINJA_ENVIRONMENT.get_template('templates/index.htm')
self.response.write(template.render(template_values))
def post(self):
success=True;
eu="";
ep="";
ee="";
ev="";
User=self.request.get("username");
Pass=self.request.get("password");
Veri=self.request.get("verify");
Emai=self.request.get("email");
if(not(re.search(userre,User))):
eu="Incorrect Username";
success=False;
if(not(re.search(passre,Pass))):
ep="Incorrect Password";
success=False;
if(not(Pass==Veri)):
ev="The password does not match";
success=False;
if(len(Emai)>0 and not(re.search(emailre,Emai))):
ee="That is not a valid password"
success=False;
if success and not db.GqlQuery("SELECT * FROM Users WHERE username = '%s'" % User).count():
userInst=Users()
userInst.username=User
userInst.passhash=make_pw_hash(User,Pass)
userInst.put()
userInstId=str(userInst.key().id())
self.response.headers.add_header('Set-Cookie', 'userid=%s; Path=/; Max-Age=86400' % make_secure_val(userInstId))
self.redirect("/blog/success")
elif db.GqlQuery("SELECT * FROM Users WHERE username = '%s'" % User).count():
logging.info(User)
eu="This username has been taken"
template_values={"username": User,"password": "", "verify":"", "email": Emai, "eusername":eu, "everify":ev, "epassword":ep,"eemail":ee}
template = JINJA_ENVIRONMENT.get_template('templates/index.htm')
self.response.write(template.render(template_values))
else:
template_values={"username": User,"password": "", "verify":"", "email": Emai, "eusername":eu, "everify":ev, "epassword":ep,"eemail":ee}
template = JINJA_ENVIRONMENT.get_template('templates/index.htm')
self.response.write(template.render(template_values))
class WelcomePage(MyHandler):
def get(self):
userhash=self.request.cookies.get('userid','DNE')
if not userhash=='DNE' and check_secure_val(userhash):
loggedUser = Users.get_by_id(int(check_secure_val(userhash)))
template_values = {"name": loggedUser.username, "username": loggedUser.username}
template = JINJA_ENVIRONMENT.get_template('templates/success.htm')
self.write(template.render(template_values))
else:
self.redirect("/blog/signup")
class LoginPage(MyHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/html'
self.render('login.htm')
def post(self):
success=True;
eu="";
ep="";
User=self.request.get("username");
Pass=self.request.get("password");
if(not(re.search(userre,User))):
eu="Incorrect Username";
success=False;
if(not(re.search(passre,Pass))):
ep="Incorrect Password";
success=False;
if not success:
template_values = {"username": User,"password": "", "eusername":eu, "epassword":ep}
template = JINJA_ENVIRONMENT.get_template('templates/login.htm')
self.response.write(template.render(template_values))
else:
if db.GqlQuery("SELECT * FROM Users WHERE username = '%s'" % User).count()==1:
loggedUser = db.GqlQuery("SELECT * FROM Users WHERE username = '%s'" % User).get()
loggedUserPassword=loggedUser.passhash
if valid_pw(User,Pass,loggedUserPassword):
usid=loggedUser.key().id()
self.response.headers.add_header('Set-Cookie', 'userid=%s; Path=/; Max-Age=86400' % make_secure_val(usid))
self.redirect("/blog/success")
else:
template_values = {"username": User,"password": "", "eusername":eu, "epassword":"invalid password"}
template = JINJA_ENVIRONMENT.get_template('templates/login.htm')
self.response.write(template.render(template_values))
else:
template_values = {"username": User,"password": "", "eusername":eu, "epassword":"no such user"}
template = JINJA_ENVIRONMENT.get_template('templates/login.htm')
self.response.write(template.render(template_values))
class RedirectPage(MyHandler):
def get(self):
self.redirect('/blog')
class LogoutPage(MyHandler):
def get(self):
self.response.headers.add_header('Set-Cookie', 'userid=; Path=/; Max-Age=86400')
self.redirect('/blog/login')
class MapPage(MyHandler):
def get(self):
userhash=self.request.cookies.get('userid','DNE')
if userhash=='DNE' or userhash=='' or not check_secure_val(userhash):
self.redirect('/blog')
else:
posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC limit 5")
markers=""
for post in posts:
logging.info(post.coords)
if post.coords != None:
markers=markers+"&markers="+str(post.coords.lat)+","+str(post.coords.lon)
url = "http://maps.googleapis.com/maps/api/staticmap?size=800x600&sensor=false%s"%markers
logging.info(url)
urllib2.urlopen(url).read()
loggedUser = Users.get_by_id(int(check_secure_val(userhash)))
self.render("map.html",url=url,username=loggedUser.username)
class FlushPage(MyHandler):
def get(self):
memcache.flush_all()
self.redirect('/blog')
application = webapp2.WSGIApplication([
(r'^/blog/newpost/?$', NewPage),
(r'^/blog/?(?:\.json)?', MainPage),
(r'^/blog/(\d+)/?(?:\.json)?', EntryPage),
(r'^/blog/signup/?$', SignupPage),
(r'^/blog/success/?$', WelcomePage),
(r'^/blog/login/?$', LoginPage),
('/', RedirectPage),
(r'^/blog/logout/?$', LogoutPage),
(r'^/blog/map/?$', MapPage),
(r'^/blog/flush/?$',FlushPage),
], debug=True)