Authentication System Documentation
This document describes the Hybrid Authentication system used in the WhatsApp Automation backend. It supports both API Key and JWT Token-based authentication for securing API endpoints.
1. Overview
The Hybrid Authentication system allows two modes of access:
1. API Key Authentication (for external integrations and automation)
2. JWT Token Authentication (for authenticated web and dashboard users)
2. API Key Authentication
API Key authentication is primarily used by external applications or users who want to connect to the system programmatically without logging in. Each user can generate multiple API keys from the dashboard in the 'API Credentials' section.
Endpoint
POST /settings/api-keys/generate
Headers
Authorization: Bearer <JWT_TOKEN>
Response Example
{
"status": 1,
"message": "New API key generated successfully",
"data": {
"_id": "66f9e1fcd31e2b11a63e1b94",
"key": "9a2d64a2d9274c83a84282b9d49b24c3",
"createdAt": "2025-10-09T09:00:00.000Z"
}
}
3. Using API Key for Authentication
Once an API key is generated, it can be used to authenticate API requests without requiring a JWT token. Pass the API key in the header using the 'x-api-key' field.
Example Request
$curl -X GET https://yourdomain.com/api/sessions \
-H 'x-api-key: YOUR_API_KEY'
Response Example
{
"status": true,
"data": [
{"sessionId": "919876543210", "status": "connected"}
]
}
4. JWT Token Authentication
JWT-based authentication is used by logged-in users through the dashboard or web portal. Users receive a JWT token after successful login, which must be included in the Authorization header.
Example Header
Authorization: Bearer <JWT_TOKEN>
Example Request
$curl -X GET https://yourdomain.com/api/sessions \
-H 'Authorization: Bearer YOUR_JWT_TOKEN'
5. Hybrid Authentication Middleware
The middleware first checks for the presence of an API key. If a valid key is found, it allows access. If no API key is present, it falls back to JWT verification.
File: middleware/hybridAuth.js
-----------------------------------
const ApiKey = require('../models/ApiKey');
const { verifyToken } = require('./authMiddleware');
async function hybridAuth(req, res, next) {
try {
const apiKey = req.headers['x-api-key'];
if (apiKey) {
const keyDoc = await ApiKey.findOne({ key: apiKey });
if (!keyDoc) return res.status(403).json({ error: 'Invalid API key' });
req.userId = keyDoc.user;
return next();
}
return verifyToken(req, res, next);
} catch (err) {
console.error('Hybrid Auth Error:', err);
res.status(500).json({ error: 'Authentication failed' });
}
}
6. API Key Schema
File: models/ApiKey.js
-----------------------------------
const mongoose = require('mongoose');
const apiKeySchema = new mongoose.Schema({
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
key: { type: String, required: true },
createdAt: { type: Date, default: Date.now }
});
module.exports = mongoose.model('ApiKey', apiKeySchema);
7. Example Node.js Usage
const axios = require('axios');
async function fetchSessions() {
try {
const res = await axios.get('https://yourdomain.com/api/sessions', {
headers: { 'x-api-key': 'YOUR_API_KEY' }
});
console.log(res.data);
} catch (err) {
console.error('Error:', err.response?.data || err.message);
}
}
fetchSessions();