first commit
Some checks failed
CI / Validate frontend and API (push) Failing after 7m27s

This commit is contained in:
Cauê Faleiros
2026-08-31 12:38:34 -03:00
parent 684f929f28
commit 701788ea08
40 changed files with 5396 additions and 380 deletions

53
server/src/auth/plugin.ts Normal file
View File

@@ -0,0 +1,53 @@
import fastifyJwt from '@fastify/jwt';
import type { FastifyPluginAsync, preHandlerHookHandler } from 'fastify';
import fastifyPlugin from 'fastify-plugin';
import { config } from '../config.js';
export type UserRole = 'student' | 'instructor' | 'admin';
export interface AuthUser {
id: string;
email: string;
role: UserRole;
name: string;
}
declare module '@fastify/jwt' {
interface FastifyJWT {
payload: AuthUser;
user: AuthUser;
}
}
declare module 'fastify' {
interface FastifyInstance {
authenticate: preHandlerHookHandler;
requireRoles: (roles: UserRole[]) => preHandlerHookHandler;
}
}
const registerAuth: FastifyPluginAsync = async (app) => {
await app.register(fastifyJwt, { secret: config.JWT_SECRET });
app.decorate('authenticate', async (request, reply) => {
try {
await request.jwtVerify();
} catch {
return reply.code(401).send({ error: 'Authentication required' });
}
});
app.decorate('requireRoles', (roles: UserRole[]) => async (request, reply) => {
try {
await request.jwtVerify();
} catch {
return reply.code(401).send({ error: 'Authentication required' });
}
if (!roles.includes(request.user.role)) {
return reply.code(403).send({ error: 'Insufficient permissions' });
}
});
};
export const authPlugin = fastifyPlugin(registerAuth, { name: 'auth' });