85 lines
2.1 KiB
Python
85 lines
2.1 KiB
Python
"""
|
|
JWT Token Generation and Validation
|
|
"""
|
|
from datetime import datetime, timedelta
|
|
from typing import Optional, Dict
|
|
import jwt
|
|
from fastapi import HTTPException, status
|
|
from app.config import settings
|
|
|
|
|
|
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
|
|
"""
|
|
Create JWT access token
|
|
|
|
Args:
|
|
data: Payload to encode (typically {"sub": user_id, "role": user_role})
|
|
expires_delta: Optional custom expiration time
|
|
|
|
Returns:
|
|
Encoded JWT token
|
|
"""
|
|
to_encode = data.copy()
|
|
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=settings.JWT_EXPIRATION_MINUTES))
|
|
to_encode.update({"exp": expire, "type": "access"})
|
|
|
|
encoded_jwt = jwt.encode(
|
|
to_encode,
|
|
settings.JWT_SECRET,
|
|
algorithm=settings.JWT_ALGORITHM
|
|
)
|
|
return encoded_jwt
|
|
|
|
|
|
def create_refresh_token(data: dict) -> str:
|
|
"""
|
|
Create JWT refresh token (longer expiration)
|
|
|
|
Args:
|
|
data: Payload to encode (typically {"sub": user_id})
|
|
|
|
Returns:
|
|
Encoded refresh token
|
|
"""
|
|
to_encode = data.copy()
|
|
expire = datetime.utcnow() + timedelta(days=settings.REFRESH_TOKEN_EXPIRATION_DAYS)
|
|
to_encode.update({"exp": expire, "type": "refresh"})
|
|
|
|
encoded_jwt = jwt.encode(
|
|
to_encode,
|
|
settings.JWT_SECRET,
|
|
algorithm=settings.JWT_ALGORITHM
|
|
)
|
|
return encoded_jwt
|
|
|
|
|
|
def verify_token(token: str) -> Dict:
|
|
"""
|
|
Verify and decode JWT token
|
|
|
|
Args:
|
|
token: JWT token string
|
|
|
|
Returns:
|
|
Decoded payload
|
|
|
|
Raises:
|
|
HTTPException: If token is invalid or expired
|
|
"""
|
|
try:
|
|
payload = jwt.decode(
|
|
token,
|
|
settings.JWT_SECRET,
|
|
algorithms=[settings.JWT_ALGORITHM]
|
|
)
|
|
return payload
|
|
except jwt.ExpiredSignatureError:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Token has expired"
|
|
)
|
|
except jwt.JWTError:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid token"
|
|
)
|