2020-09-25 23:26:06 +00:00
|
|
|
"""OAuth 2 Clients"""
|
|
|
|
from json import loads
|
|
|
|
from typing import Any, Dict, Optional
|
|
|
|
from urllib.parse import parse_qsl
|
2020-09-25 21:58:58 +00:00
|
|
|
|
|
|
|
from django.utils.crypto import constant_time_compare, get_random_string
|
|
|
|
from requests.exceptions import RequestException
|
2020-09-25 22:34:57 +00:00
|
|
|
from requests.models import Response
|
2020-09-25 21:58:58 +00:00
|
|
|
from structlog import get_logger
|
|
|
|
|
|
|
|
from passbook.sources.oauth.clients.base import BaseOAuthClient
|
|
|
|
|
|
|
|
LOGGER = get_logger()
|
|
|
|
|
|
|
|
|
|
|
|
class OAuth2Client(BaseOAuthClient):
|
|
|
|
"""OAuth2 Client"""
|
|
|
|
|
|
|
|
_default_headers = {
|
|
|
|
"Accept": "application/json",
|
|
|
|
}
|
|
|
|
|
2020-09-25 22:34:57 +00:00
|
|
|
def check_application_state(self) -> bool:
|
2020-09-25 21:58:58 +00:00
|
|
|
"Check optional state parameter."
|
2020-09-25 22:34:57 +00:00
|
|
|
stored = self.request.session.get(self.session_key, None)
|
|
|
|
returned = self.request.GET.get("state", None)
|
2020-09-25 21:58:58 +00:00
|
|
|
check = False
|
|
|
|
if stored is not None:
|
|
|
|
if returned is not None:
|
|
|
|
check = constant_time_compare(stored, returned)
|
|
|
|
else:
|
|
|
|
LOGGER.warning("No state parameter returned by the source.")
|
|
|
|
else:
|
2020-09-25 22:34:57 +00:00
|
|
|
LOGGER.warning("No state stored in the session.")
|
2020-09-25 21:58:58 +00:00
|
|
|
return check
|
|
|
|
|
2020-09-25 22:34:57 +00:00
|
|
|
def get_application_state(self) -> str:
|
|
|
|
"Generate state optional parameter."
|
|
|
|
return get_random_string(32)
|
|
|
|
|
|
|
|
def get_access_token(self, **request_kwargs) -> Optional[Dict[str, Any]]:
|
2020-09-25 21:58:58 +00:00
|
|
|
"Fetch access token from callback request."
|
2020-09-25 22:34:57 +00:00
|
|
|
callback = self.request.build_absolute_uri(self.callback or self.request.path)
|
|
|
|
if not self.check_application_state():
|
2020-09-25 21:58:58 +00:00
|
|
|
LOGGER.warning("Application state check failed.")
|
|
|
|
return None
|
2020-09-25 22:34:57 +00:00
|
|
|
if "code" in self.request.GET:
|
2020-09-25 21:58:58 +00:00
|
|
|
args = {
|
|
|
|
"client_id": self.source.consumer_key,
|
|
|
|
"redirect_uri": callback,
|
|
|
|
"client_secret": self.source.consumer_secret,
|
2020-09-25 22:34:57 +00:00
|
|
|
"code": self.request.GET["code"],
|
2020-09-25 21:58:58 +00:00
|
|
|
"grant_type": "authorization_code",
|
|
|
|
}
|
|
|
|
else:
|
|
|
|
LOGGER.warning("No code returned by the source")
|
|
|
|
return None
|
|
|
|
try:
|
|
|
|
response = self.session.request(
|
|
|
|
"post",
|
|
|
|
self.source.access_token_url,
|
|
|
|
data=args,
|
|
|
|
headers=self._default_headers,
|
|
|
|
)
|
|
|
|
response.raise_for_status()
|
|
|
|
except RequestException as exc:
|
|
|
|
LOGGER.warning("Unable to fetch access token", exc=exc)
|
|
|
|
return None
|
|
|
|
else:
|
|
|
|
return response.json()
|
|
|
|
|
2020-09-25 22:34:57 +00:00
|
|
|
def get_redirect_args(self) -> Dict[str, str]:
|
2020-09-25 21:58:58 +00:00
|
|
|
"Get request parameters for redirect url."
|
2020-09-25 22:34:57 +00:00
|
|
|
callback = self.request.build_absolute_uri(self.callback)
|
|
|
|
client_id: str = self.source.consumer_key
|
|
|
|
args: Dict[str, str] = {
|
|
|
|
"client_id": client_id,
|
2020-09-25 21:58:58 +00:00
|
|
|
"redirect_uri": callback,
|
|
|
|
"response_type": "code",
|
|
|
|
}
|
2020-09-25 22:34:57 +00:00
|
|
|
state = self.get_application_state()
|
2020-09-25 21:58:58 +00:00
|
|
|
if state is not None:
|
|
|
|
args["state"] = state
|
2020-09-25 22:34:57 +00:00
|
|
|
self.request.session[self.session_key] = state
|
2020-09-25 21:58:58 +00:00
|
|
|
return args
|
|
|
|
|
2020-09-25 23:26:06 +00:00
|
|
|
def parse_raw_token(self, raw_token: str) -> Dict[str, Any]:
|
2020-09-25 21:58:58 +00:00
|
|
|
"Parse token and secret from raw token response."
|
|
|
|
# Load as json first then parse as query string
|
|
|
|
try:
|
2020-09-25 23:26:06 +00:00
|
|
|
token_data = loads(raw_token)
|
2020-09-25 21:58:58 +00:00
|
|
|
except ValueError:
|
2020-09-25 23:26:06 +00:00
|
|
|
return dict(parse_qsl(raw_token))
|
2020-09-25 21:58:58 +00:00
|
|
|
else:
|
2020-09-25 23:26:06 +00:00
|
|
|
return token_data
|
2020-09-25 21:58:58 +00:00
|
|
|
|
2020-09-25 22:34:57 +00:00
|
|
|
def do_request(self, method: str, url: str, **kwargs) -> Response:
|
2020-09-25 21:58:58 +00:00
|
|
|
"Build remote url request. Constructs necessary auth."
|
2020-09-25 23:26:06 +00:00
|
|
|
if "token" in kwargs:
|
2020-09-26 12:00:48 +00:00
|
|
|
token = kwargs.pop("token")
|
2020-09-25 23:26:06 +00:00
|
|
|
|
2020-09-25 21:58:58 +00:00
|
|
|
params = kwargs.get("params", {})
|
2020-09-25 23:26:06 +00:00
|
|
|
params["access_token"] = token["access_token"]
|
2020-09-25 21:58:58 +00:00
|
|
|
kwargs["params"] = params
|
2020-09-25 23:26:06 +00:00
|
|
|
|
|
|
|
headers = kwargs.get("headers", {})
|
|
|
|
headers["Authorization"] = f"{token['token_type']} {token['access_token']}"
|
2020-09-26 12:00:48 +00:00
|
|
|
kwargs["headers"] = headers
|
2020-09-25 22:34:57 +00:00
|
|
|
return super().do_request(method, url, **kwargs)
|
2020-09-25 21:58:58 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def session_key(self):
|
|
|
|
return "oauth-client-{0}-request-state".format(self.source.name)
|