Spaces:
Paused

meloon / app /core /security.py
isold's picture
Feature: Add new applications
4a91ea9
Raw History Blame Contribute Delete
1.8 kB
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