70 lines
2.1 KiB
Python
70 lines
2.1 KiB
Python
from __future__ import annotations
|
|||
|
|
|
||
|
|
from datetime import datetime, timedelta, timezone
|
||
|
|
from typing import Any
|
||
|
|
|
||
|
|
from jose import JWTError, jwt
|
||
|
|
from passlib.context import CryptContext
|
||
|
|
|
||
|
|
from sakura_cloud.core.config import settings
|
||
|
|
|
||
|
|
|
||
|
|
pwd_context = CryptContext(schemes=["pbkdf2_sha256", "bcrypt"], deprecated="auto")
|
||
|
|
|
||
|
|
|
||
|
|
def hash_password(password: str) -> str:
|
||
|
|
return pwd_context.hash(password)
|
||
|
|
|
||
|
|
|
||
|
|
def verify_password(password: str, password_hash: str) -> bool:
|
||
|
|
return pwd_context.verify(password, password_hash)
|
||
|
|
|
||
|
|
|
||
|
|
def create_token(subject: str, *, token_type: str, expires_delta: timedelta, token_version: int = 0) -> str:
|
||
|
|
now = datetime.now(timezone.utc)
|
||
|
|
payload: dict[str, Any] = {
|
||
|
|
"sub": subject,
|
||
|
|
"type": token_type,
|
||
|
|
"tv": token_version,
|
||
|
|
"iss": settings.jwt_issuer,
|
||
|
|
"aud": settings.jwt_audience,
|
||
|
|
"iat": int(now.timestamp()),
|
||
|
|
"exp": int((now + expires_delta).timestamp()),
|
||
|
|
}
|
||
|
|
return jwt.encode(payload, settings.jwt_secret_key, algorithm=settings.jwt_algorithm)
|
||
|
|
|
||
|
|
|
||
|
|
def create_access_token(subject: str, token_version: int = 0) -> str:
|
||
|
|
return create_token(
|
||
|
|
subject,
|
||
|
|
token_type="access",
|
||
|
|
expires_delta=timedelta(hours=settings.jwt_access_token_expire_hours),
|
||
|
|
token_version=token_version,
|
||
|
|
)
|
||
|
|
|
||
|
|
|
||
|
|
def create_refresh_token(subject: str, token_version: int = 0) -> str:
|
||
|
|
return create_token(
|
||
|
|
subject,
|
||
|
|
token_type="refresh",
|
||
|
|
expires_delta=timedelta(days=settings.jwt_refresh_token_expire_days),
|
||
|
|
token_version=token_version,
|
||
|
|
)
|
||
|
|
|
||
|
|
|
||
|
|
def decode_token(token: str) -> dict[str, Any]:
|
||
|
|
try:
|
||
|
|
payload = jwt.decode(
|
||
|
|
token,
|
||
|
|
settings.jwt_secret_key,
|
||
|
|
algorithms=[settings.jwt_algorithm],
|
||
|
|
audience=settings.jwt_audience,
|
||
|
|
issuer=settings.jwt_issuer,
|
||
|
|
)
|
||
|
|
except JWTError as exc:
|
||
|
|
raise ValueError("Invalid token") from exc
|
||
|
|
if "exp" not in payload:
|
||
|
|
raise ValueError("Invalid token")
|
||
|
|
if payload.get("type") not in {"access", "refresh"}:
|
||
|
|
raise ValueError("Invalid token")
|
||
|
|
return payload
|