generated from nhcarrigan/template
feat: security and auditing
This commit is contained in:
@@ -5,17 +5,27 @@
|
||||
*/
|
||||
|
||||
import { FastifyReply, FastifyRequest } from "fastify";
|
||||
import { UserService } from "../services/user.service";
|
||||
|
||||
const userService = new UserService();
|
||||
|
||||
/**
|
||||
* Middleware to check if the authenticated user is an admin.
|
||||
* Must be used after app.authenticate.
|
||||
* Always checks the database to ensure admin status is current.
|
||||
*/
|
||||
export async function adminGuard(
|
||||
request: FastifyRequest,
|
||||
reply: FastifyReply
|
||||
): Promise<void> {
|
||||
const user = request.user as any;
|
||||
if (!user || !user.isAdmin) {
|
||||
const user = request.user as { id: string };
|
||||
|
||||
if (!user?.id) {
|
||||
return reply.code(401).send({ error: "Unauthorized" });
|
||||
}
|
||||
|
||||
const dbUser = await userService.getUserById(user.id);
|
||||
if (!dbUser?.isAdmin) {
|
||||
return reply.code(403).send({ error: "Forbidden: Admin access required" });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* @copyright 2026 NHCarrigan
|
||||
* @license Naomi's Public License
|
||||
* @author Naomi Carrigan
|
||||
*/
|
||||
|
||||
import { FastifyReply, FastifyRequest } from "fastify";
|
||||
import { UserService } from "../services/user.service";
|
||||
|
||||
const userService = new UserService();
|
||||
|
||||
/**
|
||||
* Middleware to check if the authenticated user is banned.
|
||||
* Must be used after app.authenticate.
|
||||
*/
|
||||
export async function bannedGuard(
|
||||
request: FastifyRequest,
|
||||
reply: FastifyReply
|
||||
): Promise<void> {
|
||||
const user = request.user as { id: string };
|
||||
|
||||
if (!user?.id) {
|
||||
return reply.code(401).send({ error: "Unauthorized" });
|
||||
}
|
||||
|
||||
const isBanned = await userService.isUserBanned(user.id);
|
||||
if (isBanned) {
|
||||
return reply.code(403).send({ error: "You have been banned from commenting" });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user