49 lines
1.3 KiB
Python
49 lines
1.3 KiB
Python
"""JWT token generation and validation."""
|
|
|
|
from datetime import datetime, timedelta, timezone
|
|
from uuid import UUID
|
|
|
|
from jose import JWTError, jwt
|
|
|
|
from app.core.config import settings
|
|
|
|
|
|
def create_access_token(user_id: UUID, email: str, expires_delta: timedelta | None = None) -> str:
|
|
"""
|
|
Create a new JWT access token.
|
|
|
|
Args:
|
|
user_id: User's UUID
|
|
email: User's email address
|
|
expires_delta: Optional custom expiration time
|
|
|
|
Returns:
|
|
Encoded JWT token string
|
|
"""
|
|
if expires_delta:
|
|
expire = datetime.now(timezone.utc) + expires_delta
|
|
else:
|
|
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
|
|
to_encode = {"sub": str(user_id), "email": email, "exp": expire, "iat": datetime.now(timezone.utc), "type": "access"}
|
|
|
|
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
|
return encoded_jwt
|
|
|
|
|
|
def decode_access_token(token: str) -> dict | None:
|
|
"""
|
|
Decode and validate a JWT access token.
|
|
|
|
Args:
|
|
token: JWT token string to decode
|
|
|
|
Returns:
|
|
Decoded token payload if valid, None otherwise
|
|
"""
|
|
try:
|
|
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
|
return payload
|
|
except JWTError:
|
|
return None
|