From 96d34a1369f9b9e9d3b4ae288a7c8ae0c812a2d4 Mon Sep 17 00:00:00 2001 From: kyrea Date: Thu, 11 Jul 2024 00:56:50 +0530 Subject: [PATCH] Added a check if the requested endpoint is enabled or not [this feature is limited to the token based endpoints] --- src/middlewares/authorize.js | 59 ++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/src/middlewares/authorize.js b/src/middlewares/authorize.js index ba6deda..4b7ac2c 100644 --- a/src/middlewares/authorize.js +++ b/src/middlewares/authorize.js @@ -16,6 +16,24 @@ import Stats from '../models/schemas/Stat.js'; */ const authorize = requiredRole => async (req, res, next) => { try { + /** + * Determine the endpoint based on the request URL. + */ + const endpoint = getEndpointFromUrl(req.originalUrl); + /** + * Check if the requested endpoint is disabled. + */ + const isEndpointEnabled = await isEndpointEnabledInStats(endpoint); + + if (!isEndpointEnabled) { + return next( + createError( + 403, + `The endpoint '${endpoint}' is currently disabled. Go to https://discord.gg/yyW389c for support.`, + ), + ); + } + /** * Extract API key from request headers. * @@ -49,6 +67,7 @@ const authorize = requiredRole => async (req, res, next) => { const updateData = { $inc: { req_quota: userData && userData.req_quota > 0 ? -1 : 0, + req_consumed: userData && userData.req_quota > 0 ? 1 : 0, req_count: userData ? 1 : 0, }, }; @@ -113,6 +132,46 @@ const authorize = requiredRole => async (req, res, next) => { } }; +/** + * Helper function to extract endpoint from the request URL. + * + * @param {string} url - The request URL. + * @returns {string} - The extracted endpoint. + */ +const getEndpointFromUrl = url => { + const urlSegments = url.split('/'); + return urlSegments[urlSegments.length - 1]; // Last segment is assumed to be the endpoint +}; + +/** + * Helper function to check if the endpoint is enabled in the Stats collection. + * + * @param {string} endpoint - The endpoint to check. + * @returns {Promise} - Promise resolving to true if enabled, false otherwise. + */ +const isEndpointEnabledInStats = async endpoint => { + try { + // Assuming 'Stats' is the correct model for endpoint settings + const settings = await Stats.findOne(); + + // Handle case where settings are not found + if (!settings) { + return false; + } + + // Check if endpoint exists in settings and isEnabled is defined + if (settings[endpoint] && typeof settings[endpoint].isEnabled !== 'undefined') { + return settings[endpoint].isEnabled; + } + + // Default to true if isEnabled is not defined or endpoint doesn't exist + return true; + } catch (error) { + console.error('Error fetching endpoint settings:', error); + return true; + } +}; + /** * Increment the specified statistics in the system stats collection. *