clonegur/backend/server/decorators/jwt.ts

23 lines
906 B
TypeScript
Raw Normal View History

2023-06-29 14:31:25 +00:00
// SHUT THE FUCK UP
// deno-lint-ignore-file no-explicit-any
import JWT from "../../utils/JWT.ts";
import HttpError from "../HttpError.ts";
import Router, { makeParameterModifier } from "../Router.ts";
export default function jwt<T extends Router = any>(salt: ((self: T) => string) | string, required = false) {
return makeParameterModifier<T>(function (_req, val?: string) {
if (val === undefined) return undefined;
const s = typeof salt === 'function' ? salt(this) : (this as any)[salt] as string;
try {
const res = JWT.decode(val, s);
if (required && res === undefined) throw new HttpError('You are not logged in.');
return res;
}
catch (e) {
if (e instanceof Error && !(e instanceof HttpError)) {
throw new HttpError(e.message, 400);
}
else throw e;
}
});
}