1
2
3
4
5
6 import base64
7 import re
8 try:
9 from urlparse import parse_qsl
10 except ImportError:
11 from cgi import parse_qsl
12 from urlparse import urlunparse
13
14 from restkit.oauth2 import Request, SignatureMethod_HMAC_SHA1
15
17 """ Simple filter to manage basic authentification"""
18
20 self.credentials = (username, password)
21
25
27 """ validate a consumer agains oauth2.Consumer object """
28 if not hasattr(consumer, "key"):
29 raise ValueError("Invalid consumer.")
30 return consumer
31
33 """ validate a token agains oauth2.Token object """
34 if token is not None and not hasattr(token, "key"):
35 raise ValueError("Invalid token.")
36 return token
37
38
40 """ oauth filter """
41
42 - def __init__(self, path, consumer, token=None, method=None,
43 realm=""):
44 """ Init OAuthFilter
45
46 :param path: path or regexp. * mean all path on wicth oauth can be
47 applied.
48 :param consumer: oauth consumer, instance of oauth2.Consumer
49 :param token: oauth token, instance of oauth2.Token
50 :param method: oauth signature method
51
52 token and method signature are optionnals. Consumer should be an
53 instance of `oauth2.Consumer`, token an instance of `oauth2.Toke`
54 signature method an instance of `oauth2.SignatureMethod`.
55
56 """
57
58 if path.endswith('*'):
59 self.match = re.compile("%s.*" % path.rsplit('*', 1)[0])
60 else:
61 self.match = re.compile("%s$" % path)
62 self.consumer = validate_consumer(consumer)
63 self.token = validate_token(token)
64 self.method = method or SignatureMethod_HMAC_SHA1()
65 self.realm = realm
66
70
72 if not self.on_path(request):
73 return
74
75 params = {}
76 form = False
77 parsed_url = request.parsed_url
78
79 if request.body and request.body is not None:
80 ctype = request.headers.iget('content-type')
81 if ctype is not None and \
82 ctype.startswith('application/x-www-form-urlencoded'):
83
84 form = True
85 params = dict(parse_qsl(request.body))
86
87
88 params.update(parse_qsl(parsed_url.query))
89
90 raw_url = urlunparse((parsed_url.scheme, parsed_url.netloc,
91 parsed_url.path, '', '', ''))
92
93 oauth_req = Request.from_consumer_and_token(self.consumer,
94 token=self.token, http_method=request.method,
95 http_url=raw_url, parameters=params)
96
97 oauth_req.sign_request(self.method, self.consumer, self.token)
98
99 if form:
100 request.body = oauth_req.to_postdata()
101
102 request.headers['Content-Length'] = len(request.body)
103 elif request.method in ('GET', 'HEAD'):
104 request.original_url = request.url
105 request.url = oauth_req.to_url()
106 else:
107 oauth_headers = oauth_req.to_header(realm=self.realm)
108 request.headers.update(oauth_headers)
109