Session caching

This commit is contained in:
2026-01-02 20:13:43 +01:00
parent caa1191736
commit c84b194792
2 changed files with 25 additions and 12 deletions
+1 -1
View File
@@ -137,7 +137,7 @@ export default function OverviewPage() {
) : ( ) : (
apps.slice(-5).map((app) => ( apps.slice(-5).map((app) => (
<div <div
key={app.name} key={app.id}
className=" className="
grid grid-cols-12 gap-4 py-3 items-center grid grid-cols-12 gap-4 py-3 items-center
text-sm text-sm
+24 -11
View File
@@ -1,13 +1,14 @@
"use server"; "use server";
import { read, write } from "@/app/api/file"; import { read, write } from "@/app/api/file";
import axios from "axios"; import axios from "axios";
import { createHash } from "crypto";
import { cookies } from "next/headers"; import { cookies } from "next/headers";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
type Users = Record<string, { roles: string[] }>; type Users = Record<string, { roles: string[] }>;
export async function getSession(): Promise< export async function getSession(): Promise<
undefined | { user: { id: number }; accessToken: string } undefined | { userId: string; accessToken: string }
> { > {
const c = await cookies(); const c = await cookies();
const accessToken = c.get("github_access")?.value; const accessToken = c.get("github_access")?.value;
@@ -16,22 +17,32 @@ export async function getSession(): Promise<
redirect("/"); redirect("/");
} }
// Test the token const tokens: Record<string, string> = await read(
try { () => ({}),
const user = ( "data",
await axios.get("https://api.github.com/user", { "sessions.json"
headers: { Authorization: `Bearer ${accessToken}` }, );
})
).data;
const tokenHash = createHash("sha256").update(accessToken).digest("hex");
try {
const userId: string =
tokens[tokenHash] ||
(
await axios.get("https://api.github.com/user", {
headers: { Authorization: `Bearer ${accessToken}` },
})
).data.id;
// Test the token
const users = Object.keys( const users = Object.keys(
await read<Users>(() => ({}), "data", "users.json") await read<Users>(() => ({}), "data", "users.json")
); );
if (!users.includes(String(user.id))) { if (!users.includes(String(userId))) {
if (users.length === 0) { if (users.length === 0) {
await write( await write(
{ [String(user.id)]: { roles: ["admin"] } } as Users, // First user is always an admin { [userId]: { roles: ["admin"] } } as Users, // First user is always an admin
"data", "data",
"users.json" "users.json"
); );
@@ -40,7 +51,9 @@ export async function getSession(): Promise<
} }
} }
return { user, accessToken }; await write({ ...tokens, [tokenHash]: userId }, "data", "sessions.json");
return { userId, accessToken };
} catch { } catch {
redirect("/"); redirect("/");
} }