2022-08-08 18:37:17 +01:00
|
|
|
from datetime import timedelta, datetime, timezone
|
|
|
|
import jwt
|
2022-11-29 22:46:53 +00:00
|
|
|
from music.magic_strings import JWT_SECRET_URI
|
2022-08-08 18:37:17 +01:00
|
|
|
from music.model.user import User
|
|
|
|
|
2022-11-29 21:13:26 +00:00
|
|
|
from google.cloud import secretmanager
|
2022-11-27 23:36:50 +00:00
|
|
|
|
2022-11-29 21:13:26 +00:00
|
|
|
secret_client = secretmanager.SecretManagerServiceClient()
|
2022-08-08 18:37:17 +01:00
|
|
|
|
|
|
|
|
2022-11-29 21:13:26 +00:00
|
|
|
def get_jwt_secret_key() -> str:
|
|
|
|
return secret_client.access_secret_version(request={"name": JWT_SECRET_URI}).payload.data.decode("UTF-8")
|
2022-08-08 18:37:17 +01:00
|
|
|
|
2022-11-27 23:36:50 +00:00
|
|
|
|
2022-08-08 18:37:17 +01:00
|
|
|
def generate_key(user: User, timeout: datetime | timedelta = timedelta(minutes=60)) -> str:
|
|
|
|
|
|
|
|
if isinstance(timeout, timedelta):
|
|
|
|
exp = timeout + datetime.now(tz=timezone.utc)
|
|
|
|
else:
|
|
|
|
exp = timeout
|
|
|
|
|
|
|
|
payload = {
|
|
|
|
"exp": exp,
|
|
|
|
"iss": "mixonomer-api",
|
|
|
|
"sub": user.username
|
|
|
|
}
|
|
|
|
|
|
|
|
return jwt.encode(payload, get_jwt_secret_key(), algorithm="HS512")
|
|
|
|
|
2022-11-27 23:36:50 +00:00
|
|
|
|
2022-08-08 18:37:17 +01:00
|
|
|
def validate_key(key: str) -> dict:
|
|
|
|
|
|
|
|
try:
|
|
|
|
decoded = jwt.decode(key, get_jwt_secret_key(), algorithms=["HS512"], options={
|
|
|
|
"require": ["exp", "sub"]
|
|
|
|
})
|
|
|
|
|
|
|
|
return decoded
|
|
|
|
|
2022-11-27 23:36:50 +00:00
|
|
|
except jwt.exceptions.PyJWTError as e:
|
2022-08-08 18:37:17 +01:00
|
|
|
pass
|