]> jfr.im git - z_archive/twitter.git/blob - twitter/auth.py
If invalid values are passed for secrets, raise an exception with a helpful error...
[z_archive/twitter.git] / twitter / auth.py
1 try:
2 import urllib.parse as urllib_parse
3 from base64 import encodebytes
4 except ImportError:
5 import urllib as urllib_parse
6 from base64 import encodestring as encodebytes
7
8
9 class Auth(object):
10 """
11 ABC for Authenticator objects.
12 """
13
14 def encode_params(self, base_url, method, params):
15 """Encodes parameters for a request suitable for including in a URL
16 or POST body. This method may also add new params to the request
17 if required by the authentication scheme in use."""
18 raise NotImplementedError()
19
20 def generate_headers(self):
21 """Generates headers which should be added to the request if required
22 by the authentication scheme in use."""
23 raise NotImplementedError()
24
25
26 class UserPassAuth(Auth):
27 """
28 Basic auth authentication using email/username and
29 password. Deprecated.
30 """
31 def __init__(self, username, password):
32 self.username = username
33 self.password = password
34
35 def encode_params(self, base_url, method, params):
36 # We could consider automatically converting unicode to utf8 strings
37 # before encoding...
38 return urllib_parse.urlencode(params)
39
40 def generate_headers(self):
41 return {b"Authorization": b"Basic " + encodebytes(
42 ("%s:%s" %(self.username, self.password))
43 .encode('utf8')).strip(b'\n')
44 }
45
46
47 class NoAuth(Auth):
48 """
49 No authentication authenticator.
50 """
51 def __init__(self):
52 pass
53
54 def encode_params(self, base_url, method, params):
55 return urllib_parse.urlencode(params)
56
57 def generate_headers(self):
58 return {}
59
60
61 class MissingCredentialsError(Exception):
62 pass