Proper auth

This commit is contained in:
2025-12-28 23:25:27 +01:00
parent 24e37e5244
commit 2b6dbeea4a
3 changed files with 66 additions and 42 deletions
+39 -2
View File
@@ -1,8 +1,14 @@
"use server";
import { read, write } from "@/app/api/file";
import axios from "axios";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
export async function getSession() {
type Users = Record<string, { roles: string[] }>;
export async function getSession(): Promise<
undefined | { user: { id: number }; accessToken: string }
> {
const c = await cookies();
const accessToken = c.get("github_access")?.value;
@@ -10,5 +16,36 @@ export async function getSession() {
redirect("/");
}
return accessToken;
// Test the token
try {
const user = (
await axios.get("https://api.github.com/user", {
headers: { Authorization: `Bearer ${accessToken}` },
})
).data;
const users = Object.keys(
await read<Users>(() => ({}), "data", "users.json")
);
if (!users.includes(String(user.id))) {
if (users.length === 0) {
await write(
{ [String(user.id)]: { roles: ["admin"] } } as Users, // First user is always an admin
"data",
"users.json"
);
} else {
throw new Error("Invalid user");
}
}
return { user, accessToken };
} catch {
redirect("/");
}
}
export async function verifySession(): Promise<boolean> {
return !(await getSession())?.accessToken;
}