Greatly reduce repeated code
This commit is contained in:
@ -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> {
|
||||
@ -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("=");
|
||||
@ -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({
|
||||
@ -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: {
|
||||
@ -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,
|
||||
@ -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();
|
||||
|
Reference in New Issue
Block a user