@piggly/fastify-chassis
Version:
An ESM/CommonJS toolkit to help you to do common operations in your back-end applications with Fastify and NodeJS.
42 lines • 1.55 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CSRFTokenMiddleware = void 0;
const index_js_1 = require("../events/index.js");
const index_js_2 = require("../errors/index.js");
/**
* CSRF token middleware.
*
* When method.from is cookie, will get the "param"
* value from cookie. E.g: request.cookies[param].
*
* When method.from is header, will get the "param"
* value from header. E.g: request.headers[param].
*
* If csrf token is invalid for any reason, it will:
* - Publish UnauthorizedAccessEvent.
* - Return InvalidCSRFTokenError.
*
* @param {Object} method The method to get the csrf token.
* @param {string} method.from The source of the csrf token.
* @param {string} method.param The parameter name to get the csrf token.
* @param {Object} deps The dependencies.
* @param {CSRFTokenService} deps.CSRF_SERVICE The csrf token service.
* @returns Callback function.
* @since 7.0.0
* @author Caique Araujo <caique@piggly.com.br>
*/
const CSRFTokenMiddleware = (method, deps) => (request, reply, done) => {
const { from, param } = method;
const { CSRF_SERVICE } = deps;
const token = from === 'header'
? CSRF_SERVICE.verifyHeader(request, param)
: CSRF_SERVICE.verifyCookie(request, param);
if (!token) {
index_js_1.UnauthorizedAccessEvent.publish(request);
done(new index_js_2.InvalidCSRFTokenError());
return;
}
done();
};
exports.CSRFTokenMiddleware = CSRFTokenMiddleware;
//# sourceMappingURL=CSRFTokenMiddleware.js.map