move API protection check into hooks, adjusting corresponding tests

This commit is contained in:
2025-11-04 09:22:53 +01:00
parent 3c16bc89e5
commit fd907c9851
10 changed files with 47 additions and 74 deletions

View File

@@ -0,0 +1,37 @@
import { describe, test, expect, vi } from 'vitest';
import { handle } from '../../src/hooks.server';
const event = {
url: new URL("http://localhost/api/list"),
cookies: { get: vi.fn(() => null) },
locals: {user: null}
};
vi.mock('$lib/auth', () => ({
decryptToken: vi.fn()
}));
describe('API-Endpoints: Zugangs-Mechanismus', () => {
test('Unautorisierter Zugriff', async () => {
const resolve = vi.fn();
const response = await handle({ event, resolve });
expect(response.status).toBe(401);
const body = await response.json();
expect(body.error).toBe('Unauthorized');
expect(resolve).not.toHaveBeenCalled();
});
test('Authentifizierter Zugriff', async () => {
event.locals = {user: { id: 'admin', admin: true }}
const resolve = vi.fn(() => new Response('ok', { status: 200 }));
const response = await handle({ event, resolve });
expect(response.status).toBe(200);
expect(await response.text()).toBe('ok');
expect(resolve).toHaveBeenCalled();
});
})