import { encode } from "@auth/core/jwt"; import { expect, type Page } from "@playwright/test"; import { prisma } from "$lib/server/prisma"; const AUTH_COOKIE = "authjs.session-token"; export const OIDC_BASE_URL = "http://localhost:9090/interaction/"; export const USERNAME = "Tico Testboy"; export const USER_EMAIL = "t.testboy@example.org"; export async function loginIfNecessary(page: Page) { if (page.url().startsWith(OIDC_BASE_URL)) { await page.locator('input[name="login"]').fill("Lucy Login"); await page.locator('input[name="password"]').fill("1234"); await page.locator("button.login-submit").click(); await page.getByRole("button", { name: "Continue" }).click(); expect(await isLoggedIn(page)).toBe(true); } } export async function isLoggedIn(page: Page): Promise { const cookies = await page.context().cookies(); return cookies.findIndex((c) => c.name === AUTH_COOKIE) !== -1; } /** * Create a session token (Cookie: authjs.session-token) to use for E2E tests * so we dont have to step through the login system every time */ export async function newSessionToken(user_id: number): Promise { const user = await prisma.user.findUniqueOrThrow({ select: { email: true, name: true }, where: { id: user_id }, }); return encode({ salt: AUTH_COOKIE, secret: process.env.AUTH_SECRET!, token: { name: user.name, email: user.email, sub: user_id.toString(), id: user_id.toString(), }, }); } export async function loginWithToken(page: Page, user_id = 1) { const token = await newSessionToken(user_id); await page.context().addCookies([{ name: AUTH_COOKIE, value: token, domain: "localhost", path: "/", httpOnly: true, sameSite: "Lax", }]); }