generated from nhcarrigan/template
feat: auth
This commit is contained in:
@@ -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);
|
||||
@@ -1,3 +1,9 @@
|
||||
/**
|
||||
* @copyright 2026 NHCarrigan
|
||||
* @license Naomi's Public License
|
||||
* @author Naomi Carrigan
|
||||
*/
|
||||
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import fp from 'fastify-plugin';
|
||||
import sensible from '@fastify/sensible';
|
||||
|
||||
Reference in New Issue
Block a user