A comprehensive Node.js backend with Firebase Authentication and role-based access control.
- 🔥 Firebase Authentication integration
- 👥 Role-based access control (Admin, Manager, User)
- 🗄️ PostgreSQL database with user management
- 🔒 JWT token verification
- 📱 RESTful API endpoints
- 🧪 Test users for development
- 📚 Comprehensive API documentation
- Admin: Full system access, can manage all users and roles
- Manager: Can view all users but cannot modify roles or user status
- User: Basic access, can only view their own profile
- Node.js (v14 or higher)
- PostgreSQL database
- Firebase project with service account key
npm installCopy the environment template:
copy .env.example .envUpdate .env with your configuration:
# Database Configuration
DB_USER=your_db_username
DB_HOST=localhost
DB_NAME=your_database_name
DB_PASS=your_db_password
DB_PORT=5432
# Server Configuration
PORT=5000
# Firebase Configuration
FIREBASE_PROJECT_ID=your_firebase_project_id
# Chatbot Configuration
OPENAI_API_KEY=your_openai_api_key_here
NODE_ENV=development- Go to Firebase Console
- Create a new project or select existing one
- Go to Project Settings → Service Accounts
- Click "Generate new private key"
- Download the JSON file and save it as
serviceAccountKey.jsonin the project root
Run the complete setup:
npm run setup-allThis will:
- Create database tables and indexes
- Insert default test users in database
- Create Firebase test users
npm run devThe server will start on http://localhost:5000
The system automatically creates these test users for development:
| Password | Role | Firebase UID | |
|---|---|---|---|
| [email protected] | admin | admin | admin-firebase-uid |
| [email protected] | manager | manager | manager-firebase-uid |
| [email protected] | user | user | user-firebase-uid |
GET /health- Check server status
POST /api/users/register- Register/login userGET /api/users/profile- Get current user profileGET /api/users- Get all users (Manager/Admin only)PUT /api/users/:userId/role- Update user role (Admin only)PUT /api/users/:userId/deactivate- Deactivate user (Admin only)PUT /api/users/:userId/activate- Activate user (Admin only)
POST /api/chatbot- Chat completion endpointGET /api/chatbot/health- Check chatbot service status
POST /api/users/test-register- Register without Firebase auth
All protected endpoints require a Firebase ID token in the Authorization header:
Authorization: Bearer <firebase_id_token>
Open test-auth.html in your browser and:
- Update the Firebase config with your project details
- Sign in with test credentials ([email protected] / admin)
- Copy the ID token
- Use the token to test API endpoints
First get an ID token, then use it to call protected endpoints:
# Get user profile
curl -H "Authorization: Bearer YOUR_ID_TOKEN" \
http://localhost:5000/api/users/profile
# Get all users (Manager/Admin only)
curl -H "Authorization: Bearer YOUR_ID_TOKEN" \
http://localhost:5000/api/users- Set Authorization header:
Bearer YOUR_ID_TOKEN - Set Content-Type:
application/json - Make requests to the API endpoints
See API_DOCUMENTATION.md for comprehensive frontend integration guide including:
- Firebase setup
- Authentication service
- API service
- React component examples
- Route protection
- Error handling
-- User roles enum
CREATE TYPE user_role AS ENUM ('admin', 'manager', 'user');
-- Users table
CREATE TABLE users (
id SERIAL PRIMARY KEY,
firebase_uid VARCHAR(255) UNIQUE NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
role user_role DEFAULT 'user',
first_name VARCHAR(100),
last_name VARCHAR(100),
is_active BOOLEAN DEFAULT true,
last_login TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);├── controllers/
│ └── user.controller.ts # User management logic
├── database/
│ └── schema.sql # Database schema
├── middleware/
│ ├── errorHandler.ts # Error handling middleware
│ ├── verifyToken.ts # Firebase token verification
│ └── roleAuth.ts # Role-based authorization
├── routes/
│ └── user.routes.ts # User API routes
├── scripts/
│ ├── setup-database.js # Database setup script
│ └── create-firebase-users.js # Firebase users creation
├── types/
│ └── index.ts # TypeScript type definitions
├── db.ts # Database connection
├── firebaseAdmin.ts # Firebase admin setup
├── index.ts # Main server file
└── test-auth.html # Testing page
npm run dev- Start development server with hot reloadnpm start- Start production servernpm run build- Build TypeScript to JavaScriptnpm run setup-db- Set up database tablesnpm run create-firebase-users- Create Firebase test usersnpm run setup-all- Complete setup (database + Firebase users)
- Define types in
types/index.ts - Create controller functions in
controllers/ - Add routes in
routes/ - Update documentation
Use the role middleware to protect endpoints:
import { requireAdmin, requireManager, requireUser } from '../middleware/roleAuth';
// Admin only
router.put('/admin-endpoint', verifyToken, requireAdmin, controllerFunction);
// Manager or Admin
router.get('/manager-endpoint', verifyToken, requireManager, controllerFunction);
// Any authenticated user
router.get('/user-endpoint', verifyToken, requireUser, controllerFunction);Before deploying to production:
- Remove test users and endpoints
- Set up proper environment variables
- Configure CORS for your frontend domain
- Set up SSL/TLS certificates
- Implement logging and monitoring
- Set up database backups
- Configure rate limiting
- Never expose Firebase service account keys in client-side code
- Always validate Firebase ID tokens on the backend
- Implement proper CORS settings for production
- Use environment variables for sensitive configuration
- Validate and sanitize all user inputs
- Use HTTPS in production environments
- Database connection errors: Check your
.envconfiguration and ensure PostgreSQL is running - Firebase authentication errors: Verify your
serviceAccountKey.jsonis correct and in the project root - Token verification failures: Ensure Firebase config matches between frontend and backend
- Permission denied errors: Check user roles and endpoint permissions
Check the console output for detailed error messages. The server logs all database operations and authentication attempts.
- Complete API Documentation - Detailed API reference with examples
- Frontend Integration Guide - Step-by-step frontend setup
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Update documentation
- Submit a pull request
This project is licensed under the ISC License.