|
| 1 | +import os |
| 2 | + |
| 3 | +import jwt |
| 4 | +from datetime import datetime, timedelta, timezone |
| 5 | + |
| 6 | +from fastapi import Header, HTTPException, status |
| 7 | + |
| 8 | +ALGORITHM = "HS256" |
| 9 | +ACCESS_TOKEN_EXPIRE_MINUTES = 30 |
| 10 | + |
| 11 | + |
| 12 | +def _get_secret_key() -> str: |
| 13 | + """Return the JWT secret key from the environment variable.""" |
| 14 | + return os.environ["AUTH_JWT_SECRET_KEY"] |
| 15 | + |
| 16 | + |
| 17 | +def create_access_token(username: str) -> str: |
| 18 | + """Create a JWT access token for the given username. |
| 19 | +
|
| 20 | + The token includes a 'sub' claim set to the username and an 'exp' claim |
| 21 | + set to now + ACCESS_TOKEN_EXPIRE_MINUTES. |
| 22 | +
|
| 23 | + Args: |
| 24 | + username: The username to encode in the token's 'sub' claim. |
| 25 | +
|
| 26 | + Returns: |
| 27 | + A signed JWT string using HS256. |
| 28 | + """ |
| 29 | + expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) |
| 30 | + payload = {"sub": username, "exp": expire} |
| 31 | + return jwt.encode(payload, _get_secret_key(), algorithm=ALGORITHM) |
| 32 | + |
| 33 | + |
| 34 | +def decode_access_token(token: str) -> str: |
| 35 | + """Decode and validate a JWT access token, returning the username. |
| 36 | +
|
| 37 | + Raises HTTPException(401) for expired or invalid tokens with appropriate |
| 38 | + error messages and WWW-Authenticate headers. |
| 39 | +
|
| 40 | + Args: |
| 41 | + token: The JWT string to decode. |
| 42 | +
|
| 43 | + Returns: |
| 44 | + The username from the token's 'sub' claim. |
| 45 | +
|
| 46 | + Raises: |
| 47 | + HTTPException: 401 if the token is expired or invalid. |
| 48 | + """ |
| 49 | + try: |
| 50 | + payload = jwt.decode(token, _get_secret_key(), algorithms=[ALGORITHM]) |
| 51 | + return payload.get("sub") |
| 52 | + except jwt.ExpiredSignatureError: |
| 53 | + raise HTTPException( |
| 54 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 55 | + detail="Token has expired", |
| 56 | + headers={"WWW-Authenticate": "Bearer"}, |
| 57 | + ) |
| 58 | + except jwt.InvalidTokenError: |
| 59 | + raise HTTPException( |
| 60 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 61 | + detail="Invalid token", |
| 62 | + headers={"WWW-Authenticate": "Bearer"}, |
| 63 | + ) |
| 64 | + |
| 65 | + |
| 66 | +async def get_current_user(authorization: str | None = Header(default=None)): |
| 67 | + """Extract and validate Bearer token. Returns username.""" |
| 68 | + if authorization is None: |
| 69 | + raise HTTPException( |
| 70 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 71 | + detail="Authorization header required", |
| 72 | + headers={"WWW-Authenticate": "Bearer"}, |
| 73 | + ) |
| 74 | + prefix, _, token = authorization.partition(" ") |
| 75 | + if prefix.lower() != "bearer" or not token: |
| 76 | + raise HTTPException( |
| 77 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 78 | + detail="Invalid authorization header", |
| 79 | + headers={"WWW-Authenticate": "Bearer"}, |
| 80 | + ) |
| 81 | + return decode_access_token(token) |
0 commit comments