38 lines
1.2 KiB
Python
38 lines
1.2 KiB
Python
import os
|
|
from datetime import datetime, timedelta, timezone
|
|
from typing import Optional, Any
|
|
import jwt
|
|
import bcrypt
|
|
|
|
SECRET_KEY: str = os.environ.get("DECNET_SECRET_KEY", "super-secret-key-change-me")
|
|
ALGORITHM: str = "HS256"
|
|
ACCESS_TOKEN_EXPIRE_MINUTES: int = 1440
|
|
|
|
|
|
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
|
return bcrypt.checkpw(
|
|
plain_password.encode("utf-8"),
|
|
hashed_password.encode("utf-8")
|
|
)
|
|
|
|
|
|
def get_password_hash(password: str) -> str:
|
|
# Use a cost factor of 12 (default for passlib/bcrypt)
|
|
salt = bcrypt.gensalt(rounds=12)
|
|
hashed = bcrypt.hashpw(password.encode("utf-8"), salt)
|
|
return hashed.decode("utf-8")
|
|
|
|
|
|
def create_access_token(data: dict[str, Any], expires_delta: Optional[timedelta] = None) -> str:
|
|
to_encode: dict[str, Any] = data.copy()
|
|
expire: datetime
|
|
if expires_delta:
|
|
expire = datetime.now(timezone.utc) + expires_delta
|
|
else:
|
|
expire = datetime.now(timezone.utc) + timedelta(minutes=15)
|
|
|
|
to_encode.update({"exp": expire})
|
|
to_encode.update({"iat": datetime.now(timezone.utc)})
|
|
encoded_jwt: str = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
|
return encoded_jwt
|