mirror of
https://github.com/zoriya/Kyoo.git
synced 2025-05-24 02:02:36 -04:00
Validate jwt claims
This commit is contained in:
parent
bcded031e2
commit
1f8652e06c
@ -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<typeof Jwt>(payload) };
|
||||
},
|
||||
};
|
||||
},
|
||||
|
@ -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",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
)
|
||||
|
Loading…
x
Reference in New Issue
Block a user