Proper auth
This commit is contained in:
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user