This commit is contained in:
2026-06-10 14:17:06 +07:00
parent 8d516fb515
commit 04a4e2cf98
5 changed files with 323 additions and 249 deletions

View File

@ -1,51 +1,69 @@
import { NextFunction, Response } from 'express';
import { Logger, ILogObj } from 'tslog';
import { NextFunction, Response } from "express";
import { Logger, ILogObj } from "tslog";
import { Request, expressjwt } from "express-jwt";
import fs from 'fs';
import { Language } from '../langs/lang';
import { ReturnHelper } from './express/return';
import express from 'express';
import fs from "fs";
import { Language } from "../langs/lang";
import { ReturnHelper } from "./express/return";
import express from "express";
import config from "config";
import jwt from "jsonwebtoken";
const log: Logger<ILogObj> = new Logger({ name: '[JwtHelper]', type: 'pretty' });
const log: Logger<ILogObj> = new Logger({ name: "[JwtHelper]", type: "pretty" });
export default class JwtHelper {
static secure = (app: express.Application) => {
static secure = (app: express.Application) => {
var publicKey = fs.readFileSync("src/helpers/key/public.key");
var publicKey = fs.readFileSync("src/helpers/key/public.key");
app.use(
expressjwt({
secret: publicKey,
algorithms: ["RS256"],
getToken: function fromHeaderOrQuerystring(req): any {
if (req.headers.authorization && req.headers.authorization.split(" ")[0] === "Bearer") {
return req.headers.authorization.split(" ")[1];
} else if (req.query && req.query.token) {
return req.query.token;
}
return null;
},
}).unless({
path: [
"/token",
/^\/uploads\/.*/, // ⚠️ TAMBAHKAN INI - exclude semua path /uploads/
],
}),
function (req: Request, res: Response, next: NextFunction) {
if (!req.auth?.data.id) {
return ReturnHelper.errorResponse(res, 403, 666, Language.lang.failed_access);
}
app.use(
expressjwt({
secret: publicKey, algorithms: ["RS256"],
getToken: function fromHeaderOrQuerystring(req): any {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
return req.headers.authorization.split(' ')[1];
} else if (req.query && req.query.token) {
return req.query.token;
}
return null;
},
}).unless({
path: [
"/token",
/^\/uploads\/.*/ // ⚠️ TAMBAHKAN INI - exclude semua path /uploads/
]
}),
function (req: Request, res: Response, next: NextFunction) {
if (!req.auth?.data.id) {
return ReturnHelper.errorResponse(res, 403, 666, Language.lang.failed_access);
}
return next();
},
);
return next();
}
)
app.use(function (err: any, req: Request, res: Response, next: NextFunction) {
if (err.name === "UnauthorizedError") {
return ReturnHelper.errorResponse(res, 403, 666, Language.lang.failed_access);
}
app.use(function (err: any, req: Request, res: Response, next: NextFunction) {
if (err.name === 'UnauthorizedError') {
return ReturnHelper.errorResponse(res, 403, 666, Language.lang.failed_access);
}
return next();
});
};
return next();
});
}
}
static token = (user: { id: string; username: string; name: string }) => {
var privateKey = fs.readFileSync("src/helpers/key/private.key");
var token = jwt.sign(
{
exp: Math.floor(Date.now() / 1000) + Number(config.get("auth.access_token_lifetime")),
data: {
id: user.id,
username: user.username,
name: user.name,
},
},
privateKey,
{ algorithm: "RS256" },
);
return token;
};
}

108
src/helpers/thirdparty.ts Normal file
View File

@ -0,0 +1,108 @@
import axios from "axios";
export default class Thirdparty {
static async GetData(url: string, field: any, token?: string) {
try {
const headers: Record<string, string> = {};
if (token) {
headers.Authorization = `Bearer ${token}`;
}
const response = await axios.get(url, { params: field, headers });
const result = response.data;
if (result.status) {
return { status: true, message: "Success fetch data", data: result.data };
} else {
// Add a default return for falsy result.status
return { status: false, message: "Unexpected response status", data: null };
}
} catch (error: any) {
const { response } = error;
return {
status: false,
message: response?.data?.error ?? response?.data?.message ?? "Unknown error",
data: null,
};
}
}
static async PostData(url: string, field: any, token?: string) {
try {
const headers: Record<string, string> = {};
if (token) {
headers.Authorization = `Bearer ${token}`;
}
const response = await axios.post(url, field, { headers });
const result = response.data;
return result;
} catch (error: any) {
const { response } = error;
return { status: false, message: response?.data?.error ?? response?.data?.message ?? "Unknown error" };
}
}
static async UploadFile(url: string, field: any, token?: string) {
try {
const headers: Record<string, string> = {};
if (token) {
headers.Authorization = `Bearer ${token}`;
}
const formData = new FormData();
// Append the file and other fields to FormData
for (const key in field) {
if (field.hasOwnProperty(key)) {
const value = field[key];
if (value instanceof Object && value.data && value.mimetype) {
// Convert file-like object to a Blob
const blob = new Blob([value.data], { type: value.mimetype });
formData.append(key, blob, value.name); // Use name as filename
} else {
formData.append(key, value); // Append non-file fields
}
}
}
const response = await axios.post(url, formData, {
headers: { ...headers, "Content-Type": "multipart/form-data" },
});
const result = response.data;
if (!result.status) throw response;
return result;
} catch (error: any) {
const { response } = error;
throw {
status: false,
message: response?.data?.error ?? response?.data?.message ?? "Unknown error",
data: null,
};
}
}
static async DownloadFile(url: string, field: any, token?: string) {
try {
const headers: Record<string, string> = {};
if (token) {
headers.Authorization = `Bearer ${token}`;
}
const response = await axios.get(url, { params: field, headers, responseType: "arraybuffer" });
const result = response.data;
return Buffer.from(result);
} catch (error: any) {
const { response } = error;
throw {
status: false,
message: response?.data?.error ?? response?.data?.message ?? "Unknown error",
data: null,
};
}
}
}