feat: implement basic authentication system
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
import { test, expect } from "./fixtures";
|
||||
|
||||
test.describe("Authentication", () => {
|
||||
test("should require login and allow logout", async ({ page }) => {
|
||||
const username = process.env.AUTH_USERNAME || "admin";
|
||||
const password = process.env.AUTH_PASSWORD || "admin";
|
||||
|
||||
await page.context().clearCookies();
|
||||
await page.goto("/");
|
||||
|
||||
await expect(page.getByText("Sign in to access your drawings")).toBeVisible();
|
||||
|
||||
await page.getByLabel("Username").fill(username);
|
||||
await page.getByLabel("Password").fill(password);
|
||||
await page.getByRole("button", { name: "Sign in" }).click();
|
||||
|
||||
// Wait for the dashboard to fully load (login updates state, no URL change)
|
||||
await expect(page.getByPlaceholder("Search drawings...")).toBeVisible({ timeout: 30000 });
|
||||
|
||||
await page.goto("/settings");
|
||||
const logoutButton = page.getByRole("button", { name: /Log out/i });
|
||||
await expect(logoutButton).toBeVisible();
|
||||
await logoutButton.click();
|
||||
|
||||
await expect(page.getByText("Sign in to access your drawings")).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { test, expect } from "./fixtures";
|
||||
import { ensurePageAuthenticated } from "./helpers/auth";
|
||||
import {
|
||||
createDrawing,
|
||||
deleteDrawing,
|
||||
@@ -42,6 +43,8 @@ test.describe("Real-time Collaboration", () => {
|
||||
|
||||
try {
|
||||
// Both users navigate to the same drawing
|
||||
await ensurePageAuthenticated(page1);
|
||||
await ensurePageAuthenticated(page2);
|
||||
await page1.goto(`/editor/${drawing.id}`);
|
||||
await page2.goto(`/editor/${drawing.id}`);
|
||||
|
||||
@@ -88,6 +91,8 @@ test.describe("Real-time Collaboration", () => {
|
||||
|
||||
try {
|
||||
// Both users navigate to the same drawing
|
||||
await ensurePageAuthenticated(page1);
|
||||
await ensurePageAuthenticated(page2);
|
||||
await page1.goto(`/editor/${drawing.id}`);
|
||||
await page2.goto(`/editor/${drawing.id}`);
|
||||
|
||||
@@ -190,6 +195,8 @@ test.describe("Real-time Collaboration", () => {
|
||||
const page2 = await context2.newPage();
|
||||
|
||||
try {
|
||||
await ensurePageAuthenticated(page1);
|
||||
await ensurePageAuthenticated(page2);
|
||||
await page1.goto(`/editor/${drawing.id}`);
|
||||
await page2.goto(`/editor/${drawing.id}`);
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { test, expect } from "./fixtures";
|
||||
import type { Locator, Page } from "@playwright/test";
|
||||
import {
|
||||
API_URL,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { test, expect } from "./fixtures";
|
||||
import * as path from "path";
|
||||
import * as fs from "fs";
|
||||
import {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { test, expect } from "./fixtures";
|
||||
import {
|
||||
API_URL,
|
||||
createDrawing,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { test, expect } from "./fixtures";
|
||||
import {
|
||||
API_URL,
|
||||
createDrawing,
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { test as base, expect } from "@playwright/test";
|
||||
|
||||
const AUTH_USERNAME = process.env.AUTH_USERNAME || "admin";
|
||||
const AUTH_PASSWORD = process.env.AUTH_PASSWORD || "admin";
|
||||
|
||||
export const test = base;
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
// Navigate to root to check if we need to login
|
||||
await page.goto("/");
|
||||
await page.waitForLoadState("domcontentloaded");
|
||||
|
||||
// If we see the login page, perform login
|
||||
const loginText = page.getByText("Sign in to access your drawings");
|
||||
if (await loginText.isVisible({ timeout: 2000 }).catch(() => false)) {
|
||||
await page.getByLabel("Username").fill(AUTH_USERNAME);
|
||||
await page.getByLabel("Password").fill(AUTH_PASSWORD);
|
||||
await page.getByRole("button", { name: "Sign in" }).click();
|
||||
// Wait for dashboard to load
|
||||
await page.getByPlaceholder("Search drawings...").waitFor({ state: "visible", timeout: 15000 });
|
||||
}
|
||||
});
|
||||
|
||||
export { expect };
|
||||
@@ -5,6 +5,58 @@ const DEFAULT_BACKEND_PORT = 8000;
|
||||
|
||||
export const API_URL = process.env.API_URL || `http://localhost:${DEFAULT_BACKEND_PORT}`;
|
||||
|
||||
const AUTH_USERNAME = process.env.AUTH_USERNAME || "admin";
|
||||
const AUTH_PASSWORD = process.env.AUTH_PASSWORD || "admin";
|
||||
|
||||
// Track authenticated API contexts
|
||||
const authenticatedContexts = new WeakSet<APIRequestContext>();
|
||||
|
||||
/**
|
||||
* Ensure the API request context is authenticated
|
||||
*/
|
||||
export async function ensureAuthenticated(request: APIRequestContext): Promise<void> {
|
||||
if (authenticatedContexts.has(request)) return;
|
||||
|
||||
// Check current auth status
|
||||
const statusResp = await request.get(`${API_URL}/auth/status`);
|
||||
if (!statusResp.ok()) {
|
||||
throw new Error(`Failed to check auth status: ${statusResp.status()}`);
|
||||
}
|
||||
|
||||
const status = (await statusResp.json()) as { enabled: boolean; authenticated: boolean };
|
||||
|
||||
if (!status.enabled) {
|
||||
// Auth is disabled, mark as "authenticated"
|
||||
authenticatedContexts.add(request);
|
||||
return;
|
||||
}
|
||||
|
||||
if (status.authenticated) {
|
||||
authenticatedContexts.add(request);
|
||||
return;
|
||||
}
|
||||
|
||||
// Need to login
|
||||
const csrfHeaders = await getCsrfHeaders(request);
|
||||
const loginResp = await request.post(`${API_URL}/auth/login`, {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...csrfHeaders,
|
||||
},
|
||||
data: {
|
||||
username: AUTH_USERNAME,
|
||||
password: AUTH_PASSWORD,
|
||||
},
|
||||
});
|
||||
|
||||
if (!loginResp.ok()) {
|
||||
const text = await loginResp.text();
|
||||
throw new Error(`API authentication failed: ${loginResp.status()} ${text}`);
|
||||
}
|
||||
|
||||
authenticatedContexts.add(request);
|
||||
}
|
||||
|
||||
type CsrfTokenResponse = {
|
||||
token: string;
|
||||
header?: string;
|
||||
@@ -137,6 +189,8 @@ export async function createDrawing(
|
||||
request: APIRequestContext,
|
||||
overrides: CreateDrawingOptions = {}
|
||||
): Promise<DrawingRecord> {
|
||||
await ensureAuthenticated(request);
|
||||
|
||||
const payload = { ...defaultDrawingPayload(), ...overrides };
|
||||
const headers = await withCsrfHeaders(request, { "Content-Type": "application/json" });
|
||||
|
||||
@@ -169,6 +223,7 @@ export async function getDrawing(
|
||||
request: APIRequestContext,
|
||||
id: string
|
||||
): Promise<DrawingRecord> {
|
||||
await ensureAuthenticated(request);
|
||||
const response = await request.get(`${API_URL}/drawings/${id}`);
|
||||
expect(response.ok()).toBe(true);
|
||||
return (await response.json()) as DrawingRecord;
|
||||
@@ -178,6 +233,7 @@ export async function deleteDrawing(
|
||||
request: APIRequestContext,
|
||||
id: string
|
||||
): Promise<void> {
|
||||
await ensureAuthenticated(request);
|
||||
const headers = await withCsrfHeaders(request);
|
||||
let response = await request.delete(`${API_URL}/drawings/${id}`, { headers });
|
||||
|
||||
@@ -202,6 +258,7 @@ export async function listDrawings(
|
||||
request: APIRequestContext,
|
||||
options: ListDrawingsOptions = {}
|
||||
): Promise<DrawingRecord[]> {
|
||||
await ensureAuthenticated(request);
|
||||
const params = new URLSearchParams();
|
||||
if (options.search) params.set("search", options.search);
|
||||
if (options.collectionId !== undefined) {
|
||||
@@ -224,6 +281,7 @@ export async function createCollection(
|
||||
request: APIRequestContext,
|
||||
name: string
|
||||
): Promise<CollectionRecord> {
|
||||
await ensureAuthenticated(request);
|
||||
const headers = await withCsrfHeaders(request, { "Content-Type": "application/json" });
|
||||
|
||||
let response = await request.post(`${API_URL}/collections`, {
|
||||
@@ -249,6 +307,7 @@ export async function createCollection(
|
||||
export async function listCollections(
|
||||
request: APIRequestContext
|
||||
): Promise<CollectionRecord[]> {
|
||||
await ensureAuthenticated(request);
|
||||
const response = await request.get(`${API_URL}/collections`);
|
||||
expect(response.ok()).toBe(true);
|
||||
return (await response.json()) as CollectionRecord[];
|
||||
@@ -258,6 +317,7 @@ export async function deleteCollection(
|
||||
request: APIRequestContext,
|
||||
id: string
|
||||
): Promise<void> {
|
||||
await ensureAuthenticated(request);
|
||||
const headers = await withCsrfHeaders(request);
|
||||
let response = await request.delete(`${API_URL}/collections/${id}`, { headers });
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { APIRequestContext, Page } from "@playwright/test";
|
||||
import { API_URL, getCsrfHeaders } from "./api";
|
||||
|
||||
type AuthStatus = {
|
||||
enabled: boolean;
|
||||
authenticated: boolean;
|
||||
};
|
||||
|
||||
const AUTH_USERNAME = process.env.AUTH_USERNAME || "admin";
|
||||
const AUTH_PASSWORD = process.env.AUTH_PASSWORD || "admin";
|
||||
|
||||
const authStatusCache = new WeakMap<APIRequestContext, AuthStatus>();
|
||||
|
||||
const fetchAuthStatus = async (request: APIRequestContext): Promise<AuthStatus> => {
|
||||
const cached = authStatusCache.get(request);
|
||||
// Only use cache if we're already authenticated
|
||||
if (cached?.authenticated) return cached;
|
||||
|
||||
const response = await request.get(`${API_URL}/auth/status`);
|
||||
if (!response.ok()) {
|
||||
const text = await response.text();
|
||||
throw new Error(`Failed to fetch auth status: ${response.status()} ${text}`);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as AuthStatus;
|
||||
authStatusCache.set(request, data);
|
||||
return data;
|
||||
};
|
||||
|
||||
const setAuthStatus = (request: APIRequestContext, status: AuthStatus) => {
|
||||
authStatusCache.set(request, status);
|
||||
};
|
||||
|
||||
export const ensureApiAuthenticated = async (request: APIRequestContext) => {
|
||||
const status = await fetchAuthStatus(request);
|
||||
if (!status.enabled || status.authenticated) {
|
||||
return;
|
||||
}
|
||||
|
||||
const headers = await getCsrfHeaders(request);
|
||||
const response = await request.post(`${API_URL}/auth/login`, {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...headers,
|
||||
},
|
||||
data: {
|
||||
username: AUTH_USERNAME,
|
||||
password: AUTH_PASSWORD,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok()) {
|
||||
const text = await response.text();
|
||||
throw new Error(`Failed to authenticate test session: ${response.status()} ${text}`);
|
||||
}
|
||||
|
||||
setAuthStatus(request, { enabled: true, authenticated: true });
|
||||
};
|
||||
|
||||
export const ensurePageAuthenticated = async (page: Page) => {
|
||||
await ensureApiAuthenticated(page.request);
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { test, expect } from "./fixtures";
|
||||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
import {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { test, expect } from "./fixtures";
|
||||
import {
|
||||
createDrawing,
|
||||
deleteDrawing,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { test, expect } from "./fixtures";
|
||||
|
||||
/**
|
||||
* E2E Tests for Theme Toggle functionality
|
||||
|
||||
Reference in New Issue
Block a user