Initial commit
This commit is contained in:
49
src/util/api.ts
Normal file
49
src/util/api.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { Context, Next } from "@hono/hono";
|
||||
import { HonoEnv } from "./types.ts";
|
||||
import Logging from "@proxnet/undead-logging";
|
||||
import z from "zod";
|
||||
import { verify } from "@hono/hono/jwt";
|
||||
import Server from "../server/server.ts";
|
||||
import { ProfileToken } from "../server/profiles/types/profile.ts";
|
||||
|
||||
const log = new Logging("APIUtils");
|
||||
|
||||
export function genericResponse(success: boolean, msg?: string, data?: null) {
|
||||
return { success, msg, data }
|
||||
};
|
||||
|
||||
export function successResponse(success: boolean, error: string) {
|
||||
return (c: Context) => {
|
||||
return c.json({ success, error });
|
||||
}
|
||||
}
|
||||
|
||||
const authHeaderSchema = z.string().transform((arg, ctx) => {
|
||||
const split = arg.split(' ');
|
||||
for (const item of split) if (item.length < 6) {
|
||||
ctx.addIssue("Authorization header is invalid");
|
||||
return;
|
||||
}
|
||||
return split[1];
|
||||
});
|
||||
export async function authenticate(c: Context<HonoEnv>, nxt: Next) {
|
||||
const secret = Deno.env.get('SECRET');
|
||||
if (!secret) return c.json(genericResponse(false, "Internal Server Error"), 500);
|
||||
|
||||
const authHeader = authHeaderSchema.safeParse(c.req.header('Authorization'));
|
||||
if (authHeader.success) {
|
||||
|
||||
try {
|
||||
const payload = await verify(authHeader.data ? authHeader.data : 'not a valid token', secret);
|
||||
const profile = await Server.Profiles.get((payload as ProfileToken).sub);
|
||||
if (!profile) return c.json(genericResponse(false, "Internal Server Error"), 500);
|
||||
|
||||
c.set('profile', profile);
|
||||
return await nxt();
|
||||
} catch (err) {
|
||||
log.w(`Authentication failed: ${(err as Error).stack}`);
|
||||
return c.json(genericResponse(false, "Internal Server Error"), 500);
|
||||
}
|
||||
|
||||
} else return c.json(genericResponse(false, "Authorization required"), 401);
|
||||
}
|
||||
Reference in New Issue
Block a user