Skip to content

Elagoht/backend-template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Backend Template with RBAC + SPA Support

A production-ready backend template built with Go that provides Role-Based Access Control (RBAC) authentication and seamless Single Page Application (SPA) hosting. Perfect for building modern web applications with a robust API backend and embedded frontend.

✨ Features

  • πŸ” Role-Based Access Control (RBAC) - Complete authentication and authorization system
  • πŸš€ Single Page Application Support - Embedded frontend serving with client-side routing
  • πŸ›‘οΈ Production-Ready Security - JWT authentication, rate limiting, CORS, secure cookies
  • πŸ—„οΈ SQLite Database - Embedded database with connection pooling and auto-migrations
  • πŸ“ File Storage - Image upload with automatic WebP conversion and resizing
  • 🎯 Clean Architecture - Modular, scalable codebase with dependency injection
  • ⚑ High Performance - Built with Chi router and optimized for speed
  • πŸ”§ Easy Configuration - Environment-based configuration management

πŸ—οΈ Architecture

backend/
β”œβ”€β”€ cli/                   # Command line interface
β”œβ”€β”€ frontend/              # Embedded frontend (SPA support)
β”œβ”€β”€ internal/
β”‚   β”œβ”€β”€ app/               # Application singleton and HTTP server
β”‚   β”œβ”€β”€ config/            # Configuration management
β”‚   β”œβ”€β”€ db/                # Database connection and initialization
β”‚   β”œβ”€β”€ infrastructure/    # Core infrastructure (permissions, tokens, storage)
β”‚   β”œβ”€β”€ middleware/        # HTTP middleware (auth, CORS, rate limiting)
β”‚   β”œβ”€β”€ module/            # Feature modules (session, health, static, storage)
β”‚   └── utils/             # Utilities (validation, cryptography, file handling)
β”œβ”€β”€ .env.example           # Environment variables template
└── go.mod                 # Go module dependencies

πŸš€ Quick Start

Prerequisites

  • Go 1.24.3 or higher

Default Credentials

The application automatically creates an admin user on first run:

  • Email: root@admin.dev
  • Password: admin123

βš™οΈ Configuration

Environment Variables

Create a .env file in the project root:

# Server
PORT=8723

# JWT Configuration (minimum 32 characters)
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production

# Token Durations (seconds)
ACCESS_TOKEN_DURATION=900      # 15 minutes
REFRESH_TOKEN_DURATION=604800  # 7 days

Frontend Integration

The template supports embedded frontends:

  1. Build your SPA and place the files in frontend/dist/
  2. The application will automatically:
    • Serve static assets (/assets/*)
    • Handle client-side routing (catch-all for SPA routes)
    • Serve index.html for non-API routes

πŸ” Authentication & RBAC

Authentication Flow

  1. Login - POST /internal/session with credentials
  2. Receive Tokens - Get JWT access token and refresh cookie
  3. API Access - Include JWT in Authorization: Bearer <token> header
  4. Token Refresh - Automatic refresh using HTTP-only cookie
  5. Logout - DELETE /internal/session to invalidate tokens

RBAC System

Database Schema:

  • users - User accounts with role associations
  • roles - Role definitions (Admin, User, etc.)
  • permissions - Granular permissions (user:create, post:delete, etc.)
  • role_permissions - Many-to-many mapping between roles and permissions

Permission Format: resource:action (e.g., user:list, post:create, admin:dashboard)

API Endpoints

Public Routes

  • GET / - SPA fallback (serves index.html)
  • GET /assets/* - Static assets
  • GET /uploads/avatar/{imageId} - Public image serving

Authentication

  • POST /internal/session - User login
  • POST /internal/session/refresh - Refresh access token
  • DELETE /internal/session - User logout

System

  • GET /internal/health - Application health check

Protected Routes (Authentication Required)

  • /uploads/ - File upload endpoints

πŸ›‘οΈ Security Features

  • JWT Authentication - Secure token-based authentication
  • Role-Based Authorization - Granular permission system
  • Rate Limiting - IP-based throttling (100 requests/minute)
  • CORS Configuration - Configured for development
  • Secure Cookies - HTTP-only, secure refresh tokens
  • Password Hashing - bcrypt for secure password storage
  • Input Validation - Comprehensive request validation

πŸ“ File Storage

Image Upload Features

  • Automatic WebP Conversion - Reduces file size without quality loss
  • Image Resizing - Configurable dimensions
  • File Validation - Type and size restrictions
  • Secure Storage - Organized upload directory structure

Supported Formats

  • Input: JPEG, PNG, WebP, GIF
  • Output: Optimized WebP format
  • Max Size: Configurable (default 10MB)

πŸ”§ Development

Building

# Development build
go run .

# Production build
go build -o backend .
./backend

Database

The application uses SQLite with:

  • Auto-migrations on startup
  • Connection pooling (25 max, 5 idle)
  • Seed data (default roles and admin user)
  • Soft delete support for user records

Code Structure

  • Singleton Pattern for core services (app, db, config, permissions)
  • Dependency Injection for clean architecture
  • Middleware Stack for cross-cutting concerns
  • Modular Design for feature isolation

πŸ“ API Usage Examples

Login

curl -X POST http://localhost:8723/internal/session \
  -H "Content-Type: application/json" \
  -d '{
    "email": "root@admin.dev",
    "password": "admin123"
  }'

Protected API Call

curl -X GET http://localhost:8723/internal/health \
  -H "Authorization: Bearer <your-jwt-token>"

File Upload

curl -X POST http://localhost:8723/uploads/avatar \
  -H "Authorization: Bearer <your-jwt-token>" \
  -F "file=@profile.jpg"

πŸ§ͺ Testing

# Run all tests
go test ./...

# Run tests with coverage
go test -cover ./...

# Run specific package tests
go test ./internal/module/session

πŸ“¦ Dependencies

Key Go modules used:

  • chi v1.5.5 - HTTP router
  • sqlite v1.14.32 - Database driver
  • golang-jwt/jwt v5.3.0 - JWT implementation
  • go-playground/validator v10.27.0 - Input validation
  • godotenv v1.5.1 - Environment configuration
  • golang.org/x/crypto v0.42.0 - Cryptography utilities

Built with ❀️ and Go!

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages