import { BoardService } from '../services/boardService.js'; /** * Middleware to require board authorization. * Role parameter defaults to allowing both 'admin' and 'member'. * Pass 'admin' to restrict to superadmin only. */ export function requireBoardAuth(requiredRole) { return async (req, res, next) => { try { const boardId = (req.params.boardId || req.params.id || req.body.boardId || req.query.boardId); if (!boardId) { res.status(400).json({ error: 'Missing board ID' }); return; } // Extract key from header, query, or body let key = ''; const authHeader = req.headers.authorization; if (authHeader && authHeader.startsWith('Bearer ')) { key = authHeader.substring(7).trim(); } else if (req.headers['x-board-key']) { key = String(req.headers['x-board-key']).trim(); } else if (req.query.key) { key = String(req.query.key).trim(); } else if (req.body.key) { key = String(req.body.key).trim(); } if (!key) { res.status(401).json({ error: 'Unauthorized: Key is missing in request headers' }); return; } const authResult = await BoardService.authenticateKey(boardId, key); if (!authResult) { res.status(403).json({ error: 'Forbidden: Invalid key for this board' }); return; } if (requiredRole && requiredRole === 'admin' && authResult.role !== 'admin') { res.status(403).json({ error: 'Forbidden: Superadmin access required' }); return; } req.boardAuth = { boardId, role: authResult.role, board: authResult.board, }; next(); } catch (error) { console.error('Error in auth middleware:', error); res.status(500).json({ error: 'Internal Server Error during authentication' }); } }; }