This project demonstrates how to implement fine-grained authorization for both users and AI agents in a Next.js application using Permit.io. It's a document management system where users can create, view, edit, and delete documents based on their roles and document ownership, and AI agents can assist with document management based on their assigned permissions.
- Role-Based Access Control (RBAC): Different roles (Admin, Editor, Viewer) have different permissions
- Attribute-Based Access Control (ABAC): Document owners have special privileges
- Fine-Grained Authorization: Using Permit.io to implement complex authorization rules
- AI Agent Roles: Define different AI agent roles with specific capabilities
- Permission Levels: Configure what AI agents can access and modify
- No Access: AI agent cannot access the resource at all
- Read Only: AI agent can only read but not modify resources
- Suggest Only: AI can suggest changes that require human approval
- Full Access: AI has full access to read and modify resources
- Approval Workflows: Require human approval for sensitive AI operations
- Audit and Monitoring: Track all AI actions and approvals
- Document Analysis: AI-powered analysis of document content and structure
- Document Summarization: Generate concise summaries of documents
- Content Improvement: AI suggestions for improving document content
- Next.js App Router: Modern React application with server components and server actions
- Responsive UI: Using Tailwind CSS and shadcn/ui components
- Dark Mode: Customizable dark mode with tailored color scheme
If you're a reader, then this blog is for you: https://dev.to/rohan_sharma/access-granted-heres-the-recipe-behind-my-ai-dms-351b
The application implements the following user authorization model:
- Admin: Can create, view, edit, and delete any document, and access the admin panel
- Editor: Can create, view, and edit documents, but can only delete their own documents
- Viewer: Can only view documents
Additionally, document owners have full control over their own documents regardless of their role.
The application implements the following AI authorization model:
-
AI Agent Roles:
- Assistant: Helps with document organization and basic tasks
- Editor: Can edit and improve document content
- Analyzer: Analyzes document content and provides insights
-
AI Capabilities:
- read_documents: Ability to read document content
- suggest_edits: Ability to suggest edits to documents
- edit_documents: Ability to directly edit documents
- create_documents: Ability to create new documents
- delete_documents: Ability to delete documents
- analyze_content: Ability to analyze document content
- summarize_content: Ability to summarize documents
- translate_content: Ability to translate documents
- generate_content: Ability to generate new content
-
Permission Levels:
- NO_ACCESS: AI agent cannot access the resource at all
- READ_ONLY: AI agent can only read but not modify resources
- SUGGEST_ONLY: AI can suggest changes that require human approval
- FULL_ACCESS: AI has full access to read and modify resources
- Node.js 18+
- Permit.io account (https://app.permit.io)
- Groq API key (https://console.groq.com)
-
Clone the repository
git clone https://github.com/RS-labhub/ai-document-management-system.git cd document-management-system
-
Install dependencies:
npm install
or
yarn install
or
bun install
-
Set up environment variables:
PERMIT_PDP_URL=your-permit-pdp-url PERMIT_SDK_TOKEN=your-permit-sdk-token GROQ_API_KEY=your-groq-api-key
npm run dev
The application will be available at http://localhost:3000.
- Admin:
- Username: admin
- Password: 2025DEVChallenge
- Editor:
- Username: newuser
- Password: 2025DEVChallenge
- Viewer:
- Username: viewer
- Password: 2025DEVChallenge
npm install -g @permitio/permit-cli
permit login
permit init
The application implements AI authorization through several key components:
The AIAgent
interface defines the structure of AI agents:
export interface AIAgent {
id: string;
name: string;
description: string;
role: AIAgentRole;
capabilities: AICapability[];
createdBy: string;
createdAt: string;
updatedAt: string;
isActive: boolean;
}
Administrators can manage AI agents through the admin panel, defining their roles and capabilities.
The AIPermissionLevel
enum defines the different levels of access that AI agents can have:
export enum AIPermissionLevel {
NO_ACCESS = "no_access",
READ_ONLY = "read_only",
SUGGEST_ONLY = "suggest_only",
FULL_ACCESS = "full_access",
}
The AIAction
interface defines the structure of actions that AI agents can perform:
export interface AIAction {
id: string;
agentId: string;
actionType: string;
resourceType: string;
resourceId: string;
status: AIActionStatus;
requestedAt: string;
completedAt?: string;
requestedBy: string;
approvedBy?: string;
rejectedBy?: string;
metadata: Record<string, any>;
result?: any;
}
The checkAIPermission
function checks if an AI agent has permission to perform an action:
export function checkAIPermission(
agentId: string,
action: string,
resourceType: string,
resourceId?: string
): {
permitted: boolean;
requiresApproval: boolean;
permissionLevel: AIPermissionLevel;
} {
// Implementation details...
}
The application implements an approval workflow for AI actions that require human oversight:
export async function requestAIAction(
agentId: string,
actionType: string,
resourceType: string,
resourceId: string,
documentTitle: string,
documentContent: string,
metadata: Record<string, any>
): Promise<{ success: boolean; action?: AIAction; message?: string }> {
// Implementation details...
}
export async function approveAIAction(
actionId: string,
userId: string
): Promise<{ success: boolean; action?: AIAction; message?: string }> {
// Implementation details...
}
export async function rejectAIAction(
actionId: string,
userId: string,
reason?: string
): Promise<{ success: boolean; action?: AIAction; message?: string }> {
// Implementation details...
}
The application integrates with Permit.io through the permit.ts
file, which provides functions for checking permissions:
import { Permit } from 'permitio';
// Initialize Permit SDK
const permit = new Permit({
pdp: process.env.PERMIT_PDP_URL,
token: process.env.PERMIT_SDK_TOKEN,
});
// Check if a user can perform an action on a resource
export async function checkPermission(
userId: string,
action: string,
resourceType: string,
resourceAttributes: Record<string, any> = {}
): Promise<boolean> {
try {
const permitted = await permit.check(userId, action, {
type: resourceType,
...resourceAttributes,
});
return permitted;
} catch (error) {
console.error('Permission check failed:', error);
return false;
}
}
- Enhanced Security: Fine-grained control over what AI agents can access and modify
- Human Oversight: Approval workflows for sensitive AI operations
- Flexibility: Different permission levels for different AI agents and resources
- Auditability: Track all AI actions and approvals
- Compliance: Meet regulatory requirements for AI systems
- Separation of Concerns: Authorization logic is separated from application code
- Centralized Policy Management: All authorization rules are defined in one place
- Consistent Enforcement: Authorization is enforced consistently across the application
- Reduced Complexity: Complex authorization rules are handled by Permit.io
- Easier Maintenance: Changes to authorization rules don't require code changes
- Audit Trail: All authorization decisions can be logged and audited
This project demonstrates how to implement fine-grained authorization for both users and AI agents in a Next.js application using Permit.io. By externalizing authorization, we can create more secure, maintainable, and flexible applications that can safely leverage AI capabilities while maintaining appropriate controls.
Set Up Your Environment
Fork
our repository to your GitHub account.Clone
your fork to your local machine. Use the commandgit clone https://github.com/RS-labhub/AI_Document_Management_System.git
.- Create a new branch for your work.
Use a descriptive name, like
fix-login-bug
oradd-user-profile-page
.
Commit Your Changes
- Commit your changes with a clear commit message.
e.g
git commit -m "Fix login bug by updating auth logic"
.
Submit a Pull Request
- Push your branch and changes to your fork on GitHub.
- Create a pull request, compare branches and submit.
- Provide a detailed description of what changes you've made and why. Link the pull request to the issue it resolves. 🔗
Review and Merge
- I will review your pull request and provide feedback or request changes if necessary.
- Once your pull request is approved, we will merge it into the main codebase 🥳
- Email: [email protected]
- Head over to my github handle from here
Thank you for visting this Repo
If you like it, star ⭐ it