Files
fiberops-web/e2e/helpers/auth.ts

75 lines
2.7 KiB
TypeScript

import { Page, request as playwrightRequest } from '@playwright/test';
export const DEMO = {
tenant: 'demo-isp',
email: 'admin@demo-isp.com',
password: 'Admin123!',
};
// Use the public API URL — Node.js requests bypass browser CORS
const API_URL = 'https://fiberops-api.juankibin.space';
// Cache token across tests to avoid rate-limiting
let cachedAuth: { accessToken: string; user: any; expiresAt: number } | null = null;
export async function loginViaAPI(creds = DEMO) {
// Return cached token if still fresh (within 4 minutes)
if (cachedAuth && Date.now() < cachedAuth.expiresAt) {
return { accessToken: cachedAuth.accessToken, user: cachedAuth.user };
}
// Retry up to 3 times with backoff
for (let attempt = 0; attempt < 3; attempt++) {
const ctx = await playwrightRequest.newContext({ baseURL: API_URL });
try {
const resp = await ctx.post('/api/v1/auth/login', {
data: { tenantSlug: creds.tenant, email: creds.email, password: creds.password },
headers: { 'Content-Type': 'application/json', 'x-tenant-slug': creds.tenant },
});
const data = await resp.json();
if (data.accessToken) {
// Cache for 4 minutes
cachedAuth = {
accessToken: data.accessToken,
user: data.user,
expiresAt: Date.now() + 4 * 60 * 1000,
};
return data;
}
console.warn(`Login attempt ${attempt + 1} returned no token:`, JSON.stringify(data).slice(0, 200));
} catch (err) {
console.warn(`Login attempt ${attempt + 1} failed:`, err);
} finally {
await ctx.dispose();
}
// Backoff
if (attempt < 2) await new Promise(r => setTimeout(r, 1000 * (attempt + 1)));
}
throw new Error('loginViaAPI: Failed to obtain token after 3 attempts');
}
export async function login(page: Page, creds = DEMO) {
// Step 1: Get token via Node.js HTTP — bypasses browser CORS entirely
const { accessToken, user } = await loginViaAPI(creds);
// Step 2: Inject zustand persist state into localStorage before navigation
await page.goto('/login');
await page.evaluate(
({ token, tenant, u }) => {
// Zustand persist format: { state: {...}, version: 0 }
localStorage.setItem('fiberops_auth', JSON.stringify({
state: { accessToken: token, tenantSlug: tenant, user: u },
version: 0,
}));
},
{ token: accessToken, tenant: creds.tenant, u: user }
);
// Step 3: Navigate to dashboard — auth guard reads localStorage and passes
await page.goto('/dashboard');
await page.waitForURL(/\/(dashboard|clients|settings)/, { timeout: 15000 });
// Step 4: Verify we're actually on the dashboard (not redirected to login)
await page.waitForSelector('h1:has-text("Dashboard")', { timeout: 10000 });
}