diff --git a/api/src/auth.ts b/api/src/auth.ts index 36812af8..398fd1f9 100644 --- a/api/src/auth.ts +++ b/api/src/auth.ts @@ -1,5 +1,6 @@ -import Elysia, { t } from "elysia"; +import Elysia, { getSchemaValidator, t } from "elysia"; import { createRemoteJWKSet, jwtVerify } from "jose"; +import { KError } from "./models/error"; const jwtSecret = process.env.JWT_SECRET ? new TextEncoder().encode(process.env.JWT_SECRET) @@ -11,22 +12,34 @@ const jwks = createRemoteJWKSet( ), ); +const Jwt = t.Object({ + sub: t.String({ description: "User id" }), + username: t.String(), + sid: t.String({ description: "Session id" }), +}); +const validator = getSchemaValidator(Jwt); + export const auth = new Elysia({ name: "auth" }) .guard({ - headers: t.Object({ - authorization: t.String({ pattern: "^Bearer .+$" }), - }), + // Those are not applied for now. See https://github.com/elysiajs/elysia/issues/1139 + detail: { + security: [{ bearer: ["read"] }, { api: ["read"] }], + }, + response: { + 401: { ...KError, description: "" }, + 403: { ...KError, description: "" }, + }, }) .macro({ permissions(perms: string[]) { return { - beforeHandle: () => {}, - resolve: async ({ headers: { authorization } }) => { + resolve: async ({ headers: { authorization }, error }) => { const bearer = authorization?.slice(7); if (!bearer) return { jwt: false }; // @ts-expect-error ts can't understand that there's two overload idk why - const { payload: jwt } = await jwtVerify(bearer, jwtSecret ?? jwks); - return { jwt }; + const { payload } = await jwtVerify(bearer, jwtSecret ?? jwks); + // TODO: use perms + return { jwt: validator.Decode(payload) }; }, }; }, diff --git a/api/src/index.ts b/api/src/index.ts index 623f271c..b029433f 100644 --- a/api/src/index.ts +++ b/api/src/index.ts @@ -55,6 +55,20 @@ app description: "Routes about images: posters, thumbnails...", }, ], + components: { + securitySchemes: { + bearer: { + type: "http", + scheme: "bearer", + bearerFormat: "opaque", + }, + api: { + type: "apiKey", + in: "header", + name: "X-API-KEY", + }, + }, + }, }, }), )