73 lines
2.4 KiB
TypeScript
73 lines
2.4 KiB
TypeScript
import fs from 'node:fs/promises';
|
|
import os from 'node:os';
|
|
import path from 'node:path';
|
|
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
import { getGameDb } from '@/lib/db/client';
|
|
import { createSession } from '@/lib/auth';
|
|
import { GET } from './route';
|
|
|
|
// v0.71.0 — /api/me tests: resolves X-Flight-Session to its user, 401 otherwise.
|
|
|
|
let dir: string;
|
|
|
|
beforeAll(async () => {
|
|
dir = await fs.mkdtemp(path.join(os.tmpdir(), 'flight-me-api-'));
|
|
process.env.FLIGHT_DB_PATH = path.join(dir, 'me.db');
|
|
});
|
|
|
|
afterAll(async () => {
|
|
delete process.env.FLIGHT_DB_PATH;
|
|
await fs.rm(dir, { recursive: true, force: true });
|
|
});
|
|
|
|
const get = (sessionId?: string) =>
|
|
GET(
|
|
new Request('http://localhost/api/me', {
|
|
headers: sessionId ? { 'X-Flight-Session': sessionId } : undefined,
|
|
}),
|
|
);
|
|
|
|
describe('GET /api/me', () => {
|
|
it('returns 401 without a session header', async () => {
|
|
const res = await get();
|
|
expect(res.status).toBe(401);
|
|
});
|
|
|
|
it('returns 401 for an unknown session id', async () => {
|
|
const res = await get('00000000-0000-4000-8000-000000000000');
|
|
expect(res.status).toBe(401);
|
|
});
|
|
|
|
it('returns 401 for an expired session', async () => {
|
|
const inst = await getGameDb();
|
|
// A session whose expiry is already in the past.
|
|
inst.raw.run('INSERT INTO sessions (id, user_id, expires_at) VALUES (?, ?, ?)', [
|
|
'expired-session-id',
|
|
'admin-kamilkrzywda',
|
|
Date.now() - 1000,
|
|
]);
|
|
const res = await get('expired-session-id');
|
|
expect(res.status).toBe(401);
|
|
});
|
|
|
|
it('returns the user for a live session (admin flag included)', async () => {
|
|
const sessionId = await createSession(await getGameDb(), 'admin-kamilkrzywda');
|
|
const res = await get(sessionId);
|
|
expect(res.status).toBe(200);
|
|
expect(await res.json()).toEqual({ username: 'kamilkrzywda', admin: true });
|
|
});
|
|
|
|
it('reports non-admin users as such', async () => {
|
|
const inst = await getGameDb();
|
|
inst.raw.run(
|
|
`INSERT INTO users (id, username, password_hash, admin, created_at)
|
|
SELECT 'user-me-test', 'me-test-user', 'aa$bb', 0, ? WHERE NOT EXISTS (SELECT 1 FROM users WHERE id = 'user-me-test')`,
|
|
[Date.now()],
|
|
);
|
|
const sessionId = await createSession(inst, 'user-me-test');
|
|
const res = await get(sessionId);
|
|
expect(res.status).toBe(200);
|
|
expect(await res.json()).toEqual({ username: 'me-test-user', admin: false });
|
|
});
|
|
});
|