feat: auth

This commit is contained in:
2026-02-04 08:04:46 -08:00
parent 8f3aeb9391
commit e167a17bd9
12 changed files with 673 additions and 9 deletions
+54
View File
@@ -0,0 +1,54 @@
import { FastifyPluginAsync, FastifyRequest } from "fastify";
import fastifyPlugin from "fastify-plugin";
import fastifyJwt from "@fastify/jwt";
import fastifyCookie from "@fastify/cookie";
import fastifyOauth2 from "@fastify/oauth2";
declare module "fastify" {
interface FastifyInstance {
authenticate: (request: FastifyRequest) => Promise<void>;
oauth2Discord: any;
}
interface FastifyRequest {
user?: any;
}
}
const authPlugin: FastifyPluginAsync = async (app) => {
// Register JWT plugin
app.register(fastifyJwt, {
secret: process.env.JWT_SECRET || "your-secret-key",
cookie: {
cookieName: "auth-token",
signed: false,
},
});
// Register cookie plugin
app.register(fastifyCookie);
// Register Discord OAuth2
app.register(fastifyOauth2, {
name: "oauth2Discord",
credentials: {
client: {
id: process.env.DISCORD_CLIENT_ID || "",
secret: process.env.DISCORD_CLIENT_SECRET || "",
},
auth: fastifyOauth2.DISCORD_CONFIGURATION,
},
startRedirectPath: "/api/auth/login",
callbackUri: `${process.env.API_URL || "http://localhost:3000"}/api/auth/callback`,
});
// Authentication decorator
app.decorate("authenticate", async (request: FastifyRequest) => {
try {
await request.jwtVerify();
} catch (err) {
throw app.httpErrors.unauthorized("Invalid token");
}
});
};
export default fastifyPlugin(authPlugin);