tests passing

This commit is contained in:
counterweight 2025-12-18 22:08:31 +01:00
parent 0995e1cc77
commit 7ebfb7a2dd
Signed by: counterweight
GPG key ID: 883EDBAA726BD96C
20 changed files with 2009 additions and 126 deletions

View file

@ -0,0 +1,112 @@
"use client";
import { createContext, useContext, useState, useEffect, ReactNode } from "react";
interface User {
id: number;
email: string;
}
interface AuthContextType {
user: User | null;
token: string | null;
isLoading: boolean;
login: (email: string, password: string) => Promise<void>;
register: (email: string, password: string) => Promise<void>;
logout: () => void;
}
const AuthContext = createContext<AuthContextType | null>(null);
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [token, setToken] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const storedToken = localStorage.getItem("token");
if (storedToken) {
setToken(storedToken);
fetchUser(storedToken);
} else {
setIsLoading(false);
}
}, []);
const fetchUser = async (authToken: string) => {
try {
const res = await fetch("http://localhost:8000/api/auth/me", {
headers: { Authorization: `Bearer ${authToken}` },
});
if (res.ok) {
const userData = await res.json();
setUser(userData);
} else {
localStorage.removeItem("token");
setToken(null);
}
} catch {
localStorage.removeItem("token");
setToken(null);
} finally {
setIsLoading(false);
}
};
const login = async (email: string, password: string) => {
const res = await fetch("http://localhost:8000/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
});
if (!res.ok) {
const error = await res.json();
throw new Error(error.detail || "Login failed");
}
const data = await res.json();
localStorage.setItem("token", data.access_token);
setToken(data.access_token);
setUser(data.user);
};
const register = async (email: string, password: string) => {
const res = await fetch("http://localhost:8000/api/auth/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
});
if (!res.ok) {
const error = await res.json();
throw new Error(error.detail || "Registration failed");
}
const data = await res.json();
localStorage.setItem("token", data.access_token);
setToken(data.access_token);
setUser(data.user);
};
const logout = () => {
localStorage.removeItem("token");
setToken(null);
setUser(null);
};
return (
<AuthContext.Provider value={{ user, token, isLoading, login, register, logout }}>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const context = useContext(AuthContext);
if (!context) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
}

View file

@ -1,8 +1,44 @@
import { AuthProvider } from "./auth-context";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
<head>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
<link
href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Instrument+Serif:ital@0;1&display=swap"
rel="stylesheet"
/>
<style>{`
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'DM Sans', system-ui, sans-serif;
-webkit-font-smoothing: antialiased;
}
input:focus {
border-color: rgba(139, 92, 246, 0.5) !important;
box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.1) !important;
}
button:hover:not(:disabled) {
transform: translateY(-1px);
box-shadow: 0 6px 20px rgba(99, 102, 241, 0.5);
}
button:active:not(:disabled) {
transform: translateY(0);
}
a:hover {
text-decoration: underline;
}
`}</style>
</head>
<body>
<AuthProvider>{children}</AuthProvider>
</body>
</html>
);
}

View file

@ -0,0 +1,36 @@
import { render, screen, cleanup } from "@testing-library/react";
import { expect, test, vi, beforeEach, afterEach } from "vitest";
import LoginPage from "./page";
const mockPush = vi.fn();
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: mockPush }),
}));
vi.mock("../auth-context", () => ({
useAuth: () => ({ login: vi.fn() }),
}));
beforeEach(() => vi.clearAllMocks());
afterEach(() => cleanup());
test("renders login form with title", () => {
render(<LoginPage />);
expect(screen.getByText("Welcome back")).toBeDefined();
});
test("renders email and password inputs", () => {
render(<LoginPage />);
expect(screen.getByLabelText("Email")).toBeDefined();
expect(screen.getByLabelText("Password")).toBeDefined();
});
test("renders sign in button", () => {
render(<LoginPage />);
expect(screen.getByRole("button", { name: "Sign in" })).toBeDefined();
});
test("renders link to signup", () => {
render(<LoginPage />);
expect(screen.getByText("Sign up")).toBeDefined();
});

195
frontend/app/login/page.tsx Normal file
View file

