add api key

This commit is contained in:
mamoss 2025-10-25 01:55:54 +07:00
parent 94ea64247f
commit f111132184
13 changed files with 291 additions and 4666 deletions

View file

@ -20,6 +20,8 @@ import { In } from "typeorm";
import { RequestWithUser } from "../middlewares/user";
import { ApiName } from "../entities/ApiName";
import { ApiHistory } from "../entities/ApiHistory";
const jwt = require("jsonwebtoken");
@Route("api/v1/org/apiKey")
@Tags("ApiKey")
@Security("bearerAuth")
@ -32,6 +34,32 @@ export class ApiKeyController extends Controller {
private apiNameRepository = AppDataSource.getRepository(ApiName);
private apiHistoryRepository = AppDataSource.getRepository(ApiHistory);
/**
* API JWT token
*
* @summary JWT API Key
*/
@Post("verify")
async verifyApiKey(@Body() requestBody: { token: string }) {
try {
const jwtSecret = process.env.JWT_SECRET || "your-default-secret-key";
console.log("JWT_SECRET from env:", process.env.JWT_SECRET ? "exists" : "not found");
console.log("Using secret:", jwtSecret);
const decoded = jwt.verify(requestBody.token, jwtSecret);
return new HttpSuccess({
valid: true,
data: decoded,
});
} catch (error: any) {
console.error("JWT Verification Error:", error.message);
return new HttpSuccess({
valid: false,
error: error.message,
});
}
}
/**
* API Api Key
*
@ -52,8 +80,33 @@ export class ApiKeyController extends Controller {
const apiName = await this.apiNameRepository.find({
where: { id: In(requestBody.apiId) },
});
const apiKey = Object.assign(new ApiKey(), requestBody);
apiKey.keyApi = require("crypto").randomBytes(64).toString("base64");
// Create JWT token with embedded data
const tokenPayload = {
keyId: apiKey.id || require("crypto").randomUUID(),
name: apiKey.name,
accessType: apiKey.accessType,
dnaRootId: apiKey.dnaRootId,
dnaChild1Id: apiKey.dnaChild1Id,
dnaChild2Id: apiKey.dnaChild2Id,
dnaChild3Id: apiKey.dnaChild3Id,
dnaChild4Id: apiKey.dnaChild4Id,
apiIds: requestBody.apiId,
createdBy: request.user.sub,
createdAt: new Date().toISOString(),
iat: Math.floor(Date.now() / 1000),
};
// Sign JWT with secret (you should use environment variable for the secret)
const jwtSecret = process.env.JWT_SECRET || "your-default-secret-key";
const jwtToken = jwt.sign(tokenPayload, jwtSecret, {
expiresIn: "365d", // 1 year expiration
});
apiKey.keyApi = jwtToken;
apiKey.apiNames = apiName;
apiKey.createdUserId = request.user.sub;
apiKey.createdFullName = request.user.name;
@ -104,6 +157,12 @@ export class ApiKeyController extends Controller {
createdUserId: _data.createdUserId,
createdFullName: _data.createdFullName,
name: _data.name,
accessType: _data.accessType,
dnaRootId: _data.dnaRootId,
dnaChild1Id: _data.dnaChild1Id,
dnaChild2Id: _data.dnaChild2Id,
dnaChild3Id: _data.dnaChild3Id,
dnaChild4Id: _data.dnaChild4Id,
apiNames: _data.apiNames.map((x) => ({
id: x.id,
name: x.name,

View file

@ -148,6 +148,7 @@ export class ProfileGovernmentHistoryController extends Controller {
let _workflow = await new permission().Workflow(req, profileId, "SYS_REGISTRY_OFFICER");
if (_workflow == false)
await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_OFFICER", profileId);
const orgRevision = await this.orgRevisionRepository.findOne({
select: ["id"],
where: {
@ -155,10 +156,22 @@ export class ProfileGovernmentHistoryController extends Controller {
orgRevisionIsCurrent: true,
},
});
// ค้นหา profile ก่อน
const record = await this.profileRepo.findOne({
where: {
where: { id: profileId },
relations: ["posType", "posLevel"],
});
if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล profile");
}
// ค้นหา profileSalary แยกต่างหาก
const profileWithSalary = await this.profileRepo.findOne({
where: {
id: profileId,
profileSalary: {
profileSalary: {
commandCode: In([
"0",
"9",
@ -175,16 +188,19 @@ export class ProfileGovernmentHistoryController extends Controller {
"15",
"16",
]),
}
},
},
relations: ["posType", "posLevel", "profileSalary"],
relations: ["profileSalary"],
order: {
profileSalary: {
order: "DESC",
createdAt: "DESC"
}
}
createdAt: "DESC",
},
},
});
// ใช้ profileSalary จาก query ที่สอง หรือ [] ถ้าไม่เจอ
record.profileSalary = profileWithSalary?.profileSalary || [];
const posMaster = await this.posMasterRepo.findOne({
where: {
orgRevisionId: orgRevision?.id,
@ -236,8 +252,8 @@ export class ProfileGovernmentHistoryController extends Controller {
orgShortName = posMaster.orgChild4?.orgChild4ShortName ?? "";
}
}
let _OrgLeave:any = []
let _profileSalary:any = null;
let _OrgLeave: any = [];
let _profileSalary: any = null;
if (record?.isLeave && record?.profileSalary.length > 0) {
// _OrgLeave = [
// record?.profileSalary[0].orgChild4 ? record?.profileSalary[0].orgChild4 : null,
@ -247,15 +263,14 @@ export class ProfileGovernmentHistoryController extends Controller {
// record?.profileSalary[0].orgRoot ? record?.profileSalary[0].orgRoot : null,
// ];
if (record.leaveType == "RETIRE") {
_profileSalary = record?.profileSalary.length > 1
? record?.profileSalary[1]
: record?.profileSalary.length > 0
_profileSalary =
record?.profileSalary.length > 1
? record?.profileSalary[1]
: record?.profileSalary.length > 0
? record?.profileSalary[0]
: null;
} else {
_profileSalary = record?.profileSalary.length > 0
? record?.profileSalary[0]
: null;
_profileSalary = record?.profileSalary.length > 0 ? record?.profileSalary[0] : null;
}
if (_profileSalary) {
_OrgLeave = [
@ -269,17 +284,20 @@ export class ProfileGovernmentHistoryController extends Controller {
_OrgLeave = [];
}
}
const orgLeave = _OrgLeave.filter((x:any) => x !== undefined && x !== null).join("\n");
const orgLeave = _OrgLeave.filter((x: any) => x !== undefined && x !== null).join("\n");
const data = {
org: record?.isLeave == false ? org : orgLeave, //สังกัด
positionField: position == null ? null : position.positionField, //สายงาน
position: record?.position, //ตำแหน่ง
posLevel: record?.posLevel == null ? null : record?.posLevel.posLevelName, //ระดับ
posMasterNo: record?.isLeave == false
? posMaster == null ? null : `${orgShortName} ${posMaster.posMasterNo}`
: _profileSalary != null
? `${_profileSalary.posNoAbb} ${_profileSalary.posNo}`
: null, //เลขที่ตำแหน่ง
posMasterNo:
record?.isLeave == false
? posMaster == null
? null
: `${orgShortName} ${posMaster.posMasterNo}`
: _profileSalary != null
? `${_profileSalary.posNoAbb} ${_profileSalary.posNo}`
: null, //เลขที่ตำแหน่ง
posType: record?.posType == null ? null : record?.posType.posTypeName, //ประเภท
posExecutive:
position == null || position.posExecutive == null
@ -310,8 +328,20 @@ export class ProfileGovernmentHistoryController extends Controller {
orgRevisionIsCurrent: true,
},
});
// ค้นหา profile ก่อน
const record = await this.profileRepo.findOne({
where: {
where: { id: profileId },
relations: ["posType", "posLevel"],
});
if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล profile");
}
// ค้นหา profileSalary แยกต่างหาก
const profileWithSalary = await this.profileRepo.findOne({
where: {
id: profileId,
profileSalary: {
commandCode: In([
@ -330,20 +360,19 @@ export class ProfileGovernmentHistoryController extends Controller {
"15",
"16",
]),
}
},
relations: {
posType: true,
posLevel: true,
profileSalary: true
},
},
relations: ["profileSalary"],
order: {
profileSalary: {
order: "DESC",
createdAt: "DESC"
}
}
createdAt: "DESC",
},
},
});
// ใช้ profileSalary จาก query ที่สอง หรือ [] ถ้าไม่เจอ
record.profileSalary = profileWithSalary?.profileSalary || [];
const posMaster = await this.posMasterRepo.findOne({
where: {
orgRevisionId: orgRevision?.id,
@ -395,8 +424,8 @@ export class ProfileGovernmentHistoryController extends Controller {
orgShortName = posMaster.orgChild4?.orgChild4ShortName;
}
}
let _OrgLeave:any = []
let _profileSalary:any = null;
let _OrgLeave: any = [];
let _profileSalary: any = null;
if (record?.isLeave && record?.profileSalary.length > 0) {
// _OrgLeave = [
// record?.profileSalary[0].orgChild4 ? record?.profileSalary[0].orgChild4 : null,
@ -406,15 +435,14 @@ export class ProfileGovernmentHistoryController extends Controller {
// record?.profileSalary[0].orgRoot ? record?.profileSalary[0].orgRoot : null,
// ];
if (record.leaveType == "RETIRE") {
_profileSalary = record?.profileSalary.length > 1
? record?.profileSalary[1]
: record?.profileSalary.length > 0
_profileSalary =
record?.profileSalary.length > 1
? record?.profileSalary[1]
: record?.profileSalary.length > 0
? record?.profileSalary[0]
: null;
} else {
_profileSalary = record?.profileSalary.length > 0
? record?.profileSalary[0]
: null;
_profileSalary = record?.profileSalary.length > 0 ? record?.profileSalary[0] : null;
}
if (_profileSalary) {
_OrgLeave = [
@ -428,19 +456,19 @@ export class ProfileGovernmentHistoryController extends Controller {
_OrgLeave = [];
}
}
const orgLeave = _OrgLeave.filter((x:any) => x !== undefined && x !== null).join("\n");
const orgLeave = _OrgLeave.filter((x: any) => x !== undefined && x !== null).join("\n");
const data = {
org: record?.isLeave == false ? org : orgLeave, //สังกัด
positionField: position == null ? null : position.positionField, //สายงาน
position: record?.position, //ตำแหน่ง
posLevel: record?.posLevel == null ? null : record?.posLevel.posLevelName, //ระดับ
posMasterNo:
record?.isLeave == false
? posMaster == null
? null
posMasterNo:
record?.isLeave == false
? posMaster == null
? null
: `${orgShortName} ${posMaster.posMasterNo}`
: _profileSalary != null
? `${_profileSalary.posNoAbb} ${_profileSalary.posNo}`
: _profileSalary != null
? `${_profileSalary.posNoAbb} ${_profileSalary.posNo}`
: null, //เลขที่ตำแหน่ง
posType: record?.posType == null ? null : record?.posType.posTypeName, //ประเภท
posExecutive:
@ -458,7 +486,7 @@ export class ProfileGovernmentHistoryController extends Controller {
govAgeAbsent: record?.govAgeAbsent,
govAgePlus: record?.govAgePlus,
reasonSameDate: record?.reasonSameDate,
isLeave: record?.isLeave
isLeave: record?.isLeave,
};
return new HttpSuccess(data);

View file

@ -149,36 +149,16 @@ export class ProfileGovernmentEmployeeController extends Controller {
orgRevisionIsCurrent: true,
},
});
// ค้นหา profile ก่อน
const record = await this.profileEmployeeRepo.findOne({
where: {
id: profileEmployeeId,
// profileSalary: {
// commandCode: In([
// "0",
// "9",
// "1",
// "2",
// "3",
// "4",
// "8",
// "10",
// "11",
// "12",
// "13",
// "14",
// "15",
// "16",
// ]),
// }
},
relations: ["posType", "posLevel"/*, "profileSalary"*/],
// order: {
// profileSalary: {
// order: "DESC",
// createdAt: "DESC"
// }
// }
where: { id: profileEmployeeId },
relations: ["posType", "posLevel"],
});
if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล profile");
}
const posMaster = await this.posMasterRepo.findOne({
where: {
orgRevisionId: orgRevision?.id,
@ -217,10 +197,10 @@ export class ProfileGovernmentEmployeeController extends Controller {
orgShortName = posMaster.orgChild4?.orgChild4ShortName;
}
}
let _OrgLeave:any = []
let orgLeave:string = ""
let posNoLeave:string = ""
let _profileSalary:any = null;
let _OrgLeave: any = [];
let orgLeave: string = "";
let posNoLeave: string = "";
let _profileSalary: any = null;
if (record?.isLeave /*&& record?.profileSalary.length > 0*/) {
const profileSalary = await this.salaryRepo.find({
select: [
@ -230,7 +210,7 @@ export class ProfileGovernmentEmployeeController extends Controller {
"orgChild3",
"orgChild4",
"posNoAbb",
"posNo"
"posNo",
],
where: {
profileEmployeeId: profileEmployeeId,
@ -253,8 +233,8 @@ export class ProfileGovernmentEmployeeController extends Controller {
},
order: {
order: "DESC",
createdAt: "DESC"
}
createdAt: "DESC",
},
});
// _OrgLeave = [
// profileSalary.length > 0 && profileSalary[0].orgChild4 ? profileSalary[0].orgChild4 : null,
@ -264,15 +244,14 @@ export class ProfileGovernmentEmployeeController extends Controller {
// profileSalary.length > 0 && profileSalary[0].orgRoot ? profileSalary[0].orgRoot : null,
// ];
if (record.leaveType == "RETIRE") {
_profileSalary = profileSalary.length > 1
? profileSalary[1]
: profileSalary.length > 0
? profileSalary[0]
: null;
_profileSalary =
profileSalary.length > 1
? profileSalary[1]
: profileSalary.length > 0
? profileSalary[0]
: null;
} else {
_profileSalary = profileSalary.length > 0
? profileSalary[0]
: null
_profileSalary = profileSalary.length > 0 ? profileSalary[0] : null;
}
if (_profileSalary) {
_OrgLeave = [
@ -285,10 +264,9 @@ export class ProfileGovernmentEmployeeController extends Controller {
} else {
_OrgLeave = [];
}
orgLeave = _OrgLeave.filter((x:any) => x !== undefined && x !== null).join("\n");
posNoLeave = _profileSalary != null
? `${_profileSalary.posNoAbb} ${_profileSalary.posNo}`
: ""
orgLeave = _OrgLeave.filter((x: any) => x !== undefined && x !== null).join("\n");
posNoLeave =
_profileSalary != null ? `${_profileSalary.posNoAbb} ${_profileSalary.posNo}` : "";
}
const data = {
org: record?.isLeave == false ? org : orgLeave, //สังกัด
@ -297,9 +275,12 @@ export class ProfileGovernmentEmployeeController extends Controller {
record?.posLevel == null
? null
: `${record?.posType?.posTypeShortName ?? ""} ${record?.posLevel?.posLevelName ?? ""}`, //ระดับ
posMasterNo: record?.isLeave == false
? posMaster == null ? null : `${orgShortName} ${posMaster.posMasterNo}`
: posNoLeave/*record && record?.profileSalary.length > 0
posMasterNo:
record?.isLeave == false
? posMaster == null
? null
: `${orgShortName} ${posMaster.posMasterNo}`
: posNoLeave /*record && record?.profileSalary.length > 0
? `${record?.profileSalary[0].posNoAbb} ${record?.profileSalary[0].posNo}`
: null*/, //
posType: record?.posType == null ? null : record?.posType.posTypeName, //ประเภท
@ -326,34 +307,16 @@ export class ProfileGovernmentEmployeeController extends Controller {
orgRevisionIsCurrent: true,
},
});
// ค้นหา profile ก่อน
const record = await this.profileEmployeeRepo.findOne({
where: {
id: profileEmployeeId,
// profileSalary:{
// commandCode: In([
// "0",
// "9",
// "1",
// "2",
// "3",
// "4",
// "8",
// "10",
// "11",
// "12",
// "13",
// "14",
// "15",
// "16",
// ]),
// }
},
relations: {
posType: true,
posLevel: true,
// profileSalary: true
},
where: { id: profileEmployeeId },
relations: ["posType", "posLevel"],
});
if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล profile");
}
const posMaster = await this.posMasterRepo.findOne({
where: {
orgRevisionId: orgRevision?.id,
@ -392,10 +355,10 @@ export class ProfileGovernmentEmployeeController extends Controller {
orgShortName = posMaster.orgChild4?.orgChild4ShortName;
}
}
let _OrgLeave:any = []
let orgLeave:string = ""
let posNoLeave:string = ""
let _profileSalary:any = null;
let _OrgLeave: any = [];
let orgLeave: string = "";
let posNoLeave: string = "";
let _profileSalary: any = null;
if (record?.isLeave /*&& record?.profileSalary.length > 0*/) {
const profileSalary = await this.salaryRepo.find({
select: [
@ -405,7 +368,7 @@ export class ProfileGovernmentEmployeeController extends Controller {
"orgChild3",
"orgChild4",
"posNoAbb",
"posNo"
"posNo",
],
where: {
profileEmployeeId: profileEmployeeId,
@ -428,8 +391,8 @@ export class ProfileGovernmentEmployeeController extends Controller {
},
order: {
order: "DESC",
createdAt: "DESC"
}
createdAt: "DESC",
},
});
// _OrgLeave = [
// profileSalary.length > 0 && profileSalary[0].orgChild4 ? profileSalary[0].orgChild4 : null,
@ -439,15 +402,14 @@ export class ProfileGovernmentEmployeeController extends Controller {
// profileSalary.length > 0 && profileSalary[0].orgRoot ? profileSalary[0].orgRoot : null,
// ];
if (record.leaveType == "RETIRE") {
_profileSalary = profileSalary.length > 1
? profileSalary[1]
: profileSalary.length > 0
? profileSalary[0]
: null;
_profileSalary =
profileSalary.length > 1
? profileSalary[1]
: profileSalary.length > 0
? profileSalary[0]
: null;
} else {
_profileSalary = profileSalary.length > 0
? profileSalary[0]
: null;
_profileSalary = profileSalary.length > 0 ? profileSalary[0] : null;
}
if (_profileSalary) {
_OrgLeave = [
@ -460,23 +422,23 @@ export class ProfileGovernmentEmployeeController extends Controller {
} else {
_OrgLeave = [];
}
orgLeave = _OrgLeave.filter((x:any) => x !== undefined && x !== null).join("\n");
posNoLeave = _profileSalary != null
? `${_profileSalary.posNoAbb} ${_profileSalary.posNo}`
: ""
orgLeave = _OrgLeave.filter((x: any) => x !== undefined && x !== null).join("\n");
posNoLeave =
_profileSalary != null ? `${_profileSalary.posNoAbb} ${_profileSalary.posNo}` : "";
}
const data = {
org: record?.isLeave == false ? org : orgLeave, //สังกัด
position: record?.position, //ตำแหน่ง
posLevel: record?.posLevel == null && record?.posType == null
? null
: `${record?.posType.posTypeShortName} ${record?.posLevel.posLevelName}`, //ระดับ
posMasterNo:
record?.isLeave == false
? posMaster == null
? null
posLevel:
record?.posLevel == null && record?.posType == null
? null
: `${record?.posType.posTypeShortName} ${record?.posLevel.posLevelName}`, //ระดับ
posMasterNo:
record?.isLeave == false
? posMaster == null
? null
: `${orgShortName} ${posMaster.posMasterNo}`
: posNoLeave/*record && record.profileSalary.length > 0
: posNoLeave /*record && record.profileSalary.length > 0
? `${record?.profileSalary[0].posNoAbb} ${record?.profileSalary[0].posNo}`
: null*/, //
posType: record?.posType == null ? null : record?.posType.posTypeName, //ประเภท
@ -490,7 +452,7 @@ export class ProfileGovernmentEmployeeController extends Controller {
govAgeAbsent: record?.govAgeAbsent ?? null, // ขาดราชการ
govAgePlus: record?.govAgePlus, // อายุราชการเกื้อกูล
dateRetireLaw: record?.dateRetireLaw ?? null, // วันที่เกษียฯอายุราชการตามกฎหมาย
isLeave: record?.isLeave
isLeave: record?.isLeave,
};
return new HttpSuccess(data);
}