Skip to content

Commit

Permalink
Added a check if the requested endpoint is enabled or not [this featu…
Browse files Browse the repository at this point in the history
…re is limited to the token based endpoints]
  • Loading branch information
kyrea committed Jul 10, 2024
1 parent eedd25b commit 96d34a1
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions src/middlewares/authorize.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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,
},
};
Expand Down Expand Up @@ -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<boolean>} - 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.
*
Expand Down

0 comments on commit 96d34a1

Please sign in to comment.