security.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. from datetime import datetime, timedelta
  2. from typing import Any, Union
  3. from jose import jwt
  4. from passlib.context import CryptContext
  5. from app.core.config import settings
  6. import string
  7. import secrets
  8. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  9. def verify_password(plain_password: str, hashed_password: str) -> bool:
  10. return pwd_context.verify(plain_password, hashed_password)
  11. def get_password_hash(password: str) -> str:
  12. return pwd_context.hash(password)
  13. def create_access_token(subject: Union[str, Any], expires_delta: timedelta = None) -> str:
  14. if expires_delta:
  15. expire = datetime.now() + expires_delta
  16. else:
  17. expire = datetime.now() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
  18. to_encode = {"exp": expire, "sub": str(subject)}
  19. encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
  20. return encoded_jwt
  21. def generate_random_password(length: int = 8) -> str:
  22. """Generate a random password containing at least one uppercase, one lowercase, one digit and one special char."""
  23. alphabet = string.ascii_letters + string.digits + "!@#$%^&*"
  24. while True:
  25. password = ''.join(secrets.choice(alphabet) for _ in range(length))
  26. if (any(c.islower() for c in password)
  27. and any(c.isupper() for c in password)
  28. and any(c.isdigit() for c in password)
  29. and any(c in "!@#$%^&*" for c in password)):
  30. return password
  31. def generate_alphanumeric_password(length: int = 8) -> str:
  32. """Generate a random password containing letters and digits only."""
  33. alphabet = string.ascii_letters + string.digits
  34. while True:
  35. password = ''.join(secrets.choice(alphabet) for _ in range(length))
  36. if (any(c.islower() for c in password)
  37. and any(c.isupper() for c in password)
  38. and any(c.isdigit() for c in password)):
  39. return password