@ -0,0 +1,195 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "../auth-context";
export default function LoginPage() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const { login } = useAuth();
const router = useRouter();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError("");
setIsSubmitting(true);
try {
await login(email, password);
router.push("/");
} catch (err) {
setError(err instanceof Error ? err.message : "Login failed");
} finally {
setIsSubmitting(false);
}
};
return (
<main style={styles.main}>
<div style={styles.container}>
<div style={styles.card}>
<div style={styles.header}>
<h1 style={styles.title}>Welcome back</h1>
<p style={styles.subtitle}>Sign in to your account</p>
</div>
<form onSubmit={handleSubmit} style={styles.form}>
{error && <div style={styles.error}>{error}</div>}
<div style={styles.field}>
<label htmlFor="email" style={styles.label}>Email</label>
<input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
style={styles.input}
placeholder="you@example.com"
required
/>
</div>
<div style={styles.field}>
<label htmlFor="password" style={styles.label}>Password</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
style={styles.input}
placeholder="••••••••"
required
/>
</div>
<button
type="submit"
style={{
...styles.button,
opacity: isSubmitting ? 0.7 : 1,
}}
disabled={isSubmitting}
>
{isSubmitting ? "Signing in..." : "Sign in"}
</button>
</form>
<p style={styles.footer}>
Don&apos;t have an account?{" "}
<a href="/signup" style={styles.link}>
Sign up
</a>
</p>
</div>
</div>
</main>
);
}
const styles: Record<string, React.CSSProperties> = {
main: {
minHeight: "100vh",
background: "linear-gradient(135deg, #0f0f23 0%, #1a1a3e 50%, #2d1b4e 100%)",
display: "flex",
alignItems: "center",
justifyContent: "center",
padding: "1rem",
},
container: {
width: "100%",
maxWidth: "420px",
},
card: {
background: "rgba(255, 255, 255, 0.03)",
backdropFilter: "blur(10px)",
border: "1px solid rgba(255, 255, 255, 0.08)",
borderRadius: "24px",
padding: "3rem 2.5rem",
boxShadow: "0 25px 50px -12px rgba(0, 0, 0, 0.5)",
},
header: {
textAlign: "center" as const,
marginBottom: "2.5rem",
},
title: {
fontFamily: "'Instrument Serif', Georgia, serif",
fontSize: "2.5rem",
fontWeight: 400,
color: "#fff",
margin: 0,
letterSpacing: "-0.02em",
},
subtitle: {
fontFamily: "'DM Sans', system-ui, sans-serif",
color: "rgba(255, 255, 255, 0.5)",
marginTop: "0.5rem",
fontSize: "0.95rem",
},
form: {
display: "flex",
flexDirection: "column" as const,
gap: "1.5rem",
},
field: {
display: "flex",
flexDirection: "column" as const,
gap: "0.5rem",
},
label: {
fontFamily: "'DM Sans', system-ui, sans-serif",
color: "rgba(255, 255, 255, 0.7)",
fontSize: "0.875rem",
fontWeight: 500,
},
input: {
fontFamily: "'DM Sans', system-ui, sans-serif",
padding: "0.875rem 1rem",
fontSize: "1rem",
background: "rgba(255, 255, 255, 0.05)",
border: "1px solid rgba(255, 255, 255, 0.1)",
borderRadius: "12px",
color: "#fff",
outline: "none",
transition: "border-color 0.2s, box-shadow 0.2s",
},
button: {
fontFamily: "'DM Sans', system-ui, sans-serif",
marginTop: "0.5rem",
padding: "1rem",
fontSize: "1rem",
fontWeight: 600,
background: "linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)",
color: "#fff",
border: "none",
borderRadius: "12px",
cursor: "pointer",
transition: "transform 0.2s, box-shadow 0.2s",
boxShadow: "0 4px 14px rgba(99, 102, 241, 0.4)",
},
error: {
fontFamily: "'DM Sans', system-ui, sans-serif",
padding: "0.875rem 1rem",
background: "rgba(239, 68, 68, 0.1)",
border: "1px solid rgba(239, 68, 68, 0.3)",
borderRadius: "12px",
color: "#fca5a5",
fontSize: "0.875rem",
textAlign: "center" as const,
},
footer: {
fontFamily: "'DM Sans', system-ui, sans-serif",
textAlign: "center" as const,
marginTop: "2rem",
color: "rgba(255, 255, 255, 0.5)",
fontSize: "0.875rem",
},
link: {
color: "#a78bfa",
textDecoration: "none",
fontWeight: 500,
},
};

View file

