Skip to content

Commit 2a316eb

Browse files
brentrubrentru
authored andcommitted
reduce line count
1 parent c25d6dc commit 2a316eb

File tree

2 files changed

+21
-20
lines changed

2 files changed

+21
-20
lines changed

adafruit_jwt.py

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -59,39 +59,36 @@ class JWT:
5959
:param str algo: Encryption algorithm used for claims. Can be None.
6060
6161
"""
62-
6362
@staticmethod
6463
def validate(jwt):
65-
"""Validates a provided JWT. Does not support nested signing.
64+
"""Validates a provided JWT. Does not support validating
65+
nested signing. Returns JOSE Header and claim set.
6666
:param str jwt: JSON Web Token.
6767
:returns: The message's decoded JOSE header and claims.
6868
:rtype: tuple
6969
"""
7070
# Verify JWT contains at least one period ('.')
7171
if jwt.find(".") == -1:
72-
raise ValueError("JWT must have at least one period")
73-
# Separate the encoded JOSE Header
74-
jose_header = jwt.split(".")[0]
75-
# Decode JOSE Header
72+
raise ValueError("ProvidedJWT must have at least one period")
73+
# Attempt to decode JOSE header
7674
try:
77-
jose_header = STRING_TOOLS.urlsafe_b64decode(jose_header)
75+
jose_header = STRING_TOOLS.urlsafe_b64decode(jwt.split(".")[0])
7876
except UnicodeError:
79-
raise UnicodeError("Invalid JOSE Header encoding.")
80-
if "type" not in jose_header:
77+
raise UnicodeError("Unable to decode JOSE header.")
78+
# Check for typ and alg in decoded JOSE header
79+
if "typ" not in jose_header:
8180
raise TypeError("JOSE Header does not contain required type key.")
8281
if "alg" not in jose_header:
83-
raise TypeError("Jose Header does not contain required alg key.")
84-
# Separate encoded claim set
85-
claims = jwt.split(".")[1]
82+
raise TypeError("Jose Header does not contain an alg key.")
83+
# Attempt to decode claim set
8684
try:
87-
claims = json.loads(STRING_TOOLS.urlsafe_b64decode(claims))
85+
claims = json.loads(STRING_TOOLS.urlsafe_b64decode(jwt.split(".")[1]))
8886
except UnicodeError:
8987
raise UnicodeError("Invalid claims encoding.")
9088
if not hasattr(claims, "keys"):
9189
raise TypeError("Provided claims is not a JSON dict. object")
9290
return (jose_header, claims)
9391

94-
9592
@staticmethod
9693
def generate(claims, private_key_data=None, algo=None):
9794
"""Generates and returns a new JSON Web Token.
@@ -108,15 +105,16 @@ def generate(claims, private_key_data=None, algo=None):
108105
# https://tools.ietf.org/html/rfc7519#section-5
109106
jose_header = {"typ": "JWT", "alg": algo}
110107
payload = "{}.{}".format(
111-
string.b42_urlsafe_encode(json.dumps(jose_header).encode("utf-8")),
112-
string.b42_urlsafe_encode(json.dumps(claims).encode("utf-8")),
108+
STRING_TOOLS.urlsafe_b64encode(json.dumps(jose_header).encode("utf-8")),
109+
STRING_TOOLS.urlsafe_b64encode(json.dumps(claims).encode("utf-8")),
113110
)
114111
# Compute the signature
115112
if algo == "none":
116113
jwt = "{}.{}".format(jose_header, claims)
117114
elif algo == "RS256" or algo == "RS384" or algo == "RS512" or algo == "RSA":
118115
#sig = sign(payload, priv_key, "SHA-256")
119-
signature = string.b42_urlsafe_encode(sign(payload, priv_key, "SHA-256"))
116+
signature = STRING_TOOLS.urlsafe_b64encode(
117+
sign(payload, priv_key, "SHA-256"))
120118
jwt = payload + "." + signature
121119
else:
122120
raise TypeError(
@@ -149,7 +147,8 @@ def urlsafe_b64encode(payload):
149147
:param bytes payload: bytes-like object.
150148
"""
151149
return STRING_TOOLS.translate(
152-
b2a_base64(payload)[:-1].decode("utf-8"), {ord("+"): "-", ord("/"): "_"}
150+
b2a_base64(payload)[
151+
:-1].decode("utf-8"), {ord("+"): "-", ord("/"): "_"}
153152
)
154153

155154
@staticmethod
@@ -168,7 +167,8 @@ def _bytes_from_decode_data(str_data):
168167
try:
169168
return str_data.encode("ascii")
170169
except:
171-
raise ValueError("string argument should contain only ASCII characters")
170+
raise ValueError(
171+
"string argument should contain only ASCII characters")
172172
elif isinstance(str_data, bit_types):
173173
return str_data
174174
else:

examples/jwt_simpletest.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,5 +19,6 @@
1919
print("Encoded JWT: ", encoded_jwt)
2020

2121
# Validate a provided JWT
22+
print("Decoding JWT...")
2223
decoded_jwt = adafruit_jwt.JWT.validate(encoded_jwt)
23-
print('Decoded JWT:\nJOSE Header: {}\nJWT Claims: {}'.format(decoded_jwt[0], decoded_jwt[1]))
24+
print('JOSE Header: {}\nJWT Claims: {}'.format(decoded_jwt[0], decoded_jwt[1]))

0 commit comments

Comments
 (0)