diff --git a/api/src/auth.ts b/api/src/auth.ts new file mode 100644 index 00000000..ea4c8ef9 --- /dev/null +++ b/api/src/auth.ts @@ -0,0 +1,36 @@ +import jwt from "@elysiajs/jwt"; +import Elysia, { t } from "elysia"; + +export let jwtSecret = process.env.JWT_SECRET!; +if (!jwtSecret) { + const auth = process.env.AUTH_SERVER ?? "http://auth:4568/auth"; + try { + const ret = await fetch(`${auth}/info`); + const info = await ret.json(); + jwtSecret = info.publicKey; + } catch (error) { + console.error(`Can't access auth server at ${auth}:\n${error}`); + } +} + +export const auth = new Elysia({ name: "auth" }) + .use(jwt({ secret: jwtSecret })) + .guard({ + headers: t.Object({ + authorization: t.String({ pattern: "^Bearer .+$" }), + }), + }) + .macro({ + permissions(perms: string[]) { + return { + beforeHandle: () => {}, + resolve: async ({ headers: { authorization }, jwt }) => { + console.log(authorization.slice(7)); + const user = await jwt.verify(authorization?.slice(7)); + console.log("macro", user); + return { user }; + }, + }; + }, + }) + .as("plugin"); diff --git a/api/src/base.ts b/api/src/base.ts index 060a9d5b..248ac1a1 100644 --- a/api/src/base.ts +++ b/api/src/base.ts @@ -50,7 +50,7 @@ export const base = new Elysia({ name: "base" }) }) .as("plugin"); -export const prefix = process.env.KYOO_PREFIX; +export const prefix = process.env.KYOO_PREFIX ?? ""; export const app = new Elysia({ prefix }) .use(base) .use(showsH) diff --git a/api/src/index.ts b/api/src/index.ts index 4f1c10ef..08142f27 100644 --- a/api/src/index.ts +++ b/api/src/index.ts @@ -1,25 +1,13 @@ -import jwt from "@elysiajs/jwt"; import { swagger } from "@elysiajs/swagger"; +import { jwtSecret } from "./auth"; +import { app } from "./base"; import { processImages } from "./controllers/seed/images"; import { migrate } from "./db"; -import { app } from "./base"; import { comment } from "./utils"; await migrate(); -let secret = process.env.JWT_SECRET; -if (!secret) { - const auth = process.env.AUTH_SERVER ?? "http://auth:4568/auth"; - try { - const ret = await fetch(`${auth}/info`); - const info = await ret.json(); - secret = info.publicKey; - } catch (error) { - console.error(`Can't access auth server at ${auth}:\n${error}`); - } -} - -if (!secret) { +if (!jwtSecret) { console.error("Missing jwt secret or auth server. exiting"); process.exit(1); } @@ -76,7 +64,6 @@ app }, }), ) - .use(jwt({ secret })) .listen(3567); console.log(`Api running at ${app.server?.hostname}:${app.server?.port}`);