datasquirel/package-shared/functions/backend/api-cred.ts

60 lines
1.8 KiB
TypeScript
Raw Normal View History

2025-01-10 19:10:28 +00:00
import fs from "fs";
import decrypt from "../dsql/decrypt";
import { CheckApiCredentialsFn } from "../../types";
/**
* # Grap API Credentials
*/
const grabApiCred: CheckApiCredentialsFn = ({
key,
database,
table,
user_id,
media,
}) => {
2024-11-06 11:58:41 +00:00
if (!key) return null;
if (!user_id) return null;
2024-11-06 11:58:41 +00:00
2024-11-06 06:26:23 +00:00
try {
const allowedKeysPath = process.env.DSQL_API_KEYS_PATH;
if (!allowedKeysPath)
throw new Error(
"process.env.DSQL_API_KEYS_PATH variable not found"
);
2024-12-06 10:31:24 +00:00
const ApiJSON = decrypt({ encryptedString: key });
2024-11-06 06:26:23 +00:00
/** @type {import("../../types").ApiKeyObject} */
2025-01-10 19:10:28 +00:00
const ApiObject: import("../../types").ApiKeyObject = JSON.parse(
ApiJSON || ""
);
2024-11-06 06:26:23 +00:00
const isApiKeyValid = fs.existsSync(
`${allowedKeysPath}/${ApiObject.sign}`
);
if (String(ApiObject.user_id) !== String(user_id)) return null;
2024-11-06 06:26:23 +00:00
if (!isApiKeyValid) return null;
if (!ApiObject.target_database) return ApiObject;
2024-12-17 17:39:50 +00:00
if (media) return ApiObject;
2024-11-06 06:26:23 +00:00
if (!database && ApiObject.target_database) return null;
const isDatabaseAllowed = ApiObject.target_database
?.split(",")
.includes(String(database));
if (isDatabaseAllowed && !ApiObject.target_table) return ApiObject;
if (isDatabaseAllowed && !table && ApiObject.target_table) return null;
const isTableAllowed = ApiObject.target_table
?.split(",")
.includes(String(table));
if (isTableAllowed) return ApiObject;
return null;
2025-01-10 19:10:28 +00:00
} catch (/** @type {any} */ error: any) {
2024-11-06 06:26:23 +00:00
console.log(`api-cred ERROR: ${error.message}`);
2024-12-17 17:39:50 +00:00
return { error: `api-cred ERROR: ${error.message}` };
2024-11-06 06:26:23 +00:00
}
};
2025-01-10 19:10:28 +00:00
export default grabApiCred;