Merge branch 'develop' into adiDev

This commit is contained in:
AdisakKanthawilang 2024-12-18 10:42:24 +07:00
commit 83eeb0d468
10 changed files with 1202 additions and 1009 deletions

View file

@ -1,5 +1,5 @@
name: release-test name: release
run-name: release-test ${{ github.actor }} run-name: release ${{ github.actor }}
on: on:
push: push:
tags: tags:
@ -7,14 +7,13 @@ on:
workflow_dispatch: workflow_dispatch:
env: env:
REGISTRY: docker.frappet.com REGISTRY: docker.frappet.com
# IMAGE_NAME: ehr/bma-ehr-node-service
IMAGE_NAME: ehr/bma-ehr-probation IMAGE_NAME: ehr/bma-ehr-probation
DEPLOY_HOST: frappet.com DEPLOY_HOST: frappet.com
# COMPOSE_PATH: /home/frappet/docker/bma-ehr
COMPOSE_PATH: /home/frappet/docker/bma/bma-ehr-probation COMPOSE_PATH: /home/frappet/docker/bma/bma-ehr-probation
jobs: jobs:
# act workflow_dispatch -W .github/workflows/release.yaml --input IMAGE_VER=test-v1 -s DOCKER_USER=sorawit -s DOCKER_PASS=P@ssword -s SSH_PASSWORD=P@ssw0rd # act workflow_dispatch -W .github/workflows/release.yaml --input IMAGE_VER=test-v1 -s DOCKER_USER=sorawit -s DOCKER_PASS=P@ssword -s SSH_PASSWORD=P@ssw0rd
release-test: release:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
@ -53,6 +52,7 @@ jobs:
with: with:
context: . context: .
platforms: linux/amd64 platforms: linux/amd64
file: docker/Dockerfile
push: true push: true
tags: ${{env.REGISTRY}}/${{env.IMAGE_NAME}}:${{ steps.gen_ver.outputs.image_ver }},${{env.REGISTRY}}/${{env.IMAGE_NAME}}:latest tags: ${{env.REGISTRY}}/${{env.IMAGE_NAME}}:${{ steps.gen_ver.outputs.image_ver }},${{env.REGISTRY}}/${{env.IMAGE_NAME}}:latest
- name: Remote Deployment - name: Remote Deployment
@ -67,21 +67,40 @@ jobs:
docker compose pull docker compose pull
docker compose up -d docker compose up -d
echo "${{ steps.gen_ver.outputs.image_ver }}"> success echo "${{ steps.gen_ver.outputs.image_ver }}"> success
- uses: snow-actions/line-notify@v1.1.0 - name: Notify Discord Success
if: success() if: success()
with: run: |
access_token: ${{ secrets.TOKEN_LINE }} curl -H "Content-Type: application/json" \
message: | -X POST \
-Success✅✅✅ -d '{
Image: ${{env.IMAGE_NAME}} "embeds": [{
Version: ${{ steps.gen_ver.outputs.IMAGE_VER }} "title": "✅ Deployment Success!",
By: ${{github.actor}} "description": "**Details:**\n- Image: `${{env.IMAGE_NAME}}`\n- Version: `${{ steps.gen_ver.outputs.image_ver }}`\n- Deployed by: `${{github.actor}}`",
- uses: snow-actions/line-notify@v1.1.0 "color": 3066993,
"footer": {
"text": "Release Notification",
"icon_url": "https://example.com/success-icon.png"
},
"timestamp": "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'"
}]
}' \
${{ secrets.DISCORD_WEBHOOK }}
- name: Notify Discord Failure
if: failure() if: failure()
with: run: |
access_token: ${{ secrets.TOKEN_LINE }} curl -H "Content-Type: application/json" \
message: | -X POST \
-Failure❌❌❌ -d '{
Image: ${{env.IMAGE_NAME}} "embeds": [{
Version: ${{ steps.gen_ver.outputs.IMAGE_VER }} "title": "❌ Deployment Failed!",
By: ${{github.actor}} "description": "**Details:**\n- Image: `${{env.IMAGE_NAME}}`\n- Version: `${{ steps.gen_ver.outputs.image_ver }}`\n- Attempted by: `${{github.actor}}`",
"color": 15158332,
"footer": {
"text": "Release Notification",
"icon_url": "https://example.com/failure-icon.png"
},
"timestamp": "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'"
}]
}' \
${{ secrets.DISCORD_WEBHOOK }}

View file

