56 lines
1.4 KiB
Python
56 lines
1.4 KiB
Python
"""JWT token generation and validation."""
|
|
from datetime import datetime, timedelta
|
|
from typing import Optional
|
|
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: Optional[timedelta] = 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.utcnow() + expires_delta
|
|
else:
|
|
expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
|
|
to_encode = {
|
|
"sub": str(user_id),
|
|
"email": email,
|
|
"exp": expire,
|
|
"iat": datetime.utcnow(),
|
|
"type": "access"
|
|
}
|
|
|
|
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
|
return encoded_jwt
|
|
|
|
|
|
def decode_access_token(token: str) -> Optional[dict]:
|
|
"""
|
|
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
|
|
|