1
2
3
4
5
6 import re
7 import urlparse
8 try:
9 from urlparse import parse_qsl
10 except ImportError:
11 from cgi import parse_qsl
12
13 from restkit.util.oauth2 import Consumer, Request, SignatureMethod_HMAC_SHA1,\
14 Token
15
17 """ validate a consumer agains oauth2.Consumer object """
18 if not isinstance(consumer, Consumer):
19 raise ValueError("Invalid consumer.")
20 return consumer
21
23 """ validate a token agains oauth2.Token object """
24 if token is not None and not isinstance(token, Token):
25 raise ValueError("Invalid token.")
26 return token
27
28
30
31 - def __init__(self, path, consumer, token=None, method=None):
32 """ Init OAuthFilter
33
34 :param path: path or regexp. * mean all path on wicth oauth can be
35 applied.
36 :param consumer: oauth consumer, instance of oauth2.Consumer
37 :param token: oauth token, instance of oauth2.Token
38 :param method: oauth signature method
39
40 token and method signature are optionnals. Consumer should be an
41 instance of `oauth2.Consumer`, token an instance of `oauth2.Toke`
42 signature method an instance of `oauth2.SignatureMethod`.
43
44 """
45
46 if path.endswith('*'):
47 self.match = re.compile("%s.*" % path.rsplit('*', 1)[0])
48 else:
49 self.match = re.compile("%s$" % path)
50 self.consumer = validate_consumer(consumer)
51 self.token = validate_token(token)
52 self.method = method or SignatureMethod_HMAC_SHA1()
53
55 path = req.uri.path or "/"
56 return (self.match.match(path) is not None)
57
59 if not self.on_path(req):
60 return
61
62 headers = dict(req.headers)
63 params = {}
64 form = False
65 if req.body and req.body is not None:
66 ctype = headers.get('Content-Type')
67 if ctype is not None and \
68 ctype.startswith('application/x-www-form-urlencoded'):
69
70 form = True
71 params = dict(parse_qsl(req.body))
72
73
74 params.update(parse_qsl(req.uri.query))
75
76 oauth_req = Request.from_consumer_and_token(self.consumer,
77 token=self.token, http_method=req.method,
78 http_url=req.url, parameters=params)
79
80 oauth_req.sign_request(self.method, self.consumer, self.token)
81
82 if form:
83 req.body = oauth_req.to_postdata()
84 elif req.method in ('GET', 'HEAD'):
85 req.url = req.final_url = oauth_req.to_url()
86 req.uri = urlparse.urlparse(req.url)
87 else:
88 oauth_headers = oauth_req.to_header()
89 for k, v in list(oauth_headers.items()):
90 if not isinstance(v, basestring):
91 v = str(v)
92 req.headers.append((k.title(), v))
93