This commit is contained in:
53
server/src/auth/plugin.ts
Normal file
53
server/src/auth/plugin.ts
Normal 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' });
|
||||
Reference in New Issue
Block a user