phase 3.1
This commit is contained in:
55
backend/app/auth/jwt.py
Normal file
55
backend/app/auth/jwt.py
Normal file
@@ -0,0 +1,55 @@
|
||||
"""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
|
||||
|
||||
Reference in New Issue
Block a user