# CorradAF RBAC Backend Implementation Plan

## 🏗️ Architecture Overview

### **Hybrid Architecture Strategy**
- **Authentik**: User management, authentication, basic groups
- **RBAC Database**: Roles, permissions, applications, resources, business logic
- **Backend API**: Bridge between frontend and both systems

### **Technology Stack Recommendation**
- **Runtime**: Node.js with TypeScript
- **Framework**: Fastify or Express.js
- **Database**: PostgreSQL with Prisma ORM
- **Authentication**: JWT with Authentik integration
- **Validation**: Zod for type-safe validation
- **Documentation**: OpenAPI/Swagger

## 📊 Database Schema Design

### **Core Tables**

```sql
-- Applications Management
CREATE TABLE applications (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(255) NOT NULL,
    slug VARCHAR(255) UNIQUE NOT NULL,
    description TEXT,
    url VARCHAR(500),
    provider_type VARCHAR(50) DEFAULT 'oauth2', -- oauth2, saml, proxy
    is_active BOOLEAN DEFAULT true,
    authentik_application_id VARCHAR(255), -- Reference to Authentik app
    oauth_client_id VARCHAR(255),
    oauth_client_secret VARCHAR(500),
    setup_type VARCHAR(50) DEFAULT 'web-app', -- web-app, api-service, enterprise, custom
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);

-- Resource Types (Menus, Components, Features)
CREATE TABLE resources (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    application_id UUID REFERENCES applications(id) ON DELETE CASCADE,
    name VARCHAR(255) NOT NULL,
    key VARCHAR(255) NOT NULL, -- Auto-generated: user-management
    type VARCHAR(50) NOT NULL, -- menu, component, feature
    path VARCHAR(500), -- For menu resources
    description TEXT,
    metadata JSONB DEFAULT '{}', -- Flexible additional data
    created_at TIMESTAMP DEFAULT NOW(),
    
    UNIQUE(application_id, key) -- Unique per application
);

-- Role Templates (Pre-defined permission sets)
CREATE TABLE role_templates (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(255) NOT NULL,
    description TEXT,
    emoji VARCHAR(10) DEFAULT '⚙️',
    permission_count INTEGER DEFAULT 0,
    permissions JSONB NOT NULL DEFAULT '{"menus": [], "components": [], "features": []}',
    is_system BOOLEAN DEFAULT false, -- System templates vs custom
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);

-- Roles (Application-scoped)
CREATE TABLE roles (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    application_id UUID REFERENCES applications(id) ON DELETE CASCADE,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    priority INTEGER DEFAULT 0,
    is_global BOOLEAN DEFAULT false,
    template_id UUID REFERENCES role_templates(id),
    permissions JSONB NOT NULL DEFAULT '{"menus": [], "components": [], "features": []}',
    authentik_group_id VARCHAR(255), -- Reference to Authentik group
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW(),
    
    UNIQUE(application_id, name) -- Unique per application
);

-- Permission Mapping (Role -> Resources)
CREATE TABLE role_permissions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    role_id UUID REFERENCES roles(id) ON DELETE CASCADE,
    resource_id UUID REFERENCES resources(id) ON DELETE CASCADE,
    actions JSONB DEFAULT '["view"]', -- ["view", "edit", "delete"]
    granted_at TIMESTAMP DEFAULT NOW(),
    
    UNIQUE(role_id, resource_id)
);

-- User-Role Assignments (Bridge to Authentik users)
CREATE TABLE user_roles (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    authentik_user_id VARCHAR(255) NOT NULL, -- Authentik user ID
    role_id UUID REFERENCES roles(id) ON DELETE CASCADE,
    application_id UUID REFERENCES applications(id) ON DELETE CASCADE,
    assigned_by VARCHAR(255), -- Authentik user ID who assigned
    assigned_at TIMESTAMP DEFAULT NOW(),
    expires_at TIMESTAMP, -- Optional expiration
    
    UNIQUE(authentik_user_id, role_id, application_id)
);

-- Enhanced Groups (Extends Authentik groups)
CREATE TABLE enhanced_groups (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    authentik_group_id VARCHAR(255) UNIQUE NOT NULL, -- Reference to Authentik
    name VARCHAR(255) NOT NULL, -- Synced from Authentik
    description TEXT,
    parent_group_id UUID REFERENCES enhanced_groups(id),
    attributes JSONB DEFAULT '{}', -- Custom attributes
    department VARCHAR(255),
    cost_center VARCHAR(255),
    location VARCHAR(255),
    manager_email VARCHAR(255),
    is_active BOOLEAN DEFAULT true,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);

-- Group-Role Assignments
CREATE TABLE group_roles (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    group_id UUID REFERENCES enhanced_groups(id) ON DELETE CASCADE,
    role_id UUID REFERENCES roles(id) ON DELETE CASCADE,
    application_id UUID REFERENCES applications(id) ON DELETE CASCADE,
    assigned_by VARCHAR(255), -- Authentik user ID
    assigned_at TIMESTAMP DEFAULT NOW(),
    
    UNIQUE(group_id, role_id, application_id)
);

-- Application Access Control
CREATE TABLE application_access (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    application_id UUID REFERENCES applications(id) ON DELETE CASCADE,
    group_id UUID REFERENCES enhanced_groups(id) ON DELETE CASCADE,
    access_type VARCHAR(50) DEFAULT 'ANY', -- ANY, ALL
    created_at TIMESTAMP DEFAULT NOW(),
    
    UNIQUE(application_id, group_id)
);

-- Audit Log
CREATE TABLE audit_logs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id VARCHAR(255) NOT NULL, -- Authentik user ID
    action VARCHAR(100) NOT NULL, -- CREATE_USER, ASSIGN_ROLE, etc.
    resource_type VARCHAR(50) NOT NULL, -- user, role, group, application
    resource_id VARCHAR(255) NOT NULL,
    old_values JSONB,
    new_values JSONB,
    ip_address INET,
    user_agent TEXT,
    application_id UUID REFERENCES applications(id),
    created_at TIMESTAMP DEFAULT NOW()
);

-- Site Settings
CREATE TABLE site_settings (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    site_name VARCHAR(255) DEFAULT 'CorradAF',
    site_description TEXT DEFAULT 'CorradAF RBAC Management System',
    site_logo VARCHAR(500),
    site_favicon VARCHAR(500),
    selected_theme VARCHAR(100) DEFAULT 'biasa',
    custom_css TEXT,
    custom_theme_file VARCHAR(500),
    settings JSONB DEFAULT '{}', -- Additional settings
    updated_by VARCHAR(255), -- Authentik user ID
    updated_at TIMESTAMP DEFAULT NOW()
);
```

