Merge branch 'develop' of github.com:Frappet/bma-ehr-probation into develop

* 'develop' of github.com:Frappet/bma-ehr-probation:
  add body
  edit permission

# Conflicts:
#	src/interfaces/call-api.ts
#	src/interfaces/permission.ts
This commit is contained in:
Warunee Tamkoo 2024-12-18 18:25:57 +07:00
commit 8c483a95a1
4 changed files with 405 additions and 416 deletions

View file

@ -1227,6 +1227,7 @@ export class ReportController extends Controller {
commandYear: number commandYear: number
templateDoc: string | null templateDoc: string | null
amount: Double | null amount: Double | null
amountSpecial?: Double | null
positionSalaryAmount: Double | null positionSalaryAmount: Double | null
mouthSalaryAmount: Double | null mouthSalaryAmount: Double | null
}[] }[]

View file

@ -1,106 +1,86 @@
import { import { Path } from "tsoa"
Controller, import axios from "axios"
Request, import { addLogSequence } from "./utils"
Get,
Post, class CallAPI {
Put, //Get
Delete, public async GetData(request: any, @Path() path: any, log = true) {
Patch, const token = "Bearer " + request.headers.authorization.replace("Bearer ", "")
Route, const url = process.env.API_URL + path
Security, try {
Tags, const response = await axios.get(url, {
Path, headers: {
} from "tsoa"; Authorization: `${token}`,
import axios from "axios"; "Content-Type": "application/json",
import { addLogSequence } from "./utils"; api_key: process.env.API_KEY,
import HttpError from "./http-error"; },
import HttpStatus from "./http-status"; })
if (log)
class CallAPI { addLogSequence(request, {
//Get action: "request",
public async GetData(request: any, @Path() path: any) { status: "success",
const token = request.headers.authorization; description: "connected",
const url = process.env.API_URL + path; request: {
try { method: "GET",
const response = await axios.get(url, { url: url,
headers: { response: JSON.stringify(response.data.result),
Authorization: `${token}`, },
"Content-Type": "application/json", })
api_key: process.env.API_KEY, return response.data.result
}, } catch (error) {
}); if (log)
addLogSequence(request, { addLogSequence(request, {
action: "request", action: "request",
status: "success", status: "error",
description: "connected", description: "unconnected",
request: { request: {
method: "GET", method: "GET",
url: url, url: url,
response: JSON.stringify(response.data.result), response: JSON.stringify(error),
}, },
}); })
return response.data.result; throw error
} catch (error) { }
addLogSequence(request, { }
action: "request", //Post
status: "error", public async PostData(request: any, @Path() path: any, sendData: any) {
description: "unconnected", const token = "Bearer " + request.headers.authorization.replace("Bearer ", "")
request: { const url = process.env.API_URL + path
method: "GET", try {
url: url, const response = await axios.post(url, sendData, {
response: JSON.stringify(error), headers: {
}, Authorization: `${token}`,
}); "Content-Type": "application/json",
if (error instanceof Error) { api_key: process.env.API_KEY,
throw new HttpError(HttpStatus.FORBIDDEN, error.message); },
} else { })
throw new HttpError(HttpStatus.FORBIDDEN, "Something went wrong!"); addLogSequence(request, {
} action: "request",
} status: "success",
} description: "connected",
//Post request: {
public async PostData(request: any, @Path() path: any, sendData: any) { method: "POST",
const token = request.headers.authorization; url: url,
const url = process.env.API_URL + path; payload: JSON.stringify(sendData),
try { response: JSON.stringify(response.data.result),
const response = await axios.post(url, sendData, { },
headers: { })
Authorization: `${token}`, return response.data.result
"Content-Type": "application/json", } catch (error) {
api_key: process.env.API_KEY, addLogSequence(request, {
}, action: "request",
}); status: "error",
addLogSequence(request, { description: "unconnected",
action: "request", request: {
status: "success", method: "POST",
description: "connected", url: url,
request: { payload: JSON.stringify(sendData),
method: "POST", response: JSON.stringify(error),
url: url, },
payload: JSON.stringify(sendData), })
response: JSON.stringify(response.data.result), throw error
}, }
}); }
return response.data.result; }
} catch (error) {
addLogSequence(request, { export default CallAPI
action: "request",
status: "error",
description: "unconnected",
request: {
method: "POST",
url: url,
payload: JSON.stringify(sendData),
response: JSON.stringify(error),
},
});
if (error instanceof Error) {
throw new HttpError(HttpStatus.FORBIDDEN, error.message);
} else {
throw new HttpError(HttpStatus.FORBIDDEN, "Something went wrong!");
}
}
}
}
export default CallAPI;

