Skip to content

FeezyHendrix/golang-react-modular-monolith-boilerplate

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Echo Boilerplate with RBAC

A comprehensive authentication and role-based access control (RBAC) boilerplate built with Go (Echo framework) backend and React (TypeScript + shadcn/ui) frontend. This project provides a solid foundation for building web applications with modern authentication features and granular permissions system.

πŸš€ Features

Backend (Go + Echo)

  • User Authentication: Sign up, sign in, sign out with JWT tokens
  • Two-Factor Authentication (2FA): TOTP-based 2FA with backup codes
  • Role-Based Access Control (RBAC): Comprehensive permissions system
  • Role Management: Create, update, delete roles with granular permissions
  • User Role Assignment: Assign multiple roles to users
  • Permission Middleware: Route-level permission enforcement
  • Password Reset: Secure password reset via email
  • Email Integration: Welcome emails, password reset, 2FA codes using Resend
  • Database: PostgreSQL with GORM ORM and automatic migrations
  • Validation: Request validation using go-playground/validator
  • Logging: Structured logging with Zap
  • Testing: Comprehensive unit tests

Frontend (React + TypeScript)

  • Modern UI: Built with shadcn/ui components and Tailwind CSS
  • Authentication Pages: Clean login/signup forms with 2FA support
  • Role Management Interface: Complete RBAC administration
  • Permissions Matrix: Visual permission management
  • User Role Assignment: Drag-and-drop role management
  • Dashboard: User profile and security management
  • Responsive Design: Mobile-friendly interface
  • Form Validation: Client-side validation with error handling
  • State Management: React hooks and context
  • Testing: Component tests with Vitest and React Testing Library
  • Type Safety: Full TypeScript support

RBAC System

  • Default Roles: Super Admin, Admin, Team, User
  • Granular Permissions: Resource-based permissions (user:read, role:write, etc.)
  • Permission Categories: User, Role, Report, Settings, System management
  • Middleware Protection: Route-level access control
  • Dynamic Role Creation: Create custom roles with specific permissions
  • Permission Inheritance: System admin privileges override all permissions

πŸ“ Project Structure

.
β”œβ”€β”€ main.go                    # Application entry point
β”œβ”€β”€ makefile                   # Comprehensive build and dev commands
β”œβ”€β”€ go.mod                     # Go module dependencies
β”œβ”€β”€ .env.example              # Environment variables template
β”œβ”€β”€ .gitignore                # Comprehensive gitignore
β”œβ”€β”€ docker-compose.dev.yml    # Development environment
β”œβ”€β”€ scripts/
β”‚   └── init-db.sql           # Database initialization
β”œβ”€β”€ internal/                  # Private application code
β”‚   β”œβ”€β”€ api/                   # HTTP handlers and routes
β”‚   β”‚   β”œβ”€β”€ api.go            # API setup with RBAC
β”‚   β”‚   β”œβ”€β”€ roles.go          # Role management endpoints
β”‚   β”‚   └── routes.go         # Protected routes with permissions
β”‚   β”œβ”€β”€ common/                # Shared utilities
β”‚   β”‚   β”œβ”€β”€ authentication_context/
β”‚   β”‚   β”œβ”€β”€ environment/
β”‚   β”‚   β”œβ”€β”€ logger/
β”‚   β”‚   β”œβ”€β”€ passwords/
β”‚   β”‚   └── validator/
β”‚   β”œβ”€β”€ db/                    # Database connection and migration
β”‚   β”œβ”€β”€ models/                # Database models with role relationships
β”‚   └── services/              # Business logic services
β”‚       β”œβ”€β”€ authentication/    # Auth service with role loading
β”‚       β”œβ”€β”€ email/            # Email service with Resend
β”‚       β”œβ”€β”€ permissions/      # RBAC service and middleware
β”‚       β”‚   β”œβ”€β”€ permissions.go # Core RBAC functionality
β”‚       β”‚   β”œβ”€β”€ middleware.go  # Permission middleware
β”‚       β”‚   └── service.go     # Database operations
β”‚       └── users/            # User management service
β”œβ”€β”€ spa/                      # React frontend
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ components/       # Reusable UI components
β”‚   β”‚   β”‚   └── roles/        # Role management components
β”‚   β”‚   β”œβ”€β”€ pages/           # Page components
β”‚   β”‚   β”‚   β”œβ”€β”€ auth/        # Authentication pages
β”‚   β”‚   β”‚   β”œβ”€β”€ RoleManagement.tsx # RBAC admin interface
β”‚   β”‚   β”‚   └── routing/     # Route configuration
β”‚   β”‚   β”œβ”€β”€ api/             # API client with RBAC endpoints
β”‚   β”‚   β”œβ”€β”€ hooks/           # Custom React hooks
β”‚   β”‚   β”œβ”€β”€ lib/             # Utility functions
β”‚   β”‚   └── test/            # Test files
β”‚   β”œβ”€β”€ package.json
β”‚   └── vite.config.ts
└── README.md

