feat: add admin questions routes
Made-with: Cursor
This commit is contained in:
@@ -1,11 +1,14 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import fp from 'fastify-plugin';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { verifyToken, isAccessPayload } from '../utils/jwt.js';
|
||||
import { unauthorized } from '../utils/errors.js';
|
||||
import { unauthorized, forbidden } from '../utils/errors.js';
|
||||
import { users } from '../db/schema/users.js';
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyInstance {
|
||||
authenticate: (req: FastifyRequest, reply: FastifyReply) => Promise<void>;
|
||||
authenticateAdmin: (req: FastifyRequest, reply: FastifyReply) => Promise<void>;
|
||||
}
|
||||
interface FastifyRequest {
|
||||
user?: { id: string; email: string };
|
||||
@@ -34,9 +37,22 @@ export async function authenticate(req: FastifyRequest, _reply: FastifyReply): P
|
||||
}
|
||||
}
|
||||
|
||||
export async function authenticateAdmin(req: FastifyRequest, _reply: FastifyReply): Promise<void> {
|
||||
if (!req.user) {
|
||||
throw unauthorized('Authentication required');
|
||||
}
|
||||
|
||||
const [user] = await req.server.db.select({ role: users.role }).from(users).where(eq(users.id, req.user.id));
|
||||
|
||||
if (!user || user.role !== 'admin') {
|
||||
throw forbidden('Admin access required');
|
||||
}
|
||||
}
|
||||
|
||||
const authPlugin = async (app: FastifyInstance) => {
|
||||
app.decorateRequest('user', undefined);
|
||||
app.decorate('authenticate', authenticate);
|
||||
app.decorate('authenticateAdmin', authenticateAdmin);
|
||||
};
|
||||
|
||||
export default fp(authPlugin, { name: 'auth' });
|
||||
export default fp(authPlugin, { name: 'auth', dependencies: ['database'] });
|
||||
|
||||
Reference in New Issue
Block a user