File size: 1,803 Bytes
4a91ea9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | from datetime import datetime, timedelta
from typing import Optional, Union
from jose import jwt, JWTError
from passlib.context import CryptContext
from app.core.config import settings
import bcrypt
# PATCH: Fix for passlib compatibility with bcrypt >= 4.0.0
# passlib attempts to access bcrypt.__about__.__version__ which was removed in 4.0.0
# It also has an issue with the "wrap bug" detection (testing with long password)
# which causes ValueError in bcrypt 4.0.0+
import passlib.handlers.bcrypt
try:
if not hasattr(bcrypt, '__about__'):
class About:
__version__ = bcrypt.__version__
bcrypt.__about__ = About()
passlib.handlers.bcrypt.bcrypt.detect_wrap_bug = lambda cmd: False
except Exception:
pass
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
MAX_PASSWORD_BYTE_LENGTH = 72
def _truncate_password(password: Union[str, bytes]) -> bytes:
if isinstance(password, str):
password = password.encode('utf-8')
if len(password) > MAX_PASSWORD_BYTE_LENGTH:
password = password[:MAX_PASSWORD_BYTE_LENGTH]
return password
def verify_password(plain_password, hashed_password):
plain_password = _truncate_password(plain_password)
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password):
password = _truncate_password(password)
return pwd_context.hash(password)
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
return encoded_jwt
|