| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- """Authentication service for JWT token generation and validation."""
- import jwt
- from datetime import datetime, timezone, timedelta
- from flask import current_app
- class AuthService:
- """Service for handling JWT authentication."""
-
- @staticmethod
- def generate_token(admin):
- """Generate a JWT token for an admin.
-
- Args:
- admin: Admin model instance
-
- Returns:
- JWT token string
- """
- expiration_days = current_app.config.get('JWT_EXPIRATION_DAYS', 7)
- secret_key = current_app.config.get('JWT_SECRET_KEY')
- algorithm = current_app.config.get('JWT_ALGORITHM', 'HS256')
-
- now = datetime.now(timezone.utc)
- payload = {
- 'admin_id': admin.id,
- 'username': admin.username,
- 'iat': now,
- 'exp': now + timedelta(days=expiration_days)
- }
-
- token = jwt.encode(payload, secret_key, algorithm=algorithm)
- return token
-
- @staticmethod
- def verify_token(token):
- """Verify and decode a JWT token.
-
- Args:
- token: JWT token string
-
- Returns:
- Decoded payload dict if valid, None if invalid
-
- Raises:
- jwt.ExpiredSignatureError: If token has expired
- jwt.InvalidTokenError: If token is invalid
- """
- secret_key = current_app.config.get('JWT_SECRET_KEY')
- algorithm = current_app.config.get('JWT_ALGORITHM', 'HS256')
-
- payload = jwt.decode(token, secret_key, algorithms=[algorithm])
- return payload
|