security.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import datetime
  4. import json
  5. from typing import Any, Union
  6. import jwt
  7. from passlib.context import CryptContext
  8. from core.config import settings
  9. ALGORITHM: str = "HS256"
  10. pwd_context = CryptContext(schemes=["bcrypt"],
  11. deprecated="auto",
  12. bcrypt__default_rounds=8)
  13. async def create_token(subject: Union[str, Any],
  14. expires_delta: datetime.timedelta = None) -> str:
  15. if expires_delta:
  16. expire = datetime.datetime.now() + expires_delta
  17. else:
  18. expire = datetime.datetime.now() + datetime.timedelta(
  19. minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
  20. to_encoded = {"exp": expire, "sub": json.dumps(subject)}
  21. encoded_jwt = jwt.encode(to_encoded,
  22. settings.SECRET_KEY,
  23. algorithm=ALGORITHM)
  24. return encoded_jwt
  25. async def verify_password(plain_password: str, hashed_password: str):
  26. return pwd_context.verify(plain_password, hashed_password)
  27. def hashed_password(password: str) -> str:
  28. return pwd_context.hash(password)