Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Greatly reduce repeated code
  • Loading branch information
regalijan committed Oct 19, 2023
1 parent 47e639b commit dd2d9f2
Show file tree
Hide file tree
Showing 34 changed files with 197 additions and 482 deletions.
24 changes: 5 additions & 19 deletions functions/api/appeals/[id]/_middleware.ts
@@ -1,3 +1,5 @@
import { jsonError } from "../../../common.js";

export async function onRequestPost(context: RequestContext) {
const { pathname } = new URL(context.request.url);

Expand All @@ -8,12 +10,7 @@ export async function onRequestPost(context: RequestContext) {
const { permissions } = context.data.current_user;

if (!(permissions & (1 << 0)) && !(permissions & (1 << 11)))
return new Response('{"error":"Forbidden"}', {
headers: {
"content-type": "application/json",
},
status: 403,
});
return jsonError("Forbidden", 403);

const { body } = context.data;
const id = context.params.id as string;
Expand All @@ -23,13 +20,7 @@ export async function onRequestPost(context: RequestContext) {
if (!pathname.endsWith("/ban")) {
const key = await context.env.DATA.get(`appeal_${id}`);

if (!key)
return new Response('{"error":"No appeal with that ID exists"}', {
headers: {
"content-type": "application/json",
},
status: 404,
});
if (!key) return jsonError("No appeal with that ID exists", 404);

context.data.appeal = JSON.parse(key);
}
Expand All @@ -38,12 +29,7 @@ export async function onRequestPost(context: RequestContext) {
body.feedback &&
(typeof body.feedback !== "string" || body.feedback.length > 512)
)
return new Response('{"error":"Invalid feedback"}', {
headers: {
"content-type": "application/json",
},
status: 400,
});
return jsonError("Invalid feedback", 400);

return await context.next();
}
9 changes: 3 additions & 6 deletions functions/api/appeals/[id]/accept.ts
@@ -1,3 +1,5 @@
import { jsonError } from "../../../common.js";

export async function onRequestPost(context: RequestContext) {
const { appeal } = context.data;
const body = new FormData();
Expand All @@ -20,12 +22,7 @@ export async function onRequestPost(context: RequestContext) {

if (!emailReq.ok) {
console.log(await emailReq.json());
return new Response('{"error":"Failed to accept appeal"}', {
headers: {
"content-type": "application/json",
},
status: 500,
});
return jsonError("Failed to accept appeal", 500);
}

const { current_user: currentUser } = context.data;
Expand Down
9 changes: 3 additions & 6 deletions functions/api/appeals/[id]/ban.ts
@@ -1,13 +1,10 @@
import { jsonError } from "../../../common.js";

export async function onRequestPost(context: RequestContext) {
const { current_user: currentUser } = context.data;

if (context.data.targetId.search(/^\d{16,19}$/) === -1)
return new Response('{"error":"Invalid target id"}', {
headers: {
"content-type": "application/json",
},
status: 400,
});
return jsonError("Invalid target id", 400);

await context.env.D1.prepare(
"INSERT INTO appeal_bans (created_at, created_by, user) VALUES (?, ?, ?);",
Expand Down
9 changes: 3 additions & 6 deletions functions/api/appeals/[id]/deny.ts
@@ -1,3 +1,5 @@
import { jsonError } from "../../../common.js";

export async function onRequestPost(context: RequestContext) {
const { appeal } = context.data;
const body = new FormData();
Expand All @@ -20,12 +22,7 @@ export async function onRequestPost(context: RequestContext) {

if (!emailReq.ok) {
console.log(await emailReq.json());
return new Response('{"error":"Failed to deny appeal"}', {
headers: {
"content-type": "application/json",
},
status: 500,
});
return jsonError("Failed to deny appeal", 500);
}

await context.env.D1.prepare("UPDATE appeals SET open = 0 WHERE id = ?;")
Expand Down
10 changes: 3 additions & 7 deletions functions/api/appeals/_middleware.ts
@@ -1,11 +1,7 @@
import { jsonError } from "../../common.js";

export async function onRequest(context: RequestContext) {
if (!context.data.current_user)
return new Response('{"error":"Not logged in"}', {
headers: {
"content-type": "application/json",
},
status: 401,
});
if (!context.data.current_user) return jsonError("Not logged in", 401);

return await context.next();
}
27 changes: 5 additions & 22 deletions functions/api/appeals/submit.ts
@@ -1,3 +1,5 @@
import { jsonError } from "../../common.js";

export async function onRequestPost(context: RequestContext) {
const { learned, whyBanned, whyUnban } = context.data.body;

Expand All @@ -12,25 +14,11 @@ export async function onRequestPost(context: RequestContext) {
!whyUnban.length ||
whyUnban.length > 2000
)
return new Response(
'{"error":"One or more fields are missing or invalid"}',
{
headers: {
"content-type": "application/json",
},
status: 400,
},
);
return jsonError("One or more fields are missing or invalid", 400);

const { current_user: currentUser } = context.data;

if (!currentUser.email)
return new Response('{"error":"No email for this session"}', {
headers: {
"content-type": "application/json",
},
status: 403,
});
if (!currentUser.email) return jsonError("No email for this session", 403);

const existingAppeals = await context.env.DATA.list({
prefix: `appeal_${currentUser.id}`,
Expand All @@ -45,12 +33,7 @@ export async function onRequestPost(context: RequestContext) {
(appeal) => (appeal.metadata as { [k: string]: any })?.open,
)
)
return new Response('{"error":"Appeal already submitted"}', {
headers: {
"content-type": "application/json",
},
status: 403,
});
return jsonError("Appeal already submitted", 403);

if (
await context.env.D1.prepare("SELECT * FROM appeal_bans WHERE user = ?;")
Expand Down
16 changes: 4 additions & 12 deletions functions/api/appeals/toggle.ts
@@ -1,22 +1,14 @@
import { jsonError } from "../../common.js";

export async function onRequestPost(context: RequestContext) {
const { active } = context.data.body;
const { permissions } = context.data.current_user;

if (!(permissions & (1 << 0)) && !(permissions & (1 << 11)))
return new Response('{"error":"Forbidden"}', {
headers: {
"content-type": "application/json",
},
status: 403,
});
return jsonError("Forbidden", 403);

if (typeof active !== "boolean")
return new Response('{"error":"Active property must be a boolean"}', {
headers: {
"content-type": "application/json",
},
status: 400,
});
return jsonError("Active property must be a boolean", 400);

if (active) {
await context.env.DATA.delete("appeal_disabled");
Expand Down
24 changes: 8 additions & 16 deletions functions/api/auth/session.ts
@@ -1,4 +1,5 @@
import GetPermissions from "../../permissions.js";
import { jsonError } from "../../common.js";
import tokenPrefixes from "../../../data/token_prefixes.json";

async function generateTokenHash(token: string): Promise<string> {
Expand All @@ -12,19 +13,10 @@ async function generateTokenHash(token: string): Promise<string> {
.replace(/=/g, "");
}

function response(body: string, status: number) {
return new Response(body, {
headers: {
"content-type": "application/json",
},
status,
});
}

export async function onRequestDelete(context: RequestContext) {
const cookies = context.request.headers.get("cookie")?.split("; ");

if (!cookies) return response('{"error":"Not logged in"}', 401);
if (!cookies) return jsonError("Not logged in", 401);

for (const cookie of cookies) {
const [name, value] = cookie.split("=");
Expand All @@ -47,12 +39,12 @@ export async function onRequestGet(context: RequestContext) {
const code = searchParams.get("code");
const state = searchParams.get("state");

if (!code) return response('{"error":"Missing code"}', 400);
if (!state) return response('{"error":"Missing state"}', 400);
if (!code) return jsonError("Missing code", 400);
if (!state) return jsonError("Missing state", 400);

const stateRedirect = await context.env.DATA.get(`state_${state}`);

if (!stateRedirect) return response('{"error":"Invalid state"}', 400);
if (!stateRedirect) return jsonError("Invalid state", 400);

const tokenReq = await fetch("https://discord.com/api/oauth2/token", {
body: new URLSearchParams({
Expand All @@ -72,7 +64,7 @@ export async function onRequestGet(context: RequestContext) {
if (!tokenReq.ok) {
console.log(await tokenReq.text());

return response('{"error":"Failed to redeem code"}', 500);
return jsonError("Failed to redeem code", 500);
}

const tokenData: {
Expand All @@ -84,7 +76,7 @@ export async function onRequestGet(context: RequestContext) {
} = await tokenReq.json();

if (tokenData.scope.search("guilds.members.read") === -1)
return response('{"error":"Do not touch the scopes!"}', 400);
return jsonError("Do not touch the scopes!", 400);

let userData: { [k: string]: any } = {
...tokenData,
Expand All @@ -99,7 +91,7 @@ export async function onRequestGet(context: RequestContext) {

if (!userReq.ok) {
console.log(await userReq.text());
return response('{"error":"Failed to retrieve user"}', 500);
return jsonError("Failed to retrieve user", 500);
}

const apiUser: { [k: string]: any } = await userReq.json();
Expand Down
25 changes: 5 additions & 20 deletions functions/api/data-transfers/create.ts
@@ -1,3 +1,5 @@
import { jsonError } from "../../common.js";

export async function onRequestPost(context: RequestContext) {
const { cookie, has_access } = context.data.body;

Expand All @@ -9,12 +11,7 @@ export async function onRequestPost(context: RequestContext) {
/_\|WARNING:-DO-NOT-SHARE-THIS\.--Sharing-this-will-allow-someone-to-log-in-as-you-and-to-steal-your-ROBUX-and-items\.\|_[A-F\d]+/,
))
)
return new Response('{"error":"Invalid request"}', {
headers: {
"content-type": "application/json",
},
status: 400,
});
return jsonError("Invalid request", 400);

const id =
(context.request.headers.get("cf-ray")?.split("-")[0] as string) +
Expand Down Expand Up @@ -53,13 +50,7 @@ export async function onRequestPost(context: RequestContext) {
},
);

if (!authedUserReq.ok)
return new Response('{"error":"Cookie is invalid"}', {
headers: {
"content-type": "application/json",
},
status: 400,
});
if (!authedUserReq.ok) return jsonError("Cookie is invalid", 400);

const authedUser: { id: number; name: string } = await authedUserReq.json();

Expand All @@ -79,13 +70,7 @@ export async function onRequestPost(context: RequestContext) {
},
);

if (!createCardReq.ok)
return new Response('{"error":"Failed to create entry"}', {
headers: {
"content-type": "application/json",
},
status: 500,
});
if (!createCardReq.ok) return jsonError("Failed to create entry", 500);

await context.env.DATA.put(
`datatransfer_${id}`,
Expand Down
9 changes: 3 additions & 6 deletions functions/api/events-team/events/_middleware.ts
@@ -1,15 +1,12 @@
import { jsonError } from "../../../common.js";

export async function onRequest(context: RequestContext) {
if (
![1 << 3, 1 << 4, 1 << 12].find(
(int) => context.data.current_user?.permissions & int,
)
)
return new Response('{"error":"Forbidden"}', {
headers: {
"content-type": "application/json",
},
status: 401,
});
return jsonError("Forbidden", 403);

return await context.next();
}
9 changes: 3 additions & 6 deletions functions/api/events-team/team-members/_middleware.ts
@@ -1,13 +1,10 @@
import { jsonError } from "../../../common.js";

export async function onRequest(context: RequestContext) {
if (
![1 << 4, 1 << 12].find((p) => context.data.current_user?.permissions & p)
)
return new Response('{"error":"Forbidden"}', {
headers: {
"content-type": "application/json",
},
status: 403,
});
return jsonError("Forbidden", 403);

return await context.next();
}

0 comments on commit dd2d9f2

Please sign in to comment.