const { requireAdminAuth } = require('../../src/middlewares/auth'); describe('Auth Middleware Unit Test', () => { let req, res, next; beforeEach(() => { req = { headers: {} }; res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; next = jest.fn(); process.env.ADMIN_API_KEY = 'test-key-123'; }); test('should reject missing Authorization header', () => { requireAdminAuth(req, res, next); expect(res.status).toHaveBeenCalledWith(403); expect(res.json).toHaveBeenCalledWith( expect.objectContaining({ error: 'Zugriff verweigert', message: 'Authorization header fehlt' }) ); expect(next).not.toHaveBeenCalled(); }); test('should reject invalid Bearer format', () => { req.headers.authorization = 'Invalid token'; requireAdminAuth(req, res, next); expect(res.status).toHaveBeenCalledWith(403); expect(res.json).toHaveBeenCalledWith( expect.objectContaining({ message: expect.stringContaining('Ungültiges Authorization Format') }) ); expect(next).not.toHaveBeenCalled(); }); test('should reject wrong token', () => { req.headers.authorization = 'Bearer wrong-token'; requireAdminAuth(req, res, next); expect(res.status).toHaveBeenCalledWith(403); expect(res.json).toHaveBeenCalledWith( expect.objectContaining({ message: 'Ungültiger Admin-Token' }) ); expect(next).not.toHaveBeenCalled(); }); test('should allow valid token', () => { req.headers.authorization = 'Bearer test-key-123'; requireAdminAuth(req, res, next); expect(next).toHaveBeenCalled(); expect(res.status).not.toHaveBeenCalled(); expect(res.json).not.toHaveBeenCalled(); }); test('should handle missing ADMIN_API_KEY', () => { delete process.env.ADMIN_API_KEY; req.headers.authorization = 'Bearer any-token'; requireAdminAuth(req, res, next); expect(res.status).toHaveBeenCalledWith(500); expect(res.json).toHaveBeenCalledWith( expect.objectContaining({ error: 'Server-Konfigurationsfehler' }) ); expect(next).not.toHaveBeenCalled(); }); });