### **Database Indexes**
```sql
-- Performance indexes
CREATE INDEX idx_user_roles_user_id ON user_roles(authentik_user_id);
CREATE INDEX idx_user_roles_role_id ON user_roles(role_id);
CREATE INDEX idx_role_permissions_role_id ON role_permissions(role_id);
CREATE INDEX idx_resources_application_type ON resources(application_id, type);
CREATE INDEX idx_enhanced_groups_authentik_id ON enhanced_groups(authentik_group_id);
CREATE INDEX idx_audit_logs_user_id ON audit_logs(user_id);
CREATE INDEX idx_audit_logs_created_at ON audit_logs(created_at);
```

## 🚀 API Architecture Design

### **API Structure**
```
/api/v1/
├── auth/                    # Authentication endpoints
│   ├── login               # Authentik OAuth redirect
│   ├── callback            # OAuth callback handler
│   ├── refresh             # Token refresh
│   └── logout              # Logout handler
├── users/                  # User management (Authentik proxy)
│   ├── GET /               # List users from Authentik
│   ├── POST /              # Create user in Authentik
│   ├── GET /:id            # Get user details
│   ├── PUT /:id            # Update user
│   ├── DELETE /:id         # Delete user
│   ├── POST /bulk          # Bulk operations
│   └── POST /sync          # Sync with Authentik
├── groups/                 # Enhanced group management
│   ├── GET /               # List enhanced groups
│   ├── POST /              # Create group (Authentik + enhanced)
│   ├── GET /:id            # Get group details
│   ├── PUT /:id            # Update group
│   ├── DELETE /:id         # Delete group
│   └── POST /:id/roles     # Assign roles to group
├── roles/                  # Role management
│   ├── GET /               # List roles
│   ├── POST /              # Create role
│   ├── GET /:id            # Get role details
│   ├── PUT /:id            # Update role
│   ├── DELETE /:id         # Delete role
│   ├── POST /:id/permissions # Assign permissions
│   └── POST /from-template # Create role from template
├── role-templates/         # Role template management
│   ├── GET /               # List templates
│   ├── POST /              # Create template
│   ├── GET /:id            # Get template
│   ├── PUT /:id            # Update template
│   ├── DELETE /:id         # Delete template
│   └── POST /:id/clone     # Clone template
├── applications/           # Application management
│   ├── GET /               # List applications
│   ├── POST /              # Create application
│   ├── GET /:id            # Get application
│   ├── PUT /:id            # Update application
│   ├── DELETE /:id         # Delete application
│   ├── GET /:id/resources  # Get app resources
│   └── POST /:id/access    # Manage access control
├── resources/              # Resource management
│   ├── GET /               # List resources
│   ├── POST /              # Create resource
│   ├── GET /:id            # Get resource
│   ├── PUT /:id            # Update resource
│   ├── DELETE /:id         # Delete resource
│   └── GET /by-type/:type  # Get by type (menu/component/feature)
├── permissions/            # Permission management
│   ├── POST /check         # Check user permissions
│   ├── GET /user/:id       # Get user permissions
│   ├── POST /assign        # Assign permissions
│   ├── POST /revoke        # Revoke permissions
│   └── GET /matrix         # Permission matrix
├── rbac/                   # RBAC management interface
│   ├── GET /overview       # System statistics
│   ├── GET /matrix         # Permission matrix
│   ├── POST /bulk-assign   # Bulk permission assignment
│   └── GET /audit          # Audit trail
├── settings/               # Site settings
│   ├── GET /               # Get current settings
│   ├── PUT /               # Update settings
│   └── POST /upload        # Upload files (logo, favicon)
└── audit/                  # Audit logging
    ├── GET /               # List audit logs
    ├── GET /:id            # Get specific log
    └── GET /export         # Export audit data
```

