def generate_token(payload: dict, exp_seconds: int) -> str:
""" generate a JWT with the given payload. uses HMAC + SHA-256 hash algorithm. the token
expires after the given number of seconds. """
jwt_secret = os.getenv("JWT_SECRET")
jwt_iss = os.getenv("JWT_ISS")
if os.getenv("DEBUG"):
# if running in debug mode, use timezone of machine
payload["iat"] = int(dt.datetime.now().timestamp())
payload["exp"] = int((dt.datetime.now() + dt.timedelta(seconds=exp_seconds)).timestamp())
else:
# if running in production, use UTC
payload["iat"] = int(dt.datetime.utcnow().timestamp())
payload["exp"] = int((dt.datetime.utcnow() + dt.timedelta(seconds=exp_seconds)).timestamp())
payload["iss"] = jwt_iss
try:
token = jwt.encode(payload, jwt_secret, algorithm="HS256")
return token.decode("utf-8")
except Exception as e:
raise(e)
评论列表
文章目录