Export token check to helper function
This commit is contained in:
parent
44786a1dd2
commit
79f0c3a1d6
|
@ -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;
|
||||
}
|
|
@ -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({
|
||||
|
|
Loading…
Reference in New Issue