UNPKG

@authxyz/local

Version:

A robust authentication library for express.js

83 lines (82 loc) 3.51 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import jwt from "jsonwebtoken"; import { ZodError } from "zod"; const { JsonWebTokenError, TokenExpiredError } = jwt; export function zodError(error) { if (error instanceof ZodError) { const message = JSON.parse(error.message); const errorMessages = message.map((errorMsg) => { var _a; const fieldName = ((_a = errorMsg.path) === null || _a === void 0 ? void 0 : _a.length) === 2 ? errorMsg.path[1] : errorMsg.path[0]; const errorMessage = errorMsg.message; return `${fieldName}: ${errorMessage}`; }); return { message: errorMessages, status: 422 }; } } export function jwtError(error) { if (error instanceof JsonWebTokenError) { return { message: "Invalid auth token", status: 401 }; } else if (error instanceof TokenExpiredError) { return { message: "Token expired", status: 401 }; } } export function duplicateDocHandler(error) { if (error instanceof Error) { if (error.message.includes("E11000 duplicate key error")) { const alreadyExists = Object.keys(error["keyValue"]); return { status: 400, message: `${alreadyExists.join()} already exists`, }; } } } export function asyncHandler(controller) { return (req, res, next) => __awaiter(this, void 0, void 0, function* () { return Promise.resolve(controller(req, res, next)).catch((err) => { let handlers = [jwtError, zodError, duplicateDocHandler]; for (const handler of handlers) { const error = handler(err); if (error) { return res.status(error.status).json({ error: error.message }); } } return res.send(err); }); }); } export function withRequestProcessors(path, processors) { return (req, res, next) => __awaiter(this, void 0, void 0, function* () { if (path === req.path) { const { pre, main, post } = processors; if (pre) { const stopRequest = yield Promise.resolve(!pre(req, res, next)); if (stopRequest) { return; } } const context = yield main(req, res, next); if (post && (context === null || context === void 0 ? void 0 : context.context)) { post(context === null || context === void 0 ? void 0 : context.context, req, res); } else { if (context === null || context === void 0 ? void 0 : context.resolveMainHandler) { context === null || context === void 0 ? void 0 : context.resolveMainHandler(); } } } else { next(); } }); }