1
1
mirror of https://github.com/Burn-E99/TheArtificer.git synced 2026-06-04 09:03:50 -04:00

update db structure to let init work correctly

This commit is contained in:
Ean Milligan
2025-04-26 13:22:45 -04:00
parent ef08cd779a
commit 76e007e2e4
44 changed files with 2543 additions and 2280 deletions

View File

@@ -1,83 +1,89 @@
import config from '../../../config.ts';
import { dbClient } from '../../db.ts';
import dbClient from '../../db/client.ts';
import {
// nanoid deps
nanoid,
// Discordeno deps
sendMessage,
// nanoid deps
nanoid,
// Discordeno deps
sendMessage,
} from '../../../deps.ts';
import { generateApiDeleteEmail } from '../../commandUtils.ts';
import utils from '../../utils.ts';
import stdResp from '../stdResponses.ts';
export const apiKeyDelete = async (requestEvent: Deno.RequestEvent, query: Map<string, string>, apiUserid: BigInt, apiUserEmail: string, apiUserDelCode: string) => {
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)) {
if ((query.get('code') || '') === apiUserDelCode) {
// User has recieved their delete code and we need to delete the account now
let erroredOut = false;
export const apiKeyDelete = async (
requestEvent: Deno.RequestEvent,
query: Map<string, string>,
apiUserid: BigInt,
apiUserEmail: string,
apiUserDelCode: string
) => {
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) {
if ((query.get('code') || '') === apiUserDelCode) {
// User has recieved their delete code and we need to delete the account now
let erroredOut = false;
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;
}
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;
}
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;
} else {
// Send OK as response to indicate key deletion was successful
requestEvent.respondWith(stdResp.OK('You have been removed from the DB, Goodbye.'));
return;
}
} else {
// Alert API user that they shouldn't be doing this
requestEvent.respondWith(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
const deleteCode = await nanoid(10);
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;
} else {
// Send OK as response to indicate key deletion was successful
requestEvent.respondWith(stdResp.OK('You have been removed from the DB, Goodbye.'));
return;
}
} else {
// Alert API user that they shouldn't be doing this
requestEvent.respondWith(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
const deleteCode = await nanoid(10);
let erroredOut = false;
let erroredOut = false;
// 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;
}
// 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;
}
// "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;
} 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;
}
}
} else {
// Alert API user that they shouldn't be doing this
requestEvent.respondWith(stdResp.Forbidden('You can only delete your own key.'));
}
} else {
// Alert API user that they messed up
requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams));
}
// "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;
} 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;
}
}
} else {
// Alert API user that they shouldn't be doing this
requestEvent.respondWith(stdResp.Forbidden('You can only delete your own key.'));
}
} else {
// Alert API user that they messed up
requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams));
}
};

View File

@@ -1,35 +1,35 @@
import { dbClient } from '../../db.ts';
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<string, string>, apiUserid: BigInt) => {
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
let erroredOut = false;
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
let erroredOut = false;
// Get all channels userid has authorized
const dbAllowedChannelQuery = await dbClient.query('SELECT * FROM allowed_channels WHERE userid = ?', [apiUserid]).catch((e) => {
utils.commonLoggers.dbError('apiChannel.ts', 'query', e);
requestEvent.respondWith(stdResp.InternalServerError('Failed to get channels.'));
erroredOut = true;
});
// Get all channels userid has authorized
const dbAllowedChannelQuery = await dbClient.query('SELECT * FROM allowed_channels WHERE userid = ?', [apiUserid]).catch((e) => {
utils.commonLoggers.dbError('apiChannel.ts', 'query', e);
requestEvent.respondWith(stdResp.InternalServerError('Failed to get channels.'));
erroredOut = true;
});
if (erroredOut) {
return;
} 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;
}
} else {
// Alert API user that they shouldn't be doing this
requestEvent.respondWith(stdResp.Forbidden('You can only view your own channels.'));
}
} else {
// Alert API user that they messed up
requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams));
}
if (erroredOut) {
return;
} 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;
}
} else {
// Alert API user that they shouldn't be doing this
requestEvent.respondWith(stdResp.Forbidden('You can only view your own channels.'));
}
} else {
// Alert API user that they messed up
requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams));
}
};

View File

