This commit is contained in:
+29
-2
@@ -22,9 +22,16 @@ export interface ServerOptions {
|
||||
export async function createServer(opts: ServerOptions) {
|
||||
const fastify = Fastify({ logger: true });
|
||||
|
||||
// CORS
|
||||
// CORS — restrictive origin list
|
||||
await fastify.register(cors, {
|
||||
origin: true,
|
||||
origin: (origin: string | undefined, cb: (err: Error | null, allow: boolean) => void) => {
|
||||
// Allow requests with no origin (same-origin, curl, etc.)
|
||||
if (!origin) return cb(null, true);
|
||||
// Allow known origins
|
||||
const allowed = ['https://web-cad-neu.server.media-on.de', 'http://localhost:5173', 'http://localhost:8082'];
|
||||
if (allowed.includes(origin)) return cb(null, true);
|
||||
cb(new Error('Not allowed by CORS'), false);
|
||||
},
|
||||
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
|
||||
});
|
||||
|
||||
@@ -62,6 +69,26 @@ export async function createServer(opts: ServerOptions) {
|
||||
|
||||
const authService = new AuthService(opts.db);
|
||||
|
||||
// Auth middleware — protect all /api/ routes except auth login/register
|
||||
fastify.addHook('onRequest', async (request: any, reply: any) => {
|
||||
const url = request.url;
|
||||
// Skip auth endpoints and health check
|
||||
if (url === '/api/auth/login' || url === '/api/auth/register' || url === '/api/health') return;
|
||||
// Skip non-API routes (static files, WebSocket)
|
||||
if (!url.startsWith('/api/')) return;
|
||||
|
||||
const auth = request.headers.authorization;
|
||||
if (!auth || !auth.startsWith('Bearer ')) {
|
||||
return reply.code(401).send({ error: 'Authentication required' });
|
||||
}
|
||||
const token = auth.slice(7);
|
||||
const user = authService.getUserFromSession(token);
|
||||
if (!user) {
|
||||
return reply.code(401).send({ error: 'Invalid or expired session' });
|
||||
}
|
||||
(request as any).user = user;
|
||||
});
|
||||
|
||||
registerAuthRoutes(fastify, authService);
|
||||
registerProjectRoutes(fastify, opts.db);
|
||||
registerDrawingRoutes(fastify, opts.db);
|
||||
|
||||
Reference in New Issue
Block a user