This commit is contained in:
DESKTOP-1R2VSQH\Lenovo ThinkPad E490 2024-08-23 14:10:34 +07:00
parent ce8bb41bda
commit 0f79425d65
17 changed files with 611 additions and 202 deletions

View file

@ -3,15 +3,13 @@ import { createDecoder, createVerifier } from "fast-jwt";
import HttpError from "../interfaces/http-error";
import HttpStatus from "../interfaces/http-status";
import { addLogSequence } from "../interfaces/utils";
import { RequestWithUser } from "./user";
if (!process.env.AUTH_PUBLIC_KEY && !process.env.AUTH_REALM_URL) {
throw new Error("Require keycloak AUTH_PUBLIC_KEY or AUTH_REALM_URL.");
}
if (
process.env.AUTH_PUBLIC_KEY &&
process.env.AUTH_REALM_URL &&
!process.env.AUTH_PREFERRED_MODE
) {
if (process.env.AUTH_PUBLIC_KEY && process.env.AUTH_REALM_URL && !process.env.AUTH_PREFERRED_MODE) {
throw new Error(
"AUTH_PREFFERRED must be specified if AUTH_PUBLIC_KEY and AUTH_REALM_URL is provided.",
);
@ -26,7 +24,7 @@ const jwtVerify = createVerifier({
const jwtDecode = createDecoder();
export async function expressAuthentication(
request: express.Request,
request: RequestWithUser,
securityName: string,
_scopes?: string[],
) {
@ -56,6 +54,18 @@ export async function expressAuthentication(
if (process.env.AUTH_PUBLIC_KEY) payload = await verifyOffline(token);
break;
}
if (!request.app.locals.logData) {
request.app.locals.logData = {};
}
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Query Data.",
// });
request.app.locals.logData.userId = payload.sub;
request.app.locals.logData.userName = payload.name;
request.app.locals.logData.user = payload.preferred_username;
return payload;
}

View file

@ -4,6 +4,12 @@ import HttpStatus from "../interfaces/http-status";
import { ValidateError } from "tsoa";
function error(error: Error, _req: Request, res: Response, _next: NextFunction) {
const logData = _req.app.locals.logData.sequence?.at(-1);
if (logData) {
logData.status = "error";
logData.description = error.message;
}
if (error instanceof HttpError) {
return res.status(error.status).json({
status: error.status,

74
src/middlewares/logs.ts Normal file
View file

@ -0,0 +1,74 @@
import { NextFunction, Request, Response } from "express";
import { Client } from "@elastic/elasticsearch";
if (!process.env.ELASTICSEARCH_INDEX) {
throw new Error("Require ELASTICSEARCH_INDEX to store log.");
}
const ELASTICSEARCH_INDEX = process.env.ELASTICSEARCH_INDEX;
const LOG_LEVEL_MAP: Record<string, number> = {
debug: 4,
info: 3,
warning: 2,
error: 1,
none: 0,
};
const elasticsearch = new Client({
node: `${process.env.ELASTICSEARCH_PROTOCOL}://${process.env.ELASTICSEARCH_HOST}:${process.env.ELASTICSEARCH_PORT}`,
});
async function logMiddleware(req: Request, res: Response, next: NextFunction) {
if (!req.url.startsWith("/api/")) return next();
let data: any;
const originalJson = res.json;
res.json = function (v: any) {
data = v;
return originalJson.call(this, v);
};
const timestamp = new Date().toISOString();
const start = performance.now();
req.app.locals.logData = {};
res.on("finish", () => {
if (!req.url.startsWith("/api/")) return;
const level = LOG_LEVEL_MAP[process.env.LOG_LEVEL ?? "debug"] || 4;
if (level === 1 && res.statusCode < 500) return;
if (level === 2 && res.statusCode < 400) return;
if (level === 3 && res.statusCode < 200) return;
const obj = {
logType: res.statusCode >= 500 ? "error" : res.statusCode >= 400 ? "warning" : "info",
ip: req.ip,
systemName: "salary",
startTimeStamp: timestamp,
endTimeStamp: new Date().toISOString(),
processTime: performance.now() - start,
host: req.hostname,
method: req.method,
endpoint: req.url,
responseCode: String(res.statusCode === 304 ? 200 : res.statusCode),
responseDescription: data?.message,
input: (level === 4 && JSON.stringify(req.body, null, 2)) || undefined,
output: (level === 4 && JSON.stringify(data, null, 2)) || undefined,
...req.app.locals.logData,
};
elasticsearch.index({
index: ELASTICSEARCH_INDEX,
document: obj,
});
});
return next();
}
export default logMiddleware;