Export token check to helper function

This commit is contained in:
Aelita4 2023-12-12 21:25:19 +01:00
parent 44786a1dd2
commit 79f0c3a1d6
Signed by: Aelita4
GPG Key ID: E44490C2025906C1
2 changed files with 45 additions and 27 deletions

View File

@ -0,0 +1,42 @@
import type AccessToken from "../../types/AccessToken";
import { getAccessToken } from "../accessTokens";
export default async function validateAccessToken(request: Request): Promise<Response | AccessToken> {
const accessToken = request.url.split("?")[1]?.split("&").filter((x) => x.split("=")[0] === "token")[0].split("=")[1];
if(accessToken === undefined) return new Response(
JSON.stringify({
code: 401,
message: "Unauthorized",
error: "Missing Access Token"
})
);
const response = await getAccessToken(accessToken);
if(response === null) return new Response(
JSON.stringify({
code: 401,
message: "Unauthorized",
error: "Invalid Access Token"
})
);
if(response.createdAt.getTime() > Date.now()) return new Response(
JSON.stringify({
code: 403,
message: "Forbidden",
data: "Access token is invalid for user " + response.username + ", are you travelling in time?"
})
);
if(response.expiresAt !== null && response.expiresAt.getTime() < Date.now()) return new Response(
JSON.stringify({
code: 403,
message: "Forbidden",
data: "Access token is invalid for user " + response.username + ", token expired"
})
);
return response;
}

View File

@ -1,33 +1,9 @@
import type { APIRoute } from "astro";
import { getAccessToken } from "../../../lib/accessTokens";
import validateAccessToken from "../../../lib/utils/validateAccessToken";
export const GET: APIRoute = async({ request }) => {
const accessToken = request.url.split("?")[1].split("&").filter((x) => x.split("=")[0] === "token")[0].split("=")[1];
const response = await getAccessToken(accessToken);
if(response === null) return new Response(
JSON.stringify({
code: 401,
message: "Unauthorized",
error: "Invalid Access Token"
})
);
if(response.createdAt.getTime() > Date.now()) return new Response(
JSON.stringify({
code: 403,
message: "Forbidden",
data: "Access token is invalid for user " + response.username + ", are you travelling in time?"
})
);
if(response.expiresAt !== null && response.expiresAt.getTime() < Date.now()) return new Response(
JSON.stringify({
code: 403,
message: "Forbidden",
data: "Access token is invalid for user " + response.username + ", token expired"
})
);
const response = await validateAccessToken(request);
if(response instanceof Response) return response;
return new Response(
JSON.stringify({