View file

@ -1,239 +1,245 @@
import axios from "axios"; import axios from "axios"
import { RequestWithUser } from "../middlewares/user"; 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 {
public async Permission(req: RequestWithUser, system: string, action: string) { class CheckAuth {
if ( private redis = require("redis")
req.headers.hasOwnProperty("api_key") &&
req.headers["api_key"] && public async Permission(req: RequestWithUser, system: string, action: string) {
req.headers["api_key"] == process.env.API_KEY if (req.headers.hasOwnProperty("api_key") && req.headers["api_key"] && req.headers["api_key"] == process.env.API_KEY) {
) { return null
return null; }
} return await new CallAPI()
return await new CallAPI() .GetData(req, "/org/permission")
.GetData(req, "/org/permission") .then(x => {
.then((x) => { let permission = false
let permission = false; let role = x.roles.find((x: any) => x.authSysId == system)
let role = x.roles.find((x: any) => x.authSysId == system); if (!role) throw "ไม่มีสิทธิ์เข้าระบบ"
if (!role) throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์เข้าระบบ"); if (role.attrOwnership == "OWNER") return "OWNER"
if (role.attrOwnership == "OWNER") return "OWNER"; if (action.trim().toLocaleUpperCase() == "CREATE") permission = role.attrIsCreate
if (action.trim().toLocaleUpperCase() == "CREATE") permission = role.attrIsCreate; if (action.trim().toLocaleUpperCase() == "DELETE") permission = role.attrIsDelete
if (action.trim().toLocaleUpperCase() == "DELETE") permission = role.attrIsDelete; if (action.trim().toLocaleUpperCase() == "GET") permission = role.attrIsGet
if (action.trim().toLocaleUpperCase() == "GET") permission = role.attrIsGet; if (action.trim().toLocaleUpperCase() == "LIST") permission = role.attrIsList
if (action.trim().toLocaleUpperCase() == "LIST") permission = role.attrIsList; if (action.trim().toLocaleUpperCase() == "UPDATE") permission = role.attrIsUpdate
if (action.trim().toLocaleUpperCase() == "UPDATE") permission = role.attrIsUpdate; if (permission == false) throw "ไม่มีสิทธิ์ใช้งานระบบนี้"
if (permission == false) return role.attrPrivilege
throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์ใช้งานระบบนี้"); })
return role.attrPrivilege; .catch(x => {
}) if (x.status != undefined) {
.catch((x) => { throw new HttpError(x.status, x.message)
if (x.status != undefined) { } else {
throw new HttpError(x.status, x.message); throw new HttpError(HttpStatus.FORBIDDEN, x)
} else { }
throw new HttpError(HttpStatus.FORBIDDEN, x); })
} }
}); public async PermissionOrg(req: RequestWithUser, system: string, action: string) {
} if (req.headers.hasOwnProperty("api_key") && req.headers["api_key"] && req.headers["api_key"] == process.env.API_KEY) {
public async PermissionOrg(req: RequestWithUser, system: string, action: string) { return {
if ( root: null,
req.headers.hasOwnProperty("api_key") && child1: null,
req.headers["api_key"] && child2: null,
req.headers["api_key"] == process.env.API_KEY child3: null,
) { child4: null,
return { }
root: null, }
child1: null, return await new CallAPI()
child2: null, .GetData(req, `/org/permission/org/${system}/${action}`)
child3: null, .then(async x => {
child4: null, let privilege = x.privilege
};
} let data: any = {
return await new CallAPI() root: [null],
.GetData(req, `/org/permission/org/${system}/${action}`) child1: [null],
.then(async (x) => { child2: [null],
let privilege = x.privilege; child3: [null],
child4: [null],
let data: any = { privilege: [null],
root: [null], }
child1: [null], let node = 4
child2: [null], if (x.orgChild1Id == null) {
child3: [null], node = 0
child4: [null], } else if (x.orgChild2Id == null) {
privilege: [null], node = 1
}; } else if (x.orgChild3Id == null) {
let node = 4; node = 2
if (x.orgChild1Id == null) { } else if (x.orgChild4Id == null) {
node = 0; node = 3
} else if (x.orgChild2Id == null) { }
node = 1; if (privilege == "OWNER") {
} else if (x.orgChild3Id == null) { data = {
node = 2; root: null,
} else if (x.orgChild4Id == null) { child1: null,
node = 3; child2: null,
} child3: null,
if (privilege == "OWNER") { child4: null,
data = { privilege: "OWNER",
root: null, }
child1: null, } else if (privilege == "ROOT") {
child2: null, data = {
child3: null, root: [x.orgRootId],
child4: null, child1: null,
privilege: "OWNER", child2: null,
}; child3: null,
} else if (privilege == "ROOT") { child4: null,
data = { privilege: "ROOT",
root: [x.orgRootId], }
child1: null, } else if (privilege == "CHILD") {
child2: null, data = {
child3: null, root: node >= 0 ? [x.orgRootId] : null,
child4: null, child1: node >= 1 ? [x.orgChild1Id] : null,
privilege: "ROOT", child2: node >= 2 ? [x.orgChild2Id] : null,
}; child3: node >= 3 ? [x.orgChild3Id] : null,
} else if (privilege == "CHILD") { child4: node >= 4 ? [x.orgChild4Id] : null,
data = { privilege: "CHILD",
root: node >= 0 ? [x.orgRootId] : null, }
child1: node >= 1 ? [x.orgChild1Id] : null, } else if (privilege == "NORMAL") {
child2: node >= 2 ? [x.orgChild2Id] : null, data = {
child3: node >= 3 ? [x.orgChild3Id] : null, root: [x.orgRootId],
child4: node >= 4 ? [x.orgChild4Id] : null, child1: [x.orgChild1Id],
privilege: "CHILD", child2: [x.orgChild2Id],
}; child3: [x.orgChild3Id],
} else if (privilege == "NORMAL") { child4: [x.orgChild4Id],
data = { privilege: "NORMAL",
root: [x.orgRootId], }
child1: [x.orgChild1Id], } else if (privilege == "SPECIFIC") {
child2: [x.orgChild2Id], }
child3: [x.orgChild3Id],
child4: [x.orgChild4Id], return data
privilege: "NORMAL", })
}; .catch(x => {
} else if (privilege == "SPECIFIC") { if (x.status != undefined) {
} throw new HttpError(x.status, x.message)
} else {
return data; throw new HttpError(HttpStatus.FORBIDDEN, x)
}) }
.catch((x) => { })
if (x.status != undefined) { }
throw new HttpError(x.status, x.message); public async PermissionOrgByUser(req: RequestWithUser, system: string, action: string, profileId: string) {
} else { if (req.headers.hasOwnProperty("api_key") && req.headers["api_key"] && req.headers["api_key"] == process.env.API_KEY) {
throw new HttpError(HttpStatus.FORBIDDEN, x); return true
} }
}); return await new CallAPI()
} .GetData(req, `/org/permission/user/${system}/${action}/${profileId}`)
public async PermissionOrgByUser( .then(async x => {
req: RequestWithUser, let org = x.org
system: string,
action: string, if (org.root != null) if (x.orgRootId != org.root[0]) throw "ไม่มีสิทธิ์เข้าถึงข้อมูล"
profileId: string, if (org.child1 != null) if (x.orgChild1Id != org.child1[0]) throw "ไม่มีสิทธิ์เข้าถึงข้อมูล"
) { if (org.child2 != null) if (x.orgChild2Id != org.child2[0]) throw "ไม่มีสิทธิ์เข้าถึงข้อมูล"
if ( if (org.child3 != null) if (x.orgChild3Id != org.child3[0]) throw "ไม่มีสิทธิ์เข้าถึงข้อมูล"
req.headers.hasOwnProperty("api_key") && if (org.child4 != null) if (x.orgChild4Id != org.child4[0]) throw "ไม่มีสิทธิ์เข้าถึงข้อมูล"
req.headers["api_key"] &&
req.headers["api_key"] == process.env.API_KEY return true
) { })
return true; .catch(x => {
} if (x.status != undefined) {
return await new CallAPI() throw new HttpError(x.status, x.message)
.GetData(req, `/org/permission/user/${system}/${action}/${profileId}`) } else {
.then(async (x) => { throw new HttpError(HttpStatus.FORBIDDEN, x)
let org = x.org; }
})
if (org.root != null) }
if (x.orgRootId != org.root[0]) public async Workflow(req: RequestWithUser, id: string, sysName: string) {
throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์เข้าถึงข้อมูล"); if (req.headers.hasOwnProperty("api_key") && req.headers["api_key"] && req.headers["api_key"] == process.env.API_KEY) {
if (org.child1 != null) return null
if (x.orgChild1Id != org.child1[0]) }
throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์เข้าถึงข้อมูล"); return await new CallAPI()
if (org.child2 != null) .PostData(req, "/org/workflow/keycloak/isofficer", {
if (x.orgChild2Id != org.child2[0]) refId: id,
throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์เข้าถึงข้อมูล"); sysName: sysName,
if (org.child3 != null) })
if (x.orgChild3Id != org.child3[0]) .then(x => {
throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์เข้าถึงข้อมูล"); return true
if (org.child4 != null) })
if (x.orgChild4Id != org.child4[0]) .catch(x => {
throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์เข้าถึงข้อมูล"); return false
})
return true; }
}) public async checkOrg(token: any, keycloakId: string) {
.catch((x) => { const redisClient = await this.redis.createClient({
if (x.status != undefined) { host: process.env.REDIS_HOST,
throw new HttpError(x.status, x.message); port: process.env.REDIS_PORT,
} else { })
throw new HttpError(HttpStatus.FORBIDDEN, x); const getAsync = promisify(redisClient.get).bind(redisClient)
} let reply = await getAsync("org_" + keycloakId)
}); if (reply != null) {
} reply = JSON.parse(reply)
public async Workflow(req: RequestWithUser, id: string, sysName: string) { } else {
if ( try {
req.headers.hasOwnProperty("api_key") && if (!keycloakId) throw "Error calling API No KeycloakId"
req.headers["api_key"] && const x = await new CallAPI().GetData(
req.headers["api_key"] == process.env.API_KEY {
) { headers: { authorization: token },
return null; },
} `/org/permission/checkOrg/${keycloakId}`,
return await new CallAPI() false
.PostData(req, "/org/workflow/keycloak/isofficer", { )
refId: id,
sysName: sysName, const data = {
}) orgRootId: x.orgRootId,
.then((x) => { orgChild1Id: x.orgChild1Id,
return true; orgChild2Id: x.orgChild2Id,
}) orgChild3Id: x.orgChild3Id,
.catch((x) => { orgChild4Id: x.orgChild4Id,
return false; }
});
} return data
public async PermissionCreate(req: RequestWithUser, system: string) { } catch (error) {
return await this.Permission(req, system, "CREATE"); console.error("Error calling API:", error)
} throw error
public async PermissionDelete(req: RequestWithUser, system: string) { }
return await this.Permission(req, system, "DELETE"); }
} }
public async PermissionGet(req: RequestWithUser, system: string) { public async PermissionCreate(req: RequestWithUser, system: string) {
return await this.Permission(req, system, "GET"); return await this.Permission(req, system, "CREATE")
} }
public async PermissionList(req: RequestWithUser, system: string) { public async PermissionDelete(req: RequestWithUser, system: string) {
return await this.Permission(req, system, "LIST"); return await this.Permission(req, system, "DELETE")
} }
public async PermissionUpdate(req: RequestWithUser, system: string) { public async PermissionGet(req: RequestWithUser, system: string) {
return await this.Permission(req, system, "UPDATE"); return await this.Permission(req, system, "GET")
} }
public async PermissionList(req: RequestWithUser, system: string) {
public async PermissionOrgCreate(req: RequestWithUser, system: string) { return await this.Permission(req, system, "LIST")
return await this.PermissionOrg(req, system, "CREATE"); }
} public async PermissionUpdate(req: RequestWithUser, system: string) {
public async PermissionOrgDelete(req: RequestWithUser, system: string) { return await this.Permission(req, system, "UPDATE")
return await this.PermissionOrg(req, system, "DELETE"); }
}
public async PermissionOrgGet(req: RequestWithUser, system: string) { public async PermissionOrgCreate(req: RequestWithUser, system: string) {
return await this.PermissionOrg(req, system, "GET"); return await this.PermissionOrg(req, system, "CREATE")
} }
public async PermissionOrgList(req: RequestWithUser, system: string) { public async PermissionOrgDelete(req: RequestWithUser, system: string) {
return await this.PermissionOrg(req, system, "LIST"); return await this.PermissionOrg(req, system, "DELETE")
} }
public async PermissionOrgUpdate(req: RequestWithUser, system: string) { public async PermissionOrgGet(req: RequestWithUser, system: string) {
return await this.PermissionOrg(req, system, "UPDATE"); return await this.PermissionOrg(req, system, "GET")
} }
public async PermissionOrgList(req: RequestWithUser, system: string) {
public async PermissionOrgUserCreate(req: RequestWithUser, system: string, profileId: string) { return await this.PermissionOrg(req, system, "LIST")
return await this.PermissionOrgByUser(req, system, "CREATE", profileId); }
} public async PermissionOrgUpdate(req: RequestWithUser, system: string) {
public async PermissionOrgUserDelete(req: RequestWithUser, system: string, profileId: string) { return await this.PermissionOrg(req, system, "UPDATE")
return await this.PermissionOrgByUser(req, system, "DELETE", profileId); }
}
public async PermissionOrgUserGet(req: RequestWithUser, system: string, profileId: string) { public async PermissionOrgUserCreate(req: RequestWithUser, system: string, profileId: string) {
return await this.PermissionOrgByUser(req, system, "GET", profileId); return await this.PermissionOrgByUser(req, system, "CREATE", profileId)
} }
public async PermissionOrgUserList(req: RequestWithUser, system: string, profileId: string) { public async PermissionOrgUserDelete(req: RequestWithUser, system: string, profileId: string) {
return await this.PermissionOrgByUser(req, system, "LIST", profileId); return await this.PermissionOrgByUser(req, system, "DELETE", profileId)
} }
public async PermissionOrgUserUpdate(req: RequestWithUser, system: string, profileId: string) { public async PermissionOrgUserGet(req: RequestWithUser, system: string, profileId: string) {
return await this.PermissionOrgByUser(req, system, "UPDATE", profileId); return await this.PermissionOrgByUser(req, system, "GET", profileId)
} }
} public async PermissionOrgUserList(req: RequestWithUser, system: string, profileId: string) {
return await this.PermissionOrgByUser(req, system, "LIST", profileId)
export default CheckAuth; }
public async PermissionOrgUserUpdate(req: RequestWithUser, system: string, profileId: string) {
return await this.PermissionOrgByUser(req, system, "UPDATE", profileId)
}
}
export default CheckAuth

View file

@ -1,79 +1,81 @@
import { NextFunction, Request, Response } from "express"; import { NextFunction, Request, Response } from "express"
import { Client } from "@elastic/elasticsearch"; import { Client } from "@elastic/elasticsearch"
import permission from "../interfaces/permission"
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.")
} }
const ELASTICSEARCH_INDEX = process.env.ELASTICSEARCH_INDEX; const ELASTICSEARCH_INDEX = process.env.ELASTICSEARCH_INDEX
const LOG_LEVEL_MAP: Record<string, number> = { const LOG_LEVEL_MAP: Record<string, number> = {
debug: 4, debug: 4,
info: 3, info: 3,
warning: 2, warning: 2,
error: 1, error: 1,
none: 0, 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: "probation",
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; 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", async () => {
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
let token: any
token = req.headers["authorization"]
const rootId = await new permission().checkOrg(token, req.app.locals.logData.userId)
const obj = {
logType: res.statusCode >= 500 ? "error" : res.statusCode >= 400 ? "warning" : "info",
ip: req.ip,
rootId: rootId ? rootId.orgRootId : null,
systemName: "probation",
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