Implement auth

This commit is contained in:
Hri7566 2024-02-22 05:25:17 -05:00
parent 63472ca3f6
commit 11967df2ae
5 changed files with 32 additions and 24 deletions

View File

View File

@ -1,12 +1,13 @@
import { createBunServeHandler } from "trpc-bun-adapter";
import { appRouter } from "./trpc";
import { appRouter, createContext } from "./trpc";
import { Logger } from "@util/Logger";
const logger = new Logger("Server");
export const server = Bun.serve(
createBunServeHandler({
router: appRouter
router: appRouter,
createContext: createContext
})
);

View File

@ -8,29 +8,31 @@ import { z } from "zod";
const logger = new Logger("tRPC");
export interface Context {
isAuthed: boolean;
}
export const createContext = async (opts: CreateBunContextOptions) => {
return {
isAuthed: false
} as Context;
isAuthed: false,
req: opts.req
};
};
const t = initTRPC.context<typeof createContext>().create();
export type Context = Awaited<ReturnType<typeof createContext>>;
const t = initTRPC.context<Context>().create();
export const router = t.router;
export const publicProcedure = t.procedure;
export const privateProcedure = publicProcedure.use(async opts => {
const { ctx } = opts;
const { req } = ctx;
const token = req.headers.get("authorization");
if (!token) throw new TRPCError({ code: "UNAUTHORIZED" });
opts.ctx.isAuthed = await checkToken(token);
if (!ctx.isAuthed) throw new TRPCError({ code: "UNAUTHORIZED" });
return opts.next({
ctx: {
isAuthed: true
}
});
return opts.next(opts);
});
export const appRouter = router({
@ -38,12 +40,6 @@ export const appRouter = router({
return prefixes;
}),
auth: publicProcedure.input(z.string()).query(async opts => {
logger.debug(opts);
const token = opts.input;
opts.ctx.isAuthed = await checkToken(token);
}),
command: privateProcedure
.input(
z.object({

View File

@ -1,13 +1,25 @@
import { createTRPCClient, httpBatchLink } from "@trpc/client";
import type { AppRouter } from "@server/api/trpc";
const apiToken = process.env.FISHING_TOKEN as string;
export const trpc = createTRPCClient<AppRouter>({
links: [
httpBatchLink({
url: "http://localhost:3000"
url: "http://localhost:3000",
headers() {
return {
Authorization: apiToken
};
}
}),
httpBatchLink({
url: "https://fishing.hri7566.info/api"
url: "https://fishing.hri7566.info/api",
headers() {
return {
Authorization: apiToken
};
}
})
]
});

View File

@ -37,9 +37,8 @@ export class MPPNetBot {
}
public bindEventListeners() {
this.client.on("hi", msg => {
this.client.on("hi", async msg => {
this.logger.info(`Connected to ${this.client.uri}`);
trpc.auth.query(process.env.FISHING_TOKEN as string);
});
this.client.on("ch", msg => {