Initial commit

This commit is contained in:
2025-07-25 19:00:06 -04:00
commit e604c7a437
52 changed files with 96098 additions and 0 deletions

49
src/util/api.ts Normal file
View 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);
}