Skip to content

Commit

Permalink
enable API token
Browse files Browse the repository at this point in the history
  • Loading branch information
mmaelicke committed Jan 22, 2025
1 parent 093948a commit 094daa3
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
10 changes: 4 additions & 6 deletions metacatalog_api/default_server.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
from fastapi import Request
from fastapi.staticfiles import StaticFiles
from pathlib import Path
from fastapi import Request, Depends
from starlette.middleware.cors import CORSMiddleware

from metacatalog_api.server import app, server
Expand All @@ -9,7 +7,7 @@
from metacatalog_api.apps.explorer.read import templates
from metacatalog_api.apps.explorer import static_files
from metacatalog_api.router.api.read import read_router as api_read_router
from metacatalog_api.router.api.create import create_router as api_create_router
from metacatalog_api.router.api.create import create_router as api_create_router, validate_api_key
from metacatalog_api.router.api.upload import upload_router
from metacatalog_api.apps.explorer.create import create_router as explorer_create
from metacatalog_api.apps.explorer.read import explorer_router
Expand Down Expand Up @@ -37,8 +35,8 @@ def index(request: Request):

# add all api routes - currently this is only splitted into read and create
app.include_router(api_read_router)
app.include_router(api_create_router)
app.include_router(upload_router)
app.include_router(api_create_router, dependencies=[Depends(validate_api_key)])
app.include_router(upload_router, dependencies=[Depends(validate_api_key)])

# add the default explorer application (the HTML)
app.mount(f"{server.app_prefix}static", static_files, name="static")
Expand Down
11 changes: 10 additions & 1 deletion metacatalog_api/router/api/create.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
from fastapi import APIRouter
from fastapi import APIRouter, Security, HTTPException
from fastapi.security import APIKeyHeader

from metacatalog_api import core
from metacatalog_api import models
from metacatalog_api import access_control

create_router = APIRouter()

async def validate_api_key(api_key: str = Security(APIKeyHeader(name="X-API-Key"))):
with core.connect() as session:
token = access_control.validate_token(session, api_key)
if token is None:
raise HTTPException(status_code=401, detail="Invalid API key")
return token

@create_router.post('/entries')
def add_entry(payload: models.EntryCreate, author_duplicates: bool = False) -> models.Metadata:
metadata = core.add_entry(payload, author_duplicates=author_duplicates)
Expand Down

0 comments on commit 094daa3

Please sign in to comment.