security.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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, is_long_term: bool = False) -> 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. if is_long_term:
  20. to_encode["long_term"] = True
  21. encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
  22. return encoded_jwt
  23. def generate_random_password(length: int = 8) -> str:
  24. """Generate a random password containing at least one uppercase, one lowercase, one digit and one special char."""
  25. alphabet = string.ascii_letters + string.digits + "!@#$%^&*"
  26. while True:
  27. password = ''.join(secrets.choice(alphabet) for _ in range(length))
  28. if (any(c.islower() for c in password)
  29. and any(c.isupper() for c in password)
  30. and any(c.isdigit() for c in password)
  31. and any(c in "!@#$%^&*" for c in password)):
  32. return password
  33. def generate_alphanumeric_password(length: int = 8) -> str:
  34. """Generate a random password containing letters and digits only."""
  35. alphabet = string.ascii_letters + string.digits
  36. while True:
  37. password = ''.join(secrets.choice(alphabet) for _ in range(length))
  38. if (any(c.islower() for c in password)
  39. and any(c.isupper() for c in password)
  40. and any(c.isdigit() for c in password)):
  41. return password