GitHunt

ERP demo API with advanced authorization

A robust ERP-grade API system built with modern TypeScript, featuring comprehensive Role-Based Access Control (RBAC), Attribute-Based Access Control (ABAC), and Policy-Based Access Control (PBAC).

Important

This example/demo is not a fully implemented application.
It is only intended to demonstrate how to use RBAC, permissions, and policies to build a flexible authorization system with database persistence for dynamic control.

Features

๐Ÿ” Advanced Authorization System

  • Role-Based Access Control (RBAC)
  • Attribute-Based Access Control (ABAC)
  • Policy-Based Access Control (PBAC)
  • Direct user permissions
  • Dynamic policy evaluation with conditions

๐Ÿ—๏ธ Modern Tech Stack

  • Backend: Hono.js (lightweight, fast web framework)
  • Database: PostgreSQL with Drizzle ORM
  • Runtime: Node.js with TypeScript
  • Testing: Vitest
  • Authentication: JWT-based auth system

๐Ÿ“‹ ERP Functionality

  • Invoice management system
  • User management
  • Role and permission management
  • Policy-based access control

Project Structure

.
โ”œโ”€โ”€ drizzle/                    # Database migrations
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ api/                   # API route handlers
โ”‚   โ”‚   โ”œโ”€โ”€ auth.ts           # Authentication endpoints
โ”‚   โ”‚   โ”œโ”€โ”€ invoices.ts       # Invoice management
โ”‚   โ”‚   โ””โ”€โ”€ rbac.ts           # RBAC management
โ”‚   โ”œโ”€โ”€ db/
โ”‚   โ”‚   โ”œโ”€โ”€ config.ts         # Database configuration
โ”‚   โ”‚   โ”œโ”€โ”€ schema.ts         # Database schema definitions
โ”‚   โ”‚   โ”œโ”€โ”€ seeder.ts         # Database seeding
โ”‚   โ”‚   โ””โ”€โ”€ reset.ts          # Database reset utilities
โ”‚   โ”œโ”€โ”€ lib/
โ”‚   โ”‚   โ””โ”€โ”€ auth.ts           # Authentication middleware
โ”‚   โ””โ”€โ”€ types/
โ”‚       โ””โ”€โ”€ app.ts            # Type definitions
โ”œโ”€โ”€ tests/                     # Test suites
โ””โ”€โ”€ README.md

Database Schema

Core Tables

  • users: User accounts with email/password authentication
  • roles: Role definitions (e.g., admin, sales, cashier)
  • permissions: Atomic resource-action permissions (e.g., invoice.create)
  • policies: Dynamic rule engine with conditions and effects
  • invoices: Sample ERP resource for demonstration

Relationships

  • user_roles: Many-to-many relationship between users and roles
  • role_permissions: Many-to-many relationship between roles and permissions
  • user_permissions: Direct user permissions (bypass roles)

Quick Start

Prerequisites

  • Node.js โ‰ฅ20.x
  • PostgreSQL database
  • pnpm package manager

Installation

  1. Clone and install dependencies
git clone https://github.com/mrmeaow/hono-pg-erp-authorization-demo.git erp-auth-demo
cd erp-auth-demo
pnpm install
  1. Environment Setup
cp .env.template .env
# Edit .env with your database credentials
  1. Database Setup

You must make sure that you have created the database for the application e.g. erp_auth_demodb and the erp_auth_demodb_test one too for testing environment.

# Push schema to database
pnpm dkit push # use '--force' if needed

# Seed with initial data
pnpm seed
  1. Start Development Server
pnpm dev

The API will be available at http://localhost:3030

Environment Variables

PORT=3030
DEBUG=true
NODE_ENV=dev
DATABASE_URL=postgresql://user:password@localhost:5432/database_name

API Endpoints

Authentication

  • POST /api/auth/register - Register new user
  • POST /api/auth/login - User login
  • GET /api/auth/profile - Get user profile (protected)

RBAC Management

  • GET /api/rbac/roles - List all roles
  • POST /api/rbac/roles - Create new role
  • GET /api/rbac/permissions - List all permissions
  • POST /api/rbac/assign-role - Assign role to user

Invoices (Sample Resource)

  • GET /api/invoices - List user invoices
  • POST /api/invoices - Create new invoice
  • GET /api/invoices/:id - Get specific invoice
  • PUT /api/invoices/:id - Update invoice
  • DELETE /api/invoices/:id - Delete invoice

Authorization System

RBAC (Role-Based Access Control)

Users are assigned roles, and roles have permissions:

// Example: Assign 'sales' role to user
POST /api/rbac/assign-role
{
  "userId": "user-uuid",
  "roleNames": ["sales"]
}

Direct Permissions

Users can have direct permissions without roles:

// Example: Grant direct invoice.create permission
{
  "userId": "user-uuid",
  "permissions": ["invoice.create"]
}

Policy-Based Access Control (PBAC)

Dynamic policies with conditions:

// Example policy
{
  "resource": "invoice",
  "actions": ["read", "update"],
  "effect": "allow",
  "conditions": [
    {
      "field": "created_by",
      "operator": "equals",
      "value": "${user.id}"
    }
  ],
  "priority": 10
}

Available Scripts

# Development
pnpm dev                # Start development server
pnpm build             # Build for production
pnpm start             # Start production server

# Database
pnpm dkit push         # Push schema changes
pnpm dkit generate     # Generate migrations
pnpm seed              # Seed database
pnpm reset             # Reset database (recommended for dev/test only)

# Testing
pnpm test              # Run test suite
pnpm typecheck         # Type checking

Testing

The project includes comprehensive test suites:

# Run all tests
pnpm test

# Test specific areas
NODE_ENV=test pnpm test auth.test.ts
NODE_ENV=test pnpm test rbac.test.ts
NODE_ENV=test pnpm test invoice.test.ts

Tests automatically use a separate test database and reset between runs.

Database Management

Development Reset

pnpm reset              # Truncate and reseed database

Migrations

pnpm dkit generate      # Generate migration from schema changes
pnpm dkit push          # Push changes directly (development)
pnpm dkit migrate       # Run pending migrations (production)

Security Features

  • Password Hashing: bcrypt with salt rounds
  • JWT Authentication: Secure token-based authentication
  • SQL Injection Protection: Drizzle ORM with parameterized queries
  • CORS Support: Configurable cross-origin requests
  • Input Validation: Type-safe request validation

Permission Examples

Resource-Action Format

invoice.create      # Create invoices
invoice.read        # Read invoices
invoice.update      # Update invoices
invoice.delete      # Delete invoices
invoice.approve     # Approve invoices
user.manage         # Manage users
role.assign         # Assign roles

Sample Roles

  • admin: Full system access
  • sales: Create/read invoices, manage customers
  • cashier: Process payments, read invoices
  • viewer: Read-only access (Note: not available seeder)

Production Deployment

  1. Build the application
pnpm build
  1. Set production environment
NODE_ENV=production
DATABASE_URL=your-production-db-url
  1. Run migrations
pnpm dkit migrate
  1. Start the server
pnpm start

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Write tests for new functionality
  4. Ensure all tests pass
  5. Submit a pull request

License

MIT License - see LICENSE file for details

Support

For questions and support, please create an issue in the repository.


Built with โค๏ธ by gh/mrmeaow using modern TypeScript and battle-tested technologies.

mrmeaow/hono-pg-erp-authorization-demo | GitHunt