A comprehensive REST API for managing employee leave requests, balances, and approvals with JWT authentication and role-based access control.
- Node.js (v14+)
- PostgreSQL (v11+)
- npm or yarn
-
Clone the repository
git clone https://github.com/SaddockAime/leave-management-system-bn.git cd leave-management-system-bn -
Install dependencies
npm install
-
Environment Setup
cp .env.example .env # Edit .env file with your database and other configurations -
Database Setup
npm run createAllTables npm run seed:all
-
Start the server
npm run dev
The API will be available at http://localhost:4000 with documentation at http://localhost:4000/api-docs
Create a .env file with these required variables:
# Database
DATABASE_URL=postgres://username:password@localhost:5432/leave_management
# JWT Authentication
JWT_SECRET=your-super-secret-jwt-key
JWT_EXPIRES_IN=24h
REFRESH_TOKEN_EXPIRES_IN=7d
# File Storage (Cloudinary)
CLOUDINARY_CLOUD_NAME=your-cloud-name
CLOUDINARY_API_KEY=your-api-key
CLOUDINARY_API_SECRET=your-api-secret
# Email (Required for notifications)
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USER=[email protected]
EMAIL_PASSWORD=your-app-password
# Google OAuth (Optional)
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
GOOGLE_CALLBACK_URL=
# Email Templates & Branding (Required)
COMPANY_NAME=Your Company Name
SUPPORT_EMAIL=[email protected]
HR_EMAIL=[email protected]
# Server
PORT=4000
NODE_ENV=development- Runtime: Node.js with TypeScript
- Framework: Express.js
- Database: PostgreSQL with TypeORM
- Authentication: JWT-based internal authentication system
- File Storage: Cloudinary for images and documents
- Documentation: Swagger/OpenAPI
- Real-time: Socket.IO for notifications
- Logging: Winston for structured logging
- Validation: Joi for request validation
- π Authentication & Authorization: Complete JWT-based auth system with user registration, login, logout, password reset, email verification, and Google OAuth
- π₯ HR Management: Comprehensive HR module with employee analytics, department performance, bulk operations, and workforce insights
- π― Recruitment System: Full recruitment lifecycle with job postings, application tracking, interview scheduling, and recruitment analytics
- π° Compensation Management: Salary administration, bonus tracking, benefits enrollment, and compensation analytics
- π Employee Onboarding: Structured onboarding processes with task templates, progress tracking, and completion analytics
- π Leave Management: Advanced leave system with multiple types, approval workflows, balance tracking, and manager tools
- π¨βπΌ Manager Tools: Team management, performance tracking, leave approvals, and department oversight
- π Document Management: Cloudinary-integrated file storage for profiles, documents, and attachments
- π Real-time Notifications: Socket.IO notifications with email integration and preference management
- π Advanced Analytics: Comprehensive reporting across HR, recruitment, compensation, and leave modules
- π΅οΈ Audit & Compliance: Complete activity tracking, security logging, and compliance reporting
- π’ Organizational Structure: Department management, manager hierarchies, and team relationships
- Swagger UI:
http://localhost:4000/api-docs - OpenAPI Spec:
http://localhost:4000/api-docs.json
The API uses internal JWT-based authentication. Users can register, login, and manage their sessions:
# Register a new user
curl -X POST http://localhost:4000/api/auth/register \
-H "Content-Type: application/json" \
-d '{"firstName": "John", "lastName": "Doe", "email": "[email protected]", "password": "password123"}'
# Login to get JWT token
curl -X POST http://localhost:4000/api/auth/login \
-H "Content-Type: application/json" \
-d '{"email": "[email protected]", "password": "password123"}'
# Use token in protected requests
curl -X GET http://localhost:4000/api/leave-requests/my-leaves \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
# Logout (invalidates token)
curl -X POST http://localhost:4000/api/auth/logout \
-H "Authorization: Bearer YOUR_JWT_TOKEN"- ADMIN: Full system access, user management, system configuration
- HR_MANAGER: Employee management, department oversight, leave policies
- MANAGER: Team management, leave approvals for direct reports
- EMPLOYEE: Basic access, personal leave requests, profile management
npm run dev # Start development server
npm run build # Build TypeScript to JavaScript
npm run start # Start production server
npm run createAllTables # Create database tables
npm run deleteAllTables # Drop all database tables
npm run seed:all # Seed database with initial data
npm run swagger:generate # Generate API documentation
npm run format # Format code with Prettiersrc/
βββ controllers/ # Request handlers
βββ services/ # Business logic
βββ models/ # Database entities
βββ routes/ # API route definitions
βββ middleware/ # Custom middleware
βββ validations/ # Request validation schemas
βββ config/ # Configuration files
βββ utils/ # Utility functions
βββ scripts/ # Database seeders
- TypeScript for type safety
- Joi for request validation
- Winston for structured logging
- ESLint and Prettier for code formatting
- JWT Authentication: Secure token-based authentication
- Role-based Access Control: Granular permissions by user role
- Input Validation: Comprehensive request validation with Joi
- File Upload Security: Type and size validation for uploads
- Audit Logging: Complete activity tracking
- Error Handling: Secure error responses without sensitive data
- User: Authentication and basic user data
- Employee: Extended employee profiles (linked to Users)
- Department: Organizational structure
- Role: User roles and permissions
- LeaveRequest: Leave applications and status
- LeaveType: Different types of leave (Annual, Sick, etc.)
- LeaveBalance: Available leave balances by type
- JobPosting: Recruitment job listings
- JobApplication: Candidate applications
- Interview: Interview scheduling and tracking
- Onboarding: Employee onboarding processes
- OnboardingTask: Individual onboarding tasks
- Salary: Employee salary information
- Bonus: Bonus allocations and tracking
- Benefit: Company benefits catalog
- EmployeeBenefit: Employee benefit enrollments
- Document: File attachments with Cloudinary integration
- Notification: System notifications and preferences
- AuditLog: Comprehensive activity tracking
- NotificationTemplate: Email and notification templates
- Users have one Employee profile (created by HR/Admin)
- Employees belong to Departments
- Employees can have Managers (hierarchical structure)
- Leave Requests belong to Employees
- Documents are attached to Leave Requests
The system provides 17 comprehensive API modules with hundreds of endpoints:
- Professional Registration Flow: New users assigned GUEST role, receive welcome email with verification
- Role-Based Progression: GUEST β EMPLOYEE when HR creates profile, with assignment notification
- Secure Authentication: JWT tokens, password reset, email verification workflows
- Google OAuth Integration: Alternative authentication method
- User role and status management (Admin only)
- Token refresh and blacklisting for enhanced security
- User profile viewing and updating
- Profile picture upload with Cloudinary integration
- Smart Role Progression: Creating employee profile automatically upgrades GUEST to EMPLOYEE
- Professional Notifications: Welcome emails sent with department and manager information
- HR-controlled employee profile creation and management
- Employee search and filtering with pagination
- Department-based employee viewing for managers
- Employee analytics and insights
- Team management and hierarchy viewing
- Team leave approval and oversight
- Performance tracking and analytics
- Direct report management
- Comprehensive HR dashboard and analytics
- Employee overview and workforce insights
- Department performance metrics
- Bulk employee operations
- HR reporting with multiple report types
- Job posting creation and management
- Application tracking and processing
- Interview scheduling and management
- Candidate evaluation and hiring workflows
- Recruitment analytics and metrics
- Salary administration and tracking
- Bonus allocation and management
- Benefits enrollment and administration
- Compensation analytics and reporting
- Payroll integration capabilities
- Structured onboarding process creation
- Task templates and checklist management
- Progress tracking and completion monitoring
- Onboarding analytics and optimization
- Advanced leave request workflows
- Multiple leave types and balance tracking
- Manager approval processes
- Leave analytics and reporting
- Department and team leave oversight
- Cloudinary-integrated file storage
- Document upload for leave requests
- File categorization and management
- Secure document access control
- Professional Email Templates: Handlebars-powered professional email designs
- Role-Based Notifications: Welcome emails for GUEST, assignment emails for EMPLOYEE
- Real-time notifications via Socket.IO
- Email notification preferences and management
- Notification history and tracking
- Custom notification templates for various workflows
- Organizational structure management
- Department creation and administration
- Manager assignment and hierarchies
- Cross-module reporting capabilities
- Advanced analytics and insights
- Data export in multiple formats
- Custom report generation
- Comprehensive activity logging
- Security event tracking
- Compliance reporting
- Audit trail management
- Protected Routes: Role-based access control across all endpoints
- Real-time Features: Socket.IO integration for live updates
- Email Services: SMTP integration for notifications and workflows
For complete API documentation, visit /api-docs when the server is running.
The system implements a sophisticated user onboarding workflow with role-based access control:
POST /api/auth/register
- β User assigned GUEST role initially
- β Professional welcome email sent with verification link
- β No JWT token returned (security best practice)
- β Email verification required before login
GET /api/auth/verify-email/:token
- β User verifies email address
- β Account activated for login
- β User can now log in with GUEST permissions
POST /api/employees (HR/Admin only)
- β HR/Admin creates employee profile for user
- β User role automatically upgraded from GUEST to EMPLOYEE
- β
Professional assignment email sent with:
- Department information
- Position details
- Manager contact information
- Employee ID and hire date
- Full access rights explanation
- β User now has complete employee functionality
- β Can submit leave requests, access documents, etc.
- β Receives role-appropriate notifications
All emails use Handlebars templates with professional design:
- Welcome Email: Clean blue gradient, verification flow explanation
- Employee Assignment: Green celebration theme, detailed role information
- Email Verification: Security-focused design with clear instructions
Templates are mobile-responsive and follow corporate design standards.
The system enforces strict access control based on user roles:
- User registration and login
- Password reset and email verification
- Google OAuth authentication
- β Profile Management: View/update profile, upload profile picture
- β
Status Checking: Check onboarding progress via
/api/auth/status - β Basic Notifications: View system notifications
- β Leave Management: Cannot create, view, or manage leave requests
- β Document Access: Cannot upload or access documents
- β Employee Features: Limited access until profile created
- β All GUEST permissions +
- β Leave Management: Create, view, update, cancel leave requests
- β Document Management: Upload and access leave documents
- β Leave History: View personal leave history and balances
- β Team Features: Basic team collaboration
- β All EMPLOYEE permissions +
- β Team Management: View and manage team leave requests
- β Approval Workflows: Approve/reject leave requests
- β Department Oversight: Department-level reporting
- β All MANAGER permissions +
- β Employee Management: Create employee profiles for GUEST users
- β System Administration: User role management, system settings
- β Advanced Analytics: Comprehensive reporting across all modules
GET / api / auth / status;Perfect for frontend applications to determine user capabilities:
{
"success": true,
"data": {
"role": "GUEST",
"emailVerified": true,
"hasEmployeeProfile": false,
"needsEmployeeProfile": true,
"status": "GUEST_AWAITING_PROFILE"
}
}-
Database Connection Failed
- Check PostgreSQL is running
- Verify
DATABASE_URLin.env
-
JWT Authentication Errors
- Check
JWT_SECRETis set in.env - Verify token format in Authorization header
- Ensure token hasn't expired or been blacklisted
- Check
-
File Upload Issues
- Verify Cloudinary credentials in
.env - Check file size limits (10MB max)
- Verify Cloudinary credentials in
-
TypeScript Compilation Errors
- Run
npx tsc --noEmitto check for errors - Ensure all dependencies are installed
- Run
NODE_ENV=development npm run dev- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
This project is licensed under the MIT License.
- Frontend Application - React frontend (if available)
This is a comprehensive enterprise HR management system with:
- β Complete HR Suite: Full employee lifecycle from recruitment to onboarding to performance management
- β Advanced Analytics: Detailed reporting across all modules with data-driven insights
- β Enterprise Security: JWT authentication, audit logging, role-based access control
- β Workflow Automation: Automated leave approvals, onboarding processes, and notifications
- β Integration Ready: Cloudinary for files, SMTP for emails, Socket.IO for real-time updates
- β Scalable Architecture: TypeScript, TypeORM, comprehensive validation, and structured logging
- β API-First Design: Complete REST API with Swagger documentation for frontend integration
Need help? Check the Swagger documentation at /api-docs or open an issue on GitHub.