34 lines
1010 B
Python
34 lines
1010 B
Python
from datetime import timedelta
|
|
import bcrypt
|
|
from jose import JWTError, jwt
|
|
from .config import settings
|
|
from .time_utils import utc_now
|
|
|
|
|
|
def verify_password(plain: str, hashed: str) -> bool:
|
|
if not plain or not hashed:
|
|
return False
|
|
try:
|
|
return bcrypt.checkpw(
|
|
plain.encode("utf-8")[:72],
|
|
hashed.encode("utf-8"),
|
|
)
|
|
except ValueError:
|
|
return False
|
|
|
|
|
|
def hash_password(plain: str) -> str:
|
|
hashed = bcrypt.hashpw(plain.encode("utf-8")[:72], bcrypt.gensalt())
|
|
return hashed.decode("utf-8")
|
|
|
|
|
|
def create_access_token(data: dict, expires_minutes: int | None = None) -> str:
|
|
to_encode = data.copy()
|
|
expire = utc_now() + timedelta(minutes=expires_minutes or settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
to_encode["exp"] = expire
|
|
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
|
|
|
|
|
def decode_token(token: str) -> dict:
|
|
return jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|