-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathREADME
More file actions
67 lines (49 loc) · 2.17 KB
/
README
File metadata and controls
67 lines (49 loc) · 2.17 KB
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
A Python helper module to have protected web APIs. This uses a simple secret key, without which the web APIs will restrict users. Thus, only authenticated users possessing the secret key can use the a web API.
This uses HMAC MD5, with a secret key to work.
Quickstart
==========
import web_auth_helper
SECRET = 'My Secret key'
# The encoded message.
s = web_auth_helper.encode(serializable_python_object, SECRET)
# Decode the encoded message.
original_object = web_auth_helper.decode(s, SECRET)
A sample usage is given below (with respect to Django)
======================================================
SECRET = 'This is a sample string used as secret key.'
------------------------------------------------------
from web_auth_helper import encode
import urlib
url = 'http://example.com/api/publish-stream/'
params = { \
'id': 111, \
'content': 'This is a sample content.' \
}
signed_request = encode(params, SECRET)
r = urllib.urlopen(url, urllib.urlencode({'signed_request': signed_request}))
r.read()
------------------------------------------------------
from web_auth_helper import decode, DecodeException
@csrf_exempt
def publish_stream_handler(request):
if request.method == 'POST':
if not request.POST.has_key('signed_request'):
return HttpResponseBadRequest('Required parameters not provided.')
else:
try:
request_params = decode(request.POST['signed_request'], SECRET)
except DecodeException:
return HttpResponseForbidden('Your request is not allowed.')
return _do_something_with_params(request_params)
else:
return HttpResponseNotAllowed(['POST'])
------------------------------------------------------
Using the 'web_api' decorator in Django views (without any extra modification)
==============================================================================
from django_helper import web_api
@csrf_exempt
@web_api(request_parameter_name='signed_request', secret_key=SECRET)
def publish_stream_handler(request):
# request.REQUEST and, request.GET or request.POST dictionaries updated
# to contain the encoded parameters.
return _do_whatever_required(request)