bauth-js
Version:
A Node.js authentication library for API requests via remote authentication service using Bearer tokens. Compatible with Express and NestJS.
57 lines • 1.95 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createBAuthMiddleware = createBAuthMiddleware;
exports.bauth = bauth;
const auth_1 = require("../auth");
function createBAuthMiddleware(options) {
const { onUnauthorized, userProperty = 'user', tokenExtractor = defaultTokenExtractor, ...authConfig } = options;
return async (req, res, next) => {
try {
const token = tokenExtractor(req);
if (!token) {
if (onUnauthorized) {
return onUnauthorized(req, res, next);
}
return res.status(401).json({ error: 'No token provided' });
}
const auth = new auth_1.BAuth(authConfig);
const result = await auth.authenticate(token);
if (!result.valid) {
if (onUnauthorized) {
return onUnauthorized(req, res, next);
}
return res.status(401).json({ error: result.error || 'Invalid token' });
}
// Attach user to request
req[userProperty] = result.user;
req.bauth = {
token,
user: result.user,
};
next();
}
catch (error) {
if (onUnauthorized) {
return onUnauthorized(req, res, next);
}
return res.status(500).json({ error: 'Authentication error' });
}
};
}
/**
* Default token extractor that looks for Bearer token in Authorization header
*/
function defaultTokenExtractor(req) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return null;
}
return authHeader.substring(7);
}
/**
* Convenience function for basic Express middleware
*/
function bauth(config) {
return createBAuthMiddleware(config);
}
//# sourceMappingURL=express.js.map