2020-07-05 21:15:07 +00:00
|
|
|
"""API Authentication"""
|
|
|
|
from base64 import b64decode
|
2020-10-18 12:34:22 +00:00
|
|
|
from typing import Any, Optional, Tuple, Union
|
2020-07-05 21:15:07 +00:00
|
|
|
|
|
|
|
from rest_framework.authentication import BaseAuthentication, get_authorization_header
|
|
|
|
from rest_framework.request import Request
|
2020-10-18 12:34:22 +00:00
|
|
|
from structlog import get_logger
|
2020-07-05 21:15:07 +00:00
|
|
|
|
|
|
|
from passbook.core.models import Token, TokenIntents, User
|
|
|
|
|
2020-10-18 12:34:22 +00:00
|
|
|
LOGGER = get_logger()
|
|
|
|
|
|
|
|
|
|
|
|
def token_from_header(raw_header: bytes) -> Optional[Token]:
|
|
|
|
"""raw_header in the Format of `Basic dGVzdDp0ZXN0`"""
|
|
|
|
auth_credentials = raw_header.decode()
|
|
|
|
# Accept headers with Type format and without
|
|
|
|
if " " in auth_credentials:
|
|
|
|
auth_type, auth_credentials = auth_credentials.split()
|
|
|
|
if auth_type.lower() != "basic":
|
|
|
|
LOGGER.debug(
|
|
|
|
"Unsupported authentication type, denying", type=auth_type.lower()
|
|
|
|
)
|
|
|
|
return None
|
2020-10-18 13:14:00 +00:00
|
|
|
try:
|
|
|
|
auth_credentials = b64decode(auth_credentials.encode()).decode()
|
|
|
|
except UnicodeDecodeError:
|
2020-10-26 10:00:19 +00:00
|
|
|
return None
|
2020-10-18 12:34:22 +00:00
|
|
|
# Accept credentials with username and without
|
|
|
|
if ":" in auth_credentials:
|
|
|
|
_, password = auth_credentials.split(":")
|
|
|
|
else:
|
|
|
|
password = auth_credentials
|
|
|
|
if password == "":
|
|
|
|
return None
|
|
|
|
tokens = Token.filter_not_expired(key=password, intent=TokenIntents.INTENT_API)
|
|
|
|
if not tokens.exists():
|
|
|
|
LOGGER.debug("Token not found")
|
|
|
|
return None
|
|
|
|
return tokens.first()
|
|
|
|
|
2020-07-05 21:15:07 +00:00
|
|
|
|
|
|
|
class PassbookTokenAuthentication(BaseAuthentication):
|
|
|
|
"""Token-based authentication using HTTP Basic authentication"""
|
|
|
|
|
|
|
|
def authenticate(self, request: Request) -> Union[Tuple[User, Any], None]:
|
|
|
|
"""Token-based authentication using HTTP Basic authentication"""
|
2020-10-18 12:34:22 +00:00
|
|
|
auth = get_authorization_header(request)
|
2020-07-05 21:15:07 +00:00
|
|
|
|
2020-10-18 12:34:22 +00:00
|
|
|
token = token_from_header(auth)
|
|
|
|
if not token:
|
2020-07-05 21:15:07 +00:00
|
|
|
return None
|
|
|
|
|
2020-10-18 12:34:22 +00:00
|
|
|
return (token.user, None)
|
2020-07-05 21:15:07 +00:00
|
|
|
|
|
|
|
def authenticate_header(self, request: Request) -> str:
|
|
|
|
return 'Basic realm="passbook"'
|