2019-12-29 23:57:39 -07:00
|
|
|
"""Handle JSON Web Token Encoding & Decoding."""
|
|
|
|
|
2020-02-03 02:35:11 -07:00
|
|
|
# Standard Library
|
2019-12-28 02:00:34 -07:00
|
|
|
import datetime
|
|
|
|
|
2020-02-03 02:35:11 -07:00
|
|
|
# Third Party
|
2019-12-28 02:00:34 -07:00
|
|
|
import jwt
|
|
|
|
|
2020-02-03 02:35:11 -07:00
|
|
|
# Project
|
2019-12-28 02:00:34 -07:00
|
|
|
from hyperglass.exceptions import RestError
|
|
|
|
|
|
|
|
|
2020-09-28 08:12:40 -07:00
|
|
|
async def jwt_decode(payload: str, secret: str) -> str:
|
|
|
|
"""Decode & validate an encoded JSON Web Token (JWT)."""
|
2019-12-28 02:00:34 -07:00
|
|
|
try:
|
|
|
|
decoded = jwt.decode(payload, secret, algorithm="HS256")
|
|
|
|
decoded = decoded["payload"]
|
|
|
|
return decoded
|
|
|
|
except (KeyError, jwt.PyJWTError) as exp:
|
|
|
|
raise RestError(str(exp)) from None
|
|
|
|
|
|
|
|
|
2020-09-28 08:12:40 -07:00
|
|
|
async def jwt_encode(payload: str, secret: str, duration: int) -> str:
|
|
|
|
"""Encode a query to a JSON Web Token (JWT)."""
|
2019-12-28 02:00:34 -07:00
|
|
|
token = {
|
|
|
|
"payload": payload,
|
|
|
|
"nbf": datetime.datetime.utcnow(),
|
|
|
|
"iat": datetime.datetime.utcnow(),
|
|
|
|
"exp": datetime.datetime.utcnow() + datetime.timedelta(seconds=duration),
|
|
|
|
}
|
|
|
|
encoded = jwt.encode(token, secret, algorithm="HS256").decode("utf-8")
|
|
|
|
return encoded
|