## 🔐 Authentication & Authorization

### **JWT Token Structure**
```typescript
interface JWTPayload {
  sub: string;           // Authentik user ID
  email: string;         // User email
  name: string;          // Full name
  groups: string[];      // Authentik group IDs
  roles: {               // RBAC roles per application
    [applicationId: string]: {
      roleId: string;
      roleName: string;
      permissions: string[];
    }[];
  };
  permissions: string[]; // Flattened permission keys
  iat: number;          // Issued at
  exp: number;          // Expires at
}
```

### **Permission Checking Service**
```typescript
class PermissionService {
  async checkPermission(
    userId: string, 
    resourceKey: string, 
    action: string = 'view',
    applicationId?: string
  ): Promise<boolean> {
    // 1. Get user roles for application
    // 2. Get permissions for those roles
    // 3. Check if resourceKey + action is allowed
    // 4. Cache result for performance
  }

  async getUserPermissions(
    userId: string, 
    applicationId?: string
  ): Promise<string[]> {
    // Return flattened list of permission keys
  }

  async refreshUserPermissions(userId: string): Promise<void> {
    // Refresh cached permissions
  }
}
```

## 🔄 Authentik Integration Strategy

### **User Management Integration**
```typescript
class AuthentikService {
  async getUsers(params: GetUsersParams): Promise<AuthentikUser[]> {
    // GET /api/v3/core/users/
  }

  async createUser(userData: CreateUserData): Promise<AuthentikUser> {
    // POST /api/v3/core/users/
    // Also create enhanced profile in RBAC DB
  }

  async updateUser(id: string, userData: UpdateUserData): Promise<AuthentikUser> {
    // PATCH /api/v3/core/users/{id}/
  }

  async deleteUser(id: string): Promise<void> {
    // DELETE /api/v3/core/users/{id}/
    // Also cleanup RBAC data
  }

  async syncUsers(): Promise<SyncResult> {
    // Sync users between Authentik and RBAC DB
  }
}
```

