Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Let's hope i didn't break anything
  • Loading branch information
regalijan committed Oct 19, 2023
1 parent 8778547 commit b6c051f
Showing 1 changed file with 90 additions and 4 deletions.
94 changes: 90 additions & 4 deletions functions/_middleware.ts
@@ -1,3 +1,4 @@
import getPermissions from "./permissions.js";
import { jsonError } from "./common.js";

async function constructHTML(context: RequestContext) {
Expand Down Expand Up @@ -26,6 +27,80 @@ async function generateTokenHash(token: string) {
.replace(/=/g, "");
}

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

if (!currentUser || currentUser.refresh_at > Date.now())
return await context.next();

const refreshedTokenResponse = await fetch(
"https://discord.com/api/v10/oauth2/token",
{
body: `grant_type=refresh_token&refresh_token=${currentUser.refresh_token}`,
headers: {
authorization: `Basic ${btoa(
context.env.DISCORD_ID + ":" + context.env.DISCORD_SECRET,
)}`,
"content-type": "application/x-www-form-urlencoded",
},
method: "POST",
},
);

if (!refreshedTokenResponse.ok) return await context.next();

const accessData: { [k: string]: any } = await refreshedTokenResponse.json();

let userData: { [k: string]: any } = {
...accessData,
refresh_at: Date.now() + 3600000,
};

const newDiscordData = await fetch("https://discord.com/api/v10/users/@me", {
headers: {
authorization: `Bearer ${accessData.access_token}`,
},
});

if (!newDiscordData.ok) return await context.next();

userData = {
...userData,
...(await newDiscordData.json()),
};

const updatedServerMemberReq = await fetch(
"https://discord.com/api/v10/users/@me/guilds/242263977986359297/member",
{
headers: {
authorization: `Bearer ${accessData.access_token}`,
},
},
);

userData.permissions = await getPermissions(
userData.id,
context,
updatedServerMemberReq.ok
? (
(await updatedServerMemberReq.json()) as {
[k: string]: any;
}
).roles
: undefined,
);

const tokenHash = await generateTokenHash(context.data.sid);

await context.env.DATA.put(`auth_${tokenHash}`, JSON.stringify(userData), {
expirationTtl: accessData.expires_in,
});

delete context.data.sid;

return await context.next();
}

async function setAuth(context: RequestContext) {
const cookies = context.request.headers.get("cookie");
const auth = context.request.headers.get("authorization");
Expand Down Expand Up @@ -67,14 +142,22 @@ async function setAuth(context: RequestContext) {
)
return jsonError("Token could not be verified", 401);

const { jti: sessionToken }: { jti: string } = JSON.parse(jwtSegments[1]);
const {
jti: sessionToken,
}: {
jti: string;
} = JSON.parse(
atob(jwtSegments[1].replaceAll("-", "+").replaceAll("_", "/")),
);

const linkedSessionData = await context.env.DATA.get(
`auth_${await generateTokenHash(sessionToken)}`,
);

if (linkedSessionData) {
context.data.current_user = JSON.parse(linkedSessionData);
context.data.sid = sessionToken;

return await context.next();
} else return jsonError("Session is invalid or expired", 401);
}
Expand All @@ -92,8 +175,10 @@ async function setAuth(context: RequestContext) {
`auth_${await generateTokenHash(value)}`,
);

if (userData) context.data.current_user = JSON.parse(userData);
else
if (userData) {
context.data.current_user = JSON.parse(userData);
context.data.sid = value;
} else
context.request.headers.append(
"set-cookie",
"_s=; HttpOnly; Max-Age=0; Path=/; Secure;",
Expand Down Expand Up @@ -187,8 +272,9 @@ async function setTheme(context: RequestContext) {

export const onRequest = [
setAuth,
refreshAuth,
setTheme,
constructHTML,
setBody,
setHeaders
setHeaders,
];

0 comments on commit b6c051f

Please sign in to comment.