@ -1,35 +0,0 @@
FROM node:18-alpine as builder
# Create app directory
WORKDIR /app
# Install app dependencies
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:18-alpine
ENV NODE_ENV production
USER node
# Create app directory
WORKDIR /app
# Install app dependencies
COPY package*.json ./
# COPY .env ./
RUN npm ci --production
COPY --from=builder /app/dist ./dist
# COPY entrypoint.sh /usr/local/bin/entrypoint.sh
# RUN chmod u+x /usr/local/bin/entrypoint.sh
# ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
CMD [ "node", "dist/app.js" ]

34
docker/Dockerfile Normal file
View file

@ -0,0 +1,34 @@
# Build Stage
FROM node:lts-alpine AS build-stage
# Create app directory
WORKDIR /app
# Install app dependencies
COPY package*.json ./
RUN npm ci
# Copy source files and build the app
COPY . .
RUN npm run build
# Production Stage
FROM node:lts-alpine
ENV NODE_ENV production
USER node
# Create app directory
WORKDIR /app
# Copy built app from build stage
COPY --from=build-stage /app/dist ./dist
# Install only production dependencies
COPY package*.json ./
RUN npm ci --production
# Define the entrypoint and default command
# If you have a custom entrypoint script
CMD [ "node", "dist/app.js" ]

View file

