Add Token model and update endpoints to use it

Refactor token validation and saving endpoints to accept a Token model
instead of a raw string. Set default values for token generation request
fields. Update TokenService cleanup to use datetime.now().
This commit is contained in:
rafaeldpsilva
2025-10-08 14:05:11 +01:00
parent 38fb3e6e96
commit da1fb2a058
3 changed files with 59 additions and 48 deletions

View File

@@ -15,7 +15,7 @@ from typing import List, Optional
from models import ( from models import (
TokenGenerateRequest, TokenResponse, TokenValidationResponse, TokenGenerateRequest, TokenResponse, TokenValidationResponse,
TokenListResponse, HealthResponse TokenListResponse, HealthResponse, Token
) )
from database import connect_to_mongo, close_mongo_connection, get_database from database import connect_to_mongo, close_mongo_connection, get_database
from token_service import TokenService from token_service import TokenService
@@ -95,6 +95,16 @@ async def generate_token(request: TokenGenerateRequest, db=Depends(get_db)):
"""Generate a new JWT token""" """Generate a new JWT token"""
try: try:
token_service = TokenService(db) token_service = TokenService(db)
if not request.data_aggregation:
request.data_aggregation = False
if not request.time_aggregation:
request.time_aggregation = False
if not request.embargo:
request.embargo = False
if not request.exp_hours:
request.exp_hours = 24
token = token_service.generate_token( token = token_service.generate_token(
name=request.name, name=request.name,
list_of_resources=request.list_of_resources, list_of_resources=request.list_of_resources,
@@ -110,16 +120,16 @@ async def generate_token(request: TokenGenerateRequest, db=Depends(get_db)):
raise HTTPException(status_code=500, detail="Internal server error") raise HTTPException(status_code=500, detail="Internal server error")
@app.post("/tokens/validate", response_model=TokenValidationResponse) @app.post("/tokens/validate", response_model=TokenValidationResponse)
async def validate_token(token: str, db=Depends(get_db)): async def validate_token(token: Token, db=Depends(get_db)):
"""Validate and decode a JWT token""" """Validate and decode a JWT token"""
try: try:
token_service = TokenService(db) token_service = TokenService(db)
is_valid = await token_service.is_token_valid(token) is_valid = await token_service.is_token_valid(token.token)
decoded = token_service.decode_token(token) if is_valid else None decoded = token_service.decode_token(token.token) if is_valid else None
return TokenValidationResponse( return TokenValidationResponse(
valid=is_valid, valid=is_valid,
token=token, token=token.token,
decoded=decoded if is_valid and "error" not in (decoded or {}) else None, decoded=decoded if is_valid and "error" not in (decoded or {}) else None,
error=decoded.get("error") if decoded and "error" in decoded else None error=decoded.get("error") if decoded and "error" in decoded else None
) )
@@ -128,11 +138,11 @@ async def validate_token(token: str, db=Depends(get_db)):
raise HTTPException(status_code=500, detail="Internal server error") raise HTTPException(status_code=500, detail="Internal server error")
@app.post("/tokens/save") @app.post("/tokens/save")
async def save_token(token: str, db=Depends(get_db)): async def save_token(token: Token, db=Depends(get_db)):
"""Save a token to database""" """Save a token to database"""
try: try:
token_service = TokenService(db) token_service = TokenService(db)
result = await token_service.insert_token(token) result = await token_service.insert_token(token.token)
return result return result
except ValueError as e: except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) raise HTTPException(status_code=400, detail=str(e))

View File

@@ -6,6 +6,9 @@ from pydantic import BaseModel, Field
from typing import List, Optional, Dict, Any from typing import List, Optional, Dict, Any
from datetime import datetime from datetime import datetime
class Token(BaseModel):
token: str = Field(..., description="JWT token")
class TokenGenerateRequest(BaseModel): class TokenGenerateRequest(BaseModel):
"""Request model for token generation""" """Request model for token generation"""
name: str = Field(..., description="Token owner name") name: str = Field(..., description="Token owner name")

View File

@@ -126,7 +126,6 @@ class TokenService:
async def is_token_valid(self, token: str) -> bool: async def is_token_valid(self, token: str) -> bool:
"""Check if token is valid and active""" """Check if token is valid and active"""
# Check if token exists and is active in database
token_record = await self.tokens_collection.find_one({ token_record = await self.tokens_collection.find_one({
"token": token, "token": token,
"active": True "active": True
@@ -135,7 +134,6 @@ class TokenService:
if not token_record: if not token_record:
return False return False
# Verify JWT signature and expiration
decoded = self.decode_token(token) decoded = self.decode_token(token)
return decoded is not None and "error" not in decoded return decoded is not None and "error" not in decoded
@@ -147,7 +145,7 @@ class TokenService:
async def cleanup_expired_tokens(self) -> int: async def cleanup_expired_tokens(self) -> int:
"""Remove expired tokens from database""" """Remove expired tokens from database"""
now = datetime.utcnow() now = datetime.now()
# Delete tokens that have expired # Delete tokens that have expired
result = await self.tokens_collection.delete_many({ result = await self.tokens_collection.delete_many({