πŸ› οΈ Quick Start

Prerequisites

  • Go 1.21+
  • Node.js 18+
  • PostgreSQL 13+
  • Docker (optional)
  • Make (for using Makefile commands)

1. Clone and Setup

git clone https://github.com/feezyhendrix/echoboilerplate.git
cd echoboilerplate

# Copy and configure environment
cp .env.example .env
# Edit .env with your database and API keys

# Check environment setup
make env-check

2. Development with Docker (Recommended)

# Start full development environment
make dev

# Or build and start fresh
make dev-build

# View logs
make dev-logs

# Stop environment
make dev-down

Access Points:

3. Local Development (Without Docker)

# Install dependencies
make deps

# Start database only
make dev-db

# Run server locally (in new terminal)
make dev-server

# Run SPA locally (in new terminal)  
make dev-spa

πŸ”§ Makefile Commands

Development

make help              # Show all available commands
make dev               # Run full development environment
make dev-build         # Build and run development environment
make dev-server        # Run server locally
make dev-spa           # Run SPA development server
make dev-db            # Start only database
make dev-logs          # Show development logs
make dev-clean         # Clean development environment

Building

make build             # Build both server and SPA
make build-server      # Build server binary
make build-spa         # Build SPA for production
make build-docker      # Build Docker images

Testing & Quality

make test              # Run all tests
make test-server       # Run server tests
make test-spa          # Run SPA tests
make test-coverage     # Generate coverage report
make lint              # Run all linters
make fmt               # Format all code
make check             # Run format, lint, and tests

Database

make db-migrate        # Run database migrations
make db-seed           # Seed database with initial data
make db-reset          # Reset database completely
make db-backup         # Create database backup
make db-console        # Connect to database console

Utilities

make clean             # Clean build artifacts
make deps              # Install all dependencies
make deps-update       # Update dependencies
make version           # Show version information
make env-check         # Check environment configuration
make security-check    # Run security checks

πŸ” RBAC System

Default Roles

Role ID Description Default Permissions
Super Admin 4 Full system access All permissions including system:admin
Admin 1 User and role management user:read/write, role:read, report:read/write, settings:read
Team 2 Collaborative access user:read, report:read/write
User 3 Basic access report:read

Permission System

Format: resource:action

Resources: user, role, report, settings, system

Actions: read, write, delete, admin

Examples:

  • user:read - View user information
  • role:write - Create and modify roles
  • system:admin - Full system administration

Using RBAC in Code

Protect Routes

// Require specific permission
roles.GET("", a.GetRoles, permissions.RequirePermission(permissions.PermissionRoleRead))

// Require any of multiple permissions
userRoutes.GET("/profile", a.GetProfile, permissions.RequireAnyPermission(
    permissions.PermissionUserRead, 
    permissions.PermissionSystemAdmin,
))

// Require role
adminRoutes.GET("/settings", a.GetSettings, permissions.RequireRole(permissions.ROLE_ID_ADMIN))

Check Permissions in Handlers

func (a *API) GetUsers(c echo.Context) error {
    user := c.Get("user").(*models.User)
    
    if !user.HasPermission(permissions.PermissionUserRead) {
        return echo.NewHTTPError(http.StatusForbidden, "Insufficient permissions")
    }
    
    // Continue with logic...
}

Frontend Permission Checks

// Check user permissions
const hasUserManagement = user.permissions.includes('user:write');

// Conditionally render UI
{hasUserManagement && (
  <Button onClick={handleCreateUser}>Create User</Button>
)}

