Skip to content

Commit

Permalink
Merge pull request #64 from MauriceBoendermaker/GH-SECRETS-Apikeys
Browse files Browse the repository at this point in the history
Gh secrets apikeys
  • Loading branch information
MauriceBoendermaker authored Jan 21, 2025
2 parents 04cbd60 + 4e58b4f commit ff6bff6
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 32 deletions.
4 changes: 4 additions & 0 deletions .github/workflows/python-app.yml
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@ jobs:
run: echo "PYTHONPATH=$(pwd)" >> $GITHUB_ENV

- name: run CargoHubV2 server
env:
WAREHOUSE_MANAGER: ${{ secrets.WAREHOUSE_MANAGER}}
FLOOR_MANAGER: ${{ secrets.FLOOR_MANAGER }}
EMPLOYEE: ${{ secrets.EMPLOYEE }}
run: |
uvicorn CargoHubV2.app.main:app --port 3000 &
sleep 10
Expand Down
18 changes: 14 additions & 4 deletions CargoHubV2/app/controllers/packinglist_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
tags=["packinglist"]
)


@router.get("/api/v2/packinglist/{order_id}")
def create_packing_list(
order_id: int,
Expand All @@ -24,10 +25,19 @@ def create_packing_list(


@router.get("/get-pdf/{filename}")
def get_pdf(filename: str):
def get_pdf(filename: str, api_key: str = Header(...)):
PDF_DIR = Path("generated_pdfs")
pdf_path = PDF_DIR/filename

# voorkomt path traversal
sanitized_filename = Path(filename).name
pdf_path = PDF_DIR/sanitized_filename

if not str(pdf_path).startswith(str(PDF_DIR)):
raise HTTPException(status_code=403, detail="Base path modified")

if pdf_path.exists():
return FileResponse(pdf_path, media_type="application/pdf", filename=filename)
return FileResponse(
pdf_path, media_type="application/pdf",
filename=sanitized_filename)
else:
raise HTTPException(status_code=404, detail="PDF not found")
raise HTTPException(status_code=404, detail="PDF not found")
14 changes: 11 additions & 3 deletions CargoHubV2/app/controllers/reporting_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,18 @@ def generate_general_report(


@router.get("/get-pdf/{filename}")
def get_pdf(filename: str):
def get_pdf(filename: str, api_key: str = Header(...)):
PDF_DIR = Path("generated_pdfs")
pdf_path = PDF_DIR/filename
# voorkomt path traversal
sanitized_filename = Path(filename).name
pdf_path = PDF_DIR/sanitized_filename

if not str(pdf_path).startswith(str(PDF_DIR)):
raise HTTPException(status_code=403, detail="Base path modified")

if pdf_path.exists():
return FileResponse(pdf_path, media_type="application/pdf", filename=filename)
return FileResponse(
pdf_path,
media_type="application/pdf", filename=sanitized_filename)
else:
raise HTTPException(status_code=404, detail="PDF not found")
77 changes: 52 additions & 25 deletions CargoHubV2/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
from CargoHubV2.app.controllers import reporting_controller
from CargoHubV2.app.controllers import packinglist_controller
from CargoHubV2.app.controllers import docks_controller
import time

import os
from dotenv import load_dotenv
from starlette.responses import JSONResponse
import logging

Expand All @@ -24,7 +26,7 @@
# welke port hij runt kan je bij command aanpassen
# default port is localhost:8000

# router van de controller gebruiken
# routers van de controllers gebruiken
app.include_router(reporting_controller.router)
app.include_router(item_groups.router)
app.include_router(item_lines.router)
Expand All @@ -34,7 +36,6 @@
app.include_router(transfers_controller.router)
app.include_router(suppliers_controller.router)
app.include_router(warehouses_controller.router)
app.include_router(load_controller.router)
app.include_router(clients_controller.router)
app.include_router(shipments_controller.router)
app.include_router(inventories_controller.router)
Expand All @@ -44,6 +45,19 @@

logger = logging.getLogger("uvicorn.error")

# haalt api keys uit env variabelen
# in github werkt dit ook, uit GH secrets
# voor lokaal runnen, moet er een .env zijn met deze 3 variabelen
load_dotenv()
warehouse_manager = os.getenv("WAREHOUSE_MANAGER")
floor_manager = os.getenv("FLOOR_MANAGER")
employee = os.getenv("EMPLOYEE")
'''
print(warehouse_manager)
print(floor_manager)
print(employee)
'''


@app.get("/")
async def root():
Expand All @@ -63,10 +77,18 @@ async def shutdown():

@app.middleware("http")
async def api_key_middleware(request: Request, call_next):
# anders kan de documentatie niet bereikt worden
excluded = ["/favicon.ico", "/openapi.json", "/docs"]

w_man_only = ["v2/reports", "v2/warehouses", "v2/clients", "v2/suppliers"]
all_managers = ["v2/item_groups", "v2/item_lines", "v2/item_types", "v2/items",
"v2/shipments", "v2/docks"]
all = ["v2/locations", "v2/transfers", "v2/orders", "v2/inventories",
"v2/packinglist"]

try:
x_api_key = request.headers.get("api-key")
if request.url.path in excluded or "/get-pdf" in request.url.path:
if request.url.path in excluded:
return await call_next(request)
response: Response = await call_next(request)

Expand All @@ -75,10 +97,32 @@ async def api_key_middleware(request: Request, call_next):
response.status_code = 422
raise HTTPException(status_code=422, detail="Missing API key")

if x_api_key != "a1b2c3d4e5":
logger.warning("Invalid API key")
response.status_code = 403
raise HTTPException(status_code=403, detail="Invalid API key")
if any(path in request.url.path for path in w_man_only):

if x_api_key != warehouse_manager:
logger.warning("Invalid API key")
response.status_code = 403
raise HTTPException(
status_code=403,
detail="Invalid API key, need to be Warehouse manager")

if any(path in request.url.path for path in all_managers):

if x_api_key != warehouse_manager and x_api_key != floor_manager:
logger.warning("Invalid API key")
response.status_code = 403
raise HTTPException(
status_code=403,
detail="Invalid API key, only Floor/Warehouse managers")

if any(path in request.url.path for path in all):

if x_api_key != warehouse_manager and x_api_key != floor_manager and x_api_key != employee:
logger.warning("Invalid API key")
response.status_code = 403
raise HTTPException(
status_code=403,
detail="Invalid API key, need to be employee of CargoHub")

return response

Expand All @@ -91,20 +135,3 @@ async def api_key_middleware(request: Request, call_next):
except Exception as exc:
logger.exception("Unexpected error occurred in middleware")
raise exc

'''
# script voor migrations voor later
from database import Base, engine
from models import warehouse_model, items_model, location_model, transfers_model # alle models die je wil migraten
# maakt alle tables
def init_db():
Base.metadata.create_all(bind=engine)
if __name__ == "__main__":
init_db()
print("Tables created successfully!")
'''

1 comment on commit ff6bff6

@github-actions
Copy link

Please sign in to comment.