|
| 1 | +import os |
| 2 | +from datetime import datetime, timedelta, timezone |
| 3 | +from functools import wraps |
| 4 | + |
| 5 | +import jwt |
| 6 | +from flask import jsonify, request |
| 7 | + |
| 8 | +JWT_SECRET_KEY = os.getenv("JWT_SECRET_KEY", "SuperSecretKey") |
| 9 | +JWT_ACCESS_TOKEN_EXPIRY = timedelta(hours=1) |
| 10 | +JWT_REFRESH_TOKEN_EXPIRY = timedelta(days=30) |
| 11 | + |
| 12 | + |
| 13 | +class TokenError(Exception): |
| 14 | + """Custom exception for token-related errors.""" |
| 15 | + |
| 16 | + def __init__(self, message, status_code): |
| 17 | + super().__init__(message) |
| 18 | + self.status_code = status_code |
| 19 | + self.message = message |
| 20 | + |
| 21 | + |
| 22 | +def generate_access_token(person_id: int) -> str: |
| 23 | + """Generate a short-lived JWT access token for a user.""" |
| 24 | + payload = { |
| 25 | + "person_id": person_id, |
| 26 | + "exp": datetime.now(timezone.utc) + JWT_ACCESS_TOKEN_EXPIRY, # Expiration |
| 27 | + "iat": datetime.now(timezone.utc), # Issued at |
| 28 | + "token_type": "access", |
| 29 | + } |
| 30 | + return jwt.encode(payload, JWT_SECRET_KEY, algorithm="HS256") |
| 31 | + |
| 32 | + |
| 33 | +def generate_refresh_token(person_id: int) -> str: |
| 34 | + """Generate a long-lived refresh token for a user.""" |
| 35 | + payload = { |
| 36 | + "person_id": person_id, |
| 37 | + "exp": datetime.now(timezone.utc) + JWT_REFRESH_TOKEN_EXPIRY, |
| 38 | + "iat": datetime.now(timezone.utc), |
| 39 | + "token_type": "refresh", |
| 40 | + } |
| 41 | + return jwt.encode(payload, JWT_SECRET_KEY, algorithm="HS256") |
| 42 | + |
| 43 | + |
| 44 | +def extract_token_from_header() -> str: |
| 45 | + """Extract the Bearer token from the Authorization header.""" |
| 46 | + auth_header = request.headers.get("Authorization") |
| 47 | + if not auth_header or not auth_header.startswith("Bearer "): |
| 48 | + raise TokenError("Token is missing or improperly formatted", 401) |
| 49 | + return auth_header.split("Bearer ")[1] |
| 50 | + |
| 51 | + |
| 52 | +def verify_token(token: str, required_type: str) -> dict: |
| 53 | + """Verify and decode a JWT token.""" |
| 54 | + try: |
| 55 | + decoded = jwt.decode(token, JWT_SECRET_KEY, algorithms=["HS256"]) |
| 56 | + if decoded.get("token_type") != required_type: |
| 57 | + raise jwt.InvalidTokenError("Invalid token type") |
| 58 | + return decoded |
| 59 | + except jwt.ExpiredSignatureError: |
| 60 | + raise TokenError("Token has expired", 401) |
| 61 | + except jwt.InvalidTokenError: |
| 62 | + raise TokenError("Invalid token", 401) |
| 63 | + |
| 64 | + |
| 65 | +def token_required(f): |
| 66 | + """Decorator to protect routes by requiring a valid token.""" |
| 67 | + |
| 68 | + @wraps(f) |
| 69 | + def decorated(*args, **kwargs): |
| 70 | + try: |
| 71 | + token = extract_token_from_header() |
| 72 | + decoded = verify_token(token, required_type="access") |
| 73 | + request.person_id = decoded["person_id"] |
| 74 | + return f(*args, **kwargs) |
| 75 | + except TokenError as e: |
| 76 | + return jsonify(message=e.message), e.status_code |
| 77 | + |
| 78 | + return decorated |
0 commit comments