66 lines
2.2 KiB
TypeScript
66 lines
2.2 KiB
TypeScript
import { describe, it, expect, afterEach, vi } from 'vitest';
|
|
import { createApp } from '../src/app';
|
|
import { auth } from '../src/auth';
|
|
import { authToken, bearer } from './helpers';
|
|
|
|
describe('GET /api/me', () => {
|
|
afterEach(() => vi.restoreAllMocks());
|
|
|
|
it('rejects an unauthenticated request', async () => {
|
|
const app = createApp();
|
|
const res = await app.request('/api/me');
|
|
expect(res.status).toBe(401);
|
|
});
|
|
|
|
it('returns the user for a valid bearer token (create -> sign-in -> me)', async () => {
|
|
const app = createApp();
|
|
const email = 'me@example.com';
|
|
const token = await authToken(app, email);
|
|
|
|
const res = await app.request('/api/me', { headers: bearer(token) });
|
|
expect(res.status).toBe(200);
|
|
const body = await res.json();
|
|
expect(body.user.email).toBe(email);
|
|
});
|
|
|
|
it('returns role "worker" for a worker token', async () => {
|
|
const app = createApp();
|
|
const token = await authToken(app, 'worker-role@example.com', 'worker');
|
|
|
|
const res = await app.request('/api/me', { headers: bearer(token) });
|
|
expect(res.status).toBe(200);
|
|
const body = await res.json();
|
|
expect(body.user.role).toBe('worker');
|
|
});
|
|
|
|
it('returns role "admin" for an admin token', async () => {
|
|
const app = createApp();
|
|
const token = await authToken(app, 'admin-role@example.com', 'admin');
|
|
|
|
const res = await app.request('/api/me', { headers: bearer(token) });
|
|
expect(res.status).toBe(200);
|
|
const body = await res.json();
|
|
expect(body.user.role).toBe('admin');
|
|
});
|
|
|
|
it("defaults role to 'worker' when the session user has no role", async () => {
|
|
const app = createApp();
|
|
// A role-less session can't arise from a real sign-in (the admin plugin always
|
|
// sets a role), so stub getSession to hit the `?? 'worker'` fallback branch.
|
|
vi.spyOn(auth.api, 'getSession').mockResolvedValue({
|
|
user: { id: 'u1', email: 'norole@example.com', name: 'No Role' },
|
|
session: {},
|
|
} as never);
|
|
|
|
const res = await app.request('/api/me', { headers: bearer('irrelevant') });
|
|
expect(res.status).toBe(200);
|
|
const body = await res.json();
|
|
expect(body.user).toEqual({
|
|
id: 'u1',
|
|
email: 'norole@example.com',
|
|
name: 'No Role',
|
|
role: 'worker',
|
|
});
|
|
});
|
|
});
|