แก้ throw error
This commit is contained in:
parent
dfcc136c79
commit
9e4f18a1d6
3 changed files with 87 additions and 72 deletions
|
|
@ -4,7 +4,7 @@ import { addLogSequence } from "./utils";
|
||||||
|
|
||||||
class CallAPI {
|
class CallAPI {
|
||||||
//Get
|
//Get
|
||||||
public async GetData(request: any, @Path() path: any) {
|
public async GetData(request: any, @Path() path: any, log = true) {
|
||||||
const token = "Bearer " + request.headers.authorization.replace("Bearer ", "");
|
const token = "Bearer " + request.headers.authorization.replace("Bearer ", "");
|
||||||
const url = process.env.API_URL + path;
|
const url = process.env.API_URL + path;
|
||||||
try {
|
try {
|
||||||
|
|
|
||||||
|
|
@ -3,8 +3,11 @@ import { RequestWithUser } from "../middlewares/user";
|
||||||
import CallAPI from "./call-api";
|
import CallAPI from "./call-api";
|
||||||
import HttpError from "./http-error";
|
import HttpError from "./http-error";
|
||||||
import HttpStatus from "./http-status";
|
import HttpStatus from "./http-status";
|
||||||
|
import { promisify } from "util";
|
||||||
|
|
||||||
class CheckAuth {
|
class CheckAuth {
|
||||||
|
private redis = require("redis");
|
||||||
|
|
||||||
public async Permission(req: RequestWithUser, system: string, action: string) {
|
public async Permission(req: RequestWithUser, system: string, action: string) {
|
||||||
if (
|
if (
|
||||||
req.headers.hasOwnProperty("api_key") &&
|
req.headers.hasOwnProperty("api_key") &&
|
||||||
|
|
@ -180,6 +183,41 @@ class CheckAuth {
|
||||||
return false;
|
return false;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
public async checkOrg(token: any, keycloakId: string) {
|
||||||
|
const redisClient = await this.redis.createClient({
|
||||||
|
host: process.env.REDIS_HOST,
|
||||||
|
port: process.env.REDIS_PORT,
|
||||||
|
});
|
||||||
|
const getAsync = promisify(redisClient.get).bind(redisClient);
|
||||||
|
try {
|
||||||
|
let reply = await getAsync("org_" + keycloakId);
|
||||||
|
if (reply != null) {
|
||||||
|
reply = JSON.parse(reply);
|
||||||
|
} else {
|
||||||
|
if (!keycloakId) throw new Error("No KeycloakId provided");
|
||||||
|
const x = await new CallAPI().GetData(
|
||||||
|
{
|
||||||
|
headers: { authorization: token },
|
||||||
|
},
|
||||||
|
`/org/permission/checkOrg/${keycloakId}`,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
orgRootId: x.orgRootId,
|
||||||
|
orgChild1Id: x.orgChild1Id,
|
||||||
|
orgChild2Id: x.orgChild2Id,
|
||||||
|
orgChild3Id: x.orgChild3Id,
|
||||||
|
orgChild4Id: x.orgChild4Id,
|
||||||
|
};
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error calling API:", error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
public async PermissionCreate(req: RequestWithUser, system: string) {
|
public async PermissionCreate(req: RequestWithUser, system: string) {
|
||||||
return await this.Permission(req, system, "CREATE");
|
return await this.Permission(req, system, "CREATE");
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,6 @@
|
||||||
import { NextFunction, Request, Response } from "express";
|
import { NextFunction, Request, Response } from "express";
|
||||||
import { Client } from "@elastic/elasticsearch";
|
import { Client } from "@elastic/elasticsearch";
|
||||||
import { AppDataSource } from "../database/data-source";
|
import permission from "../interfaces/permission";
|
||||||
import { PosMaster } from "../entities/PosMaster";
|
|
||||||
import { OrgRevision } from "../entities/OrgRevision";
|
|
||||||
import { Profile } from "../entities/Profile";
|
|
||||||
|
|
||||||
if (!process.env.ELASTICSEARCH_INDEX) {
|
if (!process.env.ELASTICSEARCH_INDEX) {
|
||||||
throw new Error("Require ELASTICSEARCH_INDEX to store log.");
|
throw new Error("Require ELASTICSEARCH_INDEX to store log.");
|
||||||
|
|
@ -22,89 +19,69 @@ const LOG_LEVEL_MAP: Record<string, number> = {
|
||||||
const elasticsearch = new Client({
|
const elasticsearch = new Client({
|
||||||
node: `${process.env.ELASTICSEARCH_PROTOCOL}://${process.env.ELASTICSEARCH_HOST}:${process.env.ELASTICSEARCH_PORT}`,
|
node: `${process.env.ELASTICSEARCH_PROTOCOL}://${process.env.ELASTICSEARCH_HOST}:${process.env.ELASTICSEARCH_PORT}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
async function logMiddleware(req: Request, res: Response, next: NextFunction) {
|
async function logMiddleware(req: Request, res: Response, next: NextFunction) {
|
||||||
if (!req.url.startsWith("/api/")) return next();
|
if (!req.url.startsWith("/api/")) return next();
|
||||||
|
|
||||||
let data: any;
|
let data: any;
|
||||||
const repoPosmaster = AppDataSource.getRepository(PosMaster);
|
|
||||||
const repoProfile = AppDataSource.getRepository(Profile);
|
|
||||||
const repoRevision = AppDataSource.getRepository(OrgRevision);
|
|
||||||
|
|
||||||
const originalJson = res.json;
|
const originalJson = res.json;
|
||||||
|
|
||||||
res.json = function (v: any) {
|
res.json = function (v: any) {
|
||||||
data = v;
|
data = v;
|
||||||
return originalJson.call(this, v);
|
return originalJson.call(this, v);
|
||||||
};
|
};
|
||||||
|
|
||||||
const timestamp = new Date().toISOString();
|
const timestamp = new Date().toISOString();
|
||||||
const start = performance.now();
|
const start = performance.now();
|
||||||
|
|
||||||
req.app.locals.logData = {};
|
req.app.locals.logData = {};
|
||||||
|
|
||||||
const revision = await repoRevision.findOne({
|
res.on("finish", async () => {
|
||||||
where: {
|
try {
|
||||||
orgRevisionIsCurrent: true ,
|
if (!req.url.startsWith("/api/")) return;
|
||||||
orgRevisionIsDraft: false
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
res.on("finish", async() => {
|
|
||||||
if (!req.url.startsWith("/api/")) return;
|
|
||||||
let system = "organization";
|
|
||||||
if (req.url.startsWith("/api/v1/org/keycloak/log/sso")) system = "inout";
|
|
||||||
if (req.url.startsWith("/api/v1/org/metadata/")) system = "master";
|
|
||||||
if (req.url.startsWith("/api/v1/org/pos/position/")) system = "master";
|
|
||||||
if (req.url.startsWith("/api/v1/org/pos/type/")) system = "master";
|
|
||||||
if (req.url.startsWith("/api/v1/org/employee/pos/position/")) system = "master";
|
|
||||||
if (req.url.startsWith("/api/v1/org/employee/pos/type/")) system = "master";
|
|
||||||
if (req.url.startsWith("/api/v1/org/auth/authRoleAttr/")) system = "admin";
|
|
||||||
if (req.url.startsWith("/api/v1/org/auth/authRole/")) system = "admin";
|
|
||||||
// if (req.url.startsWith("/api/v1/org/keycloak")) system = "admin";
|
|
||||||
if (req.url.startsWith("/api/v1/org/pos/admin/master/list")) system = "admin";
|
|
||||||
if (req.url.startsWith("/api/v1/org/super-admin/{id}")) system = "admin";
|
|
||||||
if (req.url.startsWith("/api/v1/org/permission-org/")) system = "admin";
|
|
||||||
if (req.url.startsWith("/api/v1/org/pos/assign/")) system = "admin";
|
|
||||||
if (req.url.startsWith("/api/v1/org/profile/")) system = "registry";
|
|
||||||
if (req.url.startsWith("/api/v1/org/profile-employee/")) system = "registry";
|
|
||||||
if (req.url.startsWith("/api/v1/org/profile-temp/")) system = "registry";
|
|
||||||
|
|
||||||
const level = LOG_LEVEL_MAP[process.env.LOG_LEVEL ?? "debug"] || 4;
|
const level = LOG_LEVEL_MAP[process.env.LOG_LEVEL ?? "debug"] || 4;
|
||||||
const profileByKeycloak = await repoProfile.findOne({
|
|
||||||
where: { keycloak: req.app.locals.logData.userId },
|
if (level === 1 && res.statusCode < 500) return;
|
||||||
})
|
if (level === 2 && res.statusCode < 400) return;
|
||||||
const rootId = await repoPosmaster.findOne({
|
if (level === 3 && res.statusCode < 200) return;
|
||||||
where: {
|
|
||||||
current_holderId: profileByKeycloak?.id,
|
const token = req.headers["authorization"];
|
||||||
orgRevisionId: revision?.id
|
let rootId = null;
|
||||||
},
|
|
||||||
select: ["orgRootId"],
|
try {
|
||||||
});
|
rootId = token
|
||||||
|
? await new permission().checkOrg(token, req.app.locals.logData.userId)
|
||||||
if (level === 1 && res.statusCode < 500) return;
|
: null;
|
||||||
if (level === 2 && res.statusCode < 400) return;
|
} catch (err) {
|
||||||
if (level === 3 && res.statusCode < 200) return;
|
console.warn("Error fetching rootId:", err);
|
||||||
const obj = {
|
}
|
||||||
logType: res.statusCode >= 500 ? "error" : res.statusCode >= 400 ? "warning" : "info",
|
|
||||||
ip: req.ip,
|
const obj = {
|
||||||
rootId: rootId?rootId.orgRootId:null,
|
logType: res.statusCode >= 500 ? "error" : res.statusCode >= 400 ? "warning" : "info",
|
||||||
systemName: system,
|
ip: req.ip,
|
||||||
startTimeStamp: timestamp,
|
rootId: rootId?.orgRootId ?? null,
|
||||||
endTimeStamp: new Date().toISOString(),
|
systemName: "evaluation",
|
||||||
processTime: performance.now() - start,
|
startTimeStamp: timestamp,
|
||||||
host: req.hostname,
|
endTimeStamp: new Date().toISOString(),
|
||||||
method: req.method,
|
processTime: performance.now() - start,
|
||||||
endpoint: req.url,
|
host: req.hostname,
|
||||||
responseCode: String(res.statusCode === 304 ? 200 : res.statusCode),
|
method: req.method,
|
||||||
responseDescription: data?.message,
|
endpoint: req.url,
|
||||||
input: (level === 4 && JSON.stringify(req.body, null, 2)) || undefined,
|
responseCode: String(res.statusCode === 304 ? 200 : res.statusCode),
|
||||||
output: (level === 4 && JSON.stringify(data, null, 2)) || undefined,
|
responseDescription: data?.message,
|
||||||
...req.app.locals.logData,
|
input: level === 4 ? JSON.stringify(req.body, null, 2) : undefined,
|
||||||
};
|
output: level === 4 ? JSON.stringify(data, null, 2) : undefined,
|
||||||
elasticsearch.index({
|
...req.app.locals.logData,
|
||||||
index: ELASTICSEARCH_INDEX,
|
};
|
||||||
document: obj,
|
|
||||||
});
|
// Send log to Elasticsearch
|
||||||
|
await elasticsearch.index({
|
||||||
|
index: ELASTICSEARCH_INDEX,
|
||||||
|
document: obj,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error in logMiddleware:", err);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return next();
|
return next();
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue