2021-11-28 08:42:52 +01:00
|
|
|
import asyncio
|
|
|
|
|
import os
|
2021-06-10 21:13:26 +02:00
|
|
|
import time
|
|
|
|
|
from typing import Dict
|
|
|
|
|
|
|
|
|
|
import jwt
|
|
|
|
|
from decouple import config
|
|
|
|
|
|
|
|
|
|
JWT_SECRET = config("secret")
|
|
|
|
|
JWT_ALGORITHM = config("algorithm")
|
2021-11-22 20:44:14 +01:00
|
|
|
JWT_EXPIRY_TIME = config("jwt_expiry_time", default=300, cast=int)
|
2021-06-10 21:13:26 +02:00
|
|
|
|
|
|
|
|
|
2022-03-23 21:03:50 +01:00
|
|
|
def sign_jwt() -> Dict[str, str]:
|
2021-11-22 20:44:14 +01:00
|
|
|
payload = {
|
|
|
|
|
"user_id": "admin",
|
|
|
|
|
"expires": int(round(time.time() * 1000) + JWT_EXPIRY_TIME),
|
|
|
|
|
}
|
2021-06-10 21:13:26 +02:00
|
|
|
token = jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
|
|
|
|
|
return token_response(token)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def token_response(token: str):
|
|
|
|
|
return {"access_token": token}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def decodeJWT(token: str) -> dict:
|
|
|
|
|
try:
|
2021-09-05 08:56:53 +02:00
|
|
|
decoded_token = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
|
2022-08-21 20:08:55 +02:00
|
|
|
return decoded_token if decoded_token["expires"] >= time.time() * 1000 else None
|
2021-09-25 17:58:53 +02:00
|
|
|
except Exception as e:
|
|
|
|
|
print(f"Unable to decode jwt_token {e}")
|
2021-06-10 21:13:26 +02:00
|
|
|
return {}
|
2021-11-28 08:42:52 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def handle_local_cookie():
|
|
|
|
|
remove_local_cookie()
|
|
|
|
|
|
|
|
|
|
blitz_path = os.path.join(os.path.expanduser("~"), ".blitz_api")
|
|
|
|
|
full_cookie_file_path = os.path.join(blitz_path, ".cookie")
|
|
|
|
|
enabled = config("enable_local_cookie_auth", default=False, cast=bool)
|
|
|
|
|
|
|
|
|
|
if not os.path.exists(blitz_path):
|
|
|
|
|
os.makedirs(blitz_path)
|
|
|
|
|
|
|
|
|
|
if enabled:
|
|
|
|
|
f = open(full_cookie_file_path, "w")
|
2022-03-23 21:03:50 +01:00
|
|
|
f.write(sign_jwt()["access_token"])
|
2021-11-28 08:42:52 +01:00
|
|
|
f.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def remove_local_cookie():
|
|
|
|
|
full_cookie_file_path = os.path.join(
|
|
|
|
|
os.path.expanduser("~"), ".blitz_api", ".cookie"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
if os.path.exists(path=full_cookie_file_path):
|
|
|
|
|
os.remove(full_cookie_file_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def register_cookie_updater():
|
|
|
|
|
# We need to update the cookie file once the cookie is expired
|
|
|
|
|
async def _cookie_updater():
|
|
|
|
|
while True:
|
|
|
|
|
await asyncio.sleep(JWT_EXPIRY_TIME - 10)
|
|
|
|
|
handle_local_cookie()
|
|
|
|
|
|
|
|
|
|
loop = asyncio.get_event_loop()
|
|
|
|
|
loop.create_task(_cookie_updater())
|