clonegur/backend/server/decorators/jwt.ts
2023-06-30 13:19:21 +03:00

26 lines
1008 B
TypeScript

// 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) {
if (required) throw new HttpError('You are not logged in.');
else 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;
}
});
}