-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.py~
530 lines (497 loc) · 16.9 KB
/
handlers.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
import re,time, json, logging, hashlib, base64, asyncio
from WebSK import get, post
import markdown2
from models import User, Comment, Blog, next_id
from apis import APIError,APIValueError,APIPermissionError,Page,APIResourceNotFoundError
from aiohttp import web
from config import configs
# @get('/')
# def index(request):
# users = yield from User.findAll()
# return {
# '__template__': 'test.html',
# 'users': users
# }
# @get('/')
# def index(request):
# summary = 'Hello This Sams Test!'
# blogs = [
# Blog(id='1', name='Test Blog1', summary=summary, created_at=time.time()-120),
# Blog(id='2', name='Test Blog2', summary=summary, created_at=time.time()-3600),
# Blog(id='3', name='Test Blog3', summary=summary, created_at=time.time()-7200)
# ]
# return {
# '__template__': 'blogs.html',
# 'blogs': blogs
# }
#
# # @get('/api/users')
# # def api_get_users():
# # users = yield from User.findAll(orderBy='created_at desc')
# # for u in users:
# # u.passwd = '******'
# # return dict(users=users)
# @get('/register')
# def register():
# return {
# '__template__': 'register.html'
# }
# @get('/signin')
# def signin():
# return {
# '__template__': 'signin.html'
# }
#
# @get('/manage/blogs/create')
# def manage_create_blog():
# return {
# '__template__': 'manage_blog_edit.html',
# 'id': '',
# 'action': '/api/blogs'
# }
#
# @get('/signout')
# def signout(request):
# referer = request.headers.get('Referer')
# r = web.HTTPFound(referer or '/')
# r.set_cookie(COOKIE_NAME, '-deleted-', max_age=0, httponly=True)
# logging.info('user signed out.')
# return r
#
# @get('/manage/blogs')
# def manage_blogs(*, page='1'):
# return {
# '__template__': 'manage_blogs.html',
# 'page_index': get_page_index(page)
# }
#
# @get('/blog/{id}')
# def get_blog(id):
# blog = yield from Blog.find(id)
# comments = yield from Comment.findAll('blog_id=?', [id], orderBy='created_at desc')
# for c in comments:
# c.html_content = text2html(c.content)
# blog.html_content = markdown2.markdown(blog.content)
# return {
# '__template__': 'blog.html',
# 'blog': blog,
# 'comments': comments
# }
#
# def check_admin(request):
# if request.__user__ is None or request.__user__.admin:
# raise APIPermissionError()
#
# #获取页数,主要是做一些容错处理
# def get_page_index(page_str):
# p = 1
# try:
# p = int(page_str)
# except ValueError as e:
# pass
# if p < 1:
# p = 1
# return p
#
# def text2html(text):
# lines = map(lambda s: '<p>%s</p>' % s.replace('&', '&').replace('<', '<').replace('>', '>'), filter(lambda s: s.strip() != '', text.split('\n')))
# return ''.join(lines)
# _RE_EMAIL = re.compile(r'^[a-z0-9\.\-\_]+\@[a-z0-9\-\_]+(\.[a-z0-9\-\_]+){1,4}$')
# _RE_SHA1 = re.compile(r'^[0-9a-f]{40}$')
#
# COOKIE_NAME = 'awesession'
# _COOKIE_KEY = configs.session.secret
#
# def user2cookie(user, max_age):
# '''
# Generate cookie str by user.
# '''
# # build cookie string by: id-expires-sha1
# expires = str(int(time.time() + max_age))
# s = '%s-%s-%s-%s' % (user.id, user.passwd, expires, _COOKIE_KEY)
# L = [user.id, expires, hashlib.sha1(s.encode('utf-8')).hexdigest()]
# return '-'.join(L)
#
# @asyncio.coroutine
# def cookie2user(cookie_str):
# '''
# Parse cookie and load user if cookie is valid.
# '''
# if not cookie_str:
# return None
# try:
# L = cookie_str.split('-')
# if len(L) != 3:
# return None
# uid, expires, sha1 = L
# if int(expires) < time.time():
# return None
# user = yield from User.find(uid)
# if user is None:
# return None
# s = '%s-%s-%s-%s' % (uid, user.passwd, expires, _COOKIE_KEY)
# if sha1 != hashlib.sha1(s.encode('utf-8')).hexdigest():
# logging.info('invalid sha1')
# return None
# user.passwd = '******'
# return user
# except Exception as e:
# logging.exception(e)
# return None
#
# @asyncio.coroutine
# def auth_factory(app, handler):
# @asyncio.coroutine
# def auth(request):
# logging.info('check user: %s %s' % (request.method, request.path))
# request.__user__ = None
# cookie_str = request.cookies.get(COOKIE_NAME)
# if cookie_str:
# user = yield from cookie2user(cookie_str)
# if user:
# logging.info('set current user: %s' % user.email)
# request.__user__ = user
# return (yield from handler(request))
# return auth
#
#
# @post('/api/authenticate')
# def authenticate(*, email, passwd):
# if not email:
# raise APIValueError('email', 'Invalid email.')
# if not passwd:
# raise APIValueError('passwd', 'Invalid password.')
# users = yield from User.findAll('email=?', [email])
# if len(users) == 0:
# raise APIValueError('email', 'Email not exist.')
# user = users[0]
# # check passwd:
# sha1 = hashlib.sha1()
# sha1.update(user.id.encode('utf-8'))
# sha1.update(b':')
# sha1.update(passwd.encode('utf-8'))
# if user.passwd != sha1.hexdigest():
# raise APIValueError('passwd', 'Invalid password.')
# # authenticate ok, set cookie:
# r = web.Response()
# r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True)
# user.passwd = '******'
# r.content_type = 'application/json'
# r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
# return r
#
# @post('/api/users')
# def api_register_user(*, email, name, passwd):
# if not name or not name.strip():
# raise APIValueError('name')
# if not email or not _RE_EMAIL.match(email):
# raise APIValueError('email')
# if not passwd or not _RE_SHA1.match(passwd):
# raise APIValueError('passwd')
# users = yield from User.findAll('email=?', [email])
# if len(users) > 0:
# raise APIError('register:failed', 'email', 'Email is already in use.')
# uid = next_id()
# sha1_passwd = '%s:%s' % (uid, passwd)
# user = User(id=uid, name=name.strip(), email=email, passwd=hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest(), image='http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email.encode('utf-8')).hexdigest())
# yield from user.save()
# # make session cookie:
# r = web.Response()
# r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True)
# user.passwd = '******'
# r.content_type = 'application/json'
# r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
# return r
#
# @post('/api/blogs')
# def api_create_blog(request, *, name, summary, content):
# check_admin(request)
# if not name or not name.strip():
# raise APIValueError('name', 'name cannot be empty.')
# if not summary or not summary.strip():
# raise APIValueError('summary', 'summary cannot be empty.')
# if not content or not content.strip():
# raise APIValueError('content', 'content cannot be empty.')
# blog = Blog(user_id=request.__user__.id, user_name=request.__user__.name, user_image=request.__user__.image, name=name.strip(), summary=summary.strip(), content=content.strip())
# yield from blog.save()
# return blog
#
# @get('/api/blogs')
# def api_blogs(*, page='1'):
# page_index = get_page_index(page)
# num = yield from Blog.findNumber('count(id)')
# p = Page(num, page_index)
# if num == 0:
# return dict(page=p, blogs=())
# blogs = yield from Blog.findAll(orderBy='created_at desc', limit=(p.offset, p.limit))
# return dict(page=p, blogs=blogs)
#
# @get('/api/blogs/{id}')
# def api_get_blog(*, id):
# blog = yield from Blog.find(id)
# return blog
COOKIE_NAME = 'awesession'
_COOKIE_KEY = configs.session.secret
def check_admin(request):
if request.__user__ is None or not request.__user__.admin:
raise APIPermissionError()
def get_page_index(page_str):
p = 1
try:
p = int(page_str)
except ValueError as e:
pass
if p < 1:
p = 1
return p
def user2cookie(user, max_age):
'''
Generate cookie str by user.
'''
# build cookie string by: id-expires-sha1
expires = str(int(time.time() + max_age))
s = '%s-%s-%s-%s' % (user.id, user.passwd, expires, _COOKIE_KEY)
L = [user.id, expires, hashlib.sha1(s.encode('utf-8')).hexdigest()]
return '-'.join(L)
def text2html(text):
lines = map(lambda s: '<p>%s</p>' % s.replace('&', '&').replace('<', '<').replace('>', '>'), filter(lambda s: s.strip() != '', text.split('\n')))
return ''.join(lines)
@asyncio.coroutine
def cookie2user(cookie_str):
'''
Parse cookie and load user if cookie is valid.
'''
if not cookie_str:
return None
try:
L = cookie_str.split('-')
if len(L) != 3:
return None
uid, expires, sha1 = L
if int(expires) < time.time():
return None
user = yield from User.find(uid)
if user is None:
return None
s = '%s-%s-%s-%s' % (uid, user.passwd, expires, _COOKIE_KEY)
if sha1 != hashlib.sha1(s.encode('utf-8')).hexdigest():
logging.info('invalid sha1')
return None
user.passwd = '******'
return user
except Exception as e:
logging.exception(e)
return None
@get('/')
def index(*, page='1'):
page_index = get_page_index(page)
num = yield from Blog.findNumber('count(id)')
page = Page(num)
if num == 0:
blogs = []
else:
blogs = yield from Blog.findAll(orderBy='created_at desc', limit=(page.offset, page.limit))
return {
'__template__': 'blogs.html',
'page': page,
'blogs': blogs
}
@get('/blog/{id}')
def get_blog(id):
blog = yield from Blog.find(id)
comments = yield from Comment.findAll('blog_id=?', [id], orderBy='created_at desc')
for c in comments:
c.html_content = text2html(c.content)
blog.html_content = markdown2.markdown(blog.content)
return {
'__template__': 'blog.html',
'blog': blog,
'comments': comments
}
@get('/register')
def register():
return {
'__template__': 'register.html'
}
@get('/signin')
def signin():
return {
'__template__': 'signin.html'
}
@post('/api/authenticate')
def authenticate(*, email, passwd):
if not email:
raise APIValueError('email', 'Invalid email.')
if not passwd:
raise APIValueError('passwd', 'Invalid password.')
users = yield from User.findAll('email=?', [email])
if len(users) == 0:
raise APIValueError('email', 'Email not exist.')
user = users[0]
# check passwd:
sha1 = hashlib.sha1()
sha1.update(user.id.encode('utf-8'))
sha1.update(b':')
sha1.update(passwd.encode('utf-8'))
if user.passwd != sha1.hexdigest():
raise APIValueError('passwd', 'Invalid password.')
# authenticate ok, set cookie:
r = web.Response()
r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True)
user.passwd = '******'
r.content_type = 'application/json'
r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
return r
@get('/signout')
def signout(request):
referer = request.headers.get('Referer')
r = web.HTTPFound(referer or '/')
r.set_cookie(COOKIE_NAME, '-deleted-', max_age=0, httponly=True)
logging.info('user signed out.')
return r
@get('/manage/')
def manage():
return 'redirect:/manage/comments'
@get('/manage/comments')
def manage_comments(*, page='1'):
return {
'__template__': 'manage_comments.html',
'page_index': get_page_index(page)
}
@get('/manage/blogs')
def manage_blogs(*, page='1'):
return {
'__template__': 'manage_blogs.html',
'page_index': get_page_index(page)
}
@get('/manage/blogs/create')
def manage_create_blog():
return {
'__template__': 'manage_blog_edit.html',
'id': '',
'action': '/api/blogs'
}
@get('/manage/blogs/edit')
def manage_edit_blog(*, id):
return {
'__template__': 'manage_blog_edit.html',
'id': id,
'action': '/api/blogs/%s' % id
}
@get('/manage/users')
def manage_users(*, page='1'):
return {
'__template__': 'manage_users.html',
'page_index': get_page_index(page)
}
@get('/api/comments')
def api_comments(*, page='1'):
page_index = get_page_index(page)
num = yield from Comment.findNumber('count(id)')
p = Page(num, page_index)
if num == 0:
return dict(page=p, comments=())
comments = yield from Comment.findAll(orderBy='created_at desc', limit=(p.offset, p.limit))
return dict(page=p, comments=comments)
@post('/api/blogs/{id}/comments')
def api_create_comment(id, request, *, content):
user = request.__user__
if user is None:
raise APIPermissionError('Please signin first.')
if not content or not content.strip():
raise APIValueError('content')
blog = yield from Blog.find(id)
if blog is None:
raise APIResourceNotFoundError('Blog')
comment = Comment(blog_id=blog.id, user_id=user.id, user_name=user.name, user_image=user.image, content=content.strip())
yield from comment.save()
return comment
@post('/api/comments/{id}/delete')
def api_delete_comments(id, request):
check_admin(request)
c = yield from Comment.find(id)
if c is None:
raise APIResourceNotFoundError('Comment')
yield from c.remove()
return dict(id=id)
@get('/api/users')
def api_get_users(*, page='1'):
page_index = get_page_index(page)
num = yield from User.findNumber('count(id)')
p = Page(num, page_index)
if num == 0:
return dict(page=p, users=())
users = yield from User.findAll(orderBy='created_at desc', limit=(p.offset, p.limit))
for u in users:
u.passwd = '******'
return dict(page=p, users=users)
_RE_EMAIL = re.compile(r'^[a-z0-9\.\-\_]+\@[a-z0-9\-\_]+(\.[a-z0-9\-\_]+){1,4}$')
_RE_SHA1 = re.compile(r'^[0-9a-f]{40}$')
@post('/api/users')
def api_register_user(*, email, name, passwd):
if not name or not name.strip():
raise APIValueError('name')
if not email or not _RE_EMAIL.match(email):
raise APIValueError('email')
if not passwd or not _RE_SHA1.match(passwd):
raise APIValueError('passwd')
users = yield from User.findAll('email=?', [email])
if len(users) > 0:
raise APIError('register:failed', 'email', 'Email is already in use.')
uid = next_id()
sha1_passwd = '%s:%s' % (uid, passwd)
user = User(id=uid, name=name.strip(), email=email, passwd=hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest(), image='../static/img/user.png' % hashlib.md5(email.encode('utf-8')).hexdigest())
yield from user.save()
# make session cookie:
r = web.Response()
r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True)
user.passwd = '******'
r.content_type = 'application/json'
r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
return r
@get('/api/blogs')
def api_blogs(*, page='1'):
page_index = get_page_index(page)
num = yield from Blog.findNumber('count(id)')
p = Page(num, page_index)
if num == 0:
return dict(page=p, blogs=())
blogs = yield from Blog.findAll(orderBy='created_at desc', limit=(p.offset, p.limit))
return dict(page=p, blogs=blogs)
@get('/api/blogs/{id}')
def api_get_blog(*, id):
blog = yield from Blog.find(id)
return blog
@post('/api/blogs')
def api_create_blog(request, *, name, summary, content):
check_admin(request)
if not name or not name.strip():
raise APIValueError('name', 'name cannot be empty.')
if not summary or not summary.strip():
raise APIValueError('summary', 'summary cannot be empty.')
if not content or not content.strip():
raise APIValueError('content', 'content cannot be empty.')
blog = Blog(user_id=request.__user__.id, user_name=request.__user__.name, user_image=request.__user__.image, name=name.strip(), summary=summary.strip(), content=content.strip())
yield from blog.save()
return blog
@post('/api/blogs/{id}')
def api_update_blog(id, request, *, name, summary, content):
check_admin(request)
blog = yield from Blog.find(id)
if not name or not name.strip():
raise APIValueError('name', 'name cannot be empty.')
if not summary or not summary.strip():
raise APIValueError('summary', 'summary cannot be empty.')
if not content or not content.strip():
raise APIValueError('content', 'content cannot be empty.')
blog.name = name.strip()
blog.summary = summary.strip()
blog.content = content.strip()
yield from blog.update()
return blog
@post('/api/blogs/{id}/delete')
def api_delete_blog(request, *, id):
check_admin(request)
blog = yield from Blog.find(id)
yield from blog.remove()
return dict(id=id)