Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Support TypedDict #730

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
The MIT License (MIT)

Copyright (c) 2015 José Padilla
Copyright (c) 2015-2022 José Padilla
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this probably needs rebase?


Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def find_version(*file_paths):

# General information about the project.
project = "PyJWT"
copyright = "2015, José Padilla"
copyright = "2015-2022, José Padilla"
author = "José Padilla"

# The version info for the project you're documenting, acts as replacement for
Expand Down
2 changes: 1 addition & 1 deletion jwt/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
__email__ = "hello@jpadilla.com"

__license__ = "MIT"
__copyright__ = "Copyright 2015-2020 José Padilla"
__copyright__ = "Copyright 2015-2022 José Padilla"


__all__ = [
Expand Down
48 changes: 32 additions & 16 deletions jwt/api_jws.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import binascii
import json
from collections.abc import Mapping
from typing import Any, Dict, List, Optional, Type
from sys import version_info
from typing import Dict, List, Optional, Type

from .algorithms import (
Algorithm,
Expand All @@ -17,11 +18,26 @@
)
from .utils import base64url_decode, base64url_encode

if version_info < (3, 8):
from typing_extensions import TypedDict
else:
from typing import TypedDict


class PyJWSOptions(TypedDict):
verify_signature: bool


class DecodedPyJWS(TypedDict):
payload: bytes
header: Mapping
signature: bytes


class PyJWS:
header_typ = "JWT"

def __init__(self, algorithms=None, options=None):
def __init__(self, algorithms=None, options: Optional[PyJWSOptions] = None):
self._algorithms = get_default_algorithms()
self._valid_algs = (
set(algorithms) if algorithms is not None else set(self._algorithms)
Expand All @@ -33,12 +49,12 @@ def __init__(self, algorithms=None, options=None):
del self._algorithms[key]

if options is None:
options = {}
self.options = {**self._get_default_options(), **options}
options = PyJWSOptions()
self.options = PyJWSOptions({**self._get_default_options(), **options})

@staticmethod
def _get_default_options():
return {"verify_signature": True}
def _get_default_options() -> PyJWSOptions:
return PyJWSOptions(verify_signature=True)

def register_algorithm(self, alg_id, alg_obj):
"""
Expand Down Expand Up @@ -133,12 +149,12 @@ def decode_complete(
jwt: str,
key: str = "",
algorithms: Optional[List[str]] = None,
options: Optional[Dict] = None,
options: Optional[PyJWSOptions] = None,
**kwargs,
) -> Dict[str, Any]:
) -> DecodedPyJWS:
if options is None:
options = {}
merged_options = {**self.options, **options}
options = PyJWSOptions()
merged_options = PyJWSOptions({**self.options, **options})
verify_signature = merged_options["verify_signature"]

if verify_signature and not algorithms:
Expand All @@ -151,18 +167,18 @@ def decode_complete(
if verify_signature:
self._verify_signature(signing_input, header, signature, key, algorithms)

return {
"payload": payload,
"header": header,
"signature": signature,
}
return DecodedPyJWS(
payload=payload,
header=header,
signature=signature,
)

def decode(
self,
jwt: str,
key: str = "",
algorithms: Optional[List[str]] = None,
options: Optional[Dict] = None,
options: Optional[PyJWSOptions] = None,
**kwargs,
) -> str:
decoded = self.decode_complete(jwt, key, algorithms, options, **kwargs)
Expand Down
49 changes: 32 additions & 17 deletions jwt/api_jwt.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
from calendar import timegm
from collections.abc import Iterable, Mapping
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional, Type, Union
from sys import version_info
from typing import Any, Dict, List, Optional, Type

from . import api_jws
from .exceptions import (
Expand All @@ -15,24 +16,38 @@
MissingRequiredClaimError,
)

if version_info < (3, 8):
from typing_extensions import TypedDict
else:
from typing import TypedDict


class PyJWTOptions(TypedDict):
verify_signature: bool
verify_exp: bool
verify_nbf: bool
verify_iat: bool
verify_iss: bool
require: List[str]


class PyJWT:
def __init__(self, options=None):
def __init__(self, options: Optional[PyJWTOptions] = None):
if options is None:
options = {}
self.options = {**self._get_default_options(), **options}
self.options = PyJWTOptions(**self._get_default_options(), **options)

@staticmethod
def _get_default_options() -> Dict[str, Union[bool, List[str]]]:
return {
"verify_signature": True,
"verify_exp": True,
"verify_nbf": True,
"verify_iat": True,
"verify_aud": True,
"verify_iss": True,
"require": [],
}
def _get_default_options() -> PyJWTOptions:
return PyJWTOptions(
verify_signature=True,
verify_exp=True,
verify_nbf=True,
verify_iat=True,
verify_aud=True,
verify_iss=True,
require=[],
)

def encode(
self,
Expand Down Expand Up @@ -67,11 +82,11 @@ def decode_complete(
jwt: str,
key: str = "",
algorithms: Optional[List[str]] = None,
options: Optional[Dict] = None,
options: Optional[PyJWTOptions] = None,
**kwargs,
) -> Dict[str, Any]:
if options is None:
options = {"verify_signature": True}
options = PyJWTOptions(verify_signature=True)
else:
options.setdefault("verify_signature", True)

Expand Down Expand Up @@ -102,7 +117,7 @@ def decode_complete(
if not isinstance(payload, dict):
raise DecodeError("Invalid payload string: must be a json object")

merged_options = {**self.options, **options}
merged_options = PyJWTOptions({**self.options, **options})
self._validate_claims(payload, merged_options, **kwargs)

decoded["payload"] = payload
Expand All @@ -113,7 +128,7 @@ def decode(
jwt: str,
key: str = "",
algorithms: Optional[List[str]] = None,
options: Optional[Dict] = None,
options: Optional[PyJWTOptions] = None,
**kwargs,
) -> Dict[str, Any]:
decoded = self.decode_complete(jwt, key, algorithms, options, **kwargs)
Expand Down
3 changes: 3 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ include_package_data = true
python_requires = >=3.6
packages = find:

install_requires =
typing-extensions>=4;python_version<"3.8"

[options.package_data]
* = py.typed

Expand Down