forked from asvetlov/aiohttp-csrf
-
Notifications
You must be signed in to change notification settings - Fork 7
/
manual_protection.py
68 lines (50 loc) · 1.67 KB
/
manual_protection.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
import aiohttp_csrf
from aiohttp import web
FORM_FIELD_NAME = '_csrf_token'
COOKIE_NAME = 'csrf_token'
def make_app():
csrf_policy = aiohttp_csrf.policy.FormPolicy(FORM_FIELD_NAME)
csrf_storage = aiohttp_csrf.storage.CookieStorage(COOKIE_NAME)
app = web.Application()
aiohttp_csrf.setup(app, policy=csrf_policy, storage=csrf_storage)
# IMPORTANT! You need use @csrf_protect for both methods: GET and POST
@aiohttp_csrf.csrf_protect
async def handler_get(request):
token = await aiohttp_csrf.generate_token(request)
body = '''
<html>
<head><title>Form with csrf protection</title></head>
<body>
<form method="POST" action="/">
<input type="hidden" name="{field_name}" value="{token}" />
<input type="text" name="name" />
<input type="submit" value="Say hello">
</form>
</body>
</html>
''' # noqa
body = body.format(field_name=FORM_FIELD_NAME, token=token)
return web.Response(
body=body.encode('utf-8'),
content_type='text/html',
)
@aiohttp_csrf.csrf_protect
async def handler_post(request):
post = await request.post()
body = 'Hello, {name}'.format(name=post['name'])
return web.Response(
body=body.encode('utf-8'),
content_type='text/html',
)
app.router.add_route(
'GET',
'/',
handler_get,
)
app.router.add_route(
'POST',
'/',
handler_post,
)
return app
web.run_app(make_app())