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,26 +1,12 @@
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: {
@ -28,7 +14,8 @@ class CallAPI {
"Content-Type": "application/json", "Content-Type": "application/json",
api_key: process.env.API_KEY, api_key: process.env.API_KEY,
}, },
}); })
if (log)
addLogSequence(request, { addLogSequence(request, {
action: "request", action: "request",
status: "success", status: "success",
@ -38,9 +25,10 @@ class CallAPI {
url: url, url: url,
response: JSON.stringify(response.data.result), response: JSON.stringify(response.data.result),
}, },
}); })
return response.data.result; return response.data.result
} catch (error) { } catch (error) {
if (log)
addLogSequence(request, { addLogSequence(request, {
action: "request", action: "request",
status: "error", status: "error",
@ -50,18 +38,14 @@ class CallAPI {
url: url, url: url,
response: JSON.stringify(error), response: JSON.stringify(error),
}, },
}); })
if (error instanceof Error) { throw error
throw new HttpError(HttpStatus.FORBIDDEN, error.message);
} else {
throw new HttpError(HttpStatus.FORBIDDEN, "Something went wrong!");
}
} }
} }
//Post //Post
public async PostData(request: any, @Path() path: any, sendData: any) { public async PostData(request: any, @Path() path: any, sendData: any) {
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.post(url, sendData, { const response = await axios.post(url, sendData, {
headers: { headers: {
@ -69,7 +53,7 @@ class CallAPI {
"Content-Type": "application/json", "Content-Type": "application/json",
api_key: process.env.API_KEY, api_key: process.env.API_KEY,
}, },
}); })
addLogSequence(request, { addLogSequence(request, {
action: "request", action: "request",
status: "success", status: "success",
@ -80,8 +64,8 @@ class CallAPI {
payload: JSON.stringify(sendData), payload: JSON.stringify(sendData),
response: JSON.stringify(response.data.result), response: JSON.stringify(response.data.result),
}, },
}); })
return response.data.result; return response.data.result
} catch (error) { } catch (error) {
addLogSequence(request, { addLogSequence(request, {
action: "request", action: "request",
@ -93,14 +77,10 @@ class CallAPI {
payload: JSON.stringify(sendData), payload: JSON.stringify(sendData),
response: JSON.stringify(error), response: JSON.stringify(error),
}, },
}); })
if (error instanceof Error) { throw 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,60 +1,54 @@
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 {
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["api_key"] && req.headers["api_key"] == process.env.API_KEY) {
req.headers.hasOwnProperty("api_key") && return null
req.headers["api_key"] &&
req.headers["api_key"] == process.env.API_KEY
) {
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 new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์เข้าระบบ"); if (!role) throw "ไม่มีสิทธิ์เข้าระบบ"
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) if (permission == false) throw "ไม่มีสิทธิ์ใช้งานระบบนี้"
throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์ใช้งานระบบนี้"); return role.attrPrivilege
return role.attrPrivilege;
}) })
.catch((x) => { .catch(x => {
if (x.status != undefined) { if (x.status != undefined) {
throw new HttpError(x.status, x.message); throw new HttpError(x.status, x.message)
} else { } else {
throw new HttpError(HttpStatus.FORBIDDEN, x); throw new HttpError(HttpStatus.FORBIDDEN, x)
} }
}); })
} }
public async PermissionOrg(req: RequestWithUser, system: string, action: string) { public async PermissionOrg(req: RequestWithUser, system: string, action: string) {
if ( if (req.headers.hasOwnProperty("api_key") && req.headers["api_key"] && req.headers["api_key"] == process.env.API_KEY) {
req.headers.hasOwnProperty("api_key") &&
req.headers["api_key"] &&
req.headers["api_key"] == process.env.API_KEY
) {
return { return {
root: null, root: null,
child1: null, child1: null,
child2: null, child2: null,
child3: null, child3: null,
child4: null, child4: null,
}; }
} }
return await new CallAPI() return await new CallAPI()
.GetData(req, `/org/permission/org/${system}/${action}`) .GetData(req, `/org/permission/org/${system}/${action}`)
.then(async (x) => { .then(async x => {
let privilege = x.privilege; let privilege = x.privilege
let data: any = { let data: any = {
root: [null], root: [null],
@ -63,16 +57,16 @@ class CheckAuth {
child3: [null], child3: [null],
child4: [null], child4: [null],
privilege: [null], privilege: [null],
}; }
let node = 4; let node = 4
if (x.orgChild1Id == null) { if (x.orgChild1Id == null) {
node = 0; node = 0
} else if (x.orgChild2Id == null) { } else if (x.orgChild2Id == null) {
node = 1; node = 1
} else if (x.orgChild3Id == null) { } else if (x.orgChild3Id == null) {
node = 2; node = 2
} else if (x.orgChild4Id == null) { } else if (x.orgChild4Id == null) {
node = 3; node = 3
} }
if (privilege == "OWNER") { if (privilege == "OWNER") {
data = { data = {
@ -82,7 +76,7 @@ class CheckAuth {
child3: null, child3: null,
child4: null, child4: null,
privilege: "OWNER", privilege: "OWNER",
}; }
} else if (privilege == "ROOT") { } else if (privilege == "ROOT") {
data = { data = {
root: [x.orgRootId], root: [x.orgRootId],
@ -91,7 +85,7 @@ class CheckAuth {
child3: null, child3: null,
child4: null, child4: null,
privilege: "ROOT", privilege: "ROOT",
}; }
} else if (privilege == "CHILD") { } else if (privilege == "CHILD") {
data = { data = {
root: node >= 0 ? [x.orgRootId] : null, root: node >= 0 ? [x.orgRootId] : null,
@ -100,7 +94,7 @@ class CheckAuth {
child3: node >= 3 ? [x.orgChild3Id] : null, child3: node >= 3 ? [x.orgChild3Id] : null,
child4: node >= 4 ? [x.orgChild4Id] : null, child4: node >= 4 ? [x.orgChild4Id] : null,
privilege: "CHILD", privilege: "CHILD",
}; }
} else if (privilege == "NORMAL") { } else if (privilege == "NORMAL") {
data = { data = {
root: [x.orgRootId], root: [x.orgRootId],
@ -109,131 +103,143 @@ class CheckAuth {
child3: [x.orgChild3Id], child3: [x.orgChild3Id],
child4: [x.orgChild4Id], child4: [x.orgChild4Id],
privilege: "NORMAL", privilege: "NORMAL",
}; }
} else if (privilege == "SPECIFIC") { } else if (privilege == "SPECIFIC") {
} }
return data; return data
}) })
.catch((x) => { .catch(x => {
if (x.status != undefined) { if (x.status != undefined) {
throw new HttpError(x.status, x.message); throw new HttpError(x.status, x.message)
} else { } else {
throw new HttpError(HttpStatus.FORBIDDEN, x); throw new HttpError(HttpStatus.FORBIDDEN, x)
} }
}); })
} }
public async PermissionOrgByUser( public async PermissionOrgByUser(req: RequestWithUser, system: string, action: string, profileId: string) {
req: RequestWithUser, if (req.headers.hasOwnProperty("api_key") && req.headers["api_key"] && req.headers["api_key"] == process.env.API_KEY) {
system: string, return true
action: string,
profileId: string,
) {
if (
req.headers.hasOwnProperty("api_key") &&
req.headers["api_key"] &&
req.headers["api_key"] == process.env.API_KEY
) {
return true;
} }
return await new CallAPI() return await new CallAPI()
.GetData(req, `/org/permission/user/${system}/${action}/${profileId}`) .GetData(req, `/org/permission/user/${system}/${action}/${profileId}`)
.then(async (x) => { .then(async x => {
let org = x.org; let org = x.org
if (org.root != null) if (org.root != null) if (x.orgRootId != org.root[0]) throw "ไม่มีสิทธิ์เข้าถึงข้อมูล"
if (x.orgRootId != org.root[0]) if (org.child1 != null) if (x.orgChild1Id != org.child1[0]) throw "ไม่มีสิทธิ์เข้าถึงข้อมูล"
throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์เข้าถึงข้อมูล"); if (org.child2 != null) if (x.orgChild2Id != org.child2[0]) throw "ไม่มีสิทธิ์เข้าถึงข้อมูล"
if (org.child1 != null) if (org.child3 != null) if (x.orgChild3Id != org.child3[0]) throw "ไม่มีสิทธิ์เข้าถึงข้อมูล"
if (x.orgChild1Id != org.child1[0]) if (org.child4 != null) if (x.orgChild4Id != org.child4[0]) throw "ไม่มีสิทธิ์เข้าถึงข้อมูล"
throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์เข้าถึงข้อมูล");
if (org.child2 != null)
if (x.orgChild2Id != org.child2[0])
throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์เข้าถึงข้อมูล");
if (org.child3 != null)
if (x.orgChild3Id != org.child3[0])
throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์เข้าถึงข้อมูล");
if (org.child4 != null)
if (x.orgChild4Id != org.child4[0])
throw new HttpError(HttpStatus.FORBIDDEN, "ไม่มีสิทธิ์เข้าถึงข้อมูล");
return true; return true
}) })
.catch((x) => { .catch(x => {
if (x.status != undefined) { if (x.status != undefined) {
throw new HttpError(x.status, x.message); throw new HttpError(x.status, x.message)
} else { } else {
throw new HttpError(HttpStatus.FORBIDDEN, x); throw new HttpError(HttpStatus.FORBIDDEN, x)
} }
}); })
} }
public async Workflow(req: RequestWithUser, id: string, sysName: string) { public async Workflow(req: RequestWithUser, id: string, sysName: string) {
if ( if (req.headers.hasOwnProperty("api_key") && req.headers["api_key"] && req.headers["api_key"] == process.env.API_KEY) {
req.headers.hasOwnProperty("api_key") && return null
req.headers["api_key"] &&
req.headers["api_key"] == process.env.API_KEY
) {
return null;
} }
return await new CallAPI() return await new CallAPI()
.PostData(req, "/org/workflow/keycloak/isofficer", { .PostData(req, "/org/workflow/keycloak/isofficer", {
refId: id, refId: id,
sysName: sysName, sysName: sysName,
}) })
.then((x) => { .then(x => {
return true; return true
}) })
.catch((x) => { .catch(x => {
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)
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
)
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")
} }
public async PermissionDelete(req: RequestWithUser, system: string) { public async PermissionDelete(req: RequestWithUser, system: string) {
return await this.Permission(req, system, "DELETE"); return await this.Permission(req, system, "DELETE")
} }
public async PermissionGet(req: RequestWithUser, system: string) { public async PermissionGet(req: RequestWithUser, system: string) {
return await this.Permission(req, system, "GET"); return await this.Permission(req, system, "GET")
} }
public async PermissionList(req: RequestWithUser, system: string) { public async PermissionList(req: RequestWithUser, system: string) {
return await this.Permission(req, system, "LIST"); return await this.Permission(req, system, "LIST")
} }
public async PermissionUpdate(req: RequestWithUser, system: string) { public async PermissionUpdate(req: RequestWithUser, system: string) {
return await this.Permission(req, system, "UPDATE"); return await this.Permission(req, system, "UPDATE")
} }
public async PermissionOrgCreate(req: RequestWithUser, system: string) { public async PermissionOrgCreate(req: RequestWithUser, system: string) {
return await this.PermissionOrg(req, system, "CREATE"); return await this.PermissionOrg(req, system, "CREATE")
} }
public async PermissionOrgDelete(req: RequestWithUser, system: string) { public async PermissionOrgDelete(req: RequestWithUser, system: string) {
return await this.PermissionOrg(req, system, "DELETE"); return await this.PermissionOrg(req, system, "DELETE")
} }
public async PermissionOrgGet(req: RequestWithUser, system: string) { public async PermissionOrgGet(req: RequestWithUser, system: string) {
return await this.PermissionOrg(req, system, "GET"); return await this.PermissionOrg(req, system, "GET")
} }
public async PermissionOrgList(req: RequestWithUser, system: string) { public async PermissionOrgList(req: RequestWithUser, system: string) {
return await this.PermissionOrg(req, system, "LIST"); return await this.PermissionOrg(req, system, "LIST")
} }
public async PermissionOrgUpdate(req: RequestWithUser, system: string) { public async PermissionOrgUpdate(req: RequestWithUser, system: string) {
return await this.PermissionOrg(req, system, "UPDATE"); return await this.PermissionOrg(req, system, "UPDATE")
} }
public async PermissionOrgUserCreate(req: RequestWithUser, system: string, profileId: string) { public async PermissionOrgUserCreate(req: RequestWithUser, system: string, profileId: string) {
return await this.PermissionOrgByUser(req, system, "CREATE", profileId); return await this.PermissionOrgByUser(req, system, "CREATE", profileId)
} }
public async PermissionOrgUserDelete(req: RequestWithUser, system: string, profileId: string) { public async PermissionOrgUserDelete(req: RequestWithUser, system: string, profileId: string) {
return await this.PermissionOrgByUser(req, system, "DELETE", profileId); return await this.PermissionOrgByUser(req, system, "DELETE", profileId)
} }
public async PermissionOrgUserGet(req: RequestWithUser, system: string, profileId: string) { public async PermissionOrgUserGet(req: RequestWithUser, system: string, profileId: string) {
return await this.PermissionOrgByUser(req, system, "GET", profileId); return await this.PermissionOrgByUser(req, system, "GET", profileId)
} }
public async PermissionOrgUserList(req: RequestWithUser, system: string, profileId: string) { public async PermissionOrgUserList(req: RequestWithUser, system: string, profileId: string) {
return await this.PermissionOrgByUser(req, system, "LIST", profileId); return await this.PermissionOrgByUser(req, system, "LIST", profileId)
} }
public async PermissionOrgUserUpdate(req: RequestWithUser, system: string, profileId: string) { public async PermissionOrgUserUpdate(req: RequestWithUser, system: string, profileId: string) {
return await this.PermissionOrgByUser(req, system, "UPDATE", profileId); return await this.PermissionOrgByUser(req, system, "UPDATE", profileId)
} }
} }
export default CheckAuth; export default CheckAuth

View file

@ -1,11 +1,12 @@
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,
@ -13,46 +14,47 @@ const LOG_LEVEL_MAP: Record<string, number> = {
warning: 2, warning: 2,
error: 1, error: 1,
none: 0, none: 0,
}; }
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 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 = {}
res.on("finish", () => { res.on("finish", async () => {
if (!req.url.startsWith("/api/")) return; if (!req.url.startsWith("/api/")) return
const level = LOG_LEVEL_MAP[process.env.LOG_LEVEL ?? "debug"] || 4; const level = LOG_LEVEL_MAP[process.env.LOG_LEVEL ?? "debug"] || 4
if (level === 1 && res.statusCode < 500) return; if (level === 1 && res.statusCode < 500) return
if (level === 2 && res.statusCode < 400) return; if (level === 2 && res.statusCode < 400) return
if (level === 3 && res.statusCode < 200) 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 = { const obj = {
logType: logType: res.statusCode >= 500 ? "error" : res.statusCode >= 400 ? "warning" : "info",
res.statusCode >= 500
? "error"
: res.statusCode >= 400
? "warning"
: "info",
ip: req.ip, ip: req.ip,
rootId: rootId ? rootId.orgRootId : null,
systemName: "probation", systemName: "probation",
startTimeStamp: timestamp, startTimeStamp: timestamp,
endTimeStamp: new Date().toISOString(), endTimeStamp: new Date().toISOString(),
@ -65,15 +67,15 @@ async function logMiddleware(req: Request, res: Response, next: NextFunction) {
input: (level === 4 && JSON.stringify(req.body, null, 2)) || undefined, input: (level === 4 && JSON.stringify(req.body, null, 2)) || undefined,
output: (level === 4 && JSON.stringify(data, null, 2)) || undefined, output: (level === 4 && JSON.stringify(data, null, 2)) || undefined,
...req.app.locals.logData, ...req.app.locals.logData,
}; }
elasticsearch.index({ elasticsearch.index({
index: ELASTICSEARCH_INDEX, index: ELASTICSEARCH_INDEX,
document: obj, document: obj,
}); })
}); })
return next(); return next()
} }
export default logMiddleware; export default logMiddleware