2018-11-11 12:41:48 +00:00
|
|
|
"""OAuth Clients"""
|
|
|
|
import json
|
2020-02-23 18:42:57 +00:00
|
|
|
from typing import Dict, Optional
|
2018-11-11 12:41:48 +00:00
|
|
|
from urllib.parse import parse_qs, urlencode
|
|
|
|
|
2020-02-23 18:42:57 +00:00
|
|
|
from django.http import HttpRequest
|
2018-11-11 12:41:48 +00:00
|
|
|
from django.utils.crypto import constant_time_compare, get_random_string
|
|
|
|
from django.utils.encoding import force_text
|
|
|
|
from requests import Session
|
|
|
|
from requests.exceptions import RequestException
|
|
|
|
from requests_oauthlib import OAuth1
|
2019-10-01 08:24:10 +00:00
|
|
|
from structlog import get_logger
|
2018-11-11 12:41:48 +00:00
|
|
|
|
2019-10-09 17:46:23 +00:00
|
|
|
from passbook import __version__
|
|
|
|
|
2019-10-04 08:08:53 +00:00
|
|
|
LOGGER = get_logger()
|
2018-11-11 12:41:48 +00:00
|
|
|
|
|
|
|
|
|
|
|
class BaseOAuthClient:
|
|
|
|
"""Base OAuth Client"""
|
|
|
|
|
2020-02-23 18:42:57 +00:00
|
|
|
session: Session = None
|
2018-11-11 12:41:48 +00:00
|
|
|
|
2020-05-15 20:15:01 +00:00
|
|
|
def __init__(self, inlet, token=""): # nosec
|
|
|
|
self.inlet = inlet
|
2018-11-11 12:41:48 +00:00
|
|
|
self.token = token
|
2020-02-23 18:42:57 +00:00
|
|
|
self.session = Session()
|
|
|
|
self.session.headers.update({"User-Agent": "passbook %s" % __version__})
|
2018-11-11 12:41:48 +00:00
|
|
|
|
|
|
|
def get_access_token(self, request, callback=None):
|
|
|
|
"Fetch access token from callback request."
|
2019-12-31 11:51:16 +00:00
|
|
|
raise NotImplementedError("Defined in a sub-class") # pragma: no cover
|
2018-11-11 12:41:48 +00:00
|
|
|
|
2020-02-23 18:42:57 +00:00
|
|
|
def get_profile_info(self, token: Dict[str, str]):
|
2018-11-11 12:41:48 +00:00
|
|
|
"Fetch user profile information."
|
|
|
|
try:
|
2020-02-18 20:49:23 +00:00
|
|
|
headers = {
|
|
|
|
"Authorization": f"{token['token_type']} {token['access_token']}"
|
|
|
|
}
|
2020-02-23 18:42:57 +00:00
|
|
|
response = self.session.request(
|
2020-05-15 20:15:01 +00:00
|
|
|
"get", self.inlet.profile_url, headers=headers,
|
2020-02-18 20:49:23 +00:00
|
|
|
)
|
2018-11-11 12:41:48 +00:00
|
|
|
response.raise_for_status()
|
|
|
|
except RequestException as exc:
|
2020-02-18 20:35:58 +00:00
|
|
|
LOGGER.warning("Unable to fetch user profile", exc=exc)
|
2018-11-11 12:41:48 +00:00
|
|
|
return None
|
|
|
|
else:
|
|
|
|
return response.json() or response.text
|
|
|
|
|
2020-02-18 20:49:23 +00:00
|
|
|
def get_redirect_args(self, request, callback) -> Dict[str, str]:
|
2018-11-11 12:41:48 +00:00
|
|
|
"Get request parameters for redirect url."
|
2019-12-31 11:51:16 +00:00
|
|
|
raise NotImplementedError("Defined in a sub-class") # pragma: no cover
|
2018-11-11 12:41:48 +00:00
|
|
|
|
|
|
|
def get_redirect_url(self, request, callback, parameters=None):
|
|
|
|
"Build authentication redirect url."
|
|
|
|
args = self.get_redirect_args(request, callback=callback)
|
|
|
|
additional = parameters or {}
|
|
|
|
args.update(additional)
|
|
|
|
params = urlencode(args)
|
2020-02-18 20:35:58 +00:00
|
|
|
LOGGER.info("redirect args", **args)
|
2020-05-15 20:15:01 +00:00
|
|
|
return "{0}?{1}".format(self.inlet.authorization_url, params)
|
2018-11-11 12:41:48 +00:00
|
|
|
|
|
|
|
def parse_raw_token(self, raw_token):
|
|
|
|
"Parse token and secret from raw token response."
|
2019-12-31 11:51:16 +00:00
|
|
|
raise NotImplementedError("Defined in a sub-class") # pragma: no cover
|
2018-11-11 12:41:48 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def session_key(self):
|
2020-02-18 20:49:23 +00:00
|
|
|
"""Return Session Key"""
|
2019-12-31 11:51:16 +00:00
|
|
|
raise NotImplementedError("Defined in a sub-class") # pragma: no cover
|
2018-11-11 12:41:48 +00:00
|
|
|
|
|
|
|
|
|
|
|
class OAuthClient(BaseOAuthClient):
|
|
|
|
"""OAuth1 Client"""
|
|
|
|
|
2020-02-23 18:42:57 +00:00
|
|
|
_default_headers = {
|
|
|
|
"Accept": "application/json",
|
|
|
|
}
|
|
|
|
|
|
|
|
def get_access_token(
|
|
|
|
self, request: HttpRequest, callback=None
|
|
|
|
) -> Optional[Dict[str, str]]:
|
2018-11-11 12:41:48 +00:00
|
|
|
"Fetch access token from callback request."
|
|
|
|
raw_token = request.session.get(self.session_key, None)
|
2019-12-31 11:51:16 +00:00
|
|
|
verifier = request.GET.get("oauth_verifier", None)
|
2018-11-11 12:41:48 +00:00
|
|
|
if raw_token is not None and verifier is not None:
|
2020-02-23 18:42:57 +00:00
|
|
|
data = {
|
|
|
|
"oauth_verifier": verifier,
|
|
|
|
"oauth_callback": callback,
|
|
|
|
"token": raw_token,
|
|
|
|
}
|
2018-11-11 12:41:48 +00:00
|
|
|
callback = request.build_absolute_uri(callback or request.path)
|
|
|
|
callback = force_text(callback)
|
|
|
|
try:
|
2020-02-23 18:42:57 +00:00
|
|
|
response = self.session.request(
|
2019-12-31 11:51:16 +00:00
|
|
|
"post",
|
2020-05-15 20:15:01 +00:00
|
|
|
self.inlet.access_token_url,
|
2019-12-31 11:51:16 +00:00
|
|
|
data=data,
|
2020-02-23 18:42:57 +00:00
|
|
|
headers=self._default_headers,
|
2019-12-31 11:51:16 +00:00
|
|
|
)
|
2018-11-11 12:41:48 +00:00
|
|
|
response.raise_for_status()
|
|
|
|
except RequestException as exc:
|
2020-02-18 20:35:58 +00:00
|
|
|
LOGGER.warning("Unable to fetch access token", exc=exc)
|
2018-11-11 12:41:48 +00:00
|
|
|
return None
|
|
|
|
else:
|
2020-02-23 18:42:57 +00:00
|
|
|
return response.json()
|
2018-11-11 12:41:48 +00:00
|
|
|
return None
|
|
|
|
|
|
|
|
def get_request_token(self, request, callback):
|
|
|
|
"Fetch the OAuth request token. Only required for OAuth 1.0."
|
|
|
|
callback = force_text(request.build_absolute_uri(callback))
|
|
|
|
try:
|
2020-02-23 18:42:57 +00:00
|
|
|
response = self.session.request(
|
|
|
|
"post",
|
2020-05-15 20:15:01 +00:00
|
|
|
self.inlet.request_token_url,
|
2020-02-23 18:42:57 +00:00
|
|
|
data={"oauth_callback": callback},
|
|
|
|
headers=self._default_headers,
|
2019-12-31 11:51:16 +00:00
|
|
|
)
|
2018-11-11 12:41:48 +00:00
|
|
|
response.raise_for_status()
|
|
|
|
except RequestException as exc:
|
2020-02-18 20:35:58 +00:00
|
|
|
LOGGER.warning("Unable to fetch request token", exc=exc)
|
2018-11-11 12:41:48 +00:00
|
|
|
return None
|
|
|
|
else:
|
|
|
|
return response.text
|
|
|
|
|
|
|
|
def get_redirect_args(self, request, callback):
|
|
|
|
"Get request parameters for redirect url."
|
|
|
|
callback = force_text(request.build_absolute_uri(callback))
|
|
|
|
raw_token = self.get_request_token(request, callback)
|
|
|
|
token, secret = self.parse_raw_token(raw_token)
|
|
|
|
if token is not None and secret is not None:
|
|
|
|
request.session[self.session_key] = raw_token
|
|
|
|
return {
|
2019-12-31 11:51:16 +00:00
|
|
|
"oauth_token": token,
|
|
|
|
"oauth_callback": callback,
|
2018-11-11 12:41:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
def parse_raw_token(self, raw_token):
|
|
|
|
"Parse token and secret from raw token response."
|
|
|
|
if raw_token is None:
|
|
|
|
return (None, None)
|
2019-10-01 09:08:56 +00:00
|
|
|
query_string = parse_qs(raw_token)
|
2019-12-31 11:51:16 +00:00
|
|
|
token = query_string.get("oauth_token", [None])[0]
|
|
|
|
secret = query_string.get("oauth_token_secret", [None])[0]
|
2018-11-11 12:41:48 +00:00
|
|
|
return (token, secret)
|
|
|
|
|
|
|
|
def request(self, method, url, **kwargs):
|
|
|
|
"Build remote url request. Constructs necessary auth."
|
2019-12-31 11:51:16 +00:00
|
|
|
user_token = kwargs.pop("token", self.token)
|
2018-11-11 12:41:48 +00:00
|
|
|
token, secret = self.parse_raw_token(user_token)
|
2019-12-31 11:51:16 +00:00
|
|
|
callback = kwargs.pop("oauth_callback", None)
|
|
|
|
verifier = kwargs.get("data", {}).pop("oauth_verifier", None)
|
2018-11-11 12:41:48 +00:00
|
|
|
oauth = OAuth1(
|
2020-05-15 20:15:01 +00:00
|
|
|
reinlet_owner_key=token,
|
|
|
|
reinlet_owner_secret=secret,
|
|
|
|
client_key=self.inlet.consumer_key,
|
|
|
|
client_secret=self.inlet.consumer_secret,
|
2018-11-11 12:41:48 +00:00
|
|
|
verifier=verifier,
|
|
|
|
callback_uri=callback,
|
|
|
|
)
|
2019-12-31 11:51:16 +00:00
|
|
|
kwargs["auth"] = oauth
|
2020-02-23 18:42:57 +00:00
|
|
|
return super(OAuthClient, self).session.request(method, url, **kwargs)
|
2018-11-11 12:41:48 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def session_key(self):
|
2020-05-15 20:15:01 +00:00
|
|
|
return "oauth-client-{0}-request-token".format(self.inlet.name)
|
2018-11-11 12:41:48 +00:00
|
|
|
|
|
|
|
|
|
|
|
class OAuth2Client(BaseOAuthClient):
|
|
|
|
"""OAuth2 Client"""
|
|
|
|
|
2020-02-23 18:42:57 +00:00
|
|
|
_default_headers = {
|
|
|
|
"Accept": "application/json",
|
|
|
|
}
|
|
|
|
|
2019-12-31 11:45:29 +00:00
|
|
|
# pylint: disable=unused-argument
|
2018-11-11 12:41:48 +00:00
|
|
|
def check_application_state(self, request, callback):
|
|
|
|
"Check optional state parameter."
|
|
|
|
stored = request.session.get(self.session_key, None)
|
2019-12-31 11:51:16 +00:00
|
|
|
returned = request.GET.get("state", None)
|
2018-11-11 12:41:48 +00:00
|
|
|
check = False
|
|
|
|
if stored is not None:
|
|
|
|
if returned is not None:
|
|
|
|
check = constant_time_compare(stored, returned)
|
|
|
|
else:
|
2020-05-15 20:15:01 +00:00
|
|
|
LOGGER.warning("No state parameter returned by the inlet.")
|
2018-11-11 12:41:48 +00:00
|
|
|
else:
|
2019-12-31 11:51:16 +00:00
|
|
|
LOGGER.warning("No state stored in the sesssion.")
|
2018-11-11 12:41:48 +00:00
|
|
|
return check
|
|
|
|
|
|
|
|
def get_access_token(self, request, callback=None, **request_kwargs):
|
|
|
|
"Fetch access token from callback request."
|
|
|
|
callback = request.build_absolute_uri(callback or request.path)
|
|
|
|
if not self.check_application_state(request, callback):
|
2019-12-31 11:51:16 +00:00
|
|
|
LOGGER.warning("Application state check failed.")
|
2018-11-11 12:41:48 +00:00
|
|
|
return None
|
2019-12-31 11:51:16 +00:00
|
|
|
if "code" in request.GET:
|
2018-11-11 12:41:48 +00:00
|
|
|
args = {
|
2020-05-15 20:15:01 +00:00
|
|
|
"client_id": self.inlet.consumer_key,
|
2019-12-31 11:51:16 +00:00
|
|
|
"redirect_uri": callback,
|
2020-05-15 20:15:01 +00:00
|
|
|
"client_secret": self.inlet.consumer_secret,
|
2019-12-31 11:51:16 +00:00
|
|
|
"code": request.GET["code"],
|
|
|
|
"grant_type": "authorization_code",
|
2018-11-11 12:41:48 +00:00
|
|
|
}
|
|
|
|
else:
|
2020-05-15 20:15:01 +00:00
|
|
|
LOGGER.warning("No code returned by the inlet")
|
2018-11-11 12:41:48 +00:00
|
|
|
return None
|
|
|
|
try:
|
2020-02-23 18:42:57 +00:00
|
|
|
response = self.session.request(
|
|
|
|
"post",
|
2020-05-15 20:15:01 +00:00
|
|
|
self.inlet.access_token_url,
|
2020-02-23 18:42:57 +00:00
|
|
|
data=args,
|
|
|
|
headers=self._default_headers,
|
|
|
|
**request_kwargs,
|
2019-12-31 11:51:16 +00:00
|
|
|
)
|
2018-11-11 12:41:48 +00:00
|
|
|
response.raise_for_status()
|
|
|
|
except RequestException as exc:
|
2020-02-18 20:35:58 +00:00
|
|
|
LOGGER.warning("Unable to fetch access token", exc=exc)
|
2018-11-11 12:41:48 +00:00
|
|
|
return None
|
|
|
|
else:
|
2020-02-23 18:42:57 +00:00
|
|
|
return response.json()
|
2018-11-11 12:41:48 +00:00
|
|
|
|
2019-12-31 11:45:29 +00:00
|
|
|
# pylint: disable=unused-argument
|
2018-11-11 12:41:48 +00:00
|
|
|
def get_application_state(self, request, callback):
|
|
|
|
"Generate state optional parameter."
|
|
|
|
return get_random_string(32)
|
|
|
|
|
|
|
|
def get_redirect_args(self, request, callback):
|
|
|
|
"Get request parameters for redirect url."
|
|
|
|
callback = request.build_absolute_uri(callback)
|
|
|
|
args = {
|
2020-05-15 20:15:01 +00:00
|
|
|
"client_id": self.inlet.consumer_key,
|
2019-12-31 11:51:16 +00:00
|
|
|
"redirect_uri": callback,
|
|
|
|
"response_type": "code",
|
2018-11-11 12:41:48 +00:00
|
|
|
}
|
|
|
|
state = self.get_application_state(request, callback)
|
|
|
|
if state is not None:
|
2019-12-31 11:51:16 +00:00
|
|
|
args["state"] = state
|
2018-11-11 12:41:48 +00:00
|
|
|
request.session[self.session_key] = state
|
|
|
|
return args
|
|
|
|
|
|
|
|
def parse_raw_token(self, raw_token):
|
|
|
|
"Parse token and secret from raw token response."
|
|
|
|
if raw_token is None:
|
|
|
|
return (None, None)
|
|
|
|
# Load as json first then parse as query string
|
|
|
|
try:
|
|
|
|
token_data = json.loads(raw_token)
|
|
|
|
except ValueError:
|
2019-12-31 11:51:16 +00:00
|
|
|
token = parse_qs(raw_token).get("access_token", [None])[0]
|
2018-11-11 12:41:48 +00:00
|
|
|
else:
|
2019-12-31 11:51:16 +00:00
|
|
|
token = token_data.get("access_token", None)
|
2018-11-11 12:41:48 +00:00
|
|
|
return (token, None)
|
|
|
|
|
|
|
|
def request(self, method, url, **kwargs):
|
|
|
|
"Build remote url request. Constructs necessary auth."
|
2019-12-31 11:51:16 +00:00
|
|
|
user_token = kwargs.pop("token", self.token)
|
2018-11-11 12:41:48 +00:00
|
|
|
token, _ = self.parse_raw_token(user_token)
|
|
|
|
if token is not None:
|
2019-12-31 11:51:16 +00:00
|
|
|
params = kwargs.get("params", {})
|
|
|
|
params["access_token"] = token
|
|
|
|
kwargs["params"] = params
|
2020-02-23 18:42:57 +00:00
|
|
|
return super(OAuth2Client, self).session.request(method, url, **kwargs)
|
2018-11-11 12:41:48 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def session_key(self):
|
2020-05-15 20:15:01 +00:00
|
|
|
return "oauth-client-{0}-request-state".format(self.inlet.name)
|
2018-11-11 12:41:48 +00:00
|
|
|
|
|
|
|
|
2020-05-15 20:15:01 +00:00
|
|
|
def get_client(inlet, token=""): # nosec
|
|
|
|
"Return the API client for the given inlet."
|
2018-11-11 12:41:48 +00:00
|
|
|
cls = OAuth2Client
|
2020-05-15 20:15:01 +00:00
|
|
|
if inlet.request_token_url:
|
2018-11-11 12:41:48 +00:00
|
|
|
cls = OAuthClient
|
2020-05-15 20:15:01 +00:00
|
|
|
return cls(inlet, token)
|