tiny-school-hub-api-backend

module
v0.1.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 24, 2025 License: GPL-3.0

README ΒΆ

Tiny School Hub API Backend

Go Version AWS SDK

A production-ready, Kubernetes-native backend for school communication and management.

🎯 Overview

Tiny School Hub is a vendor-neutral, cloud-agnostic backend service built with Go, designed to run on any Kubernetes distribution. It provides secure communication between teachers and parents with class management, photo sharing, absence tracking, and messaging.

Key Features
  • πŸ” Security-First: Argon2id password hashing, JWT authentication, RBAC
  • ☸️ Kubernetes-Native: Health probes, graceful shutdown, HPA, NetworkPolicies
  • 🌐 Vendor-Neutral: No cloud-specific SDKs, works with any S3-compatible storage
  • πŸ“¦ 12-Factor App: Configuration via environment, stateless, portable
  • πŸš€ Production-Ready: AWS SDK v2, structured logging, rate limiting
  • πŸ§ͺ Testable: Clean architecture, dependency injection, interfaces

πŸ“‹ Quick Start

# 1. Clone and setup
git clone https://github.com/TinySchoolHub/tiny-school-hub-api-backend.git
cd tiny-school-hub-api-backend
cp .env.example .env

# 2. Install development tools and pre-commit hooks
make install-tools
make install-hooks

# 3. Start local infrastructure (PostgreSQL + MinIO)
make docker-up

# 4. Start the API server (migrations run automatically!)
make run
# Server starts on http://localhost:8080
# Database migrations are embedded and run on startup ✨

πŸ—οΈ Architecture

tiny-school-hub-api-backend/
β”œβ”€β”€ cmd/api/              # Application entry point
β”œβ”€β”€ internal/
β”‚   β”œβ”€β”€ config/           # Configuration management
β”‚   β”œβ”€β”€ core/
β”‚   β”‚   β”œβ”€β”€ auth/         # JWT & password hashing (Argon2id)
β”‚   β”‚   └── domain/       # Domain models & errors
β”‚   β”œβ”€β”€ http/
β”‚   β”‚   β”œβ”€β”€ handlers/     # HTTP request handlers
β”‚   β”‚   └── middleware/   # Auth, CORS, rate limiting
β”‚   β”œβ”€β”€ repository/       # Data persistence interfaces
β”‚   β”‚   └── postgres/     # PostgreSQL implementations
β”‚   └── storage/          # S3-compatible storage (AWS SDK v2)
β”œβ”€β”€ pkg/log/              # Structured logging
β”œβ”€β”€ migrations/           # Database migrations
└── deploy/
    β”œβ”€β”€ helm/             # Helm charts
    └── kustomize/        # Kustomize overlays
Technology Stack
  • Language: Go 1.24+
  • Router: Chi (lightweight, idiomatic)
  • Database: PostgreSQL 16+
  • Storage: S3-compatible (MinIO, AWS S3, etc.)
  • Auth: JWT (golang-jwt/jwt), Argon2id
  • Logging: Zerolog (structured JSON)
  • Migrations: golang-migrate
  • Container: Docker (multi-stage, scratch-based)
  • Orchestration: Kubernetes + Helm

πŸ” Security

Authentication & Authorization
  • Password Hashing: Argon2id (memory-hard, GPU-resistant)
  • JWT Tokens:
    • Short-lived access tokens (15 minutes)
    • Long-lived refresh tokens (7 days) with rotation
    • Token revocation support
  • RBAC: Three roles (TEACHER, PARENT, ADMIN)
  • Class-Scoped Access: Membership validation on all operations
Infrastructure Security
  • Container: Non-root user, read-only filesystem, dropped capabilities
  • Network: Kubernetes NetworkPolicies restrict ingress/egress
  • Secrets: Environment-based, never hardcoded
  • Rate Limiting: Per-IP throttling to prevent abuse
  • CORS: Configurable allowed origins
Data Protection
  • PII Protection: No sensitive data in logs
  • SQL Injection: Parameterized queries throughout
  • File Uploads: Content-type whitelist, size limits (5MB)
  • Error Handling: Structured responses, no stack traces

