diff --git a/src/api.ts b/src/api.ts index 9b01e76..793866d 100644 --- a/src/api.ts +++ b/src/api.ts @@ -17,7 +17,6 @@ import stdResp from './endpoints/stdResponses.ts'; // start() returns nothing // start initializes and runs the entire API for the bot const start = async (): Promise => { - const server = Deno.listen({ port: config.api.port }); log(LT.INFO, `HTTP api running at: http://localhost:${config.api.port}/`); // rateLimitTime holds all users with the last time they started a rate limit timer @@ -26,199 +25,176 @@ const start = async (): Promise => { const rateLimitCnt = new Map(); // Catching every request made to the server - for await (const conn of server) { - (async () => { - const httpConn = Deno.serveHttp(conn); - for await (const requestEvent of httpConn) { - const request = requestEvent.request; - log(LT.LOG, `Handling request: ${JSON.stringify(request.headers)} | ${JSON.stringify(request.method)} | ${JSON.stringify(request.url)}`); - // Check if user is authenticated to be using this API - let authenticated = false; - let rateLimited = false; - let updateRateLimitTime = false; - let apiUserid = 0n; - let apiUseridStr = ''; - let apiUserEmail = ''; - let apiUserDelCode = ''; + Deno.serve({ port: config.api.port }, async (request) => { + log(LT.LOG, `Handling request: ${JSON.stringify(request.headers)} | ${JSON.stringify(request.method)} | ${JSON.stringify(request.url)}`); + // Check if user is authenticated to be using this API + let authenticated = false; + let rateLimited = false; + let updateRateLimitTime = false; + let apiUserid = 0n; + let apiUseridStr = ''; + let apiUserEmail = ''; + let apiUserDelCode = ''; - // Check the requests API key - if (request.headers.has('X-Api-Key')) { - // Get the userid and flags for the specific key - const dbApiQuery = await dbClient.query('SELECT userid, email, deleteCode FROM all_keys WHERE apiKey = ? AND active = 1 AND banned = 0', [ - request.headers.get('X-Api-Key'), - ]); + // Check the requests API key + if (request.headers.has('X-Api-Key')) { + // Get the userid and flags for the specific key + const dbApiQuery = await dbClient.query('SELECT userid, email, deleteCode FROM all_keys WHERE apiKey = ? AND active = 1 AND banned = 0', [ + request.headers.get('X-Api-Key'), + ]); - // If only one user returned, is not banned, and is currently active, mark as authenticated - if (dbApiQuery.length === 1) { - apiUserid = BigInt(dbApiQuery[0].userid); - apiUserEmail = dbApiQuery[0].email; - apiUserDelCode = dbApiQuery[0].deleteCode; - authenticated = true; + // If only one user returned, is not banned, and is currently active, mark as authenticated + if (dbApiQuery.length === 1) { + apiUserid = BigInt(dbApiQuery[0].userid); + apiUserEmail = dbApiQuery[0].email; + apiUserDelCode = dbApiQuery[0].deleteCode; + authenticated = true; - // Rate limiting inits - apiUseridStr = apiUserid.toString(); - const apiTimeNow = new Date().getTime(); + // Rate limiting inits + apiUseridStr = apiUserid.toString(); + const apiTimeNow = new Date().getTime(); - // Check if user has sent a request recently - if (rateLimitTime.has(apiUseridStr) && (rateLimitTime.get(apiUseridStr) || 0) + config.api.rateLimitTime > apiTimeNow) { - // Get current count - const currentCnt = rateLimitCnt.get(apiUseridStr) || 0; - if (currentCnt < config.api.rateLimitCnt) { - // Limit not yet exceeded, update count - rateLimitCnt.set(apiUseridStr, currentCnt + 1); - } else { - // Limit exceeded, prevent API use - rateLimited = true; - } - } else { - // Update the maps - updateRateLimitTime = true; - rateLimitCnt.set(apiUseridStr, 1); - } - } - } - - if (!rateLimited) { - // Get path and query as a string - const [urlPath, tempQ] = request.url.split('?'); - const path = urlPath.split('api')[1]; - - // Turn the query into a map (if it exists) - const query = new Map(); - if (tempQ !== undefined) { - tempQ.split('&').forEach((e: string) => { - log(LT.LOG, `Parsing request query ${request} ${e}`); - const [option, params] = e.split('='); - query.set(option.toLowerCase(), params); - }); - } - - if (path) { - if (authenticated) { - // Handle the authenticated request - switch (request.method) { - case 'GET': - switch (path.toLowerCase()) { - case '/key': - case '/key/': - endpoints.get.apiKeyAdmin(requestEvent, query, apiUserid); - break; - case '/channel': - case '/channel/': - endpoints.get.apiChannel(requestEvent, query, apiUserid); - break; - case '/roll': - case '/roll/': - endpoints.get.apiRoll(requestEvent, query, apiUserid); - break; - default: - // Alert API user that they messed up - requestEvent.respondWith(stdResp.NotFound('Auth Get')); - break; - } - break; - case 'POST': - switch (path.toLowerCase()) { - case '/channel/add': - case '/channel/add/': - endpoints.post.apiChannelAdd(requestEvent, query, apiUserid); - break; - default: - // Alert API user that they messed up - requestEvent.respondWith(stdResp.NotFound('Auth Post')); - break; - } - break; - case 'PUT': - switch (path.toLowerCase()) { - case '/key/ban': - case '/key/ban/': - case '/key/unban': - case '/key/unban/': - case '/key/activate': - case '/key/activate/': - case '/key/deactivate': - case '/key/deactivate/': - endpoints.put.apiKeyManage(requestEvent, query, apiUserid, path); - break; - case '/channel/ban': - case '/channel/ban/': - case '/channel/unban': - case '/channel/unban/': - endpoints.put.apiChannelManageBan(requestEvent, query, apiUserid, path); - break; - case '/channel/activate': - case '/channel/activate/': - case '/channel/deactivate': - case '/channel/deactivate/': - endpoints.put.apiChannelManageActive(requestEvent, query, apiUserid, path); - break; - default: - // Alert API user that they messed up - requestEvent.respondWith(stdResp.NotFound('Auth Put')); - break; - } - break; - case 'DELETE': - switch (path.toLowerCase()) { - case '/key/delete': - case '/key/delete/': - endpoints.delete.apiKeyDelete(requestEvent, query, apiUserid, apiUserEmail, apiUserDelCode); - break; - default: - // Alert API user that they messed up - requestEvent.respondWith(stdResp.NotFound('Auth Del')); - break; - } - break; - default: - // Alert API user that they messed up - requestEvent.respondWith(stdResp.MethodNotAllowed('Auth')); - break; - } - - // Update rate limit details - if (updateRateLimitTime) { - const apiTimeNow = new Date().getTime(); - rateLimitTime.set(apiUseridStr, apiTimeNow); - } - } else if (!authenticated) { - // Handle the unathenticated request - switch (request.method) { - case 'GET': - switch (path.toLowerCase()) { - case '/key': - case '/key/': - endpoints.get.apiKey(requestEvent, query); - break; - case '/heatmap.png': - endpoints.get.heatmapPng(requestEvent); - break; - default: - // Alert API user that they messed up - requestEvent.respondWith(stdResp.NotFound('NoAuth Get')); - break; - } - break; - default: - // Alert API user that they messed up - requestEvent.respondWith(stdResp.MethodNotAllowed('NoAuth')); - break; - } - } + // Check if user has sent a request recently + if (rateLimitTime.has(apiUseridStr) && (rateLimitTime.get(apiUseridStr) || 0) + config.api.rateLimitTime > apiTimeNow) { + // Get current count + const currentCnt = rateLimitCnt.get(apiUseridStr) || 0; + if (currentCnt < config.api.rateLimitCnt) { + // Limit not yet exceeded, update count + rateLimitCnt.set(apiUseridStr, currentCnt + 1); } else { - requestEvent.respondWith(stdResp.Forbidden('What are you trying to do?')); + // Limit exceeded, prevent API use + rateLimited = true; } - } else if (authenticated && rateLimited) { - // Alert API user that they are doing this too often - requestEvent.respondWith(stdResp.TooManyRequests('Slow down, servers are expensive and this bot is free to use.')); } else { - // Alert API user that they shouldn't be doing this - requestEvent.respondWith(stdResp.Forbidden('Why are you here?')); + // Update the maps + updateRateLimitTime = true; + rateLimitCnt.set(apiUseridStr, 1); } } - })(); - } + } + + if (!rateLimited) { + // Get path and query as a string + const [urlPath, tempQ] = request.url.split('?'); + const path = urlPath.split('api')[1]; + + // Turn the query into a map (if it exists) + const query = new Map(); + if (tempQ !== undefined) { + tempQ.split('&').forEach((e: string) => { + log(LT.LOG, `Parsing request query ${request} ${e}`); + const [option, params] = e.split('='); + query.set(option.toLowerCase(), params); + }); + } + + if (path) { + if (authenticated) { + // Update rate limit details + if (updateRateLimitTime) { + const apiTimeNow = new Date().getTime(); + rateLimitTime.set(apiUseridStr, apiTimeNow); + } + + // Handle the authenticated request + switch (request.method) { + case 'GET': + switch (path.toLowerCase()) { + case '/key': + case '/key/': + return await endpoints.get.apiKeyAdmin(query, apiUserid); + case '/channel': + case '/channel/': + return await endpoints.get.apiChannel(query, apiUserid); + case '/roll': + case '/roll/': + return await endpoints.get.apiRoll(query, apiUserid, request); + default: + // Alert API user that they messed up + return stdResp.NotFound('Auth Get'); + } + break; + case 'POST': + switch (path.toLowerCase()) { + case '/channel/add': + case '/channel/add/': + return await endpoints.post.apiChannelAdd(query, apiUserid); + default: + // Alert API user that they messed up + return stdResp.NotFound('Auth Post'); + } + break; + case 'PUT': + switch (path.toLowerCase()) { + case '/key/ban': + case '/key/ban/': + case '/key/unban': + case '/key/unban/': + case '/key/activate': + case '/key/activate/': + case '/key/deactivate': + case '/key/deactivate/': + return await endpoints.put.apiKeyManage(query, apiUserid, path); + case '/channel/ban': + case '/channel/ban/': + case '/channel/unban': + case '/channel/unban/': + return await endpoints.put.apiChannelManageBan(query, apiUserid, path); + case '/channel/activate': + case '/channel/activate/': + case '/channel/deactivate': + case '/channel/deactivate/': + return await endpoints.put.apiChannelManageActive(query, apiUserid, path); + default: + // Alert API user that they messed up + return stdResp.NotFound('Auth Put'); + } + break; + case 'DELETE': + switch (path.toLowerCase()) { + case '/key/delete': + case '/key/delete/': + return await endpoints.delete.apiKeyDelete(query, apiUserid, apiUserEmail, apiUserDelCode); + default: + // Alert API user that they messed up + return stdResp.NotFound('Auth Del'); + } + break; + default: + // Alert API user that they messed up + return stdResp.MethodNotAllowed('Auth'); + } + } else if (!authenticated) { + // Handle the unathenticated request + switch (request.method) { + case 'GET': + switch (path.toLowerCase()) { + case '/key': + case '/key/': + return await endpoints.get.apiKey(query); + case '/heatmap.png': + return endpoints.get.heatmapPng(); + default: + // Alert API user that they messed up + return stdResp.NotFound('NoAuth Get'); + } + break; + default: + // Alert API user that they messed up + return stdResp.MethodNotAllowed('NoAuth'); + } + } + } else { + return stdResp.Forbidden('What are you trying to do?'); + } + } else if (authenticated && rateLimited) { + // Alert API user that they are doing this too often + return stdResp.TooManyRequests('Slow down, servers are expensive and this bot is free to use.'); + } else { + // Alert API user that they shouldn't be doing this + return stdResp.Forbidden('Why are you here?'); + } + }); }; export default { start }; diff --git a/src/endpoints/deletes/apiKeyDelete.ts b/src/endpoints/deletes/apiKeyDelete.ts index f7bd307..a02b717 100644 --- a/src/endpoints/deletes/apiKeyDelete.ts +++ b/src/endpoints/deletes/apiKeyDelete.ts @@ -10,13 +10,7 @@ import { generateApiDeleteEmail } from '../../commandUtils.ts'; import utils from '../../utils.ts'; import stdResp from '../stdResponses.ts'; -export const apiKeyDelete = async ( - requestEvent: Deno.RequestEvent, - query: Map, - apiUserid: BigInt, - apiUserEmail: string, - apiUserDelCode: string, -) => { +export const apiKeyDelete = async (query: Map, apiUserid: bigint, apiUserEmail: string, apiUserDelCode: string): Promise => { if (query.has('user') && (query.get('user') || '').length > 0 && query.has('email') && (query.get('email') || '').length > 0) { if (apiUserid === BigInt(query.get('user') || '0') && apiUserEmail === query.get('email')) { if (query.has('code') && (query.get('code') || '').length > 0) { @@ -26,28 +20,25 @@ export const apiKeyDelete = async ( await dbClient.execute('DELETE FROM allowed_channels WHERE userid = ?', [apiUserid]).catch((e) => { utils.commonLoggers.dbError('apiKeyDelete.ts:25', 'insert into', e); - requestEvent.respondWith(stdResp.InternalServerError('Channel Clean Failed.')); erroredOut = true; }); if (erroredOut) { - return; + return stdResp.InternalServerError('Channel Clean Failed.'); } await dbClient.execute('DELETE FROM all_keys WHERE userid = ?', [apiUserid]).catch((e) => { utils.commonLoggers.dbError('apiKeyDelete.ts:34', 'delete from', e); - requestEvent.respondWith(stdResp.InternalServerError('Delete Key Failed.')); erroredOut = true; }); if (erroredOut) { - return; + return stdResp.InternalServerError('Delete Key Failed.'); } else { // Send OK as response to indicate key deletion was successful - requestEvent.respondWith(stdResp.OK('You have been removed from the DB, Goodbye.')); - return; + return stdResp.OK('You have been removed from the DB, Goodbye.'); } } else { // Alert API user that they shouldn't be doing this - requestEvent.respondWith(stdResp.Forbidden('Invalid Delete Code.')); + return stdResp.Forbidden('Invalid Delete Code.'); } } else { // User does not have their delete code yet, so we need to generate one and email it to them @@ -58,32 +49,29 @@ export const apiKeyDelete = async ( // Execute the DB modification await dbClient.execute('UPDATE all_keys SET deleteCode = ? WHERE userid = ?', [deleteCode, apiUserid]).catch((e) => { utils.commonLoggers.dbError('apiKeyDelete.ts:57', 'update', e); - requestEvent.respondWith(stdResp.InternalServerError('Delete Code Failed')); erroredOut = true; }); if (erroredOut) { - return; + return stdResp.InternalServerError('Delete Code Failed'); } // "Send" the email await sendMessage(config.api.email, generateApiDeleteEmail(apiUserEmail, deleteCode)).catch(() => { - requestEvent.respondWith(stdResp.InternalServerError('Failed to send email.')); erroredOut = true; }); if (erroredOut) { - return; + return stdResp.InternalServerError('Failed to send email.'); } else { // Send API key as response - requestEvent.respondWith(stdResp.FailedDependency('Please look for an email containing a Delete Key and run this query again with said key.')); - return; + return stdResp.FailedDependency('Please look for an email containing a Delete Key and run this query again with said key.'); } } } else { // Alert API user that they shouldn't be doing this - requestEvent.respondWith(stdResp.Forbidden('You can only delete your own key.')); + return stdResp.Forbidden('You can only delete your own key.'); } } else { // Alert API user that they messed up - requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams)); + return stdResp.BadRequest(stdResp.Strings.missingParams); } }; diff --git a/src/endpoints/gets/apiChannel.ts b/src/endpoints/gets/apiChannel.ts index dd3a885..ff9d362 100644 --- a/src/endpoints/gets/apiChannel.ts +++ b/src/endpoints/gets/apiChannel.ts @@ -2,7 +2,7 @@ import dbClient from '../../db/client.ts'; import stdResp from '../stdResponses.ts'; import utils from '../../utils.ts'; -export const apiChannel = async (requestEvent: Deno.RequestEvent, query: Map, apiUserid: BigInt) => { +export const apiChannel = async (query: Map, apiUserid: bigint): Promise => { if (query.has('user') && (query.get('user') || '').length > 0) { if (apiUserid === BigInt(query.get('user') || '0')) { // Flag to see if there is an error inside the catch @@ -11,25 +11,23 @@ export const apiChannel = async (requestEvent: Deno.RequestEvent, query: Map { utils.commonLoggers.dbError('apiChannel.ts', 'query', e); - requestEvent.respondWith(stdResp.InternalServerError('Failed to get channels.')); erroredOut = true; }); if (erroredOut) { - return; + return stdResp.InternalServerError('Failed to get channels.'); } else { // Customized strinification to handle BigInts correctly const returnChannels = JSON.stringify(dbAllowedChannelQuery, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)); // Send channel list as response - requestEvent.respondWith(stdResp.OK(returnChannels)); - return; + return stdResp.OK(returnChannels); } } else { // Alert API user that they shouldn't be doing this - requestEvent.respondWith(stdResp.Forbidden('You can only view your own channels.')); + return stdResp.Forbidden('You can only view your own channels.'); } } else { // Alert API user that they messed up - requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams)); + return stdResp.BadRequest(stdResp.Strings.missingParams); } }; diff --git a/src/endpoints/gets/apiKey.ts b/src/endpoints/gets/apiKey.ts index d3de715..ae8159d 100644 --- a/src/endpoints/gets/apiKey.ts +++ b/src/endpoints/gets/apiKey.ts @@ -10,7 +10,7 @@ import { generateApiKeyEmail } from '../../commandUtils.ts'; import utils from '../../utils.ts'; import stdResp from '../stdResponses.ts'; -export const apiKey = async (requestEvent: Deno.RequestEvent, query: Map) => { +export const apiKey = async (query: Map): Promise => { if (query.has('user') && (query.get('user') || '').length > 0 && query.has('email') && (query.get('email') || '').length > 0) { // Generate new secure key const newKey = await nanoid(25); @@ -23,30 +23,27 @@ export const apiKey = async (requestEvent: Deno.RequestEvent, query: Map { utils.commonLoggers.dbError('apiKey.ts:27', 'insert into', e); - requestEvent.respondWith(stdResp.InternalServerError('Failed to store key.')); erroredOut = true; }); // Exit this case now if catch errored if (erroredOut) { - return; + return stdResp.InternalServerError('Failed to store key.'); } // "Send" the email await sendMessage(config.api.email, generateApiKeyEmail(query.get('email') || 'no email', newKey)).catch(() => { - requestEvent.respondWith(stdResp.InternalServerError('Failed to send email.')); erroredOut = true; }); if (erroredOut) { - return; + return stdResp.InternalServerError('Failed to send email.'); } else { // Send basic OK to indicate key has been sent - requestEvent.respondWith(stdResp.OK('Email Sent.')); - return; + return stdResp.OK('Email Sent.'); } } else { // Alert API user that they messed up - requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams)); + return stdResp.BadRequest(stdResp.Strings.missingParams); } }; diff --git a/src/endpoints/gets/apiKeyAdmin.ts b/src/endpoints/gets/apiKeyAdmin.ts index 6f0858e..dd6fc1e 100644 --- a/src/endpoints/gets/apiKeyAdmin.ts +++ b/src/endpoints/gets/apiKeyAdmin.ts @@ -7,7 +7,7 @@ import { import stdResp from '../stdResponses.ts'; import utils from '../../utils.ts'; -export const apiKeyAdmin = async (requestEvent: Deno.RequestEvent, query: Map, apiUserid: BigInt) => { +export const apiKeyAdmin = async (query: Map, apiUserid: bigint): Promise => { if (query.has('user') && (query.get('user') || '').length > 0 && query.has('a') && (query.get('a') || '').length > 0) { if (apiUserid === config.api.admin && apiUserid === BigInt(query.get('a') || '0')) { // Generate new secure key @@ -19,24 +19,22 @@ export const apiKeyAdmin = async (requestEvent: Deno.RequestEvent, query: Map { utils.commonLoggers.dbError('apiKeyAdmin.ts:24', 'insert into', e); - requestEvent.respondWith(stdResp.InternalServerError('Failed to store key.')); erroredOut = true; }); // Exit this case now if catch errored if (erroredOut) { - return; + return stdResp.InternalServerError('Failed to store key.'); } else { // Send API key as response - requestEvent.respondWith(stdResp.OK(JSON.stringify({ key: newKey, userid: query.get('user') }))); - return; + return stdResp.OK(JSON.stringify({ key: newKey, userid: query.get('user') })); } } else { // Only allow the db admin to use this API - requestEvent.respondWith(stdResp.Forbidden(stdResp.Strings.restricted)); + return stdResp.Forbidden(stdResp.Strings.restricted); } } else { // Alert API user that they messed up - requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams)); + return stdResp.BadRequest(stdResp.Strings.missingParams); } }; diff --git a/src/endpoints/gets/apiRoll.ts b/src/endpoints/gets/apiRoll.ts index ced6844..2d501cd 100644 --- a/src/endpoints/gets/apiRoll.ts +++ b/src/endpoints/gets/apiRoll.ts @@ -1,5 +1,6 @@ import config from '../../../config.ts'; import dbClient from '../../db/client.ts'; +import { queries } from '../../db/common.ts'; import { // Discordeno deps cache, @@ -14,7 +15,7 @@ import stdResp from '../stdResponses.ts'; const apiWarning = `The following roll was conducted using my built in API. If someone in this channel did not request this roll, please report API abuse here: <${config.api.supportURL}>`; -export const apiRoll = async (requestEvent: Deno.RequestEvent, query: Map, apiUserid: BigInt) => { +export const apiRoll = async (query: Map, apiUserid: bigint, request: Request): Promise => { // Make sure query contains all the needed parts if ( query.has('rollstr') && @@ -26,8 +27,7 @@ export const apiRoll = async (requestEvent: Deno.RequestEvent, query: Map utils.commonLoggers.dbError('apiRoll.ts:65', 'insert', e)); - return; + + // Alert API user that they messed up + return stdResp.BadRequest('rollCmd is required.'); } if (query.has('o') && query.get('o')?.toLowerCase() !== 'd' && query.get('o')?.toLowerCase() !== 'a') { - // Alert API user that they messed up - requestEvent.respondWith(stdResp.BadRequest("Order must be set to 'a' or 'd'.")); - // Always log API rolls for abuse detection dbClient .execute(queries.insertRollLogCmd(1, 1), [originalCommand, 'BadOrder', null]) .catch((e) => utils.commonLoggers.dbError('apiRoll.ts:66', 'insert', e)); - return; + + // Alert API user that they messed up + return stdResp.BadRequest("Order must be set to 'a' or 'd'."); } // Clip off the leading prefix. API calls must be formatted with a prefix at the start to match how commands are sent in Discord @@ -106,7 +104,7 @@ export const apiRoll = async (requestEvent: Deno.RequestEvent, query: Map { apiRoll: true, - api: { requestEvent, channelId: BigInt(query.get('channel') || '0'), userId: BigInt(query.get('user') || '') }, + api: { request, channelId: BigInt(query.get('channel') || '0'), userId: BigInt(query.get('user') || '') }, rollCmd, modifiers, originalCommand, @@ -115,18 +113,16 @@ export const apiRoll = async (requestEvent: Deno.RequestEvent, query: Map { +export const heatmapPng = (): Response => { const file = Deno.readFileSync('./src/endpoints/gets/heatmap.png'); const imageHeaders = new Headers(); imageHeaders.append('Content-Type', 'image/png'); // Send basic OK to indicate key has been sent - requestEvent.respondWith( - new Response(file, { - status: STATUS_CODE.OK, - statusText: STATUS_TEXT[STATUS_CODE.OK], - headers: imageHeaders, - }), - ); + return new Response(file, { + status: STATUS_CODE.OK, + statusText: STATUS_TEXT[STATUS_CODE.OK], + headers: imageHeaders, + }); }; diff --git a/src/endpoints/posts/apiChannelAdd.ts b/src/endpoints/posts/apiChannelAdd.ts index c90ad42..3a833c7 100644 --- a/src/endpoints/posts/apiChannelAdd.ts +++ b/src/endpoints/posts/apiChannelAdd.ts @@ -2,7 +2,7 @@ import dbClient from '../../db/client.ts'; import stdResp from '../stdResponses.ts'; import utils from '../../utils.ts'; -export const apiChannelAdd = async (requestEvent: Deno.RequestEvent, query: Map, apiUserid: BigInt) => { +export const apiChannelAdd = async (query: Map, apiUserid: bigint): Promise => { if (query.has('user') && (query.get('user') || '').length > 0 && query.has('channel') && (query.get('channel') || '').length > 0) { if (apiUserid === BigInt(query.get('user') || '0')) { // Flag to see if there is an error inside the catch @@ -11,24 +11,22 @@ export const apiChannelAdd = async (requestEvent: Deno.RequestEvent, query: Map< // Insert new user/channel pair into the db await dbClient.execute('INSERT INTO allowed_channels(userid,channelid) values(?,?)', [apiUserid, BigInt(query.get('channel') || '0')]).catch((e) => { utils.commonLoggers.dbError('apiChannelAdd.ts:17', 'insert into', e); - requestEvent.respondWith(stdResp.InternalServerError('Failed to store channel.')); erroredOut = true; }); // Exit this case now if catch errored if (erroredOut) { - return; + return stdResp.InternalServerError('Failed to store channel.'); } else { // Send OK to indicate modification was successful - requestEvent.respondWith(stdResp.OK('Successfully added channel.')); - return; + return stdResp.OK('Successfully added channel.'); } } else { // Alert API user that they shouldn't be doing this - requestEvent.respondWith(stdResp.Forbidden('You can only add channels to your key.')); + return stdResp.Forbidden('You can only add channels to your key.'); } } else { // Alert API user that they messed up - requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams)); + return stdResp.BadRequest(stdResp.Strings.missingParams); } }; diff --git a/src/endpoints/puts/apiChannelManageActive.ts b/src/endpoints/puts/apiChannelManageActive.ts index e04c02e..fe57c20 100644 --- a/src/endpoints/puts/apiChannelManageActive.ts +++ b/src/endpoints/puts/apiChannelManageActive.ts @@ -2,7 +2,7 @@ import dbClient from '../../db/client.ts'; import stdResp from '../stdResponses.ts'; import utils from '../../utils.ts'; -export const apiChannelManageActive = async (requestEvent: Deno.RequestEvent, query: Map, apiUserid: BigInt, path: string) => { +export const apiChannelManageActive = async (query: Map, apiUserid: bigint, path: string): Promise => { if (query.has('channel') && (query.get('channel') || '').length > 0 && query.has('user') && (query.get('user') || '').length > 0) { if (apiUserid === BigInt(query.get('user') || '0')) { // Flag to see if there is an error inside the catch @@ -21,24 +21,22 @@ export const apiChannelManageActive = async (requestEvent: Deno.RequestEvent, qu .execute('UPDATE allowed_channels SET active = ? WHERE userid = ? AND channelid = ?', [value, apiUserid, BigInt(query.get('channel') || '0')]) .catch((e) => { utils.commonLoggers.dbError('apiChannelManageActive.ts:25', 'update', e); - requestEvent.respondWith(stdResp.InternalServerError('Failed to update channel.')); erroredOut = true; }); // Exit this case now if catch errored if (erroredOut) { - return; + return stdResp.InternalServerError('Failed to update channel.'); } else { // Send API key as response - requestEvent.respondWith(stdResp.OK(`Successfully active to ${value}.`)); - return; + return stdResp.OK(`Successfully active to ${value}.`); } } else { // Alert API user that they shouldn't be doing this - requestEvent.respondWith(stdResp.Forbidden('You can only manage your own channels.')); + return stdResp.Forbidden('You can only manage your own channels.'); } } else { // Alert API user that they messed up - requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams)); + return stdResp.BadRequest(stdResp.Strings.missingParams); } }; diff --git a/src/endpoints/puts/apiChannelManageBan.ts b/src/endpoints/puts/apiChannelManageBan.ts index 06978c3..d66c147 100644 --- a/src/endpoints/puts/apiChannelManageBan.ts +++ b/src/endpoints/puts/apiChannelManageBan.ts @@ -3,7 +3,7 @@ import dbClient from '../../db/client.ts'; import stdResp from '../stdResponses.ts'; import utils from '../../utils.ts'; -export const apiChannelManageBan = async (requestEvent: Deno.RequestEvent, query: Map, apiUserid: BigInt, path: string) => { +export const apiChannelManageBan = async (query: Map, apiUserid: bigint, path: string): Promise => { if ( query.has('a') && (query.get('a') || '').length > 0 && @@ -29,24 +29,22 @@ export const apiChannelManageBan = async (requestEvent: Deno.RequestEvent, query .execute('UPDATE allowed_channels SET banned = ? WHERE userid = ? AND channelid = ?', [value, apiUserid, BigInt(query.get('channel') || '0')]) .catch((e) => { utils.commonLoggers.dbError('apiChannelManageBan.ts:28', 'update', e); - requestEvent.respondWith(stdResp.InternalServerError('Failed to update channel.')); erroredOut = true; }); // Exit this case now if catch errored if (erroredOut) { - return; + return stdResp.InternalServerError('Failed to update channel.'); } else { // Send OK to indicate modification was successful - requestEvent.respondWith(stdResp.OK(`Successfully active to ${value}.`)); - return; + return stdResp.OK(`Successfully active to ${value}.`); } } else { // Alert API user that they shouldn't be doing this - requestEvent.respondWith(stdResp.Forbidden(stdResp.Strings.restricted)); + return stdResp.Forbidden(stdResp.Strings.restricted); } } else { // Alert API user that they messed up - requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams)); + return stdResp.BadRequest(stdResp.Strings.missingParams); } }; diff --git a/src/endpoints/puts/apiKeyManage.ts b/src/endpoints/puts/apiKeyManage.ts index 75d5fb7..45bde9d 100644 --- a/src/endpoints/puts/apiKeyManage.ts +++ b/src/endpoints/puts/apiKeyManage.ts @@ -3,7 +3,7 @@ import dbClient from '../../db/client.ts'; import stdResp from '../stdResponses.ts'; import utils from '../../utils.ts'; -export const apiKeyManage = async (requestEvent: Deno.RequestEvent, query: Map, apiUserid: BigInt, path: string) => { +export const apiKeyManage = async (query: Map, apiUserid: bigint, path: string): Promise => { if (query.has('a') && (query.get('a') || '').length > 0 && query.has('user') && (query.get('user') || '').length > 0) { if (apiUserid === config.api.admin && apiUserid === BigInt(query.get('a') || '0')) { // Flag to see if there is an error inside the catch @@ -28,24 +28,22 @@ export const apiKeyManage = async (requestEvent: Deno.RequestEvent, query: Map { utils.commonLoggers.dbError('apiKeyManage.ts', 'update', e); - requestEvent.respondWith(stdResp.InternalServerError(`Failed to ${key} to ${value}.`)); erroredOut = true; }); // Exit this case now if catch errored if (erroredOut) { - return; + return stdResp.InternalServerError(`Failed to ${key} to ${value}.`); } else { // Send OK as response to indicate modification was successful - requestEvent.respondWith(stdResp.OK(`Successfully ${key} to ${value}.`)); - return; + return stdResp.OK(`Successfully ${key} to ${value}.`); } } else { // Alert API user that they shouldn't be doing this - requestEvent.respondWith(stdResp.Forbidden('You can only manage your own key.')); + return stdResp.Forbidden('You can only manage your own key.'); } } else { // Alert API user that they messed up - requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams)); + return stdResp.BadRequest(stdResp.Strings.missingParams); } }; diff --git a/src/mod.d.ts b/src/mod.d.ts index 4af00ba..4bfda5a 100644 --- a/src/mod.d.ts +++ b/src/mod.d.ts @@ -29,7 +29,7 @@ export type RollModifiers = { export type QueuedRoll = { apiRoll: boolean; api: { - requestEvent: Deno.RequestEvent; + request: Request; channelId: bigint; userId: bigint; };