2025-01-09 18:36:24 +02:00
|
|
|
import type { Application, NextFunction, Request, Response } from "express";
|
2024-07-18 21:35:17 +03:00
|
|
|
import log from "../services/log.js";
|
2025-03-07 22:31:55 +01:00
|
|
|
import NotFoundError from "../errors/not_found_error.js";
|
2025-03-07 23:29:35 +01:00
|
|
|
import ForbiddenError from "../errors/forbidden_error.js";
|
2025-03-07 23:35:19 +01:00
|
|
|
import HttpError from "../errors/http_error.js";
|
2023-05-07 15:23:46 +02:00
|
|
|
|
2024-04-07 14:13:57 +03:00
|
|
|
function register(app: Application) {
|
2025-03-08 00:15:46 +01:00
|
|
|
|
|
|
|
app.use((err: unknown | Error, req: Request, res: Response, next: NextFunction) => {
|
|
|
|
|
|
|
|
const isCsrfTokenError = typeof err === "object"
|
|
|
|
&& err
|
|
|
|
&& "code" in err
|
|
|
|
&& err.code === "EBADCSRFTOKEN";
|
|
|
|
|
|
|
|
if (isCsrfTokenError) {
|
|
|
|
log.error(`Invalid CSRF token: ${req.headers["x-csrf-token"]}, secret: ${req.cookies["_csrf"]}`);
|
|
|
|
return next(new ForbiddenError("Invalid CSRF token"));
|
2023-05-07 15:23:46 +02:00
|
|
|
}
|
|
|
|
|
2025-03-08 00:15:46 +01:00
|
|
|
return next(err);
|
2023-05-07 15:23:46 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
// catch 404 and forward to error handler
|
|
|
|
app.use((req, res, next) => {
|
2025-03-07 22:31:55 +01:00
|
|
|
const err = new NotFoundError(`Router not found for request ${req.method} ${req.url}`);
|
2023-05-07 15:23:46 +02:00
|
|
|
next(err);
|
|
|
|
});
|
|
|
|
|
|
|
|
// error handler
|
2025-03-07 23:35:19 +01:00
|
|
|
app.use((err: unknown | Error, req: Request, res: Response, _next: NextFunction) => {
|
|
|
|
|
|
|
|
const statusCode = (err instanceof HttpError) ? err.statusCode : 500;
|
|
|
|
const errMessage = (err instanceof Error && statusCode !== 404)
|
|
|
|
? err
|
|
|
|
: `${statusCode} ${req.method} ${req.url}`;
|
2023-05-07 15:23:46 +02:00
|
|
|
|
2025-03-07 23:35:19 +01:00
|
|
|
log.info(errMessage);
|
|
|
|
|
|
|
|
res.status(statusCode).send({
|
|
|
|
message: err instanceof Error ? err.message : "Unknown Error"
|
2023-05-07 15:23:46 +02:00
|
|
|
});
|
2025-03-07 23:35:19 +01:00
|
|
|
|
2023-05-07 15:23:46 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2024-07-18 21:42:44 +03:00
|
|
|
export default {
|
2023-05-07 15:23:46 +02:00
|
|
|
register
|
|
|
|
};
|