httpie-cli/httpie/plugins/builtin.py

80 lines
2.1 KiB
Python
Raw Normal View History

from base64 import b64encode
2013-09-21 23:46:15 +02:00
import requests.auth
from .base import AuthPlugin
2013-09-21 23:46:15 +02:00
2016-07-04 20:30:55 +02:00
# noinspection PyAbstractClass
2013-09-21 23:46:15 +02:00
class BuiltinAuthPlugin(AuthPlugin):
package_name = '(builtin)'
class HTTPBasicAuth(requests.auth.HTTPBasicAuth):
2019-08-31 18:33:54 +02:00
def __call__(
self,
request: requests.PreparedRequest
) -> requests.PreparedRequest:
"""
Override username/password serialization to allow unicode.
See https://github.com/httpie/cli/issues/212
"""
# noinspection PyTypeChecker
2019-08-31 18:33:54 +02:00
request.headers['Authorization'] = type(self).make_header(
self.username, self.password).encode('latin1')
2019-08-31 18:33:54 +02:00
return request
@staticmethod
2019-08-31 18:33:54 +02:00
def make_header(username: str, password: str) -> str:
credentials = f'{username}:{password}'
token = b64encode(credentials.encode()).strip().decode('latin1')
return f'Basic {token}'
2021-12-01 18:37:57 +01:00
class HTTPBearerAuth(requests.auth.AuthBase):
def __init__(self, token: str) -> None:
self.token = token
def __call__(self, request: requests.PreparedRequest) -> requests.PreparedRequest:
request.headers['Authorization'] = f'Bearer {self.token}'
return request
2013-09-21 23:46:15 +02:00
class BasicAuthPlugin(BuiltinAuthPlugin):
name = 'Basic HTTP auth'
auth_type = 'basic'
netrc_parse = True
2013-09-21 23:46:15 +02:00
# noinspection PyMethodOverriding
2019-08-31 18:33:54 +02:00
def get_auth(self, username: str, password: str) -> HTTPBasicAuth:
return HTTPBasicAuth(username, password)
2013-09-21 23:46:15 +02:00
class DigestAuthPlugin(BuiltinAuthPlugin):
name = 'Digest HTTP auth'
auth_type = 'digest'
netrc_parse = True
2013-09-21 23:46:15 +02:00
# noinspection PyMethodOverriding
2019-08-31 18:33:54 +02:00
def get_auth(
self,
username: str,
password: str
) -> requests.auth.HTTPDigestAuth:
2013-09-21 23:46:15 +02:00
return requests.auth.HTTPDigestAuth(username, password)
2021-12-01 18:37:57 +01:00
class BearerAuthPlugin(BuiltinAuthPlugin):
name = 'Bearer HTTP Auth'
auth_type = 'bearer'
netrc_parse = False
auth_parse = False
# noinspection PyMethodOverriding
def get_auth(self, **kwargs) -> requests.auth.HTTPDigestAuth:
return HTTPBearerAuth(self.raw_auth)