@ -1,204 +1,176 @@
import { import { Controller, Route, Security, Tags, Body, Request, SuccessResponse, Response, Get, Put, Post, Path, Delete, Query } from "tsoa"
Controller, import { setLogDataDiff } from "../interfaces/utils"
Route,
Security,
Tags,
Body,
Request,
SuccessResponse,
Response,
Get,
Put,
Post,
Path,
Delete,
Query,
} from "tsoa";
import { setLogDataDiff } from "../interfaces/utils";
import { AppDataSource } from "../database/data-source"; import { AppDataSource } from "../database/data-source"
import HttpSuccess from "../interfaces/http-success"; import HttpSuccess from "../interfaces/http-success"
import HttpStatusCode from "../interfaces/http-status"; import HttpStatusCode from "../interfaces/http-status"
import HttpError from "../interfaces/http-error"; import HttpError from "../interfaces/http-error"
import permission from "../interfaces/permission"; import permission from "../interfaces/permission"
import { RequestWithUser } from "../middlewares/user"; import { RequestWithUser } from "../middlewares/user"
import { Appoint, CreateAppoint, Person, UpdateAppoint } from "../entities/Appoint"; import { Appoint, CreateAppoint, Person, UpdateAppoint } from "../entities/Appoint"
import { AppointDirector } from "../entities/AppointDirector"; import { AppointDirector } from "../entities/AppointDirector"
@Route("api/v1/probation/appoint") @Route("api/v1/probation/appoint")
@Tags("Appoint Director") @Tags("Appoint Director")
@Security("bearerAuth") @Security("bearerAuth")
@Response( @Response(HttpStatusCode.INTERNAL_SERVER_ERROR, "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง")
HttpStatusCode.INTERNAL_SERVER_ERROR,
"เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
)
export class AppointController extends Controller { export class AppointController extends Controller {
private appointRepository = AppDataSource.getRepository(Appoint); private appointRepository = AppDataSource.getRepository(Appoint)
private appointDirectorRepository = AppDataSource.getRepository(AppointDirector); private appointDirectorRepository = AppDataSource.getRepository(AppointDirector)
/** /**
* API * API
* *
* @summary * @summary
* *
*/ */
@Get("") @Get("")
async GetList( async GetList(@Query() keyword: string = "", @Query("page") page: number = 1, @Query("pageSize") pageSize: number = 10, @Request() request: RequestWithUser) {
@Query() keyword: string = "", await new permission().PermissionList(request, "SYS_PROBATION")
@Query("page") page: number = 1, const _data = await new permission().PermissionOrgList(request, "SYS_PROBATION")
@Query("pageSize") pageSize: number = 10,
@Request() request: RequestWithUser,
) {
await new permission().PermissionList(request, "SYS_PROBATION");
const _data = await new permission().PermissionOrgList(request, "SYS_PROBATION");
const conditions: any = {}; const conditions: any = {}
if (_data.root != undefined && _data.root != null && _data.root[0] != null) { if (_data.root != undefined && _data.root != null && _data.root[0] != null) {
conditions.root = _data.root; conditions.root = _data.root
} }
if (_data.child1 != undefined && _data.child1 != null && _data.child1[0] != null) { if (_data.child1 != undefined && _data.child1 != null && _data.child1[0] != null) {
conditions.child1 = _data.child1; conditions.child1 = _data.child1
} }
if (_data.child2 != undefined && _data.child2 != null && _data.child2[0] != null) { if (_data.child2 != undefined && _data.child2 != null && _data.child2[0] != null) {
conditions.child2 = _data.child2; conditions.child2 = _data.child2
} }
if (_data.child3 != undefined && _data.child3 != null && _data.child3[0] != null) { if (_data.child3 != undefined && _data.child3 != null && _data.child3[0] != null) {
conditions.child3 = _data.child3; conditions.child3 = _data.child3
} }
if (_data.child4 != undefined && _data.child4 != null && _data.child4[0] != null) { if (_data.child4 != undefined && _data.child4 != null && _data.child4[0] != null) {
conditions.child4 = _data.child4; conditions.child4 = _data.child4
} }
const appoint = await this.appointRepository.find({ const appoint = await this.appointRepository.find({
relations: ["personal"], relations: ["personal"],
where: { personal: conditions }, where: { personal: conditions },
}); })
return new HttpSuccess(appoint); return new HttpSuccess(appoint)
} }
/** /**
* API * API
* *
* @summary * @summary
* *
*/ */
@Get("list/{id}") @Get("list/{id}")
async GetListCommand(@Request() request: RequestWithUser, @Path() id: string) { async GetListCommand(@Request() request: RequestWithUser, @Path() id: string) {
const appoint = await this.appointRepository.find({ const appoint = await this.appointRepository.find({
relations: ["directors"], relations: ["directors"],
where: { profileId: id, status: "DONE" }, where: { profileId: id, status: "DONE" },
}); })
return new HttpSuccess(appoint); return new HttpSuccess(appoint)
} }
/** /**
* API * API
* *
* @summary * @summary
* *
*/ */
@Post("") @Post("")
async Create(@Request() request: RequestWithUser, @Body() requestBody: CreateAppoint) { async Create(@Request() request: RequestWithUser, @Body() requestBody: CreateAppoint) {
await new permission().PermissionCreate(request, "SYS_PROBATION"); await new permission().PermissionCreate(request, "SYS_PROBATION")
const data: any = { const data: any = {
topic: requestBody.topic, topic: requestBody.topic,
profileId: requestBody.profileId, profileId: requestBody.profileId,
createdUserId: request.user.sub, createdUserId: request.user.sub,
createdFullName: request.user.name, createdFullName: request.user.name,
}; }
const before = null; const before = null
const appoint = await this.appointRepository.save(data, { data: request }); const appoint = await this.appointRepository.save(data, { data: request })
setLogDataDiff(request, { before, after: appoint }); setLogDataDiff(request, { before, after: appoint })
return new HttpSuccess(appoint.id); return new HttpSuccess(appoint.id)
} }
/** /**
* API * API
* *
* @summary API id * @summary API id
* *
*/ */
@Get("{id}") @Get("{id}")
async GetById(@Request() request: RequestWithUser, @Path() id: string) { async GetById(@Request() request: RequestWithUser, @Path() id: string) {
let _workflow = await new permission().Workflow(request, id, "SYS_PROBATION"); let _workflow = await new permission().Workflow(request, id, "SYS_PROBATION")
if (_workflow == false) await new permission().PermissionGet(request, "SYS_PROBATION"); if (_workflow == false) await new permission().PermissionGet(request, "SYS_PROBATION")
const appoint = await this.appointRepository.findOne({ const appoint = await this.appointRepository.findOne({
select: ["id", "topic", "status", "profileId"], select: ["id", "topic", "status", "profileId"],
where: { id }, where: { id },
relations: ["directors"], relations: ["directors"],
}); })
return new HttpSuccess(appoint); return new HttpSuccess(appoint)
} }
/** /**
* API * API
* *
* @summary * @summary
* *
*/ */
@Put("{id}") @Put("{id}")
async Update( async Update(@Request() request: RequestWithUser, @Body() requestBody: UpdateAppoint, @Path() id: string) {
@Request() request: RequestWithUser, await new permission().PermissionUpdate(request, "SYS_PROBATION")
@Body() requestBody: UpdateAppoint,
@Path() id: string,
) {
await new permission().PermissionUpdate(request, "SYS_PROBATION");
const appoint: any = await this.appointRepository.findOne({ where: { id } }); const appoint: any = await this.appointRepository.findOne({ where: { id } })
if (!appoint) { if (!appoint) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลการแต่งตั้งคณะกรรมการฯ"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลการแต่งตั้งคณะกรรมการฯ")
} }
const before = appoint; const before = appoint
appoint.topic = requestBody.topic; appoint.topic = requestBody.topic
appoint.updateUserId = request.user.sub; appoint.updateUserId = request.user.sub
appoint.updateFullName = request.user.name; appoint.updateFullName = request.user.name
await this.appointDirectorRepository.delete({ appointId: id })
const directors: any = await requestBody.persons.map((x: Person) => ({
...x,
appointId: id,
createdUserId: request.user.sub,
createdFullName: request.user.name,
updateUserId: request.user.sub,
updateFullName: request.user.name,
}))
await this.appointDirectorRepository.save(directors)
await this.appointDirectorRepository.delete({ appointId: id }); await this.appointRepository.save(appoint, { data: request })
const directors = await requestBody.persons.map((x: Person) => ({ setLogDataDiff(request, { before, after: appoint })
...x,
appointId: id,
createdUserId: request.user.sub,
createdFullName: request.user.name,
updateUserId: request.user.sub,
updateFullName: request.user.name,
}));
await this.appointDirectorRepository.save(directors);
await this.appointRepository.save(appoint, { data: request }); return new HttpSuccess()
setLogDataDiff(request, { before, after: appoint }); }
return new HttpSuccess(); /**
} * API
*
* @summary
*
*/
@Delete("{id}")
public async deleteRole(@Path() id: string, @Request() request: RequestWithUser) {
await new permission().PermissionDelete(request, "SYS_PROBATION")
/** await this.appointDirectorRepository.delete({ appointId: id })
* API
*
* @summary
*
*/
@Delete("{id}")
public async deleteRole(@Path() id: string, @Request() request: RequestWithUser) {
await new permission().PermissionDelete(request, "SYS_PROBATION");
await this.appointDirectorRepository.delete({ appointId: id }); const result = await this.appointRepository.delete({ id })
if (!result) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล")
const result = await this.appointRepository.delete({ id }); return new HttpSuccess()
if (!result) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูล"); }
return new HttpSuccess();
}
} }