πŸ“š API Documentation

Authentication Endpoints

POST /api/v1/auth/signin

{
  "email": "[email protected]",
  "password": "password123"
}

Response includes user with roles:

{
  "access_token": "eyJhbGciOiJIUzI1NiIs...",
  "refresh_token": "eyJhbGciOiJIUzI1NiIs...",
  "user": {
    "id": 1,
    "email": "[email protected]",
    "userRoles": [
      {
        "role": {
          "id": 1,
          "name": "Admin",
          "permissions": [
            {"name": "user:read", "resource": "user", "action": "read"},
            {"name": "role:read", "resource": "role", "action": "read"}
          ]
        }
      }
    ]
  }
}

RBAC Endpoints

GET /api/v1/roles

Get all roles with permissions (requires role:read)

POST /api/v1/roles

Create new role (requires role:write)

{
  "name": "Manager",
  "description": "Department manager role",
  "isActive": true
}

POST /api/v1/user-roles/assign

Assign role to user (requires user:write)

{
  "userId": 123,
  "roleId": 2
}

GET /api/v1/permissions

Get all available permissions (requires role:read)

🎨 Frontend RBAC Components

Role Management Page (/roles)

  • Role Management Tab: Create, edit, delete roles
  • User Assignment Tab: Assign roles to users
  • Permissions Matrix Tab: Visual permission grid

Key Components

// Role management
<RoleManagement />

// User role assignment  
<UserRoleAssignment userId={123} userName="John Doe" />

// Permissions matrix
<PermissionsMatrix />

Permission-Based UI

// Hide/show based on permissions
{user.hasPermission('user:write') && (
  <CreateUserButton />
)}

// Different views for different roles
{user.hasRole(ROLE_ID_ADMIN) ? (
  <AdminDashboard />
) : (
  <UserDashboard />
)}

πŸ§ͺ Testing

Run All Tests

make test

Backend Tests

make test-server              # Run tests
make test-server-coverage     # Generate coverage report
make test-integration         # Run integration tests

Frontend Tests

make test-spa                 # Run SPA tests

Test RBAC System

The boilerplate includes comprehensive tests for:

  • Permission checking functions
  • Middleware enforcement
  • Role assignment logic
  • API endpoint protection

πŸš€ Deployment

Production Build

# Build everything for production
make build

# Build Docker images
make build-docker

# Deploy to staging
make deploy-staging

# Deploy to production  
make deploy-prod

Environment Configuration

Development: Copy .env.example to .env Production: Set environment variables in your deployment platform

Required Variables:

  • POSTGRES_* - Database connection
  • AUTHENTICATION_JWT_SECRET - JWT signing key (32+ characters)
  • AUTHENTICATION__PASSWORD_RESET_TOKEN_ENCRYPTION_KEY - Password reset encryption
  • RESEND_API_KEY or SENDGRID__API_KEY - Email service

πŸ”’ Security Features

  • Password Hashing: bcrypt with salt
  • JWT Tokens: Secure token-based authentication with role information
  • 2FA Support: TOTP with backup codes
  • RBAC: Granular permission system with middleware enforcement
  • Rate Limiting: Protection against brute force attacks
  • CORS: Configurable cross-origin resource sharing
  • Input Validation: Server and client-side validation
  • Secure Headers: Security middleware
  • Email Verification: Account verification flow
  • Permission Inheritance: System admin override capabilities

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes and add tests
  4. Run quality checks: make check
  5. Commit your changes (git commit -m 'Add amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

Development Guidelines

  • Follow Go and TypeScript best practices
  • Write tests for new features (especially RBAC components)
  • Update documentation as needed
  • Use conventional commit messages
  • Ensure all tests pass: make test
  • Run security checks: make security-check

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • Echo - High performance Go web framework
  • GORM - Go ORM library with excellent relationship support
  • shadcn/ui - Beautiful UI components
  • Tailwind CSS - Utility-first CSS framework
  • Vite - Fast build tool
  • Resend - Email API service

πŸ“ž Support

If you have any questions or need help:

  • Open an issue on GitHub
  • Check the comprehensive documentation
  • Review existing issues for solutions
  • Use make help to see all available commands

Built with ❀️ for modern web applications with security in mind

About

Golang Echo React Boilerplate

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published