test(api): centralize auth helpers on server-side createUser

This commit is contained in:
Bas van Rossem
2026-06-17 17:29:46 +02:00
parent 8bfdfb736e
commit f6bd8eb036
5 changed files with 72 additions and 110 deletions

54
apps/api/test/helpers.ts Normal file
View File

@@ -0,0 +1,54 @@
import type { Hono } from 'hono';
import { auth } from '../src/auth';
import { db } from '../src/db/client';
import { activities } from '../src/db/schema';
const PASSWORD = 'sterk-wachtwoord-123';
const json = { 'content-type': 'application/json' };
// Create a user server-side. Prefer the admin plugin's createUser (bypasses
// `disableSignUp` and sets the role); fall back to signUpEmail while the admin
// plugin isn't wired yet (sign-up is still open at that point). Either way the
// test no longer depends on the public sign-up *route*.
export async function createTestUser(email: string, role: 'worker' | 'admin' = 'worker') {
const api = auth.api as {
createUser?: (args: {
body: { email: string; password: string; name: string; role: 'worker' | 'admin' };
}) => Promise<unknown>;
};
const name = email.split('@')[0] || 'User';
if (typeof api.createUser === 'function') {
await api.createUser({ body: { email, password: PASSWORD, name, role } });
} else {
await auth.api.signUpEmail({ body: { email, password: PASSWORD, name } });
}
}
export async function authToken(
app: Hono,
email: string,
role: 'worker' | 'admin' = 'worker'
): Promise<string> {
await createTestUser(email, role);
const signin = await app.request('/api/auth/sign-in/email', {
method: 'POST',
headers: json,
body: JSON.stringify({ email, password: PASSWORD }),
});
const token = signin.headers.get('set-auth-token');
if (!token) throw new Error('no token');
return token;
}
export function bearer(token: string): Record<string, string> {
return { authorization: `Bearer ${token}`, 'content-type': 'application/json' };
}
// Insert an activity straight into the DB (test setup that should not depend on authz).
export async function seedActivity(
name: string,
insoleTypes: string[] = ['Kurk', 'Berk', '3D']
): Promise<number> {
const [row] = await db.insert(activities).values({ name, insoleTypes }).returning();
return row.id;
}