File diff suppressed because it is too large Load diff

View file

@ -20,6 +20,7 @@ import { setLogDataDiff } from "../interfaces/utils";
import { Personal, PostPersonal } from "../entities/Personal"; import { Personal, PostPersonal } from "../entities/Personal";
import permission from "../interfaces/permission"; import permission from "../interfaces/permission";
import { Assign } from "../entities/Assign"; import { Assign } from "../entities/Assign";
import { Brackets } from "typeorm";
@Route("api/v1/probation/personal") @Route("api/v1/probation/personal")
@Tags("Personal") @Tags("Personal")
@ -101,6 +102,7 @@ export class PersonalController extends Controller {
@Get("list") @Get("list")
async ListPersonal( async ListPersonal(
@Query() status: string = "", @Query() status: string = "",
@Query() keyword: string = "",
@Query("page") page: number = 1, @Query("page") page: number = 1,
@Query("pageSize") pageSize: number = 10, @Query("pageSize") pageSize: number = 10,
@Request() request: RequestWithUser, @Request() request: RequestWithUser,
@ -133,12 +135,39 @@ export class PersonalController extends Controller {
conditions.child4 = _data.child4; conditions.child4 = _data.child4;
} }
const [lists, total] = await this.personalRepository.findAndCount({ const searchKeyword = await (keyword ? keyword.trim() : null);
order: { createdAt: "DESC" },
where: conditions, const [lists, total] = await AppDataSource.getRepository(Personal)
skip: (page - 1) * pageSize, .createQueryBuilder("personal")
take: pageSize, .where(conditions)
}); .andWhere(
new Brackets((qb) => {
qb.orWhere(
searchKeyword
? `CONCAT(prefixName, firstName," ",lastName) like '%${keyword}%'`
: "1=1",
{
keyword: `%${searchKeyword}%`,
},
);
qb.orWhere(searchKeyword ? `positionName like '%${keyword}%'` : "1=1", {
keyword: `%${searchKeyword}%`,
});
qb.orWhere(searchKeyword ? `positionLevelName like '%${keyword}%'` : "1=1", {
keyword: `%${searchKeyword}%`,
});
qb.orWhere(searchKeyword ? `organization like '%${keyword}%'` : "1=1", {
keyword: `%${searchKeyword}%`,
});
qb.orWhere(searchKeyword ? `order_number like '%${keyword}%'` : "1=1", {
keyword: `%${searchKeyword}%`,
});
}),
)
.orderBy("updatedAt", "DESC")
.skip((page - 1) * pageSize)
.take(pageSize)
.getManyAndCount();
if (!lists) { if (!lists) {
throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, "ไม่สามารถแสดงข้อมูลได้"); throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, "ไม่สามารถแสดงข้อมูลได้");
@ -146,32 +175,54 @@ export class PersonalController extends Controller {
let result: any = []; let result: any = [];
await Promise.all( for (let i = 0; i < lists.length; i++) {
lists.map(async (item, index) => { const probation_no = await this.assignRepository.count({
const probation_no = await this.assignRepository.count({ where: { personal_id: lists[i].personal_id },
where: { });
personal_id: item.personal_id,
},
});
await result.push({ await result.push({
personal_id: item.personal_id, personal_id: lists[i].personal_id,
ordering: index + 1, ordering: i + 1,
name: item.prefixName + item.firstName + " " + item.lastName, name: lists[i].prefixName + lists[i].firstName + " " + lists[i].lastName,
idcard: item.idcard, prefixName: lists[i].prefixName,
prefixName: item.prefixName, firstName: lists[i].firstName,
firstName: item.firstName, lastName: lists[i].lastName,
lastName: item.lastName, idcard: lists[i].idcard,
position_line: item.positionName, position_line: lists[i].positionName,
position_level: item.positionLevelName, position_level: lists[i].positionLevelName,
position_type: item.positionTypeName, position_type: lists[i].positionTypeName,
organization: item.organization, organization: lists[i].organization,
probation_no: probation_no, probation_no: probation_no,
order_number: item.order_number, order_number: lists[i].order_number,
probation_status: item.probation_status, probation_status: lists[i].probation_status,
}); });
}), }
); // await Promise.all(
// lists.map(async (item, index) => {
// const probation_no = await this.assignRepository.count({
// where: {
// personal_id: item.personal_id,
// },
// });
// await result.push({
// personal_id: item.personal_id,
// ordering: index + 1,
// name: item.prefixName + item.firstName + " " + item.lastName,
// idcard: item.idcard,
// // prefixName: item.prefixName,
// // firstName: item.firstName,
// // lastName: item.lastName,
// position_line: item.positionName,
// position_level: item.positionLevelName,
// position_type: item.positionTypeName,
// organization: item.organization,
// probation_no: probation_no,
// order_number: item.order_number,
// probation_status: item.probation_status,
// });
// }),
// );
return new HttpSuccess({ data: result, total: total }); return new HttpSuccess({ data: result, total: total });
} }

View file

@ -52,13 +52,13 @@ export class CreateAppoint {
export type Person = { export type Person = {
profileId: string profileId: string
name: string name: string | null
position: string position?: string | null
positionType: string positionType?: string | null
positionLevel: string positionLevel?: string | null
role: string role: string | null
posNo: string posNo?: string | null
actFullName: string actFullName?: string | null
} }
export class UpdateAppoint { export class UpdateAppoint {

View file

@ -1,96 +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";
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),
throw error; },
} })
} throw error
//Post }
public async PostData(request: any, @Path() path: any, sendData: any) { }
const token = request.headers.authorization; //Post
const url = process.env.API_URL + path; public async PostData(request: any, @Path() path: any, sendData: any) {
try { const token = "Bearer " + request.headers.authorization.replace("Bearer ", "")
const response = await axios.post(url, sendData, { const url = process.env.API_URL + path
headers: { try {
Authorization: `${token}`, const response = await axios.post(url, sendData, {
"Content-Type": "application/json", headers: {
api_key: process.env.API_KEY, Authorization: `${token}`,
}, "Content-Type": "application/json",
}); api_key: process.env.API_KEY,
addLogSequence(request, { },
action: "request", })
status: "success", addLogSequence(request, {
description: "connected", action: "request",
request: { status: "success",
method: "POST", description: "connected",
url: url, request: {
payload: JSON.stringify(sendData), method: "POST",
response: JSON.stringify(response.data.result), url: url,
}, payload: JSON.stringify(sendData),
}); response: JSON.stringify(response.data.result),
return response.data.result; },
} catch (error) { })
addLogSequence(request, { return response.data.result
action: "request", } catch (error) {
status: "error", addLogSequence(request, {
description: "unconnected", action: "request",
request: { status: "error",
method: "POST", description: "unconnected",
url: url, request: {
payload: JSON.stringify(sendData), method: "POST",
response: JSON.stringify(error), url: url,
}, payload: JSON.stringify(sendData),
}); response: JSON.stringify(error),
throw error; },
} })
} throw error
}
}
} }
export default CallAPI; export default CallAPI

View file

@ -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 (req.headers.hasOwnProperty("api_key") && req.headers["api_key"] && 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
@ -155,6 +158,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)
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")
} }

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