πŸ“‘ API Endpoints

Authentication (Public)
POST   /v1/auth/register   - User registration
POST   /v1/auth/login      - User login
POST   /v1/auth/refresh    - Refresh access token
POST   /v1/auth/logout     - Logout & revoke token
Classes (Protected)
POST   /v1/classes         - Create class (Teacher/Admin)
GET    /v1/classes         - List my classes
GET    /v1/classes/:id     - Get class details
GET    /v1/classes/:id/members - List members (Teacher)
Photos (Protected)
POST   /v1/classes/:id/photos - Get presigned upload URL (Teacher)
GET    /v1/classes/:id/photos - List photos with view URLs
Health Checks
GET    /healthz            - Liveness probe
GET    /readyz             - Readiness probe (checks DB + S3)

πŸ—„οΈ Database Schema

  • users - Authentication & roles
  • profiles - User display information
  • classes - Class definitions
  • class_members - User-class associations
  • photos - Photo metadata (S3 keys only)
  • absences - Student absence tracking
  • messages - Direct messaging
  • announcements - Class/global announcements
  • refresh_tokens - Token management

All tables include proper indexes, foreign keys, and timestamps.

Database Migrations

✨ Migrations are now embedded and run automatically!

  • Migration files are compiled into the Go binary using go:embed
  • Migrations run automatically on application startup
  • No separate migration tool or container needed
  • Version tracking is handled automatically via schema_migrations table
  • Safe to restart - only new migrations are applied

To add a new migration:

  1. Create files in migrations/: 000010_your_migration.up.sql and 000010_your_migration.down.sql
  2. Copy them to internal/repository/postgres/migrations/ for embedding
  3. Restart the application - migration runs automatically!

See migrations README for more details.

πŸš€ Deployment

Local Development
# Start infrastructure
docker-compose up -d

# Start server (migrations run automatically)
make run
Docker
# Build image
docker build -t tinyschoolhub/api:latest .

# Run container
docker run -p 8080:8080 \
  -e DATABASE_URL="..." \
  -e JWT_SECRET="..." \
  -e STORAGE_ENDPOINT="..." \
  tinyschoolhub/api:latest
Kubernetes with Helm
# Install
helm install tiny-school-hub deploy/helm/tiny-school-hub \
  --set config.env=production \
  --set database.url="postgres://..." \
  --set storage.endpoint="s3.amazonaws.com" \
  --create-namespace \
  --namespace tiny-school-hub

# Upgrade
helm upgrade tiny-school-hub deploy/helm/tiny-school-hub

# Uninstall
helm uninstall tiny-school-hub
Kubernetes with Kustomize
# Dev environment
kubectl apply -k deploy/kustomize/dev

# Staging environment
kubectl apply -k deploy/kustomize/staging

# Production environment
kubectl apply -k deploy/kustomize/prod

πŸ”§ Configuration

All configuration via environment variables. See .env.example for complete list.

Required Variables
# Server
PORT=8080
ENV=production

# Database
DATABASE_URL=postgres://user:pass@host:5432/dbname

# JWT
JWT_SECRET=your-secret-key-change-in-production
JWT_ACCESS_EXPIRY=15m
JWT_REFRESH_EXPIRY=168h

# S3-Compatible Storage
STORAGE_ENDPOINT=s3.amazonaws.com
STORAGE_REGION=us-east-1
STORAGE_BUCKET=your-bucket
STORAGE_ACCESS_KEY=your-access-key
STORAGE_SECRET_KEY=your-secret-key
STORAGE_USE_PATH_STYLE=false
STORAGE_INSECURE=false

# Application
RATE_LIMIT=100
CORS_ALLOWED_ORIGINS=https://app.example.com

# Logging
LOG_LEVEL=info
LOG_FORMAT=json

πŸ§ͺ Testing & Code Quality

# Run all tests
make test

# Run tests with coverage
make test-coverage

# Lint code
make lint

# Format code
make fmt

# Run all pre-commit checks
make pre-commit
Pre-commit Hooks

This project uses Git pre-commit hooks to ensure code quality:

