CJR61 Claude Sonnet 4.6 commited on
Commit
bbc3fe2
·
1 Parent(s): 900d811

Add API key auth for predict and dashboard

Browse files

- app/auth.py: check_predict_key (X-API-Key header),
check_dashboard_key (?key= query param)
- /predict/ requires X-API-Key header (PREDICT_API_KEY env secret)
- /dashboard/* requires ?key= query param (DASHBOARD_KEY env secret)
- Dashboard JS auto-appends key from URL to all fetch calls
- HF Space set to public; secrets stored in HF Space settings

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

app/auth.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from fastapi import Header, Query, HTTPException
3
+
4
+ _PREDICT_KEY = os.getenv("PREDICT_API_KEY", "")
5
+ _DASHBOARD_KEY = os.getenv("DASHBOARD_KEY", "")
6
+
7
+
8
+ def check_predict_key(x_api_key: str = Header(..., alias="X-API-Key")):
9
+ if _PREDICT_KEY and x_api_key != _PREDICT_KEY:
10
+ raise HTTPException(status_code=403, detail="Invalid API key")
11
+
12
+
13
+ def check_dashboard_key(key: str = Query(..., description="Dashboard access key")):
14
+ if _DASHBOARD_KEY and key != _DASHBOARD_KEY:
15
+ raise HTTPException(status_code=403, detail="Invalid dashboard key")
app/dashboard/index.html CHANGED
@@ -131,6 +131,12 @@
131
  </div>
132
 
133
  <script>
 
 
 
 
 
 
134
  let activeTab = 'logs';
135
 
136
  function switchTab(tab, el) {
@@ -154,7 +160,7 @@ function setBar(id, pct) {
154
 
155
  async function loadStatus() {
156
  try {
157
- const d = await fetch('/dashboard/status/').then(r => r.json());
158
  document.getElementById('cpu-val').textContent = d.cpu_percent + '%';
159
  setBar('cpu-bar', d.cpu_percent);
160
 
@@ -174,7 +180,7 @@ async function loadStatus() {
174
 
175
  async function loadLogs() {
176
  try {
177
- const d = await fetch('/dashboard/logs/?lines=150').then(r => r.json());
178
  document.getElementById('log-meta').textContent =
179
  `Showing last ${d.lines.length} of ${d.total} total lines`;
180
  const box = document.getElementById('log-box');
@@ -193,7 +199,7 @@ async function loadLogs() {
193
 
194
  async function loadRecords() {
195
  try {
196
- const d = await fetch('/dashboard/database/').then(r => r.json());
197
  document.getElementById('db-meta').textContent = `Total records: ${d.total}`;
198
  const tbody = document.getElementById('db-body');
199
  if (!d.records.length) {
@@ -217,7 +223,7 @@ async function loadRecords() {
217
 
218
  async function loadImages() {
219
  try {
220
- const d = await fetch('/dashboard/uploads/').then(r => r.json());
221
  document.getElementById('img-meta').textContent = `Total uploads: ${d.total}`;
222
  const grid = document.getElementById('img-grid');
223
  if (!d.files.length) {
 
131
  </div>
132
 
133
  <script>
134
+ // Extract key from current URL and append to all API calls
135
+ const _key = new URLSearchParams(location.search).get('key') || '';
136
+ function api(path) {
137
+ return path + (path.includes('?') ? '&' : '?') + 'key=' + encodeURIComponent(_key);
138
+ }
139
+
140
  let activeTab = 'logs';
141
 
142
  function switchTab(tab, el) {
 
160
 
161
  async function loadStatus() {
162
  try {
163
+ const d = await fetch(api('/dashboard/status/')).then(r => r.json());
164
  document.getElementById('cpu-val').textContent = d.cpu_percent + '%';
165
  setBar('cpu-bar', d.cpu_percent);
166
 
 
180
 
181
  async function loadLogs() {
182
  try {
183
+ const d = await fetch(api('/dashboard/logs/?lines=150')).then(r => r.json());
184
  document.getElementById('log-meta').textContent =
185
  `Showing last ${d.lines.length} of ${d.total} total lines`;
186
  const box = document.getElementById('log-box');
 
199
 
200
  async function loadRecords() {
201
  try {
202
+ const d = await fetch(api('/dashboard/database/')).then(r => r.json());
203
  document.getElementById('db-meta').textContent = `Total records: ${d.total}`;
204
  const tbody = document.getElementById('db-body');
205
  if (!d.records.length) {
 
223
 
224
  async function loadImages() {
225
  try {
226
+ const d = await fetch(api('/dashboard/uploads/')).then(r => r.json());
227
  document.getElementById('img-meta').textContent = `Total uploads: ${d.total}`;
228
  const grid = document.getElementById('img-grid');
229
  if (!d.files.length) {
app/dashboard/router.py CHANGED
@@ -1,10 +1,12 @@
1
  import os
2
  import csv
3
  import psutil
4
- from fastapi import APIRouter, Request
5
  from fastapi.responses import HTMLResponse, FileResponse, JSONResponse
 
6
 
7
- router = APIRouter(prefix="/dashboard", tags=["dashboard"])
 
8
 
9
  _HTML = os.path.join(os.path.dirname(__file__), "index.html")
10
 
 
1
  import os
2
  import csv
3
  import psutil
4
+ from fastapi import APIRouter, Request, Depends
5
  from fastapi.responses import HTMLResponse, FileResponse, JSONResponse
6
+ from app.auth import check_dashboard_key
7
 
8
+ router = APIRouter(prefix="/dashboard", tags=["dashboard"],
9
+ dependencies=[Depends(check_dashboard_key)])
10
 
11
  _HTML = os.path.join(os.path.dirname(__file__), "index.html")
12
 
app/main.py CHANGED
@@ -5,6 +5,8 @@ from app.model import load_model, predict_image
5
  from app.utils import save_uploaded_file, append_to_csv
6
  from app.log import logger, configure_logger
7
  from app.dashboard.router import router as dashboard_router
 
 
8
  import os
9
  from app.utils import preprocess_image, is_valid_image
10
  from contextlib import asynccontextmanager
@@ -57,7 +59,7 @@ async def read_root():
57
  return {"message": "Connection successful!"}
58
 
59
  # Inference API
60
- @app.post("/predict/")
61
  async def predict(file: UploadFile = File(...)):
62
  # Save uploaded image and generate ID
63
  try:
 
5
  from app.utils import save_uploaded_file, append_to_csv
6
  from app.log import logger, configure_logger
7
  from app.dashboard.router import router as dashboard_router
8
+ from app.auth import check_predict_key
9
+ from fastapi import Depends
10
  import os
11
  from app.utils import preprocess_image, is_valid_image
12
  from contextlib import asynccontextmanager
 
59
  return {"message": "Connection successful!"}
60
 
61
  # Inference API
62
+ @app.post("/predict/", dependencies=[Depends(check_predict_key)])
63
  async def predict(file: UploadFile = File(...)):
64
  # Save uploaded image and generate ID
65
  try: