dsql-admin/dsql-app/package-shared/functions/backend/api-cred.js

49 lines
1.6 KiB
JavaScript
Raw Normal View History

2024-11-05 11:12:42 +00:00
// @ts-check
const fs = require("fs");
2024-12-06 13:24:26 +00:00
const decrypt = require("../dsql/decrypt");
2024-11-05 11:12:42 +00:00
2024-11-06 12:06:51 +00:00
/** @type {import("../../types").CheckApiCredentialsFn} */
2024-11-27 11:23:44 +00:00
const grabApiCred = ({ key, database, table, user_id }) => {
2024-11-06 12:06:51 +00:00
if (!key) return null;
2024-11-27 11:23:44 +00:00
if (!user_id) return null;
2024-11-06 11:13:31 +00:00
2024-11-05 11:12:42 +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 13:24:26 +00:00
const ApiJSON = decrypt({ encryptedString: key });
2024-11-06 12:06:51 +00:00
/** @type {import("../../types").ApiKeyObject} */
2024-11-05 11:12:42 +00:00
const ApiObject = JSON.parse(ApiJSON || "");
const isApiKeyValid = fs.existsSync(
`${allowedKeysPath}/${ApiObject.sign}`
);
2024-11-27 11:23:44 +00:00
if (String(ApiObject.user_id) !== String(user_id)) return null;
2024-11-05 11:12:42 +00:00
if (!isApiKeyValid) return null;
if (!ApiObject.target_database) return ApiObject;
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;
2024-11-05 14:18:40 +00:00
} catch (/** @type {any} */ error) {
console.log(`api-cred ERROR: ${error.message}`);
2024-11-05 11:12:42 +00:00
return null;
}
};
module.exports = grabApiCred;