-
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
import jwt
|
||||
from pwdlib import PasswordHash
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
_password_hash = PasswordHash.recommended() # Argon2id
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return _password_hash.hash(password)
|
||||
|
||||
|
||||
def verify_password(password: str, hashed: str) -> bool:
|
||||
return _password_hash.verify(password, hashed)
|
||||
|
||||
|
||||
# Used to keep login timing similar whether or not the email exists.
|
||||
DUMMY_HASH = hash_password("timing-equaliser-not-a-real-password")
|
||||
|
||||
|
||||
def create_access_token(subject: str, role: str) -> tuple[str, int]:
|
||||
expires_in = settings.JWT_EXPIRE_MINUTES * 60
|
||||
now = datetime.now(UTC)
|
||||
payload = {
|
||||
"sub": subject,
|
||||
"role": role,
|
||||
"type": "access",
|
||||
"iat": now,
|
||||
"exp": now + timedelta(seconds=expires_in),
|
||||
}
|
||||
token = jwt.encode(payload, settings.JWT_SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
|
||||
return token, expires_in
|
||||
|
||||
|
||||
def decode_access_token(token: str) -> dict:
|
||||
"""Raises jwt.PyJWTError on invalid/expired tokens."""
|
||||
payload = jwt.decode(
|
||||
token,
|
||||
settings.JWT_SECRET_KEY,
|
||||
algorithms=[settings.JWT_ALGORITHM],
|
||||
options={"require": ["sub", "exp", "iat"]},
|
||||
)
|
||||
if payload.get("type") != "access":
|
||||
raise jwt.InvalidTokenError("wrong token type")
|
||||
return payload
|
||||
Reference in New Issue
Block a user