Files
dockship/src/core/auth/session.ts
T
2026-02-14 16:42:11 +01:00

69 lines
1.8 KiB
TypeScript

"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<string, { roles: string[] }>;
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<string, string> = 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<Users>(() => ({}), "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<boolean> {
return !(await getSession())?.accessToken;
}