auth_service.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. """Authentication service for JWT token generation and validation."""
  2. import jwt
  3. from datetime import datetime, timezone, timedelta
  4. from flask import current_app
  5. class AuthService:
  6. """Service for handling JWT authentication."""
  7. @staticmethod
  8. def generate_token(admin):
  9. """Generate a JWT token for an admin.
  10. Args:
  11. admin: Admin model instance
  12. Returns:
  13. JWT token string
  14. """
  15. expiration_days = current_app.config.get('JWT_EXPIRATION_DAYS', 7)
  16. secret_key = current_app.config.get('JWT_SECRET_KEY')
  17. algorithm = current_app.config.get('JWT_ALGORITHM', 'HS256')
  18. now = datetime.now(timezone.utc)
  19. payload = {
  20. 'admin_id': admin.id,
  21. 'username': admin.username,
  22. 'iat': now,
  23. 'exp': now + timedelta(days=expiration_days)
  24. }
  25. token = jwt.encode(payload, secret_key, algorithm=algorithm)
  26. return token
  27. @staticmethod
  28. def verify_token(token):
  29. """Verify and decode a JWT token.
  30. Args:
  31. token: JWT token string
  32. Returns:
  33. Decoded payload dict if valid, None if invalid
  34. Raises:
  35. jwt.ExpiredSignatureError: If token has expired
  36. jwt.InvalidTokenError: If token is invalid
  37. """
  38. secret_key = current_app.config.get('JWT_SECRET_KEY')
  39. algorithm = current_app.config.get('JWT_ALGORITHM', 'HS256')
  40. payload = jwt.decode(token, secret_key, algorithms=[algorithm])
  41. return payload