Skip to content

feat: Go backend scaffold with JWT auth, sensor API, ML inference, and rate limiting#7

Merged
gagan-devv merged 2 commits into
mainfrom
backend-init
Mar 20, 2026
Merged

feat: Go backend scaffold with JWT auth, sensor API, ML inference, and rate limiting#7
gagan-devv merged 2 commits into
mainfrom
backend-init

Conversation

@gagan-devv

Copy link
Copy Markdown
Owner

Summary

Migrates the TerraDetect backend from Python/Flask to Go (Gin), as part
of the broader Python → Go + Expo migration plan. The Python backend is
preserved in full on the archive/python-backend branch.


What's changed

New: Go backend (backend/)

  • main.go — Gin router with all routes wired, CORS configured
  • config/ — env var loading with startup validation (fails fast on missing vars)
  • db/ — MongoDB Atlas connection with compound index on sensor_data and TTL index on token denylist
  • middleware/ — JWT auth middleware + IP-based rate limiting via ulule/limiter
  • models/User, Device, SensorReading structs matching existing MongoDB schema
  • handlers/auth.go — Register, Login, Refresh, Logout with proper JWT access/refresh token flow
  • handlers/sensor.go — ESP32 ingest (POST /api/esp32), latest reading, paginated history
  • handlers/device.go — Device ID registration check
  • handlers/predict.go — Crop recommendation, suitability analysis, fertilizer suggestion (ported from Python)
  • handlers/weather.go — Server-side WeatherAPI proxy (API key never reaches client)
  • inference/onnx.go — ONNX runtime wrapper for crop and fertilizer models

New: ML export (ml/)

  • export_onnx.py — converts crop-model.pkl and fertilizer-model.pkl to ONNX
  • validate_onnx.py — verifies ONNX predictions match scikit-learn output before promoting
  • crop-model.onnx / fertilizer-model.onnx — exported model artifacts

Security fixes (vs Python version)

  • Session-based auth replaced with short-lived JWT access tokens (15 min) + refresh tokens (30 days)
  • Refresh token denylist in MongoDB — logout actually invalidates tokens
  • Rate limiting on all public endpoints (5/min login, 3/min register, 2/sec ESP32)
  • Weather API key moved server-side — was previously hardcoded in script.js
  • Dead VALID_DEVICE_IDS set removed
  • API_KEY = "YOUR_SUPER_SECRET_KEY" placeholder route removed

ESP32 firmware (sketches/)

  • client.setInsecure() replaced with setCACert(ROOT_CA) — ISRG Root X1 pinned
  • secrets.h pattern introduced — API key, device ID, and backend URL out of .ino
  • secrets.h.template comm

@gagan-devv gagan-devv merged commit ca234ed into main Mar 20, 2026
2 of 5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant