82 lines
2.3 KiB
TypeScript
82 lines
2.3 KiB
TypeScript
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
|
import { Hono } from 'hono';
|
|
|
|
const db = {
|
|
$queryRaw: mock(),
|
|
};
|
|
|
|
mock.module('@/lib/prisma', () => ({
|
|
default: db,
|
|
getPrismaClient: mock(() => db),
|
|
UnitOfWork: class {},
|
|
}));
|
|
|
|
mock.module('@/modules/auth/auth', () => ({
|
|
auth: {
|
|
api: {
|
|
getSession: mock(),
|
|
},
|
|
},
|
|
}));
|
|
|
|
import {
|
|
isPublicApiRequest,
|
|
sessionAuthMiddleware,
|
|
} from '@/http/session-auth';
|
|
import { auth } from '@/modules/auth/auth';
|
|
|
|
describe('session auth', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
});
|
|
|
|
it('classifies public API requests', () => {
|
|
expect(isPublicApiRequest('OPTIONS', '/api/v1/groups')).toBe(true);
|
|
expect(isPublicApiRequest('GET', '/api/v1/health')).toBe(true);
|
|
expect(isPublicApiRequest('POST', '/api/v1/auth/sign-in/email')).toBe(true);
|
|
expect(isPublicApiRequest('GET', '/api/v1/groups')).toBe(false);
|
|
expect(isPublicApiRequest('GET', '/api/v1/attendees')).toBe(false);
|
|
});
|
|
|
|
it('allows public requests without a session', async () => {
|
|
const app = new Hono();
|
|
app.use('*', sessionAuthMiddleware);
|
|
app.get('/api/v1/health', (c) => c.json({ status: 'ok' }));
|
|
|
|
const res = await app.request('/api/v1/health');
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(auth.api.getSession).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('rejects protected requests without a session', async () => {
|
|
auth.api.getSession.mockResolvedValue(null);
|
|
|
|
const app = new Hono();
|
|
app.use('*', sessionAuthMiddleware);
|
|
app.get('/api/v1/groups', (c) => c.json({}));
|
|
|
|
const res = await app.request('/api/v1/groups');
|
|
|
|
expect(res.status).toBe(401);
|
|
expect(await res.json()).toMatchObject({ code: 'unauthorized' });
|
|
});
|
|
|
|
it('sets the user and session for authenticated requests', async () => {
|
|
const session = {
|
|
user: { id: 'user-1', name: 'Ana' },
|
|
session: { id: 'session-1' },
|
|
};
|
|
auth.api.getSession.mockResolvedValue(session as never);
|
|
|
|
const app = new Hono();
|
|
app.use('*', sessionAuthMiddleware);
|
|
app.get('/api/v1/groups', (c) => c.json({ userId: c.get('user').id }));
|
|
|
|
const res = await app.request('/api/v1/groups');
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(await res.json()).toEqual({ userId: 'user-1' });
|
|
expect(auth.api.getSession).toHaveBeenCalledTimes(1);
|
|
});
|
|
}); |