dauth-md-node
v3.0.2
Published
Express middleware for JWT-based authentication against the [Dauth](https://dauth.ovh) service. Verifies tenant JWTs and fetches the authenticated user from the Dauth backend, attaching it to `req.user`.
Downloads
845
Readme
dauth-md-node
Express middleware for JWT-based authentication against the Dauth service. Verifies tenant JWTs and fetches the authenticated user from the Dauth backend, attaching it to req.user.
Installation
npm install dauth-md-node
# or
yarn add dauth-md-nodeQuick Start
import express from 'express';
import { dauth, IRequestDauth } from 'dauth-md-node';
const app = express();
// Apply DAuth middleware to protected routes
const dauthMiddleware = dauth({
domainName: 'your-domain-name',
tsk: 'your-tenant-secret-key',
});
app.get('/api/protected', dauthMiddleware, (req, res) => {
// req.user is populated with the authenticated user object
res.json({ user: req.user });
});
app.listen(4000);API
dauth(options)
Factory function that returns an Express middleware.
| Parameter | Type | Description |
|---|---|---|
| domainName | string | Your Dauth domain name (used for API routing) |
| tsk | string | Tenant Secret Key for local JWT verification |
Middleware Behavior
- Extracts the
Authorizationheader from the request - Verifies the JWT locally using the provided
tsk(Tenant Secret Key) - Fetches the full user object from the Dauth backend (
GET /app/:domainName/user) - Attaches the user to
req.user - Calls
next()on success
Error Responses
| Scenario | Status | Response Status Field |
|---|---|---|
| Missing Authorization header | 403 | token-not-found |
| JWT expired | 401 | token-expired |
| Invalid JWT or bad TSK | 401 | tsk-not-invalid or token-invalid |
| User not found in Dauth backend | 404 | user-not-found |
| Dauth backend server error | 500 | error |
| Other backend status | 501 | request-error |
req.user Object
When authentication succeeds, req.user contains:
interface IDauthUser {
_id: string;
name: string;
lastname: string;
nickname: string;
email: string;
isVerified: boolean;
language: string;
avatar: { id: string; url: string };
role: string;
telPrefix: string;
telSuffix: string;
createdAt: Date;
updatedAt: Date;
lastLogin: Date;
}Both IDauthUser and IRequestDauth are exported from the package for type-safe usage in consumer code.
Real-World Integration Example
This is the pattern used in easymediacloud-backend-node, which delegates all user authentication to Dauth.
1. Initialize the middleware from environment variables
// src/middlewares/auth.middleware.ts
import { dauth, IRequestDauth } from 'dauth-md-node';
import config from '../config/config';
export const dauth_md = dauth({
tsk: config.dauth.TSK as string,
domainName: config.dauth.DOMAIN_NAME as string,
});Environment variables (.env.development):
DAUTH_TSK=your-tenant-secret-key
DAUTH_DOMAIN_NAME=your-domain-name2. Build custom middleware chains on top
After dauth_md populates req.user, add your own guards:
// src/middlewares/auth.middleware.ts (continued)
import { Response, NextFunction } from 'express';
export const is_verified = async (req: IRequestDauth, res: Response, next: NextFunction) => {
if (req.user.isVerified === false) {
return res.status(401).send({ status: 'not-verified', message: 'Email not verified' });
}
next();
};
export const ensure_admin = async (req: IRequestDauth, res: Response, next: NextFunction) => {
if (req.user.isVerified === false) {
return res.status(401).send({ status: 'not-verified', message: 'Email not verified' });
}
if (req.user.role !== 'admin') {
return res.status(401).send({ status: 'not-admin', message: 'Admin role required' });
}
next();
};3. Apply middleware chains to routes
// src/core/licenses/router/licenses.router.ts
import { Router } from 'express';
import { dauth_md, is_verified, ensure_admin } from '../../../middlewares/auth.middleware';
import * as controller from '../controllers/licenses.controller';
const licenseApi = Router();
licenseApi
.post('/create-license', [dauth_md, is_verified], controller.createLicense)
.get('/get-my-licenses', [dauth_md, is_verified], controller.getMyLicenses)
.patch('/enable-license/:licenseId', [dauth_md, ensure_admin], controller.enableLicense)
.delete('/delete-license/:licenseId', [dauth_md, is_verified], controller.deleteLicense);
export default licenseApi;4. Access the user in controllers
// src/core/licenses/controllers/licenses.controller.ts
export const getMyLicenses = async (req: IRequestDauth, res: Response) => {
const userId = req.user._id;
const licenses = await License.find({ user: userId });
res.status(200).json({ status: 'success', data: licenses });
};Environment Detection
- Development (
NODE_ENV=development): Routes API calls tohttp://localhost:4012/api/v1 - Production: Routes API calls to
https://dauth.ovh/api/v1
Development
pnpm start # Watch mode (tsdx watch)
pnpm build # Production build (CJS + ESM)
pnpm test # Run Jest tests
pnpm lint # ESLint via tsdx
pnpm size # Check bundle size (10KB budget per entry)
pnpm analyze # Bundle size analysis with visualizationBundle Outputs
- CJS:
dist/index.js(with.development.jsand.production.min.jsvariants) - ESM:
dist/dauth-md-node.esm.js - Types:
dist/index.d.ts
Dependencies
express>= 4jsonwebtoken>= 9mongoose>= 8node-fetch^2.6
Author
David T. Pizarro Frick
License
MIT