@@ -1,52 +1,52 @@
import config from '../../../config.ts';
import { dbClient } from '../../db.ts';
import dbClient from '../../db/client.ts';
import {
// nanoid deps
nanoid,
// Discordeno deps
sendMessage,
// nanoid deps
nanoid,
// Discordeno deps
sendMessage,
} from '../../../deps.ts';
import { generateApiKeyEmail } from '../../commandUtils.ts';
import utils from '../../utils.ts';
import stdResp from '../stdResponses.ts';
export const apiKey = async (requestEvent: Deno.RequestEvent, query: Map<string, string>) => {
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);
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);
// Flag to see if there is an error inside the catch
let erroredOut = false;
// Flag to see if there is an error inside the catch
let erroredOut = false;
// Insert new key/user pair into the db
await dbClient.execute('INSERT INTO all_keys(userid,apiKey,email) values(?,?,?)', [BigInt(query.get('user') || '0'), newKey, (query.get('email') || '').toLowerCase()]).catch(
(e) => {
utils.commonLoggers.dbError('apiKey.ts:27', 'insert into', e);
requestEvent.respondWith(stdResp.InternalServerError('Failed to store key.'));
erroredOut = true;
},
);
// Insert new key/user pair into the db
await dbClient
.execute('INSERT INTO all_keys(userid,apiKey,email) values(?,?,?)', [BigInt(query.get('user') || '0'), newKey, (query.get('email') || '').toLowerCase()])
.catch((e) => {
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;
}
// Exit this case now if catch errored
if (erroredOut) {
return;
}
// "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;
});
// "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;
} else {
// Send basic OK to indicate key has been sent
requestEvent.respondWith(stdResp.OK('Email Sent.'));
return;
}
} else {
// Alert API user that they messed up
requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams));
}
if (erroredOut) {
return;
} else {
// Send basic OK to indicate key has been sent
requestEvent.respondWith(stdResp.OK('Email Sent.'));
return;
}
} else {
// Alert API user that they messed up
requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams));
}
};

View File

@@ -1,42 +1,42 @@
import config from '../../../config.ts';
import { dbClient } from '../../db.ts';
import dbClient from '../../db/client.ts';
import {
// nanoid deps
nanoid,
// nanoid deps
nanoid,
} from '../../../deps.ts';
import stdResp from '../stdResponses.ts';
import utils from '../../utils.ts';
export const apiKeyAdmin = async (requestEvent: Deno.RequestEvent, query: Map<string, string>, apiUserid: BigInt) => {
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
const newKey = await nanoid(25);
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
const newKey = await nanoid(25);
// Flag to see if there is an error inside the catch
let erroredOut = false;
// Flag to see if there is an error inside the catch
let erroredOut = false;
// Insert new key/user pair into the db
await dbClient.execute('INSERT INTO all_keys(userid,apiKey) values(?,?)', [apiUserid, newKey]).catch((e) => {
utils.commonLoggers.dbError('apiKeyAdmin.ts:24', 'insert into', e);
requestEvent.respondWith(stdResp.InternalServerError('Failed to store key.'));
erroredOut = true;
});
// Insert new key/user pair into the db
await dbClient.execute('INSERT INTO all_keys(userid,apiKey) values(?,?)', [apiUserid, newKey]).catch((e) => {
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;
} else {
// Send API key as response
requestEvent.respondWith(stdResp.OK(JSON.stringify({ 'key': newKey, 'userid': query.get('user') })));
return;
}
} else {
// Only allow the db admin to use this API
requestEvent.respondWith(stdResp.Forbidden(stdResp.Strings.restricted));
}
} else {
// Alert API user that they messed up
requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams));
}
// Exit this case now if catch errored
if (erroredOut) {
return;
} else {
// Send API key as response
requestEvent.respondWith(stdResp.OK(JSON.stringify({ key: newKey, userid: query.get('user') })));
return;
}
} else {
// Only allow the db admin to use this API
requestEvent.respondWith(stdResp.Forbidden(stdResp.Strings.restricted));
}
} else {
// Alert API user that they messed up
requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams));
}
};

View File

@@ -1,11 +1,11 @@
import config from '../../../config.ts';
import { dbClient, queries } from '../../db.ts';
import dbClient from '../../db/client.ts';
import {
// Discordeno deps
cache,
// Log4Deno deps
log,
LT,
// Discordeno deps
cache,
// Log4Deno deps
log,
LT,
} from '../../../deps.ts';
import { QueuedRoll, RollModifiers } from '../../mod.d.ts';
import utils from '../../utils.ts';
@@ -15,107 +15,116 @@ 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<string, string>, apiUserid: BigInt) => {
// Make sure query contains all the needed parts
if (
(query.has('rollstr') && ((query.get('rollstr') || '').length > 0)) && (query.has('channel') && ((query.get('channel') || '').length > 0)) &&
(query.has('user') && ((query.get('user') || '').length > 0))
) {
if (query.has('n') && query.has('m')) {
// Alert API user that they shouldn't be doing this
requestEvent.respondWith(stdResp.BadRequest('Cannot have both \'n\' and \'m\'.'));
return;
}
// Make sure query contains all the needed parts
if (
query.has('rollstr') &&
(query.get('rollstr') || '').length > 0 &&
query.has('channel') &&
(query.get('channel') || '').length > 0 &&
query.has('user') &&
(query.get('user') || '').length > 0
) {
if (query.has('n') && query.has('m')) {
// Alert API user that they shouldn't be doing this
requestEvent.respondWith(stdResp.BadRequest("Cannot have both 'n' and 'm'."));
return;
}
// Check if user is authenticated to use this endpoint
let authorized = false;
let hideWarn = false;
// Check if user is authenticated to use this endpoint
let authorized = false;
let hideWarn = false;
// Check if the db has the requested userid/channelid combo, and that the requested userid matches the userid linked with the api key
const dbChannelQuery = await dbClient.query('SELECT active, banned FROM allowed_channels WHERE userid = ? AND channelid = ?', [apiUserid, BigInt(query.get('channel') || '0')]);
if (dbChannelQuery.length === 1 && (apiUserid === BigInt(query.get('user') || '0')) && dbChannelQuery[0].active && !dbChannelQuery[0].banned) {
// Get the guild from the channel and make sure user is in said guild
const guild = cache.channels.get(BigInt(query.get('channel') || ''))?.guild;
if (guild && guild.members.get(BigInt(query.get('user') || ''))?.id) {
const dbGuildQuery = await dbClient.query('SELECT active, banned, hidewarn FROM allowed_guilds WHERE guildid = ? AND channelid = ?', [
guild.id,
BigInt(query.get('channel') || '0'),
]);
// Check if the db has the requested userid/channelid combo, and that the requested userid matches the userid linked with the api key
const dbChannelQuery = await dbClient.query('SELECT active, banned FROM allowed_channels WHERE userid = ? AND channelid = ?', [
apiUserid,
BigInt(query.get('channel') || '0'),
]);
if (dbChannelQuery.length === 1 && apiUserid === BigInt(query.get('user') || '0') && dbChannelQuery[0].active && !dbChannelQuery[0].banned) {
// Get the guild from the channel and make sure user is in said guild
const guild = cache.channels.get(BigInt(query.get('channel') || ''))?.guild;
if (guild && guild.members.get(BigInt(query.get('user') || ''))?.id) {
const dbGuildQuery = await dbClient.query('SELECT active, banned, hidewarn FROM allowed_guilds WHERE guildid = ? AND channelid = ?', [
guild.id,
BigInt(query.get('channel') || '0'),
]);
// Make sure guild allows API rolls
if (dbGuildQuery.length === 1 && dbGuildQuery[0].active && !dbGuildQuery[0].banned) {
authorized = true;
hideWarn = dbGuildQuery[0].hidewarn;
}
}
}
// Make sure guild allows API rolls
if (dbGuildQuery.length === 1 && dbGuildQuery[0].active && !dbGuildQuery[0].banned) {
authorized = true;
hideWarn = dbGuildQuery[0].hidewarn;
}
}
}
if (authorized) {
// Rest of this command is in a try-catch to protect all sends/edits from erroring out
try {
// Make sure rollCmd is not undefined
let rollCmd = query.get('rollstr') || '';
const originalCommand = query.get('rollstr');
if (authorized) {
// Rest of this command is in a try-catch to protect all sends/edits from erroring out
try {
// Make sure rollCmd is not undefined
let rollCmd = query.get('rollstr') || '';
const originalCommand = query.get('rollstr');
if (rollCmd.length === 0) {
// Alert API user that they messed up
requestEvent.respondWith(stdResp.BadRequest('rollCmd is required.'));
if (rollCmd.length === 0) {
// Alert API user that they messed up
requestEvent.respondWith(stdResp.BadRequest('rollCmd is required.'));
// Always log API rolls for abuse detection
dbClient.execute(queries.insertRollLogCmd(1, 1), [originalCommand, 'EmptyInput', null]).catch((e) => utils.commonLoggers.dbError('apiRoll.ts:65', 'insert', e));
return;
}
// Always log API rolls for abuse detection
dbClient
.execute(queries.insertRollLogCmd(1, 1), [originalCommand, 'EmptyInput', null])
.catch((e) => utils.commonLoggers.dbError('apiRoll.ts:65', 'insert', e));
return;
}
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\'.'));
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;
}
// 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;
}
// Clip off the leading prefix. API calls must be formatted with a prefix at the start to match how commands are sent in Discord
rollCmd = rollCmd.substring(rollCmd.indexOf(config.prefix) + 2).replace(/%20/g, ' ');
// Clip off the leading prefix. API calls must be formatted with a prefix at the start to match how commands are sent in Discord
rollCmd = rollCmd.substring(rollCmd.indexOf(config.prefix) + 2).replace(/%20/g, ' ');
const modifiers: RollModifiers = {
noDetails: query.has('nd'),
superNoDetails: query.has('snd'),
spoiler: query.has('s') ? '||' : '',
maxRoll: query.has('m'),
nominalRoll: query.has('n'),
gmRoll: query.has('gms'),
gms: query.has('gms') ? (query.get('gms') || '').split(',') : [],
order: query.has('o') ? (query.get('o')?.toLowerCase() || '') : '',
count: query.has('c'),
valid: true,
apiWarn: hideWarn ? '' : apiWarning,
};
const modifiers: RollModifiers = {
noDetails: query.has('nd'),
superNoDetails: query.has('snd'),
spoiler: query.has('s') ? '||' : '',
maxRoll: query.has('m'),
nominalRoll: query.has('n'),
gmRoll: query.has('gms'),
gms: query.has('gms') ? (query.get('gms') || '').split(',') : [],
order: query.has('o') ? query.get('o')?.toLowerCase() || '' : '',
count: query.has('c'),
valid: true,
apiWarn: hideWarn ? '' : apiWarning,
};
// Parse the roll and get the return text
await queueRoll(
<QueuedRoll> {
apiRoll: true,
api: { requestEvent, channelId: BigInt(query.get('channel') || '0'), userId: BigInt(query.get('user') || '') },
rollCmd,
modifiers,
originalCommand,
},
);
} catch (err) {
// Handle any errors we missed
log(LT.ERROR, `Unhandled Error: ${JSON.stringify(err)}`);
requestEvent.respondWith(stdResp.InternalServerError('Something went wrong.'));
}
} else {
// Alert API user that they messed up
requestEvent.respondWith(
stdResp.Forbidden(
`Verify you are a member of the guild you are sending this roll to. If you are, the ${config.name} may not have that registered, please send a message in the guild so ${config.name} can register this. This registration is temporary, so if you see this error again, just poke your server again.`,
),
);
}
} else {
// Alert API user that they shouldn't be doing this
requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams));
}
// Parse the roll and get the return text
await queueRoll(<QueuedRoll>{
apiRoll: true,
api: { requestEvent, channelId: BigInt(query.get('channel') || '0'), userId: BigInt(query.get('user') || '') },
rollCmd,
modifiers,
originalCommand,
});
} catch (err) {
// Handle any errors we missed
log(LT.ERROR, `Unhandled Error: ${JSON.stringify(err)}`);
requestEvent.respondWith(stdResp.InternalServerError('Something went wrong.'));
}
} else {
// Alert API user that they messed up
requestEvent.respondWith(
stdResp.Forbidden(
`Verify you are a member of the guild you are sending this roll to. If you are, the ${config.name} may not have that registered, please send a message in the guild so ${config.name} can register this. This registration is temporary, so if you see this error again, just poke your server again.`
)
);
}
} else {
// Alert API user that they shouldn't be doing this
requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams));
}
};

View File

@@ -1,19 +1,19 @@
import {
// httpd deps
Status,
STATUS_TEXT,
// httpd deps
STATUS_CODE,
STATUS_TEXT,
} from '../../../deps.ts';
export const heatmapPng = async (requestEvent: Deno.RequestEvent) => {
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.OK,
statusText: STATUS_TEXT[Status.OK],
headers: imageHeaders,
}),
);
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,
})
);
};

View File

@@ -1,34 +1,34 @@
import { dbClient } from '../../db.ts';
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<string, string>, apiUserid: BigInt) => {
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
let erroredOut = false;
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
let erroredOut = false;
// 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;
});
// 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;
} else {
// Send OK to indicate modification was successful
requestEvent.respondWith(stdResp.OK('Successfully added channel.'));
return;
}
} else {
// Alert API user that they shouldn't be doing this
requestEvent.respondWith(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));
}
// Exit this case now if catch errored
if (erroredOut) {
return;
} else {
// Send OK to indicate modification was successful
requestEvent.respondWith(stdResp.OK('Successfully added channel.'));
return;
}
} else {
// Alert API user that they shouldn't be doing this
requestEvent.respondWith(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));
}
};

View File

@@ -1,41 +1,44 @@
import { dbClient } from '../../db.ts';
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<string, string>, apiUserid: BigInt, path: string) => {
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
let value, erroredOut = false;
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
let value,
erroredOut = false;
// Determine value to set
if (path.toLowerCase().indexOf('de') > 0) {
value = 0;
} else {
value = 1;
}
// Determine value to set
if (path.toLowerCase().indexOf('de') > 0) {
value = 0;
} else {
value = 1;
}
// Update the requested entry
await dbClient.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;
});
// Update the requested entry
await dbClient
.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;
} else {
// Send API key as response
requestEvent.respondWith(stdResp.OK(`Successfully active to ${value}.`));
return;
}
} else {
// Alert API user that they shouldn't be doing this
requestEvent.respondWith(stdResp.Forbidden('You can only manage your own channels.'));
}
} else {
// Alert API user that they messed up
requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams));
}
// Exit this case now if catch errored
if (erroredOut) {
return;
} else {
// Send API key as response
requestEvent.respondWith(stdResp.OK(`Successfully active to ${value}.`));
return;
}
} else {
// Alert API user that they shouldn't be doing this
requestEvent.respondWith(stdResp.Forbidden('You can only manage your own channels.'));
}
} else {
// Alert API user that they messed up
requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams));
}
};

View File

@@ -1,45 +1,52 @@
import config from '../../../config.ts';
import { dbClient } from '../../db.ts';
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<string, string>, apiUserid: BigInt, path: string) => {
if (
(query.has('a') && ((query.get('a') || '').length > 0)) && (query.has('channel') && ((query.get('channel') || '').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
let value, erroredOut = false;
if (
query.has('a') &&
(query.get('a') || '').length > 0 &&
query.has('channel') &&
(query.get('channel') || '').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
let value,
erroredOut = false;
// Determine value to set
if (path.toLowerCase().indexOf('un') > 0) {
value = 0;
} else {
value = 1;
}
// Determine value to set
if (path.toLowerCase().indexOf('un') > 0) {
value = 0;
} else {
value = 1;
}
// Execute the DB modification
await dbClient.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;
});
// Execute the DB modification
await dbClient
.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;
} else {
// Send OK to indicate modification was successful
requestEvent.respondWith(stdResp.OK(`Successfully active to ${value}.`));
return;
}
} else {
// Alert API user that they shouldn't be doing this
requestEvent.respondWith(stdResp.Forbidden(stdResp.Strings.restricted));
}
} else {
// Alert API user that they messed up
requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams));
}
// Exit this case now if catch errored
if (erroredOut) {
return;
} else {
// Send OK to indicate modification was successful
requestEvent.respondWith(stdResp.OK(`Successfully active to ${value}.`));
return;
}
} else {
// Alert API user that they shouldn't be doing this
requestEvent.respondWith(stdResp.Forbidden(stdResp.Strings.restricted));
}
} else {
// Alert API user that they messed up
requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams));
}
};

View File

@@ -1,51 +1,51 @@
import config from '../../../config.ts';
import { dbClient } from '../../db.ts';
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<string, string>, apiUserid: BigInt, path: string) => {
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
let key: string,
value: number,
erroredOut = false;
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
let key: string,
value: number,
erroredOut = false;
// Determine key to edit
if (path.toLowerCase().indexOf('ban') > 0) {
key = 'banned';
} else {
key = 'active';
}
// Determine key to edit
if (path.toLowerCase().indexOf('ban') > 0) {
key = 'banned';
} else {
key = 'active';
}
// Determine value to set
if (path.toLowerCase().indexOf('de') > 0 || path.toLowerCase().indexOf('un') > 0) {
value = 0;
} else {
value = 1;
}
// Determine value to set
if (path.toLowerCase().indexOf('de') > 0 || path.toLowerCase().indexOf('un') > 0) {
value = 0;
} else {
value = 1;
}
// Execute the DB modification
await dbClient.execute('UPDATE all_keys SET ?? = ? WHERE userid = ?', [key, value, apiUserid]).catch((e) => {
utils.commonLoggers.dbError('apiKeyManage.ts', 'update', e);
requestEvent.respondWith(stdResp.InternalServerError(`Failed to ${key} to ${value}.`));
erroredOut = true;
});
// Execute the DB modification
await dbClient.execute('UPDATE all_keys SET ?? = ? WHERE userid = ?', [key, value, apiUserid]).catch((e) => {
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;
} else {
// Send OK as response to indicate modification was successful
requestEvent.respondWith(stdResp.OK(`Successfully ${key} to ${value}.`));
return;
}
} else {
// Alert API user that they shouldn't be doing this
requestEvent.respondWith(stdResp.Forbidden('You can only manage your own key.'));
}
} else {
// Alert API user that they messed up
requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams));
}
// Exit this case now if catch errored
if (erroredOut) {
return;
} else {
// Send OK as response to indicate modification was successful
requestEvent.respondWith(stdResp.OK(`Successfully ${key} to ${value}.`));
return;
}
} else {
// Alert API user that they shouldn't be doing this
requestEvent.respondWith(stdResp.Forbidden('You can only manage your own key.'));
}
} else {
// Alert API user that they messed up
requestEvent.respondWith(stdResp.BadRequest(stdResp.Strings.missingParams));
}
};

View File

@@ -1,23 +1,25 @@
import {
// httpd deps
Status,
STATUS_TEXT,
// httpd deps
StatusCode,
STATUS_CODE,
STATUS_TEXT,
} from '../../deps.ts';
const genericResponse = (customText: string, status: Status) => new Response(customText || STATUS_TEXT[status], { status: status, statusText: STATUS_TEXT[status] });
const genericResponse = (customText: string, status: StatusCode) =>
new Response(customText || STATUS_TEXT[status], { status: status, statusText: STATUS_TEXT[status] });
export default {
BadRequest: (customText: string) => genericResponse(customText, Status.BadRequest),
FailedDependency: (customText: string) => genericResponse(customText, Status.FailedDependency),
InternalServerError: (customText: string) => genericResponse(customText, Status.InternalServerError),
Forbidden: (customText: string) => genericResponse(customText, Status.Forbidden),
MethodNotAllowed: (customText: string) => genericResponse(customText, Status.MethodNotAllowed),
NotFound: (customText: string) => genericResponse(customText, Status.NotFound),
OK: (customText: string) => genericResponse(customText, Status.OK),
RequestTimeout: (customText: string) => genericResponse(customText, Status.RequestTimeout),
TooManyRequests: (customText: string) => genericResponse(customText, Status.TooManyRequests),
Strings: {
missingParams: 'Missing Parameters.',
restricted: 'This API is restricted.',
},
BadRequest: (customText: string) => genericResponse(customText, STATUS_CODE.BadRequest),
FailedDependency: (customText: string) => genericResponse(customText, STATUS_CODE.FailedDependency),
InternalServerError: (customText: string) => genericResponse(customText, STATUS_CODE.InternalServerError),
Forbidden: (customText: string) => genericResponse(customText, STATUS_CODE.Forbidden),
MethodNotAllowed: (customText: string) => genericResponse(customText, STATUS_CODE.MethodNotAllowed),
NotFound: (customText: string) => genericResponse(customText, STATUS_CODE.NotFound),
OK: (customText: string) => genericResponse(customText, STATUS_CODE.OK),
RequestTimeout: (customText: string) => genericResponse(customText, STATUS_CODE.RequestTimeout),
TooManyRequests: (customText: string) => genericResponse(customText, STATUS_CODE.TooManyRequests),
Strings: {
missingParams: 'Missing Parameters.',
restricted: 'This API is restricted.',
},
};