add delete and undelete endpoints

This commit is contained in:
Ean Milligan
2026-04-09 16:24:26 -04:00
parent 5ec93890bc
commit 52abe6f3a8
7 changed files with 112 additions and 34 deletions

80
mod.ts
View File

@@ -21,19 +21,21 @@ const genericResponse = (status: StatusCode, customText = '') =>
Deno.serve({ port: config.api.port }, async (req) => {
const urlPath = req.url.split('?')[0] ?? '';
const path = (urlPath.split('api')[1] ?? '').toLowerCase().trim();
let rawPath = (urlPath.split('api')[1] ?? '').trim();
if (rawPath.endsWith('/')) rawPath = rawPath.slice(0, -1);
const path = rawPath;
console.log(urlPath, path);
let failed = false;
if (req.method === 'GET') {
// handle all gets
} else if (req.method === 'POST' && (path === '/enroll' || path === '/enroll/')) {
} else if (req.method === 'POST' && path === '/enroll') {
const body = await req.json();
let readFailure = false;
const userNameMatches = await dbClient.query('SELECT name FROM users WHERE name = ?', [body.name]).catch(() => {
readFailure = true;
failed = true;
});
if (readFailure) return genericResponse(STATUS_CODE.InternalServerError, "Couldn't read DB.");
if (failed) return genericResponse(STATUS_CODE.InternalServerError, "Couldn't read DB.");
if (userNameMatches.length === 0) {
if (body.name.length < 4 || body.name.length > 20) return genericResponse(STATUS_CODE.BadRequest, `Name too ${body.name.length < 4 ? 'short' : 'long'}.`);
@@ -42,12 +44,11 @@ Deno.serve({ port: config.api.port }, async (req) => {
const id = nanoid();
let writeFailure = false;
await dbClient.execute('INSERT INTO users(id,name,pin,email) values(?,?,?,?)', [id, body.name, body.pin, body.email]).catch(() => {
writeFailure = true;
failed = true;
});
if (writeFailure) {
if (failed) {
return genericResponse(STATUS_CODE.InternalServerError, "Couldn't write DB.");
} else {
return genericResponse(STATUS_CODE.OK, JSON.stringify({ id }));
@@ -58,11 +59,10 @@ Deno.serve({ port: config.api.port }, async (req) => {
} else {
const body = await req.json();
let readFailure = false;
const loginMatch = await dbClient.query('SELECT id, email, deleteCode FROM users WHERE name = ? AND pin = ?', [body.name, body.pin]).catch(() => {
readFailure = true;
failed = true;
});
if (readFailure) return genericResponse(STATUS_CODE.InternalServerError, "Couldn't read DB.");
if (failed) return genericResponse(STATUS_CODE.InternalServerError, "Couldn't read DB.");
if (loginMatch.length === 0) return genericResponse(STATUS_CODE.Forbidden, 'Invalid name/PIN combination.');
const id = loginMatch[0].id;
const email = loginMatch[0].email;
@@ -71,47 +71,57 @@ Deno.serve({ port: config.api.port }, async (req) => {
switch (req.method) {
case 'POST':
if (path === '/auth' || path === '/auth/') {
if (path === '/auth') {
return genericResponse(STATUS_CODE.OK, JSON.stringify({ id, hasEmail }));
}
break;
case 'PUT':
if (path.startsWith('/undelete/')) {
const planId = path.replace('/undelete/', '');
const planMatch = await dbClient.query('SELECT ownerId FROM plans WHERE id = ?', [planId]).catch(() => {
failed = true;
});
if (failed) return genericResponse(STATUS_CODE.InternalServerError, "Couldn't read DB.");
if (!planMatch.length) return genericResponse(STATUS_CODE.NotFound, 'Plan ID does not exist.');
if (planMatch[0].ownerId !== id) return genericResponse(STATUS_CODE.Forbidden, "You don't own this plan.");
await dbClient.execute('UPDATE plans SET deleted = 0 WHERE id = ?', [planId]).catch(() => {
failed = true;
});
if (failed) return genericResponse(STATUS_CODE.InternalServerError, "Couldn't update DB.");
return genericResponse(STATUS_CODE.OK, 'Plan deleted.');
}
break;
case 'DELETE':
if (path === '/unenroll' || '/unenroll/') {
if (path === '/unenroll') {
if (!hasEmail || body.deleteCode.trim() === deleteCode) {
let deleteFailure = false;
await dbClient.execute('DELETE FROM plans WHERE ownerId = ?', [id]).catch(() => {
deleteFailure = true;
failed = true;
});
if (deleteFailure) return genericResponse(STATUS_CODE.InternalServerError, "Couldn't delete plans.");
if (failed) return genericResponse(STATUS_CODE.InternalServerError, "Couldn't delete plans.");
await dbClient.execute('DELETE FROM users WHERE id = ?', [id]).catch(() => {
deleteFailure = true;
failed = true;
});
if (deleteFailure) return genericResponse(STATUS_CODE.InternalServerError, "Couldn't delete user.");
if (failed) return genericResponse(STATUS_CODE.InternalServerError, "Couldn't delete user.");
return genericResponse(STATUS_CODE.OK, 'Deleted user and plans.');
} else if (hasEmail && !deleteCode) {
let updateFailure = false;
const newDeleteCode = nanoid();
await dbClient.execute('UPDATE users SET deleteCode = ? WHERE id = ?', [newDeleteCode, id]).catch(() => {
updateFailure = true;
failed = true;
});
if (updateFailure) return genericResponse(STATUS_CODE.InternalServerError, "Couldn't set deleteCode.");
if (failed) return genericResponse(STATUS_CODE.InternalServerError, "Couldn't set deleteCode.");
const nowDT = new Date().getTime();
let fetchFailed = false;
if (zohoAuthExpireDT < nowDT) {
const getNewAuthToken = await fetch(
`https://accounts.zoho.com/oauth/v2/token?client_id=${config.email.clientId}&client_secret=${config.email.clientSecret}&grant_type=client_credentials&scope=ZohoMail.messages.CREATE`,
{ method: 'POST' },
).catch(() => {
fetchFailed = true;
failed = true;
});
if (fetchFailed || !getNewAuthToken) return genericResponse(STATUS_CODE.InternalServerError, "Couldn't get auth token.");
if (failed || !getNewAuthToken) return genericResponse(STATUS_CODE.InternalServerError, "Couldn't get auth token.");
const newAuthToken = await getNewAuthToken.json();
zohoHeaders.set('Authorization', `Zoho-oauthtoken ${newAuthToken.access_token}`);
@@ -128,9 +138,9 @@ Deno.serve({ port: config.api.port }, async (req) => {
content: `Notice: account deletion is permanent and will delete all plans saved under your account.<br/><br/>Please use the following Delete Code to delete your account:<br/><br/>${newDeleteCode}`,
}),
}).catch(() => {
fetchFailed = true;
failed = true;
});
if (fetchFailed || !sendEmailReq) return genericResponse(STATUS_CODE.InternalServerError, "Couldn't send email.");
if (failed || !sendEmailReq) return genericResponse(STATUS_CODE.InternalServerError, "Couldn't send email.");
const sentEmail = await sendEmailReq.json();
if (sentEmail.status.code !== 200) return genericResponse(STATUS_CODE.InternalServerError, 'Failed to send email.');
@@ -147,6 +157,20 @@ Deno.serve({ port: config.api.port }, async (req) => {
} else {
return genericResponse(STATUS_CODE.InternalServerError, 'How are you here?');
}
} else if (path.startsWith('/delete/')) {
const planId = path.replace('/delete/', '');
const planMatch = await dbClient.query('SELECT ownerId FROM plans WHERE id = ?', [planId]).catch(() => {
failed = true;
});
if (failed) return genericResponse(STATUS_CODE.InternalServerError, "Couldn't read DB.");
if (!planMatch.length) return genericResponse(STATUS_CODE.NotFound, 'Plan ID does not exist.');
if (planMatch[0].ownerId !== id) return genericResponse(STATUS_CODE.Forbidden, "You don't own this plan.");
await dbClient.execute('UPDATE plans SET deleted = 1 WHERE id = ?', [planId]).catch(() => {
failed = true;
});
if (failed) return genericResponse(STATUS_CODE.InternalServerError, "Couldn't update DB.");
return genericResponse(STATUS_CODE.OK, 'Plan deleted.');
}
break;
}