34 lines
836 B
Python
34 lines
836 B
Python
"""Application Security."""
|
|
|
|
from datetime import UTC, datetime, timedelta
|
|
|
|
import jwt
|
|
from pwdlib import PasswordHash
|
|
|
|
SECRET_KEY = "change-me" # generate with: openssl rand -hex 32, load from env
|
|
ALGORITHM = "HS256"
|
|
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
|
|
|
password_hash = PasswordHash.recommended()
|
|
|
|
|
|
def hash_password(plain_text: str) -> str:
|
|
return password_hash.hash(plain_text)
|
|
|
|
|
|
def verify_password(plain_text: str, hashed_text: str) -> bool:
|
|
return password_hash.verify(plain_text, hashed_text)
|
|
|
|
|
|
def create_access_token(subject: str) -> str:
|
|
expire = datetime.now(UTC) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
payload = {"sub": subject, "exp": expire}
|
|
return jwt.encode(
|
|
payload,
|
|
SECRET_KEY,
|
|
)
|
|
|
|
|
|
def decode_access_token(token: str) -> dict:
|
|
return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|