# Install hooks (runs automatically before each commit)
make install-hooks

# Run checks manually
make pre-commit

# Bypass hooks (emergency only)
git commit --no-verify -m "message"

What gets checked:

  • βœ… Code formatting (gofmt)
  • βœ… Go vet (suspicious constructs)
  • βœ… Build compilation
  • βœ… Unit tests
  • βœ… Module dependencies (go mod tidy)
  • βœ… Security scanning (gosec, if installed)
  • βœ… Sensitive data detection
  • βœ… SQL migration validation

See Pre-commit Documentation for details.

🌊 Development Workflow

This project uses GitFlow for branch management and Renovate for dependency updates.

🎯 NEW: Complete Workflow Guide

πŸ‘‰ πŸ“– Read the Complete Workflow Guide πŸ‘ˆ

Everything you need to know:

  • βœ… Daily development workflow
  • βœ… Creating releases step-by-step
  • βœ… Hotfix procedures
  • βœ… What happens automatically (CI/CD)
  • βœ… Command cheat sheet
  • βœ… Troubleshooting guide
Quick Start
# Clone and setup
git clone https://github.com/TinySchoolHub/tiny-school-hub-api-backend.git
cd tiny-school-hub-api-backend

# Run GitFlow setup (first time only)
./scripts/setup-gitflow.sh

# Start working on a feature
git checkout develop
git pull origin develop
git checkout -b feature/my-awesome-feature

# Make changes, commit, and push
git add .
git commit -m "feat: add awesome feature"
git push -u origin feature/my-awesome-feature

# Create PR: feature/my-awesome-feature β†’ develop
Branches
  • main - Production-ready code (protected)
  • develop - Integration branch for next release (protected)
  • feature/* - New features (branch from develop)
  • bugfix/* - Bug fixes (branch from develop)
  • hotfix/* - Urgent production fixes (branch from main)
  • release/* - Release preparation (branch from develop)
Automated Dependency Updates

Renovate automatically creates PRs for:

  • βœ… Go module updates (grouped together)
  • βœ… GitHub Actions updates
  • βœ… Docker base image updates
  • πŸ€– Patch updates auto-merge after CI passes

Review and merge dependency PRs regularly to stay up to date.

Documentation

πŸ“š Documentation

πŸ“„ License

Private. All rights reserved.

πŸ™‹ Support

For issues or questions, please contact the development team.

Troubleshooting

Server won't start:

  • Check .env file exists with all required variables
  • Verify database is accessible: psql $DATABASE_URL
  • Check storage endpoint is reachable

Database connection errors:

  • Ensure PostgreSQL is running: docker-compose ps
  • Migrations run automatically on startup - check logs for migration errors
  • Check DATABASE_URL format

Storage errors:

  • Verify S3 credentials are correct
  • Check endpoint URL (include http:// for insecure)
  • Test with MinIO locally first

Build errors:

  • Update Go to 1.24+: go version
  • Clean dependencies: go clean -modcache && go mod tidy
  • Rebuild: make build

πŸ“Š Project Stats

  • Lines of Code: ~3,500+
  • Binary Size: 16MB (optimized)
  • Dependencies: Minimal, all actively maintained
  • Go Version: 1.24+
  • Database Tables: 9
  • API Endpoints: 13+
  • Security: Argon2id + JWT + RBAC

πŸ“„ License

This project is licensed under the GNU General Public License v3.0 - see the LICENSE file for details.

What this means:
  • βœ… You can use this software for any purpose
  • βœ… You can modify and distribute it
  • βœ… You can use it commercially
  • ⚠️ You must disclose source code when distributing
  • ⚠️ You must use the same license for derivatives
  • ⚠️ You must state changes made to the code
Contributing

Contributions are welcome! By contributing to this project, you agree that your contributions will be licensed under the GPLv3 license.


Built with ❀️ for TinySchoolHub
Last Updated: November 22, 2025
Status: Production Ready βœ…
License: GPLv3 - Free and Open Source Software

Directories ΒΆ

Path Synopsis
cmd
api command
internal
pkg
log

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL