Create auth middleware in elysia

This commit is contained in:
Zoe Roux 2025-03-24 21:32:47 +01:00
parent 50549f20de
commit 068b19c936
No known key found for this signature in database
3 changed files with 40 additions and 17 deletions

36
api/src/auth.ts Normal file
View File

@ -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");

View File

@ -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)

View File

@ -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}`);