A modern, secure, and scalable Document Management System built with Next.js, MongoDB, and AWS S3. TheDMS provides comprehensive document storage, management, and search capabilities with advanced user authentication and role-based access control.
# Clone the repository
git clone https://github.com/thenitishmind/Database-Management-System.git
cd Database-Management-System
# Install dependencies
npm install
# Set up environment variables
cp .env.example .env.local
# Start development server
npm run devVisit http://localhost:3000 to access the application.
- Features
- Architecture Overview
- Project Structure
- Core Modules
- Components
- API Endpoints
- Workflow Chart
- Installation Guide
- Configuration
- Deployment
- Contributing
- Secure user authentication with NextAuth.js
- Role-based access control (Admin/User)
- Session management with MongoDB store
- Protected routes and middleware
- Upload, view, and download documents
- Document categorization and tagging
- Version control and history tracking
- Bulk document operations
- Real-time document search
- Enhanced S3-based search with pagination
- Smart search algorithms
- Loan-specific document searches
- AWS S3 integration for secure storage
- Automatic file compression and optimization
- Scalable storage architecture
- CDN support for fast delivery
- User creation and management
- Role assignment and permissions
- User activity tracking
- Administrative controls
- Comprehensive administrative interface
- System diagnostics and monitoring
- User activity analytics
- Document usage statistics
graph TB
Client[Client Browser] --> NextJS[Next.js Application]
NextJS --> Auth[NextAuth.js]
NextJS --> API[API Routes]
API --> MongoDB[(MongoDB Database)]
API --> S3[AWS S3 Storage]
API --> Session[Session Store]
Auth --> MongoDB
Session --> MongoDB
subgraph "Frontend Layer"
NextJS
Components[React Components]
Pages[App Router Pages]
end
subgraph "Backend Layer"
API
Middleware[Express Middleware]
Auth
end
subgraph "Data Layer"
MongoDB
S3
Session
end
TheDms/
├── 📁 src/
│ ├── 📁 app/ # Next.js App Router
│ │ ├── 📄 layout.tsx # Root layout component
│ │ ├── 📄 page.tsx # Home page
│ │ ├── 📁 admin/ # Admin pages
│ │ │ ├── 📄 page.tsx # Admin dashboard
│ │ │ ├── 📁 documents/ # Document management
│ │ │ ├── 📁 users/ # User management
│ │ │ ├── 📁 login/ # Admin login
│ │ │ ├── 📁 s3-browser/ # S3 file browser
│ │ │ └── 📁 aws-diagnostics/ # AWS diagnostics
│ │ ├── 📁 api/ # API routes
│ │ │ ├── 📁 auth/ # Authentication endpoints
│ │ │ ├── 📁 documents/ # Document operations
│ │ │ ├── 📁 users/ # User management
│ │ │ ├── 📁 s3-operations/ # S3 operations
│ │ │ ├── 📁 admin/ # Admin operations
│ │ │ └── 📁 *-search/ # Various search endpoints
│ │ ├── 📁 documents/ # Document viewer pages
│ │ ├── 📁 loan-documents/ # Loan-specific documents
│ │ ├── 📁 login/ # User login
│ │ ├── 📁 search/ # Search interfaces
│ │ └── 📁 user-dashboard/ # User dashboard
│ ├── 📁 components/ # Reusable React components
│ │ ├── 📄 AuthProvider.tsx # Authentication context
│ │ ├── 📄 ProtectedRoute.tsx # Route protection
│ │ ├── 📄 DocumentViewer.tsx # Document display
│ │ ├── 📄 EnhancedSearch.tsx # Advanced search
│ │ ├── 📄 UserManagement.tsx # User admin interface
│ │ └── 📁 admin/ # Admin-specific components
│ ├── 📁 lib/ # Utility libraries
│ │ ├── 📄 auth.ts # Authentication utilities
│ │ ├── 📄 db.ts # Database connections
│ │ ├── 📄 s3.ts # S3 operations
│ │ ├── 📄 config.ts # Configuration management
│ │ └── 📄 logger.ts # Logging utilities
│ └── 📁 models/ # Data models
│ ├── 📄 User.ts # User model
│ └── 📄 Document.ts # Document model
├── 📁 public/ # Static assets
│ └── 📁 uploads/ # File uploads
├── 📁 data/ # Data files
│ └── 📄 fallback-db.json # Fallback data
├── 📁 dataconnect/ # Firebase Data Connect
├── 📄 server.js # Express server
├── 📄 package.json # Dependencies
├── 📄 next.config.js # Next.js configuration
├── 📄 tailwind.config.js # Tailwind CSS config
└── 📄 README.md # This file
- Purpose: Handles user authentication and session management
- Features:
- JWT token generation and validation
- Password hashing with bcryptjs
- Session persistence
- Role-based access control
- Dependencies: NextAuth.js, bcryptjs, jsonwebtoken
- Purpose: MongoDB connection and operations
- Features:
- Connection pooling and caching
- Error handling and retry logic
- CRUD operations
- Schema validation
- Dependencies: MongoDB, Mongoose
- Purpose: AWS S3 file operations
- Features:
- File upload and download
- Presigned URL generation
- Bucket management
- File compression
- Dependencies: AWS SDK v3
- Location: Various API routes (
api/*-search/) - Purpose: Advanced document search capabilities
- Features:
- Full-text search
- Metadata-based filtering
- Pagination
- Real-time suggestions
- Types:
- Enhanced search
- S3-based search
- Loan-specific search
- Smart search
- Location:
src/components/UserManagement.tsx - Purpose: Administrative user operations
- Features:
- User creation and deletion
- Role assignment
- Activity monitoring
- Bulk operations
- Location:
src/components/DocumentViewer.tsx - Purpose: Document operations and display
- Features:
- File upload and processing
- Document preview
- Download management
- Version control
// Context provider for authentication state
- Manages user session
- Provides auth methods
- Handles login/logout
- Role-based rendering// Route protection wrapper
- Authentication checks
- Role-based access
- Redirect handling
- Loading states// Document display component
- File preview
- Download functionality
- Metadata display
- Error handling// Advanced search interface
- Real-time search
- Filter options
- Result pagination
- Search suggestions// Main admin interface
- System overview
- Quick actions
- Statistics display
- Navigation menu// User administration
- User CRUD operations
- Role management
- Activity tracking
- Bulk actions// S3 file browser
- Folder navigation
- File operations
- Upload interface
- Bucket managementPOST /api/auth/login- User loginPOST /api/auth/logout- User logoutGET /api/auth/session- Get current sessionPOST /api/auth/register- User registration
GET /api/documents- List documentsPOST /api/documents- Upload documentGET /api/documents/[id]- Get document detailsDELETE /api/documents/[id]- Delete documentGET /api/documents/download/[id]- Download document
GET /api/users- List usersPOST /api/users- Create userPUT /api/users/[id]- Update userDELETE /api/users/[id]- Delete user
GET /api/enhanced-search- Enhanced document searchGET /api/s3-search- S3-based searchGET /api/loan-search- Loan document searchGET /api/realtime-search- Real-time search
GET /api/s3-operations/list- List S3 objectsPOST /api/s3-operations/upload- Upload to S3DELETE /api/s3-operations/delete- Delete S3 objectGET /api/s3-operations/presigned- Get presigned URL
GET /api/admin/dashboard- Admin dashboard dataGET /api/admin/stats- System statisticsPOST /api/admin/bulk-operations- Bulk operationsGET /api/admin/logs- System logs
flowchart TD
A[User Access] --> B{Authentication Required?}
B -->|No| C[Public Pages]
B -->|Yes| D[Login Page]
D --> E{Valid Credentials?}
E -->|No| F[Login Error]
E -->|Yes| G{User Role?}
F --> D
G -->|Admin| H[Admin Dashboard]
G -->|User| I[User Dashboard]
H --> J[Admin Functions]
I --> K[User Functions]
J --> L[User Management]
J --> M[Document Management]
J --> N[System Diagnostics]
J --> O[S3 Browser]
K --> P[View Documents]
K --> Q[Upload Documents]
K --> R[Search Documents]
K --> S[Download Documents]
L --> L1[Create User]
L --> L2[Edit User]
L --> L3[Delete User]
L --> L4[Assign Roles]
M --> M1[Upload to S3]
M --> M2[Manage Documents]
M --> M3[Set Permissions]
M --> M4[View Analytics]
P --> P1{Document Access?}
P1 -->|Allowed| P2[Display Document]
P1 -->|Denied| P3[Access Error]
Q --> Q1[File Validation]
Q1 --> Q2{Valid File?}
Q2 -->|Yes| Q3[Upload to S3]
Q2 -->|No| Q4[Upload Error]
Q3 --> Q5[Update Database]
Q5 --> Q6[Success Message]
R --> R1[Search Input]
R1 --> R2[Query Processing]
R2 --> R3{Search Type?}
R3 -->|Enhanced| R4[Enhanced Search API]
R3 -->|S3| R5[S3 Search API]
R3 -->|Loan| R6[Loan Search API]
R4 --> R7[Display Results]
R5 --> R7
R6 --> R7
S --> S1{Download Permission?}
S1 -->|Yes| S2[Generate Presigned URL]
S1 -->|No| S3[Access Denied]
S2 --> S4[Download File]
style A fill:#e1f5fe
style H fill:#fff3e0
style I fill:#f3e5f5
style Q3 fill:#e8f5e8
style S2 fill:#e8f5e8
- Entry Point: User accesses the application
- Authentication Check: System verifies if authentication is required
- Login Process: Credentials validation through NextAuth.js
- Role Determination: System assigns appropriate dashboard based on user role
- Dashboard Access: Comprehensive admin interface with system overview
- User Management: Create, edit, delete users with role assignments
- Document Management: Upload documents to S3, manage permissions
- System Monitoring: Access diagnostics and system logs
- Document Access: View documents based on permissions
- Upload Process: File validation, S3 upload, database update
- Search Operations: Multiple search types with real-time results
- Download Process: Permission check and presigned URL generation
- Upload Flow: Validation → S3 Storage → Database Update → Confirmation
- Search Flow: Input → Processing → API Selection → Results Display
- Download Flow: Permission Check → URL Generation → File Download
- Authentication: NextAuth.js with JWT tokens
- Authorization: Role-based access control
- Data Protection: MongoDB encryption and S3 security
- Session Management: Secure session storage with MongoDB
- Node.js 18+
- MongoDB Atlas or local MongoDB
- AWS S3 Bucket
- npm or yarn package manager
-
Clone Repository
git clone <repository-url> cd TheDms
-
Install Dependencies
npm install
-
Environment Setup
cp .env.example .env.local
-
Configure Environment Variables
# Database MONGODB_URI=mongodb+srv://username:[email protected]/bizloan MONGODB_DB=bizloan # AWS S3 AWS_ACCESS_KEY_ID=your-access-key AWS_SECRET_ACCESS_KEY=your-secret-key AWS_DEFAULT_REGION=ap-south-1 PRIMARY_BUCKET=thedms # NextAuth NEXTAUTH_URL=http://localhost:3000 NEXTAUTH_SECRET=your-secret-key SESSION_SECRET=your-session-secret
-
Start Development Server
npm run dev
-
Initialize Admin User
npm run init:admin
| Variable | Description | Required | Default |
|---|---|---|---|
MONGODB_URI |
MongoDB connection string | Yes | - |
MONGODB_DB |
Database name | Yes | bizloan |
AWS_ACCESS_KEY_ID |
AWS access key | Yes | - |
AWS_SECRET_ACCESS_KEY |
AWS secret key | Yes | - |
PRIMARY_BUCKET |
S3 bucket name | Yes | thedms |
NEXTAUTH_URL |
Application URL | Yes | - |
NEXTAUTH_SECRET |
NextAuth secret | Yes | - |
SESSION_SECRET |
Session secret | Yes | - |
// next.config.js
const nextConfig = {
experimental: {
serverComponentsExternalPackages: ['mongoose']
},
images: {
domains: ['thedms.s3.amazonaws.com']
}
};// tailwind.config.js
module.exports = {
content: ['./src/**/*.{js,ts,jsx,tsx}'],
theme: {
extend: {
colors: {
primary: '#3b82f6',
secondary: '#6366f1'
}
}
}
};-
Connect Repository
- Link your GitHub repository to Vercel
-
Environment Variables
- Add all required environment variables in Vercel dashboard
-
Build Settings
Build Command: npm run build Output Directory: .next Install Command: npm install
-
Domain Configuration
- Update
NEXTAUTH_URLwith your Vercel domain
- Update
-
EC2 Setup
# Install Node.js and PM2 curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - sudo apt-get install -y nodejs sudo npm install -g pm2
-
Application Setup
git clone <repository> cd TheDms npm install npm run build
-
Process Management
pm2 start server.js --name thedms pm2 startup pm2 save
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["npm", "start"]- Code Splitting: Automatic route-based splitting
- Image Optimization: Next.js Image component
- CSS Optimization: Tailwind CSS purging
- Bundle Analysis: webpack-bundle-analyzer
- Database Indexing: MongoDB compound indexes
- Connection Pooling: MongoDB connection reuse
- Caching: Redis for session storage
- CDN: CloudFront for S3 assets
- Error Tracking: Sentry integration
- Performance Monitoring: Vercel Analytics
- Logging: Winston with log rotation
- Health Checks: API endpoint monitoring
- JWT tokens with secure headers
- Session encryption
- CSRF protection
- Rate limiting
- MongoDB encryption at rest
- S3 bucket policies
- Environment variable protection
- Input validation and sanitization
- Role-based permissions
- Route-level protection
- API endpoint security
- File access validation
// Required for protected endpoints
{
"Authorization": "Bearer <jwt-token>",
"Content-Type": "application/json"
}// Success Response
{
"success": true,
"data": {...},
"message": "Operation successful"
}
// Error Response
{
"success": false,
"error": "Error description",
"code": "ERROR_CODE"
}# Run all tests
npm test
# Test API connections
npm run test:connections
# Test document operations
npm run test:document
# Test admin functions
npm run test:admin- Unit Tests: Component and utility testing
- Integration Tests: API endpoint testing
- E2E Tests: Full workflow testing
- Performance Tests: Load and stress testing
- Fork the repository
- Create feature branch:
git checkout -b feature/new-feature - Install dependencies:
npm install - Make changes and test
- Submit pull request
- ESLint: Code linting and formatting
- Prettier: Code formatting
- TypeScript: Type safety
- Conventional Commits: Commit message format
- Descriptive commit messages
- Test coverage for new features
- Documentation updates
- Code review approval required
- GitHub Issues: Bug reports and feature requests
- Discussions: General questions and help
- Wiki: Detailed documentation and guides
For enterprise support, custom features, and professional services, please contact the development team.
TheDMS - Empowering organizations with secure, scalable document management solutions.
Built with ❤️ using Next.js, MongoDB, and AWS S3.