"use server"; import testAuth from "@/lib/server/auth"; import { read, write } from "@/lib/server/file"; import { NodeJsonTemplate } from "@/lib/server/types"; import axios from "axios"; import { createHash } from "crypto"; import { cookies } from "next/headers"; import { redirect } from "next/navigation"; type Users = Record; export async function getSession(): Promise< undefined | { userId: string; accessToken: string } > { const c = await cookies(); const accessToken = c.get("github_access")?.value; if (!accessToken) { redirect("/"); } const tokens: Record = await read( () => ({}), "data", "sessions.json", ); 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( await read(() => ({}), "data", "users.json"), ); if (!users.includes(String(userId))) { if (users.length === 0) { await write( { [userId]: { roles: ["admin"] } } as Users, // First user is always an admin "data", "users.json", ); const { key } = await read(NodeJsonTemplate, "data", "node.json"); console.log(`Node key: ${key}\ncwd: ${process.cwd()}`); } else { throw new Error("Invalid user"); } } await write({ ...tokens, [tokenHash]: userId }, "data", "sessions.json"); return { userId, accessToken }; } catch { redirect("/"); } } export async function verifySession(): Promise { return !(await getSession())?.accessToken; }