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,
Put,
Delete,
Patch,
Route,
Security,
Tags,
Path,
} from "tsoa";
import axios from "axios";
import { addLogSequence } from "./utils";
import HttpError from "./http-error";
import HttpStatus from "./http-status";
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 = request.headers.authorization; const token = "Bearer " + request.headers.authorization.replace("Bearer ", "")
const url = process.env.API_URL + path; const url = process.env.API_URL + path
try { try {
const response = await axios.get(url, { const response = await axios.get(url, {
headers: { headers: {
Authorization: `${token}`, Authorization: `${token}`,
"Content-Type": "application/json", "Content-Type": "application/json",
api_key: process.env.API_KEY, api_key: process.env.API_KEY,
}, },
}); })
addLogSequence(request, { if (log)
action: "request", addLogSequence(request, {
status: "success", action: "request",
description: "connected", status: "success",
request: { description: "connected",
method: "GET", request: {
url: url, method: "GET",
response: JSON.stringify(response.data.result), url: url,
}, response: JSON.stringify(response.data.result),
}); },
return response.data.result; })
} catch (error) { return response.data.result
addLogSequence(request, { } catch (error) {
action: "request", if (log)
status: "error", addLogSequence(request, {
description: "unconnected", action: "request",
request: { status: "error",
method: "GET", description: "unconnected",
url: url, request: {
response: JSON.stringify(error), method: "GET",
}, url: url,
}); response: JSON.stringify(error),
if (error instanceof Error) { },
throw new HttpError(HttpStatus.FORBIDDEN, error.message); })
} else { throw error
throw new HttpError(HttpStatus.FORBIDDEN, "Something went wrong!"); }
} }
} //Post
} public async PostData(request: any, @Path() path: any, sendData: any) {
//Post const token = "Bearer " + request.headers.authorization.replace("Bearer ", "")
public async PostData(request: any, @Path() path: any, sendData: any) { const url = process.env.API_URL + path
const token = request.headers.authorization; try {
const url = process.env.API_URL + path; const response = await axios.post(url, sendData, {
try { headers: {
const response = await axios.post(url, sendData, { Authorization: `${token}`,
headers: { "Content-Type": "application/json",
Authorization: `${token}`, api_key: process.env.API_KEY,
"Content-Type": "application/json", },
api_key: process.env.API_KEY, })
}, addLogSequence(request, {
}); action: "request",
addLogSequence(request, { status: "success",
action: "request", description: "connected",
status: "success", request: {
description: "connected", method: "POST",
request: { url: url,
method: "POST", payload: JSON.stringify(sendData),
url: url, response: JSON.stringify(response.data.result),
payload: JSON.stringify(sendData), },
response: JSON.stringify(response.data.result), })
}, return response.data.result
}); } catch (error) {
return response.data.result; addLogSequence(request, {
} catch (error) { action: "request",
addLogSequence(request, { status: "error",
action: "request", description: "unconnected",
status: "error", request: {
description: "unconnected", method: "POST",
request: { url: url,
method: "POST", payload: JSON.stringify(sendData),
url: url, response: JSON.stringify(error),
payload: JSON.stringify(sendData), },
response: JSON.stringify(error), })
}, throw error
}); }
if (error instanceof Error) { }
throw new HttpError(HttpStatus.FORBIDDEN, error.message);
} else {
throw new HttpError(HttpStatus.FORBIDDEN, "Something went wrong!");
}
}
}
} }
export default CallAPI; 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 { class CheckAuth {
public async Permission(req: RequestWithUser, system: string, action: string) { private redis = require("redis")
if (
req.headers.hasOwnProperty("api_key") &&
req.headers["api_key"] &&
req.headers["api_key"] == process.env.API_KEY
) {
return null;
}
return await new CallAPI()
.GetData(req, "/org/permission")
.then((x) => {
let permission = false;
let role = x.roles.find((x: any) => x.authSysId == system);
if (!role) throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์เข้าระบบ");
if (role.attrOwnership == "OWNER") return "OWNER";
if (action.trim().toLocaleUpperCase() == "CREATE") permission = role.attrIsCreate;
if (action.trim().toLocaleUpperCase() == "DELETE") permission = role.attrIsDelete;
if (action.trim().toLocaleUpperCase() == "GET") permission = role.attrIsGet;
if (action.trim().toLocaleUpperCase() == "LIST") permission = role.attrIsList;
if (action.trim().toLocaleUpperCase() == "UPDATE") permission = role.attrIsUpdate;
if (permission == false)
throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์ใช้งานระบบนี้");
return role.attrPrivilege;
})
.catch((x) => {
if (x.status != undefined) {
throw new HttpError(x.status, x.message);
} 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
) {
return {
root: null,
child1: null,
child2: null,
child3: null,
child4: null,
};
}
return await new CallAPI()
.GetData(req, `/org/permission/org/${system}/${action}`)
.then(async (x) => {
let privilege = x.privilege;
let data: any = { public async Permission(req: RequestWithUser, system: string, action: string) {
root: [null], if (req.headers.hasOwnProperty("api_key") && req.headers["api_key"] && req.headers["api_key"] == process.env.API_KEY) {
child1: [null], return null
child2: [null], }
child3: [null], return await new CallAPI()
child4: [null], .GetData(req, "/org/permission")
privilege: [null], .then(x => {
}; let permission = false
let node = 4; let role = x.roles.find((x: any) => x.authSysId == system)
if (x.orgChild1Id == null) { if (!role) throw "ไม่มีสิทธิ์เข้าระบบ"
node = 0; if (role.attrOwnership == "OWNER") return "OWNER"
} else if (x.orgChild2Id == null) { if (action.trim().toLocaleUpperCase() == "CREATE") permission = role.attrIsCreate
node = 1; if (action.trim().toLocaleUpperCase() == "DELETE") permission = role.attrIsDelete
} else if (x.orgChild3Id == null) { if (action.trim().toLocaleUpperCase() == "GET") permission = role.attrIsGet
node = 2; if (action.trim().toLocaleUpperCase() == "LIST") permission = role.attrIsList
} else if (x.orgChild4Id == null) { if (action.trim().toLocaleUpperCase() == "UPDATE") permission = role.attrIsUpdate
node = 3; if (permission == false) throw "ไม่มีสิทธิ์ใช้งานระบบนี้"
} return role.attrPrivilege
if (privilege == "OWNER") { })
data = { .catch(x => {
root: null, if (x.status != undefined) {
child1: null, throw new HttpError(x.status, x.message)
child2: null, } else {
child3: null, throw new HttpError(HttpStatus.FORBIDDEN, x)
child4: null, }
privilege: "OWNER", })
}; }
} else if (privilege == "ROOT") { public async PermissionOrg(req: RequestWithUser, system: string, action: string) {
data = { if (req.headers.hasOwnProperty("api_key") && req.headers["api_key"] && req.headers["api_key"] == process.env.API_KEY) {
root: [x.orgRootId], return {
child1: null, root: null,
child2: null, child1: null,
child3: null, child2: null,
child4: null, child3: null,
privilege: "ROOT", child4: null,
}; }
} else if (privilege == "CHILD") { }
data = { return await new CallAPI()
root: node >= 0 ? [x.orgRootId] : null, .GetData(req, `/org/permission/org/${system}/${action}`)
child1: node >= 1 ? [x.orgChild1Id] : null, .then(async x => {
child2: node >= 2 ? [x.orgChild2Id] : null, let privilege = x.privilege
child3: node >= 3 ? [x.orgChild3Id] : null,
child4: node >= 4 ? [x.orgChild4Id] : null,
privilege: "CHILD",
};
} else if (privilege == "NORMAL") {
data = {
root: [x.orgRootId],
child1: [x.orgChild1Id],
child2: [x.orgChild2Id],
child3: [x.orgChild3Id],
child4: [x.orgChild4Id],
privilege: "NORMAL",
};
} else if (privilege == "SPECIFIC") {
}
return data; let data: any = {
}) root: [null],
.catch((x) => { child1: [null],
if (x.status != undefined) { child2: [null],
throw new HttpError(x.status, x.message); child3: [null],
} else { child4: [null],
throw new HttpError(HttpStatus.FORBIDDEN, x); privilege: [null],
} }
}); let node = 4
} if (x.orgChild1Id == null) {
public async PermissionOrgByUser( node = 0
req: RequestWithUser, } else if (x.orgChild2Id == null) {
system: string, node = 1
action: string, } else if (x.orgChild3Id == null) {
profileId: string, node = 2
) { } else if (x.orgChild4Id == null) {
if ( node = 3
req.headers.hasOwnProperty("api_key") && }
req.headers["api_key"] && if (privilege == "OWNER") {
req.headers["api_key"] == process.env.API_KEY data = {
) { root: null,
return true; child1: null,
} child2: null,
return await new CallAPI() child3: null,
.GetData(req, `/org/permission/user/${system}/${action}/${profileId}`) child4: null,
.then(async (x) => { privilege: "OWNER",
let org = x.org; }
} else if (privilege == "ROOT") {
data = {
root: [x.orgRootId],
child1: null,
child2: null,
child3: null,
child4: null,
privilege: "ROOT",
}
} else if (privilege == "CHILD") {
data = {
root: node >= 0 ? [x.orgRootId] : null,
child1: node >= 1 ? [x.orgChild1Id] : null,
child2: node >= 2 ? [x.orgChild2Id] : null,
child3: node >= 3 ? [x.orgChild3Id] : null,
child4: node >= 4 ? [x.orgChild4Id] : null,
privilege: "CHILD",
}
} else if (privilege == "NORMAL") {
data = {
root: [x.orgRootId],
child1: [x.orgChild1Id],
child2: [x.orgChild2Id],
child3: [x.orgChild3Id],
child4: [x.orgChild4Id],
privilege: "NORMAL",
}
} else if (privilege == "SPECIFIC") {
}
if (org.root != null) return data
if (x.orgRootId != org.root[0]) })
throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์เข้าถึงข้อมูล"); .catch(x => {
if (org.child1 != null) if (x.status != undefined) {
if (x.orgChild1Id != org.child1[0]) throw new HttpError(x.status, x.message)
throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์เข้าถึงข้อมูล"); } else {
if (org.child2 != null) throw new HttpError(HttpStatus.FORBIDDEN, x)
if (x.orgChild2Id != org.child2[0]) }
throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์เข้าถึงข้อมูล"); })
if (org.child3 != null) }
if (x.orgChild3Id != org.child3[0]) public async PermissionOrgByUser(req: RequestWithUser, system: string, action: string, profileId: 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.child4 != null) return true
if (x.orgChild4Id != org.child4[0]) }
throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์เข้าถึงข้อมูล"); return await new CallAPI()
.GetData(req, `/org/permission/user/${system}/${action}/${profileId}`)
.then(async x => {
let org = x.org
return true; if (org.root != null) if (x.orgRootId != org.root[0]) throw "ไม่มีสิทธิ์เข้าถึงข้อมูล"
}) if (org.child1 != null) if (x.orgChild1Id != org.child1[0]) throw "ไม่มีสิทธิ์เข้าถึงข้อมูล"
.catch((x) => { if (org.child2 != null) if (x.orgChild2Id != org.child2[0]) throw "ไม่มีสิทธิ์เข้าถึงข้อมูล"
if (x.status != undefined) { if (org.child3 != null) if (x.orgChild3Id != org.child3[0]) throw "ไม่มีสิทธิ์เข้าถึงข้อมูล"
throw new HttpError(x.status, x.message); if (org.child4 != null) if (x.orgChild4Id != org.child4[0]) throw "ไม่มีสิทธิ์เข้าถึงข้อมูล"
} else {
throw new HttpError(HttpStatus.FORBIDDEN, x);
}
});
}
public async Workflow(req: RequestWithUser, id: string, sysName: string) {
if (
req.headers.hasOwnProperty("api_key") &&
req.headers["api_key"] &&
req.headers["api_key"] == process.env.API_KEY
) {
return null;
}
return await new CallAPI()
.PostData(req, "/org/workflow/keycloak/isofficer", {
refId: id,
sysName: sysName,
})
.then((x) => {
return true;
})
.catch((x) => {
return false;
});
}
public async PermissionCreate(req: RequestWithUser, system: string) {
return await this.Permission(req, system, "CREATE");
}
public async PermissionDelete(req: RequestWithUser, system: string) {
return await this.Permission(req, system, "DELETE");
}
public async PermissionGet(req: RequestWithUser, system: string) {
return await this.Permission(req, system, "GET");
}
public async PermissionList(req: RequestWithUser, system: string) {
return await this.Permission(req, system, "LIST");
}
public async PermissionUpdate(req: RequestWithUser, system: string) {
return await this.Permission(req, system, "UPDATE");
}
public async PermissionOrgCreate(req: RequestWithUser, system: string) { return true
return await this.PermissionOrg(req, system, "CREATE"); })
} .catch(x => {
public async PermissionOrgDelete(req: RequestWithUser, system: string) { if (x.status != undefined) {
return await this.PermissionOrg(req, system, "DELETE"); throw new HttpError(x.status, x.message)
} } else {
public async PermissionOrgGet(req: RequestWithUser, system: string) { throw new HttpError(HttpStatus.FORBIDDEN, x)
return await this.PermissionOrg(req, system, "GET"); }
} })
public async PermissionOrgList(req: RequestWithUser, system: string) { }
return await this.PermissionOrg(req, system, "LIST"); public async Workflow(req: RequestWithUser, id: string, sysName: string) {
} if (req.headers.hasOwnProperty("api_key") && req.headers["api_key"] && req.headers["api_key"] == process.env.API_KEY) {
public async PermissionOrgUpdate(req: RequestWithUser, system: string) { return null
return await this.PermissionOrg(req, system, "UPDATE"); }
} return await new CallAPI()
.PostData(req, "/org/workflow/keycloak/isofficer", {
refId: id,
sysName: sysName,
})
.then(x => {
return true
})
.catch(x => {
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)
let reply = await getAsync("org_" + keycloakId)
if (reply != null) {
reply = JSON.parse(reply)
} else {
try {
if (!keycloakId) throw "Error calling API No KeycloakId"
const x = await new CallAPI().GetData(
{
headers: { authorization: token },
},
`/org/permission/checkOrg/${keycloakId}`,
false
)
public async PermissionOrgUserCreate(req: RequestWithUser, system: string, profileId: string) { const data = {
return await this.PermissionOrgByUser(req, system, "CREATE", profileId); orgRootId: x.orgRootId,
} orgChild1Id: x.orgChild1Id,
public async PermissionOrgUserDelete(req: RequestWithUser, system: string, profileId: string) { orgChild2Id: x.orgChild2Id,
return await this.PermissionOrgByUser(req, system, "DELETE", profileId); orgChild3Id: x.orgChild3Id,
} orgChild4Id: x.orgChild4Id,
public async PermissionOrgUserGet(req: RequestWithUser, system: string, profileId: string) { }
return await this.PermissionOrgByUser(req, system, "GET", profileId);
} return data
public async PermissionOrgUserList(req: RequestWithUser, system: string, profileId: string) { } catch (error) {
return await this.PermissionOrgByUser(req, system, "LIST", profileId); console.error("Error calling API:", error)
} throw error
public async PermissionOrgUserUpdate(req: RequestWithUser, system: string, profileId: string) { }
return await this.PermissionOrgByUser(req, system, "UPDATE", profileId); }
} }
public async PermissionCreate(req: RequestWithUser, system: string) {
return await this.Permission(req, system, "CREATE")
}
public async PermissionDelete(req: RequestWithUser, system: string) {
return await this.Permission(req, system, "DELETE")
}
public async PermissionGet(req: RequestWithUser, system: string) {
return await this.Permission(req, system, "GET")
}
public async PermissionList(req: RequestWithUser, system: string) {
return await this.Permission(req, system, "LIST")
}
public async PermissionUpdate(req: RequestWithUser, system: string) {
return await this.Permission(req, system, "UPDATE")
}
public async PermissionOrgCreate(req: RequestWithUser, system: string) {
return await this.PermissionOrg(req, system, "CREATE")
}
public async PermissionOrgDelete(req: RequestWithUser, system: string) {
return await this.PermissionOrg(req, system, "DELETE")
}
public async PermissionOrgGet(req: RequestWithUser, system: string) {
return await this.PermissionOrg(req, system, "GET")
}
public async PermissionOrgList(req: RequestWithUser, system: string) {
return await this.PermissionOrg(req, system, "LIST")
}
public async PermissionOrgUpdate(req: RequestWithUser, system: string) {
return await this.PermissionOrg(req, system, "UPDATE")
}
public async PermissionOrgUserCreate(req: RequestWithUser, system: string, profileId: string) {
return await this.PermissionOrgByUser(req, system, "CREATE", profileId)
}
public async PermissionOrgUserDelete(req: RequestWithUser, system: string, profileId: string) {
return await this.PermissionOrgByUser(req, system, "DELETE", profileId)
}
public async PermissionOrgUserGet(req: RequestWithUser, system: string, profileId: string) {
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)
}
public async PermissionOrgUserUpdate(req: RequestWithUser, system: string, profileId: string) {
return await this.PermissionOrgByUser(req, system, "UPDATE", profileId)
}
} }
export default CheckAuth; 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