@ -1,68 +1,199 @@
import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";
import { expect, test, vi, beforeEach, afterEach } from "vitest";
import { expect, test, vi, beforeEach, afterEach, describe } from "vitest";
import Home from "./page";
// Mock next/navigation
const mockPush = vi.fn();
vi.mock("next/navigation", () => ({
useRouter: () => ({
push: mockPush,
}),
}));
// Default mock values
let mockUser: { id: number; email: string } | null = { id: 1, email: "test@example.com" };
let mockToken: string | null = "valid-token";
let mockIsLoading = false;
const mockLogout = vi.fn();
vi.mock("./auth-context", () => ({
useAuth: () => ({
user: mockUser,
token: mockToken,
isLoading: mockIsLoading,
logout: mockLogout,
}),
}));
beforeEach(() => {
vi.restoreAllMocks();
vi.clearAllMocks();
// Reset to authenticated state
mockUser = { id: 1, email: "test@example.com" };
mockToken = "valid-token";
mockIsLoading = false;
});
afterEach(() => {
cleanup();
});
test("renders loading state initially", () => {
vi.spyOn(global, "fetch").mockImplementation(() => new Promise(() => {}));
render(<Home />);
expect(screen.getByText("...")).toBeDefined();
});
describe("Home - Authenticated", () => {
test("renders loading state when isLoading is true", () => {
mockIsLoading = true;
vi.spyOn(global, "fetch").mockImplementation(() => new Promise(() => {}));
test("renders counter value after fetch", async () => {
vi.spyOn(global, "fetch").mockResolvedValue({
json: () => Promise.resolve({ value: 42 }),
} as Response);
render(<Home />);
expect(screen.getByText("Loading...")).toBeDefined();
});
render(<Home />);
await waitFor(() => {
expect(screen.getByText("42")).toBeDefined();
test("renders user email in header", async () => {
vi.spyOn(global, "fetch").mockResolvedValue({
json: () => Promise.resolve({ value: 42 }),
} as Response);
render(<Home />);
expect(screen.getByText("test@example.com")).toBeDefined();
});
test("renders sign out button", async () => {
vi.spyOn(global, "fetch").mockResolvedValue({
json: () => Promise.resolve({ value: 42 }),
} as Response);
render(<Home />);
expect(screen.getByText("Sign out")).toBeDefined();
});
test("clicking sign out calls logout", async () => {
vi.spyOn(global, "fetch").mockResolvedValue({
json: () => Promise.resolve({ value: 42 }),
} as Response);
render(<Home />);
fireEvent.click(screen.getByText("Sign out"));
expect(mockLogout).toHaveBeenCalled();
});
test("renders counter value after fetch", async () => {
vi.spyOn(global, "fetch").mockResolvedValue({
json: () => Promise.resolve({ value: 42 }),
} as Response);
render(<Home />);
await waitFor(() => {
expect(screen.getByText("42")).toBeDefined();
});
});
test("fetches counter with auth header", async () => {
const fetchSpy = vi.spyOn(global, "fetch").mockResolvedValue({
json: () => Promise.resolve({ value: 0 }),
} as Response);
render(<Home />);
await waitFor(() => {
expect(fetchSpy).toHaveBeenCalledWith(
"http://localhost:8000/api/counter",
expect.objectContaining({
headers: { Authorization: "Bearer valid-token" },
})
);
});
});
test("renders increment button", async () => {
vi.spyOn(global, "fetch").mockResolvedValue({
json: () => Promise.resolve({ value: 0 }),
} as Response);
render(<Home />);
expect(screen.getByText("Increment")).toBeDefined();
});
test("clicking increment button calls API with auth header", async () => {
const fetchSpy = vi
.spyOn(global, "fetch")
.mockResolvedValueOnce({ json: () => Promise.resolve({ value: 0 }) } as Response)
.mockResolvedValueOnce({ json: () => Promise.resolve({ value: 1 }) } as Response);
render(<Home />);
await waitFor(() => expect(screen.getByText("0")).toBeDefined());
fireEvent.click(screen.getByText("Increment"));
await waitFor(() => {
expect(fetchSpy).toHaveBeenCalledWith(
"http://localhost:8000/api/counter/increment",
expect.objectContaining({
method: "POST",
headers: { Authorization: "Bearer valid-token" },
})
);
});
});
test("clicking increment updates displayed count", async () => {
vi.spyOn(global, "fetch")
.mockResolvedValueOnce({ json: () => Promise.resolve({ value: 0 }) } as Response)
.mockResolvedValueOnce({ json: () => Promise.resolve({ value: 1 }) } as Response);
render(<Home />);
await waitFor(() => expect(screen.getByText("0")).toBeDefined());
fireEvent.click(screen.getByText("Increment"));
await waitFor(() => expect(screen.getByText("1")).toBeDefined());
});
});
test("renders +1 button", async () => {
vi.spyOn(global, "fetch").mockResolvedValue({
json: () => Promise.resolve({ value: 0 }),
} as Response);
describe("Home - Unauthenticated", () => {
test("redirects to login when not authenticated", async () => {
mockUser = null;
mockToken = null;
render(<Home />);
expect(screen.getByText("+1")).toBeDefined();
});
render(<Home />);
test("clicking button calls increment endpoint", async () => {
const fetchSpy = vi.spyOn(global, "fetch")
.mockResolvedValueOnce({ json: () => Promise.resolve({ value: 0 }) } as Response)
.mockResolvedValueOnce({ json: () => Promise.resolve({ value: 1 }) } as Response);
await waitFor(() => {
expect(mockPush).toHaveBeenCalledWith("/login");
});
});
render(<Home />);
await waitFor(() => expect(screen.getByText("0")).toBeDefined());
test("returns null when not authenticated", () => {
mockUser = null;
mockToken = null;
fireEvent.click(screen.getByText("+1"));
const { container } = render(<Home />);
// Should render nothing (just redirects)
expect(container.querySelector("main")).toBeNull();
});
await waitFor(() => {
expect(fetchSpy).toHaveBeenCalledWith(
"http://localhost:8000/api/counter/increment",
{ method: "POST" }
);
test("does not fetch counter when no token", () => {
mockUser = null;
mockToken = null;
const fetchSpy = vi.spyOn(global, "fetch");
render(<Home />);
expect(fetchSpy).not.toHaveBeenCalled();
});
});
test("clicking button updates displayed count", async () => {
vi.spyOn(global, "fetch")
.mockResolvedValueOnce({ json: () => Promise.resolve({ value: 0 }) } as Response)
.mockResolvedValueOnce({ json: () => Promise.resolve({ value: 1 }) } as Response);
describe("Home - Loading State", () => {
test("does not redirect while loading", () => {
mockIsLoading = true;
mockUser = null;
mockToken = null;
render(<Home />);
await waitFor(() => expect(screen.getByText("0")).toBeDefined());
render(<Home />);
fireEvent.click(screen.getByText("+1"));
await waitFor(() => expect(screen.getByText("1")).toBeDefined());
expect(mockPush).not.toHaveBeenCalled();
});
test("shows loading indicator while loading", () => {
mockIsLoading = true;
render(<Home />);
expect(screen.getByText("Loading...")).toBeDefined();
});
});

View file

@ -1,40 +1,177 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "./auth-context";
export default function Home() {
const [count, setCount] = useState<number | null>(null);
const { user, token, isLoading, logout } = useAuth();
const router = useRouter();
useEffect(() => {
fetch("http://localhost:8000/api/counter")
.then((res) => res.json())
.then((data) => setCount(data.value));
}, []);
if (!isLoading && !user) {
router.push("/login");
}
}, [isLoading, user, router]);
useEffect(() => {
if (token) {
fetch("http://localhost:8000/api/counter", {
headers: { Authorization: `Bearer ${token}` },
})
.then((res) => res.json())
.then((data) => setCount(data.value))
.catch(() => setCount(null));
}
}, [token]);
const increment = async () => {
if (!token) return;
const res = await fetch("http://localhost:8000/api/counter/increment", {
method: "POST",
headers: { Authorization: `Bearer ${token}` },
});
const data = await res.json();
setCount(data.value);
};
if (isLoading) {
return (
<main style={styles.main}>
<div style={styles.loader}>Loading...</div>
</main>
);
}
if (!user) {
return null;
}
return (
<main style={{ padding: "2rem", fontFamily: "system-ui", textAlign: "center" }}>
<h1 style={{ fontSize: "6rem", margin: "2rem 0" }}>
{count === null ? "..." : count}
</h1>
<button
onClick={increment}
style={{
fontSize: "1.5rem",
padding: "1rem 2rem",
cursor: "pointer",
}}
>
+1
</button>
<main style={styles.main}>
<div style={styles.header}>
<div style={styles.userInfo}>
<span style={styles.userEmail}>{user.email}</span>
<button onClick={logout} style={styles.logoutBtn}>
Sign out
</button>
</div>
</div>
<div style={styles.content}>
<div style={styles.counterCard}>
<span style={styles.counterLabel}>Current Count</span>
<h1 style={styles.counter}>{count === null ? "..." : count}</h1>
<button onClick={increment} style={styles.incrementBtn}>
<span style={styles.plusIcon}>+</span>
Increment
</button>
</div>
</div>
</main>
);
}
const styles: Record<string, React.CSSProperties> = {
main: {
minHeight: "100vh",
background: "linear-gradient(135deg, #0f0f23 0%, #1a1a3e 50%, #2d1b4e 100%)",
display: "flex",
flexDirection: "column",
},
loader: {
flex: 1,
display: "flex",
alignItems: "center",
justifyContent: "center",
fontFamily: "'DM Sans', system-ui, sans-serif",
color: "rgba(255, 255, 255, 0.5)",
fontSize: "1.125rem",
},
header: {
padding: "1.5rem 2rem",
borderBottom: "1px solid rgba(255, 255, 255, 0.06)",
},
userInfo: {
display: "flex",
alignItems: "center",
justifyContent: "flex-end",
gap: "1rem",
},
userEmail: {
fontFamily: "'DM Sans', system-ui, sans-serif",
color: "rgba(255, 255, 255, 0.6)",
fontSize: "0.875rem",
},
logoutBtn: {
fontFamily: "'DM Sans', system-ui, sans-serif",
padding: "0.5rem 1rem",
fontSize: "0.875rem",
fontWeight: 500,
background: "rgba(255, 255, 255, 0.05)",
color: "rgba(255, 255, 255, 0.7)",
border: "1px solid rgba(255, 255, 255, 0.1)",
borderRadius: "8px",
cursor: "pointer",
transition: "all 0.2s",
},
content: {
flex: 1,
display: "flex",
alignItems: "center",
justifyContent: "center",
padding: "2rem",
},
counterCard: {
background: "rgba(255, 255, 255, 0.03)",
backdropFilter: "blur(10px)",
border: "1px solid rgba(255, 255, 255, 0.08)",
borderRadius: "32px",
padding: "4rem 5rem",
textAlign: "center",
boxShadow: "0 25px 50px -12px rgba(0, 0, 0, 0.5)",
},
counterLabel: {
fontFamily: "'DM Sans', system-ui, sans-serif",
display: "block",
color: "rgba(255, 255, 255, 0.4)",
fontSize: "0.875rem",
textTransform: "uppercase",
letterSpacing: "0.1em",
marginBottom: "1rem",
},
counter: {
fontFamily: "'Instrument Serif', Georgia, serif",
fontSize: "8rem",
fontWeight: 400,
color: "#fff",
margin: 0,
lineHeight: 1,
background: "linear-gradient(135deg, #fff 0%, #a78bfa 100%)",
WebkitBackgroundClip: "text",
WebkitTextFillColor: "transparent",
backgroundClip: "text",
},
incrementBtn: {
fontFamily: "'DM Sans', system-ui, sans-serif",
marginTop: "2.5rem",
padding: "1rem 2.5rem",
fontSize: "1.125rem",
fontWeight: 600,
background: "linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)",
color: "#fff",
border: "none",
borderRadius: "16px",
cursor: "pointer",
display: "inline-flex",
alignItems: "center",
gap: "0.5rem",
transition: "transform 0.2s, box-shadow 0.2s",
boxShadow: "0 4px 14px rgba(99, 102, 241, 0.4)",
},
plusIcon: {
fontSize: "1.5rem",
fontWeight: 400,
},
};

View file

@ -0,0 +1,37 @@
import { render, screen, cleanup } from "@testing-library/react";
import { expect, test, vi, beforeEach, afterEach } from "vitest";
import SignupPage from "./page";
const mockPush = vi.fn();
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: mockPush }),
}));
vi.mock("../auth-context", () => ({
useAuth: () => ({ register: vi.fn() }),
}));
beforeEach(() => vi.clearAllMocks());
afterEach(() => cleanup());
test("renders signup form with title", () => {
render(<SignupPage />);
expect(screen.getByRole("heading", { name: "Create account" })).toBeDefined();
});
test("renders email and password inputs", () => {
render(<SignupPage />);
expect(screen.getByLabelText("Email")).toBeDefined();
expect(screen.getByLabelText("Password")).toBeDefined();
expect(screen.getByLabelText("Confirm Password")).toBeDefined();
});
test("renders create account button", () => {
render(<SignupPage />);
expect(screen.getByRole("button", { name: "Create account" })).toBeDefined();
});
test("renders link to login", () => {
render(<SignupPage />);
expect(screen.getByText("Sign in")).toBeDefined();
});

View file

@ -0,0 +1,220 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "../auth-context";
export default function SignupPage() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [error, setError] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const { register } = useAuth();
const router = useRouter();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError("");
if (password !== confirmPassword) {
setError("Passwords do not match");
return;
}
if (password.length < 6) {
setError("Password must be at least 6 characters");
return;
}
setIsSubmitting(true);
try {
await register(email, password);
router.push("/");
} catch (err) {
setError(err instanceof Error ? err.message : "Registration failed");
} finally {
setIsSubmitting(false);
}
};
return (
<main style={styles.main}>
<div style={styles.container}>
<div style={styles.card}>
<div style={styles.header}>
<h1 style={styles.title}>Create account</h1>
<p style={styles.subtitle}>Get started with your journey</p>
</div>
<form onSubmit={handleSubmit} style={styles.form}>
{error && <div style={styles.error}>{error}</div>}
<div style={styles.field}>
<label htmlFor="email" style={styles.label}>Email</label>
<input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
style={styles.input}
placeholder="you@example.com"
required
/>
</div>
<div style={styles.field}>
<label htmlFor="password" style={styles.label}>Password</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
style={styles.input}
placeholder="••••••••"
required
/>
</div>
<div style={styles.field}>
<label htmlFor="confirmPassword" style={styles.label}>Confirm Password</label>
<input
id="confirmPassword"
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
style={styles.input}
placeholder="••••••••"
required
/>
</div>
<button
type="submit"
style={{
...styles.button,
opacity: isSubmitting ? 0.7 : 1,
}}
disabled={isSubmitting}
>
{isSubmitting ? "Creating account..." : "Create account"}
</button>
</form>
<p style={styles.footer}>
Already have an account?{" "}
<a href="/login" style={styles.link}>
Sign in
</a>
</p>
</div>
</div>
</main>
);
}
const styles: Record<string, React.CSSProperties> = {
main: {
minHeight: "100vh",
background: "linear-gradient(135deg, #0f0f23 0%, #1a1a3e 50%, #2d1b4e 100%)",
display: "flex",
alignItems: "center",
justifyContent: "center",
padding: "1rem",
},
container: {
width: "100%",
maxWidth: "420px",
},
card: {
background: "rgba(255, 255, 255, 0.03)",
backdropFilter: "blur(10px)",
border: "1px solid rgba(255, 255, 255, 0.08)",
borderRadius: "24px",
padding: "3rem 2.5rem",
boxShadow: "0 25px 50px -12px rgba(0, 0, 0, 0.5)",
},
header: {
textAlign: "center" as const,
marginBottom: "2.5rem",
},
title: {
fontFamily: "'Instrument Serif', Georgia, serif",
fontSize: "2.5rem",
fontWeight: 400,
color: "#fff",
margin: 0,
letterSpacing: "-0.02em",
},
subtitle: {
fontFamily: "'DM Sans', system-ui, sans-serif",
color: "rgba(255, 255, 255, 0.5)",
marginTop: "0.5rem",
fontSize: "0.95rem",
},
form: {
display: "flex",
flexDirection: "column" as const,
gap: "1.5rem",
},
field: {
display: "flex",
flexDirection: "column" as const,
gap: "0.5rem",
},
label: {
fontFamily: "'DM Sans', system-ui, sans-serif",
color: "rgba(255, 255, 255, 0.7)",
fontSize: "0.875rem",
fontWeight: 500,
},
input: {
fontFamily: "'DM Sans', system-ui, sans-serif",
padding: "0.875rem 1rem",
fontSize: "1rem",
background: "rgba(255, 255, 255, 0.05)",
border: "1px solid rgba(255, 255, 255, 0.1)",
borderRadius: "12px",
color: "#fff",
outline: "none",
transition: "border-color 0.2s, box-shadow 0.2s",
},
button: {
fontFamily: "'DM Sans', system-ui, sans-serif",
marginTop: "0.5rem",
padding: "1rem",
fontSize: "1rem",
fontWeight: 600,
background: "linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)",
color: "#fff",
border: "none",
borderRadius: "12px",
cursor: "pointer",
transition: "transform 0.2s, box-shadow 0.2s",
boxShadow: "0 4px 14px rgba(99, 102, 241, 0.4)",
},
error: {
fontFamily: "'DM Sans', system-ui, sans-serif",
padding: "0.875rem 1rem",
background: "rgba(239, 68, 68, 0.1)",
border: "1px solid rgba(239, 68, 68, 0.3)",
borderRadius: "12px",
color: "#fca5a5",
fontSize: "0.875rem",
textAlign: "center" as const,
},
footer: {
fontFamily: "'DM Sans', system-ui, sans-serif",
textAlign: "center" as const,
marginTop: "2rem",
color: "rgba(255, 255, 255, 0.5)",
fontSize: "0.875rem",
},
link: {
color: "#a78bfa",
textDecoration: "none",
fontWeight: 500,
},
};

283
frontend/e2e/auth.spec.ts Normal file
View file

@ -0,0 +1,283 @@
import { test, expect, Page } from "@playwright/test";
// Helper to generate unique email for each test
function uniqueEmail(): string {
return `test-${Date.now()}-${Math.random().toString(36).substring(7)}@example.com`;
}
// Helper to clear localStorage
async function clearAuth(page: Page) {
await page.evaluate(() => localStorage.clear());
}
test.describe("Authentication Flow", () => {
test.beforeEach(async ({ page }) => {
await clearAuth(page);
});
test("redirects to login when not authenticated", async ({ page }) => {
await page.goto("/");
await expect(page).toHaveURL("/login");
});
test("login page has correct form elements", async ({ page }) => {
await page.goto("/login");
await expect(page.locator("h1")).toHaveText("Welcome back");
await expect(page.locator('input[type="email"]')).toBeVisible();
await expect(page.locator('input[type="password"]')).toBeVisible();
await expect(page.locator('button[type="submit"]')).toHaveText("Sign in");
await expect(page.locator('a[href="/signup"]')).toBeVisible();
});
test("signup page has correct form elements", async ({ page }) => {
await page.goto("/signup");
await expect(page.locator("h1")).toHaveText("Create account");
await expect(page.locator('input[type="email"]')).toBeVisible();
await expect(page.locator('input[type="password"]').first()).toBeVisible();
await expect(page.locator('input[type="password"]').nth(1)).toBeVisible();
await expect(page.locator('button[type="submit"]')).toHaveText("Create account");
await expect(page.locator('a[href="/login"]')).toBeVisible();
});
test("can navigate from login to signup", async ({ page }) => {
await page.goto("/login");
await page.click('a[href="/signup"]');
await expect(page).toHaveURL("/signup");
});
test("can navigate from signup to login", async ({ page }) => {
await page.goto("/signup");
await page.click('a[href="/login"]');
await expect(page).toHaveURL("/login");
});
});
test.describe("Signup", () => {
test.beforeEach(async ({ page }) => {
await clearAuth(page);
});
test("can create a new account", async ({ page }) => {
const email = uniqueEmail();
await page.goto("/signup");
await page.fill('input[type="email"]', email);
await page.fill('input[type="password"]', "password123");
await page.locator('input[type="password"]').nth(1).fill("password123");
await page.click('button[type="submit"]');
// Should redirect to home after signup
await expect(page).toHaveURL("/");
// Should show user email
await expect(page.getByText(email)).toBeVisible();
});
test("shows error for duplicate email", async ({ page }) => {
const email = uniqueEmail();
// First registration
await page.goto("/signup");
await page.fill('input[type="email"]', email);
await page.fill('input[type="password"]', "password123");
await page.locator('input[type="password"]').nth(1).fill("password123");
await page.click('button[type="submit"]');
await expect(page).toHaveURL("/");
// Clear and try again with same email
await clearAuth(page);
await page.goto("/signup");
await page.fill('input[type="email"]', email);
await page.fill('input[type="password"]', "password123");
await page.locator('input[type="password"]').nth(1).fill("password123");
await page.click('button[type="submit"]');
// Should show error
await expect(page.getByText("Email already registered")).toBeVisible();
});
test("shows error for password mismatch", async ({ page }) => {
await page.goto("/signup");
await page.fill('input[type="email"]', uniqueEmail());
await page.fill('input[type="password"]', "password123");
await page.locator('input[type="password"]').nth(1).fill("differentpassword");
await page.click('button[type="submit"]');
await expect(page.getByText("Passwords do not match")).toBeVisible();
});
test("shows error for short password", async ({ page }) => {
await page.goto("/signup");
await page.fill('input[type="email"]', uniqueEmail());
await page.fill('input[type="password"]', "short");
await page.locator('input[type="password"]').nth(1).fill("short");
await page.click('button[type="submit"]');
await expect(page.getByText("Password must be at least 6 characters")).toBeVisible();
});
test("shows loading state while submitting", async ({ page }) => {
await page.goto("/signup");
await page.fill('input[type="email"]', uniqueEmail());
await page.fill('input[type="password"]', "password123");
await page.locator('input[type="password"]').nth(1).fill("password123");
// Start submission and check for loading state
const submitPromise = page.click('button[type="submit"]');
await expect(page.locator('button[type="submit"]')).toHaveText("Creating account...");
await submitPromise;
});
});
test.describe("Login", () => {
const testEmail = `login-test-${Date.now()}@example.com`;
const testPassword = "testpassword123";
test.beforeAll(async ({ browser }) => {
// Create a test user
const page = await browser.newPage();
await page.goto("/signup");
await page.fill('input[type="email"]', testEmail);
await page.fill('input[type="password"]', testPassword);
await page.locator('input[type="password"]').nth(1).fill(testPassword);
await page.click('button[type="submit"]');
await expect(page).toHaveURL("/");
await page.close();
});
test.beforeEach(async ({ page }) => {
await clearAuth(page);
});
test("can login with valid credentials", async ({ page }) => {
await page.goto("/login");
await page.fill('input[type="email"]', testEmail);
await page.fill('input[type="password"]', testPassword);
await page.click('button[type="submit"]');
await expect(page).toHaveURL("/");
await expect(page.getByText(testEmail)).toBeVisible();
});
test("shows error for wrong password", async ({ page }) => {
await page.goto("/login");
await page.fill('input[type="email"]', testEmail);
await page.fill('input[type="password"]', "wrongpassword");
await page.click('button[type="submit"]');
await expect(page.getByText("Incorrect email or password")).toBeVisible();
});
test("shows error for non-existent user", async ({ page }) => {
await page.goto("/login");
await page.fill('input[type="email"]', "nonexistent@example.com");
await page.fill('input[type="password"]', "password123");
await page.click('button[type="submit"]');
await expect(page.getByText("Incorrect email or password")).toBeVisible();
});
test("shows loading state while submitting", async ({ page }) => {
await page.goto("/login");
await page.fill('input[type="email"]', testEmail);
await page.fill('input[type="password"]', testPassword);
const submitPromise = page.click('button[type="submit"]');
await expect(page.locator('button[type="submit"]')).toHaveText("Signing in...");
await submitPromise;
});
});
test.describe("Logout", () => {
test("can logout", async ({ page }) => {
const email = uniqueEmail();
// Sign up first
await page.goto("/signup");
await page.fill('input[type="email"]', email);
await page.fill('input[type="password"]', "password123");
await page.locator('input[type="password"]').nth(1).fill("password123");
await page.click('button[type="submit"]');
await expect(page).toHaveURL("/");
// Click logout
await page.click("text=Sign out");
// Should redirect to login
await expect(page).toHaveURL("/login");
});
test("cannot access home after logout", async ({ page }) => {
const email = uniqueEmail();
// Sign up
await page.goto("/signup");
await page.fill('input[type="email"]', email);
await page.fill('input[type="password"]', "password123");
await page.locator('input[type="password"]').nth(1).fill("password123");
await page.click('button[type="submit"]');
await expect(page).toHaveURL("/");
// Logout
await page.click("text=Sign out");
await expect(page).toHaveURL("/login");
// Try to access home
await page.goto("/");
await expect(page).toHaveURL("/login");
});
});
test.describe("Session Persistence", () => {
test("session persists after page reload", async ({ page }) => {
const email = uniqueEmail();
// Sign up
await page.goto("/signup");
await page.fill('input[type="email"]', email);
await page.fill('input[type="password"]', "password123");
await page.locator('input[type="password"]').nth(1).fill("password123");
await page.click('button[type="submit"]');
await expect(page).toHaveURL("/");
await expect(page.getByText(email)).toBeVisible();
// Reload page
await page.reload();
// Should still be logged in
await expect(page).toHaveURL("/");
await expect(page.getByText(email)).toBeVisible();
});
test("token is stored in localStorage", async ({ page }) => {
const email = uniqueEmail();
await page.goto("/signup");
await page.fill('input[type="email"]', email);
await page.fill('input[type="password"]', "password123");
await page.locator('input[type="password"]').nth(1).fill("password123");
await page.click('button[type="submit"]');
await expect(page).toHaveURL("/");
// Check localStorage
const token = await page.evaluate(() => localStorage.getItem("token"));
expect(token).toBeTruthy();
expect(token!.length).toBeGreaterThan(10);
});
test("token is cleared on logout", async ({ page }) => {
const email = uniqueEmail();
await page.goto("/signup");
await page.fill('input[type="email"]', email);
await page.fill('input[type="password"]', "password123");
await page.locator('input[type="password"]').nth(1).fill("password123");
await page.click('button[type="submit"]');
await expect(page).toHaveURL("/");
await page.click("text=Sign out");
const token = await page.evaluate(() => localStorage.getItem("token"));
expect(token).toBeNull();
});
});

View file

@ -1,29 +1,148 @@
import { test, expect } from "@playwright/test";
import { test, expect, Page } from "@playwright/test";
test("displays counter value", async ({ page }) => {
await page.goto("/");
await expect(page.locator("h1")).not.toHaveText("...");
// Helper to generate unique email for each test
function uniqueEmail(): string {
return `counter-${Date.now()}-${Math.random().toString(36).substring(7)}@example.com`;
}
// Helper to authenticate a user
async function authenticate(page: Page): Promise<string> {
const email = uniqueEmail();
await page.evaluate(() => localStorage.clear());
await page.goto("/signup");
await page.fill('input[type="email"]', email);
await page.fill('input[type="password"]', "password123");
await page.locator('input[type="password"]').nth(1).fill("password123");
await page.click('button[type="submit"]');
await expect(page).toHaveURL("/");
return email;
}
test.describe("Counter - Authenticated", () => {
test("displays counter value", async ({ page }) => {
await authenticate(page);
await expect(page.locator("h1")).toBeVisible();
// Counter should be a number (not loading state)
const text = await page.locator("h1").textContent();
expect(text).toMatch(/^\d+$/);
});
test("displays current count label", async ({ page }) => {
await authenticate(page);
await expect(page.getByText("Current Count")).toBeVisible();
});
test("clicking increment button increases counter", async ({ page }) => {
await authenticate(page);
await expect(page.locator("h1")).not.toHaveText("...");
const before = await page.locator("h1").textContent();
await page.click("text=Increment");
await expect(page.locator("h1")).toHaveText(String(Number(before) + 1));
});
test("clicking increment multiple times", async ({ page }) => {
await authenticate(page);
await expect(page.locator("h1")).not.toHaveText("...");
const before = Number(await page.locator("h1").textContent());
await page.click("text=Increment");
await page.click("text=Increment");
await page.click("text=Increment");
await expect(page.locator("h1")).toHaveText(String(before + 3));
});
test("counter persists after page reload", async ({ page }) => {
await authenticate(page);
await expect(page.locator("h1")).not.toHaveText("...");
const before = await page.locator("h1").textContent();
await page.click("text=Increment");
const expected = String(Number(before) + 1);
await expect(page.locator("h1")).toHaveText(expected);
await page.reload();
await expect(page.locator("h1")).toHaveText(expected);
});
test("counter is shared between users", async ({ page, browser }) => {
// First user increments
await authenticate(page);
await expect(page.locator("h1")).not.toHaveText("...");
const initialValue = Number(await page.locator("h1").textContent());
await page.click("text=Increment");
await page.click("text=Increment");
const afterFirst = initialValue + 2;
await expect(page.locator("h1")).toHaveText(String(afterFirst));
// Second user in new context sees the same value
const page2 = await browser.newPage();
await authenticate(page2);
await expect(page2.locator("h1")).toHaveText(String(afterFirst));
// Second user increments
await page2.click("text=Increment");
await expect(page2.locator("h1")).toHaveText(String(afterFirst + 1));
// First user reloads and sees the increment
await page.reload();
await expect(page.locator("h1")).toHaveText(String(afterFirst + 1));
await page2.close();
});
});
test("clicking +1 increments the counter", async ({ page }) => {
await page.goto("/");
await expect(page.locator("h1")).not.toHaveText("...");
test.describe("Counter - Unauthenticated", () => {
test("redirects to login when accessing counter without auth", async ({ page }) => {
await page.evaluate(() => localStorage.clear());
await page.goto("/");
await expect(page).toHaveURL("/login");
});
const before = await page.locator("h1").textContent();
await page.click("button");
await expect(page.locator("h1")).toHaveText(String(Number(before) + 1));
test("shows login form when redirected", async ({ page }) => {
await page.evaluate(() => localStorage.clear());
await page.goto("/");
await expect(page.locator("h1")).toHaveText("Welcome back");
});
});
test("counter persists after reload", async ({ page }) => {
await page.goto("/");
await expect(page.locator("h1")).not.toHaveText("...");
test.describe("Counter - Session Integration", () => {
test("can access counter after login", async ({ page }) => {
const email = uniqueEmail();
const before = await page.locator("h1").textContent();
await page.click("button");
const expected = String(Number(before) + 1);
await expect(page.locator("h1")).toHaveText(expected);
// Sign up first
await page.goto("/signup");
await page.fill('input[type="email"]', email);
await page.fill('input[type="password"]', "password123");
await page.locator('input[type="password"]').nth(1).fill("password123");
await page.click('button[type="submit"]');
await expect(page).toHaveURL("/");
await page.reload();
await expect(page.locator("h1")).toHaveText(expected);
// Logout
await page.click("text=Sign out");
await expect(page).toHaveURL("/login");
// Login again
await page.fill('input[type="email"]', email);
await page.fill('input[type="password"]', "password123");
await page.click('button[type="submit"]');
await expect(page).toHaveURL("/");
// Counter should be visible
await expect(page.locator("h1")).toBeVisible();
const text = await page.locator("h1").textContent();
expect(text).toMatch(/^\d+$/);
});
test("counter API requires authentication", async ({ page }) => {
// Try to access counter API directly without auth
const response = await page.request.get("http://localhost:8000/api/counter");
expect(response.status()).toBe(403);
});
test("counter increment API requires authentication", async ({ page }) => {
const response = await page.request.post("http://localhost:8000/api/counter/increment");
expect(response.status()).toBe(403);
});
});