### **Group Synchronization**
```typescript
class GroupSyncService {
  async syncGroupFromAuthentik(authentikGroupId: string): Promise<void> {
    // 1. Get group from Authentik
    // 2. Create/update in enhanced_groups table
    // 3. Maintain custom attributes
  }

  async createGroupInAuthentik(groupData: CreateGroupData): Promise<string> {
    // 1. Create in Authentik
    // 2. Create enhanced group record
    // 3. Return Authentik group ID
  }
}
```

## 📝 Implementation Strategy

### **Phase 1: Foundation (Week 1-2)**
1. **Database Setup**
   - PostgreSQL database creation
   - Prisma schema implementation
   - Migration scripts
   - Seed data for role templates

2. **Basic API Structure**
   - Express/Fastify setup with TypeScript
   - Authentication middleware
   - Basic CRUD endpoints
   - Error handling

3. **Authentik Integration**
   - OAuth2/OIDC client setup
   - JWT token handling
   - Basic user endpoint proxy

### **Phase 2: Core RBAC (Week 3-4)**
1. **Role & Permission System**
   - Role management endpoints
   - Permission assignment logic
   - Role template system
   - Permission checking service

2. **Resource Management**
   - Resource CRUD operations
   - Auto-key generation
   - Application scoping

3. **Enhanced Groups**
   - Group synchronization
   - Custom attributes
   - Hierarchy management

### **Phase 3: Advanced Features (Week 5-6)**
1. **Application Management**
   - Application setup wizard
   - Provider configuration
   - Access control policies

2. **Permission Matrix**
   - Complex permission queries
   - Bulk operations
   - Real-time updates

3. **Audit System**
   - Activity logging
   - Export functionality
   - Compliance reporting

### **Phase 4: Performance & Production (Week 7-8)**
1. **Performance Optimization**
   - Caching layer (Redis)
   - Database query optimization
   - Permission checking performance

2. **Security Hardening**
   - Rate limiting
   - Input validation
   - Security headers

3. **Production Setup**
   - Docker containers
   - Environment configuration
   - Monitoring and logging

## 🛠️ Technology Implementation

### **Recommended Stack**
```json
{
  "runtime": "Node.js 18+",
  "framework": "Fastify",
  "database": "PostgreSQL 15+",
  "orm": "Prisma",
  "validation": "Zod",
  "authentication": "Authentik OAuth2/JWT",
  "caching": "Redis",
  "documentation": "Swagger/OpenAPI",
  "testing": "Jest + Supertest",
  "deployment": "Docker"
}
```

### **Key Dependencies**
```json
{
  "dependencies": {
    "fastify": "^4.x",
    "@fastify/cors": "^8.x",
    "@fastify/jwt": "^7.x",
    "@fastify/swagger": "^8.x",
    "@prisma/client": "^5.x",
    "zod": "^3.x",
    "axios": "^1.x",
    "redis": "^4.x",
    "multer": "^1.x",
    "winston": "^3.x"
  },
  "devDependencies": {
    "prisma": "^5.x",
    "typescript": "^5.x",
    "@types/node": "^20.x",
    "jest": "^29.x",
    "supertest": "^6.x"
  }
}
```

This architecture provides a robust, scalable backend that maintains the hybrid approach you want - leveraging Authentik for user management while giving you full control over the RBAC business logic.

Would you like me to start implementing any specific part of this backend plan? 