Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:46:40 +08:00
commit 66f1bf4fb0
33 changed files with 6059 additions and 0 deletions

View File

@@ -0,0 +1,45 @@
# React Allauth Skill (Frontend)
Plug google/django-allauth headless authentication flows into a Vite React app: copies the React SPA example modules, wires auth context/routes, fixes provider URLs, adds proxying, and provides Playwright tests and styling references.
## What This Skill Provides
- Copies allauth React SPA modules into `frontend/src/user_management/`, renames to `.jsx`, and integrates auth routes with your existing router.
- Configures API base URLs, CSRF handling, and social callback URLs to point at the Django backend (`/_allauth/...`).
- Adds Vite proxy rules for `/_allauth` (and expects existing `/api` proxy) to `https://localhost:8000` with self-signed certs.
- Wraps the app in `AuthContextProvider`, adds auth-aware nav, and removes demo routes (e.g., `/calculator`).
- Supports multi-step flows (email verification, passkeys) with pending-flow redirects.
- Bundles Playwright end-to-end tests for signup/login/logout/code-login/password-reset.
- Includes a styling reference listing all 35 auth components needing UI polish.
## Prerequisites
- React + Vite frontend already set up (see `react-setup` skill).
- Django backend with django-allauth headless enabled and HTTPS at `https://localhost:8000`.
- mkcert-based HTTPS for frontend (`https://localhost:5173`).
- React Router in use; API config exporting `API_BASE_URL`.
## Setup Summary (see SKILL.md for line-by-line edits)
1) **Clone & copy example modules** from `django-allauth/examples/react-spa/frontend/src` into `frontend/src/user_management/` (files renamed `.jsx`).
2) **Install dependency**: `npm --prefix ./frontend install @github/webauthn-json`.
3) **App wrapper**: wrap your app in `<AuthContextProvider>` in `frontend/src/App.jsx`.
4) **API base URL**: in `user_management/lib/allauth.jsx`, import `API_BASE_URL` and prefix `/_allauth/${Client.BROWSER}/v1` with it.
5) **Routes**: create `frontend/src/router/AuthRouter.jsx` exposing `createAuthRoutes(config)`; merge into `createAppRouter` alongside your existing routes. Remove demo `/calculator` route.
6) **Redirects**: set `LOGIN_REDIRECT_URL = '/'`; update password-change/other redirects from `/calculator` to your desired path (default dashboard/home).
7) **Social callback fix**: set `callback_url: callbackURL` in `redirectToProvider` so backend URL is respected.
8) **Vite proxy**: add `/_allauth` proxy to `vite.config.js` targeting backend with `secure:false`.
9) **Auth-aware nav**: surface Login/Logout links conditioned on `useAuthStatus` (navbar or Home fallback).
10) **Flow handling**: add pending-flow redirects in signup/passkey/email verification and `AuthChangeRedirector`.
11) **Styling reference**: copy `references/styling-guide.md` to project root as `react-allauth-styling-reference.md` for later UI work.
12) **Tests**: run Playwright suite in `scripts/test_auth_flows.py` (requires backend + frontend running, pytest<9, playwright+chromium).
## Outputs/Artifacts
- Auth modules under `frontend/src/user_management/` wired to your router.
- Vite proxy updated for `/_allauth`.
- Auth context wrapping `App`.
- Optional styling reference file in project root.
- Playwright E2E tests ready to validate flows.
## Notes & Gotchas
- Backend must expose headless endpoints at `/_allauth/...` and serve email links pointing to the frontend (e.g., `https://localhost:5173`).
- Keep AUTH flows on HTTPS; proxy uses `secure:false` to accept mkcert certs.
- Tests expect email backend to write files to `sent_emails/`; adjust if using SMTP.
- If renaming frontend host/port, update `API_BASE_URL`, email links, and test selectors accordingly.

View File

@@ -0,0 +1,587 @@
---
name: react-allauth
description: Configure React frontend with django-allauth headless API integration, including authentication UI, auth state management, protected routes, and social authentication flows
---
## Purpose
Configure a React frontend application to integrate with django-allauth's headless API, enabling complete authentication workflows including signup, login, email verification, password reset, and social authentication. This skill handles the entire setup process from copying authentication modules to validating flows with automated testing.
## Prerequisites
Before starting this configuration, ensure the following requirements are met:
- **React project with Vite** - A React frontend application initialized with Vite
- **Django backend with django-allauth** - Django backend configured with django-allauth headless API (in settings.py - Look for allauth in INSTALLED_APPS)
- **HTTPS development environment** - Both frontend and backend running over HTTPS (mkcert recommended for local SSL certificates)
- **React Router** - Project uses `react-router-dom` for routing
- **API configuration** - An `API_BASE_URL` constant exported from a config file (typically `src/config/api.js` or `src/config/api.jsx`)
- **Project structure** - Frontend source code located in `frontend/src/` with standard Vite directory structure
## Steps Overview
1. Clone Repository and Copy Authentication Modules
2. Install Required Dependencies
3. Update App.jsx to Include Authentication Context
4. Configure API Base URL in allauth.jsx
5. Update Redirect URLs
6. Copy Authentication Router and Integrate Routes
7. Fix Social Authentication Callback URL
8. Configure Vite Proxy for Authentication Endpoints
9. Add Auth-Aware Navigation Link
10. Enable Flow-Based Signup Navigation
11. Validate Authentication Flows with Automated Testing
12. Copy Styling Reference Guide
13. Stop Background Tasks
---
### Step 1: Clone Repository and Copy Authentication Modules
Clone the django-allauth repository at the project root:
```bash
git clone https://github.com/pennersr/django-allauth
```
Refactor authentication components by renaming `.js` files to `.jsx`:
```bash
find django-allauth/examples/react-spa/frontend/src/ -name "*.js" -exec bash -c 'mv "$0" "${0%.js}.jsx"' {} \;
```
Copy the authentication modules into the React project:
```bash
mkdir -p frontend/src/user_management
find django-allauth/examples/react-spa/frontend/src/ -mindepth 1 -maxdepth 1 -type d -exec cp -r {} frontend/src/user_management/ \;
```
This creates a `user_management` directory in the React project and copies all authentication-related folders from the cloned repository. The `django-allauth/` directory remains available for later steps in this skill.
---
### Step 2: Install Required Dependencies
Install the WebAuthn dependency required by the authentication modules:
```bash
npm --prefix ./frontend install @github/webauthn-json
```
---
### Step 3: Update App.jsx to Include Authentication Context
**File:** `frontend/src/App.jsx`
Import the `AuthContextProvider` and wrap the app's content with it:
```jsx
import { AuthContextProvider } from './user_management/auth'
```
Wrap the existing app content (typically the router) with `<AuthContextProvider>`:
```jsx
<AuthContextProvider>
{/* Existing app content */}
</AuthContextProvider>
```
---
### Step 4: Configure API Base URL in allauth.jsx
**File:** `frontend/src/user_management/lib/allauth.jsx`
After the `getCSRFToken` import, add:
```jsx
import { API_BASE_URL } from '../../config/api'
```
Then update the API endpoint path from:
```jsx
`/_allauth/${Client.BROWSER}/v1`
```
To:
```jsx
`${API_BASE_URL}/_allauth/${Client.BROWSER}/v1`
```
---
### Step 5: Update Redirect URLs
Update redirect paths from `/calculator` to `/dashboard`:
**File:** `frontend/src/user_management/auth/routing.jsx`
Change the `LOGIN_REDIRECT_URL` path to:
```jsx
LOGIN_REDIRECT_URL: '/'
```
**File:** `frontend/src/user_management/account/ChangePassword.jsx`
Replace any occurrence of `'/calculator'` with `'/dashboard'`
---
### Step 6: Copy Authentication Router and Integrate Routes
Copy the authentication router file and clean up the cloned repository:
```bash
cp django-allauth/examples/react-spa/frontend/src/Router.jsx frontend/src/router/AuthRouter.jsx && rm -rf django-allauth
```
**File:** `frontend/src/router/AuthRouter.jsx`
Update all import paths to use the `user_management` directory:
Change:
```jsx
import { AuthChangeRedirector, AnonymousRoute, AuthenticatedRoute } from './auth'
```
To:
```jsx
import { AuthChangeRedirector, AnonymousRoute, AuthenticatedRoute } from '../user_management/auth'
```
Update all component imports (like `Login`, `Signup`, `ChangeEmail`, etc.) from relative paths to use `user_management`:
Change:
```jsx
import Login from './account/Login'
import Signup from './account/Signup'
// ... etc
```
To:
```jsx
import Login from '../user_management/account/Login'
import Signup from '../user_management/account/Signup'
// ... etc
```
Update the `Root` import:
```jsx
import Root from '../layouts/Root'
```
Update the `useConfig` import:
```jsx
import { useConfig } from '../user_management/auth/hooks'
```
**File:** `frontend/src/router/AppRoutes.jsx`
Import and integrate authentication routes into `createAppRouter`:
```jsx
import Root from "../layouts/Root";
import Home from "../pages/Home";
import { createAuthRoutes } from './AuthRouter';
export function createAppRouter(config) {
const authRoutes = createAuthRoutes(config);
return [
{
path: "/",
element: <Root />,
children: [
{
path: "/",
element: <Home />,
},
...authRoutes
],
},
];
}
```
**File:** `frontend/src/router/AuthRouter.jsx`
Rename the exported function and export the routes array:
Change:
```jsx
function createRouter (config) {
return createBrowserRouter([
{
path: '/',
element: <AuthChangeRedirector><Root /></AuthChangeRedirector>,
children: [
// ... routes
]
}
])
}
export default function Router () {
const [router, setRouter] = useState(null)
const config = useConfig()
useEffect(() => {
setRouter(createRouter(config))
}, [config])
return router ? <RouterProvider router={router} /> : null
}
```
To:
```jsx
export function createAuthRoutes (config) {
return [
// ... all the route objects from the children array
]
}
```
Remove the `/calculator` route as it's not needed.
---
### Step 7: Fix Social Authentication Callback URL
**File:** `frontend/src/user_management/lib/allauth.jsx`
Find the `redirectToProvider` function and update the `callback_url` parameter.
Change:
```jsx
callback_url: window.location.protocol + '//' + window.location.host + callbackURL,
```
To:
```jsx
callback_url: callbackURL,
```
This configuration ensures social authentication callbacks use the correct backend URL instead of the frontend host.
---
### Step 8: Configure Vite Proxy for Authentication Endpoints
**File:** `frontend/vite.config.js`
Add the `/_allauth` proxy configuration to forward authentication requests to the Django backend.
Add to the `proxy` object:
```js
'/_allauth': {
target: 'https://localhost:8000',
changeOrigin: true,
secure: false, // Allow self-signed certificates
},
```
**Expected result:**
```js
proxy: {
'/api': {
target: 'https://localhost:8000',
changeOrigin: true,
secure: false,
},
'/_allauth': {
target: 'https://localhost:8000',
changeOrigin: true,
secure: false,
},
}
```
---
### Step 9: Add Auth-Aware Navigation Link
First, search the project to determine if a navbar or header component exists.
#### If a navbar component exists:
Import the auth status helper and toggle the navigation link based on whether the user is logged in:
```jsx
import { useAuthStatus } from "@/user_management/auth";
import { Link } from "react-router-dom";
const [, authInfo] = useAuthStatus();
{authInfo.isAuthenticated ? (
<Link to="/account/logout">
<NavigationMenuLink className={navigationMenuTriggerStyle()}>
Logout
</NavigationMenuLink>
</Link>
) : (
<Link to="/account/login">
<NavigationMenuLink className={navigationMenuTriggerStyle()}>
Login
</NavigationMenuLink>
</Link>
)}
```
#### If NO navbar component exists:
Add auth-aware navigation links to the landing page.
**File:** `frontend/src/pages/Home.jsx`
Import the required dependencies at the top:
```jsx
import { useAuthStatus } from "@/user_management/auth";
import { Link } from "react-router-dom";
```
Add the navigation links in the component JSX:
```jsx
const [, authInfo] = useAuthStatus();
return (
<div>
<nav style={{ padding: '1rem', borderBottom: '1px solid #ccc' }}>
{authInfo.isAuthenticated ? (
<Link to="/account/logout" style={{ marginRight: '1rem' }}>
Logout
</Link>
) : (
<Link to="/account/login" style={{ marginRight: '1rem' }}>
Login
</Link>
)}
</nav>
{/* Rest of Home page content */}
</div>
);
```
**Note:** Linking to `/account/logout` ensures authenticated users reach the confirmation screen before finalizing the logout. Anonymous visitors continue to see the Login link.
---
### Step 10: Enable Flow-Based Signup Navigation
This step configures multi-step signup flows (like email verification + passkey creation) to navigate correctly between steps without intermediate redirects.
#### Step 10.1: Configure Signup Screens to Handle Pending Flows
**Files:**
- `frontend/src/user_management/account/Signup.jsx`
- `frontend/src/user_management/mfa/SignupByPasskey.jsx`
Add the following imports at the top of each signup component:
```jsx
import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { pathForFlow } from '../auth'
```
Inside each component, instantiate the navigate function:
```jsx
const navigate = useNavigate()
```
Add a `useEffect` hook that watches for pending flows in the response:
```jsx
useEffect(() => {
if (response.content) {
const pending = response.content?.data?.flows?.find(flow => flow.is_pending)
if (pending) {
navigate(pathForFlow(pending), { replace: true })
}
}
}, [response.content, navigate])
```
This configuration ensures users are redirected to the next step in the signup flow (e.g., email verification) without leaving the signup page in the history stack.
#### Step 10.2: Update Authentication Redirector for Pending Flows
**File:** `frontend/src/user_management/auth/routing.jsx`
Update the `AuthChangeRedirector` component to check for pending flows before redirecting to the default login redirect URL.
In the `LOGGED_IN` branch, add logic to call `pathForPendingFlow(auth)` before defaulting to `LOGIN_REDIRECT_URL`:
```jsx
if (auth.status === AuthStatus.LOGGED_IN) {
const pendingPath = pathForPendingFlow(auth)
if (pendingPath) {
navigate(pendingPath, { replace: true })
} else {
navigate(LOGIN_REDIRECT_URL, { replace: true })
}
}
```
This logic prevents users from being redirected to the dashboard when pending authentication steps remain.
#### Step 10.3: Configure Email Verification to Handle Flows
**File:** `frontend/src/user_management/account/VerifyEmailByCode.jsx`
Replace the static `<Navigate>` component return with a `useEffect` hook that handles flow-based redirects.
Add the required imports:
```jsx
import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { pathForFlow } from '../auth'
```
Instantiate navigate:
```jsx
const navigate = useNavigate()
```
Replace the `<Navigate>` return with a `useEffect` that redirects based on the response:
```jsx
useEffect(() => {
const content = response.content
if (!content) {
return
}
const flows = content.data?.flows
if (flows?.length) {
const pending = flows.find(flow => flow.is_pending)
if (pending) {
navigate(pathForFlow(pending), { replace: true })
return
}
}
if (content.status === 200) {
navigate('/account/email', { replace: true })
} else if (content.status === 401) {
navigate('/account/login', { replace: true })
}
}, [response.content, navigate])
```
This configuration ensures email verification redirects to the next pending flow step (e.g., passkey creation) or falls back to the appropriate default page.
---
### Step 11: Validate Authentication Flows with Automated Testing
Run the comprehensive authentication flow test suite to validate the entire integration. This step confirms all authentication flows work correctly end-to-end.
#### Step 11.1: Install Testing Dependencies
Activate the Django virtual environment and install Playwright for browser automation testing:
```bash
source venv/bin/activate
# Install pytest only if missing
python -c "import pytest" 2>/dev/null || pip install 'pytest>=7.4,<9.0'
# Install playwright only if missing
python -c "import playwright" 2>/dev/null || pip install playwright
# Install chromium only if Playwright hasn't installed it yet
playwright show-browsers | grep -q "chromium" \
|| playwright install chromium
```
#### Step 11.2: Check and Start Servers, Then Run the Test Suite
Before running tests, verify both servers are running and start them if needed.
**Check if backend is running on port 8000:**
```bash
lsof -i :8000
```
**If backend is not running, start it:**
Activate the virtual environment, and run the startup script in the background:
```bash
source venv/bin/activate && \
uvicorn backend.asgi:application \
--host 127.0.0.1 \
--port 8000 \
--ssl-keyfile ./certs/localhost+2-key.pem \
--ssl-certfile ./certs/localhost+2.pem
```
**Check if frontend is running on port 5173:**
```bash
lsof -i :5173
```
**If frontend is not running, start it:**
Start the development server in the background:
```bash
npm --prefix ./frontend run dev
```
**Wait for servers to be ready:**
Allow a few seconds for both servers to fully initialize before proceeding with tests.
**Execute the test suite:**
From the Django project root with the virtual environment activated:
Activate the virtual environment `source venv/bin/activate` and run the test script at: `scripts/test_auth_flows.py`
The test suite includes:
1. **test_01_signup** - User signup flow validation
2. **test_02_email_verification** - Email verification workflow
3. **test_03_password_login** - Password-based authentication
4. **test_04_logout** - Logout functionality
5. **test_05_code_login** - Passwordless code-based login
6. **test_06_password_reset** - Password reset workflow
**Prerequisites for testing:**
- Django backend running on `https://localhost:8000`
- React frontend running on `https://localhost:5173`
- Email backend configured to save emails to `sent_emails/` directory
- Clean database state (tests create unique users with timestamps)
**Test execution:**
- Tests run with visible browser (`headless=False`) for debugging
- Each test is independent and creates its own test user
- Tests clean up email files between runs
- Verbose output (`verbosity=2`) shows detailed test progress
**Note:** Tests run sequentially and may take several minutes to complete due to browser automation and wait times for email delivery.
---
### Step 12: Copy Styling Reference Guide
Read the styling reference guide from the skill's bundled resources and write it to the project root for later use.
The styling guide is located at `references/styling-guide.md` within this skill's directory. Read this file and write its contents to `react-allauth-styling-reference.md` in the project root.
This file lists all 35 authentication components that require styling and can be referenced by styling skills. Delete this file after styling is complete.
---
### Step 13: Stop Background Tasks
Terminate any background commands or servers started during the configuration process.

View File

@@ -0,0 +1,75 @@
# React-Allauth Components Requiring Styling
## Overview
This file lists all authentication components that require styling. These components are functional but use minimal styling from the django-allauth example repository. Apply consistent design using a styling skill (e.g., `apply-shadcn`).
## Components Requiring Styling
### Account Files (15 files)
1. `frontend/src/user_management/account/Login.jsx`
2. `frontend/src/user_management/account/RequestLoginCode.jsx`
3. `frontend/src/user_management/account/ConfirmLoginCode.jsx`
4. `frontend/src/user_management/account/Logout.jsx`
5. `frontend/src/user_management/account/Signup.jsx`
6. `frontend/src/user_management/account/ChangeEmail.jsx`
7. `frontend/src/user_management/account/VerifyEmail.jsx`
8. `frontend/src/user_management/account/VerifyEmailByCode.jsx`
9. `frontend/src/user_management/account/VerificationEmailSent.jsx`
10. `frontend/src/user_management/account/RequestPasswordReset.jsx`
11. `frontend/src/user_management/account/ConfirmPasswordResetCode.jsx`
12. `frontend/src/user_management/account/ChangePassword.jsx`
13. `frontend/src/user_management/account/ResetPassword.jsx`
14. `frontend/src/user_management/account/Reauthenticate.jsx`
### Social Account Files (3 files)
1. `frontend/src/user_management/socialaccount/ProviderSignup.jsx`
2. `frontend/src/user_management/socialaccount/ProviderCallback.jsx`
3. `frontend/src/user_management/socialaccount/ManageProviders.jsx`
### MFA Files (15 files)
1. `frontend/src/user_management/mfa/MFAOverview.jsx`
2. `frontend/src/user_management/mfa/ActivateTOTP.jsx`
3. `frontend/src/user_management/mfa/DeactivateTOTP.jsx`
4. `frontend/src/user_management/mfa/AuthenticateTOTP.jsx`
5. `frontend/src/user_management/mfa/ReauthenticateTOTP.jsx`
6. `frontend/src/user_management/mfa/RecoveryCodes.jsx`
7. `frontend/src/user_management/mfa/GenerateRecoveryCodes.jsx`
8. `frontend/src/user_management/mfa/AuthenticateRecoveryCodes.jsx`
9. `frontend/src/user_management/mfa/ReauthenticateRecoveryCodes.jsx`
10. `frontend/src/user_management/mfa/AddWebAuthn.jsx`
11. `frontend/src/user_management/mfa/ListWebAuthn.jsx`
12. `frontend/src/user_management/mfa/AuthenticateWebAuthn.jsx`
13. `frontend/src/user_management/mfa/ReauthenticateWebAuthn.jsx`
14. `frontend/src/user_management/mfa/SignupByPasskey.jsx`
15. `frontend/src/user_management/mfa/CreateSignupPasskey.jsx`
16. `frontend/src/user_management/mfa/Trust.jsx`
### Component Files (2 files)
1. `frontend/src/user_management/components/Button.jsx`
2. `frontend/src/user_management/mfa/WebAuthnLoginButton.jsx`
**Total:** 35 files requiring styling
## Button Component Duplication Issue
Two Button.jsx files exist in the project:
1. **`frontend/src/components/ui/button.jsx`** - shadcn/ui Button component with full styling variants
2. **`frontend/src/user_management/components/Button.jsx`** - Wrapper component that uses shadcn/ui Button
**Recommended approach:** Keep both files as they serve different purposes:
- **`frontend/src/components/ui/button.jsx`** - Core shadcn/ui component with styling system
- **`frontend/src/user_management/components/Button.jsx`** - Wrapper that ensures authentication components use consistent button styling
## Notes
- All components use React Router for navigation
- Components expect shadcn/ui components to be available via `@/components/ui/` imports
- The authentication context (`AuthContextProvider`) must wrap all components
- Components use the allauth API client from `user_management/lib/allauth.jsx`

View File

@@ -0,0 +1,353 @@
#!/usr/bin/env python3
"""
Professional test suite for Django-Allauth authentication flows.
Tests: Signup, Email Verification, Password Login, Logout, Code Login, Password Reset
"""
import os
import re
import time
import unittest
from pathlib import Path
from playwright.sync_api import sync_playwright
# Find project root by looking for Django project markers
# Works regardless of whether skill is installed at project or user level
def find_project_root():
"""Find Django project root by looking for manage.py or venv."""
cwd = Path.cwd()
# Search upwards for Django project markers
current = cwd
for _ in range(10): # Prevent infinite loop
# Look for Django project markers
if (current / 'manage.py').exists() and (current / 'venv').exists():
return current
if current.parent == current: # Reached filesystem root
break
current = current.parent
# Fallback: use current working directory
return cwd
PROJECT_ROOT = find_project_root()
EMAIL_DIR = PROJECT_ROOT / 'sent_emails'
class AuthenticationFlowTests(unittest.TestCase):
"""Test suite for complete authentication flows."""
@classmethod
def setUpClass(cls):
"""Set up test fixtures before running any tests."""
cls.password = "SecureTestPassword123!"
cls.new_password = "NewSecurePassword456!"
cls.playwright = None
cls.browser = None
cls.context = None
cls.page = None
def setUp(self):
"""Set up before each test."""
# Each test gets its own email to avoid conflicts
self.email = f"testuser_{int(time.time() * 1000)}@example.com"
time.sleep(0.1) # Ensure unique timestamps
self.clear_email_folder()
@staticmethod
def clear_email_folder():
"""Clear all emails from the email folder."""
if EMAIL_DIR.exists():
for f in EMAIL_DIR.iterdir():
f.unlink()
@staticmethod
def get_latest_email_content(wait_time=3):
"""Read the most recently created email file."""
# Wait for email file to be written
for _ in range(wait_time * 10): # Check every 100ms
if EMAIL_DIR.exists():
files = list(EMAIL_DIR.iterdir())
if files:
latest_file = max(files, key=lambda f: f.stat().st_ctime)
return latest_file.read_text()
time.sleep(0.1)
return None
@staticmethod
def extract_verification_code(email_content):
"""Extract the verification code from email."""
# Match 6-character alphanumeric code
pattern = r'^\s*([A-Z0-9]{6})\s*$'
match = re.search(pattern, email_content, re.MULTILINE)
return match.group(1) if match else None
@staticmethod
def extract_login_code(email_content):
"""Extract the login code from email."""
pattern = r'^\s*([A-Z0-9]{6})\s*$'
match = re.search(pattern, email_content, re.MULTILINE)
if match:
return match.group(1)
pattern = r'code:\s*([A-Z0-9]{6})'
match = re.search(pattern, email_content, re.IGNORECASE)
return match.group(1) if match else None
@staticmethod
def extract_password_reset_url(email_content):
"""Extract the password reset URL from email."""
pattern = r'https://localhost:5173/account/password/reset/key/([^\s\n]+)'
match = re.search(pattern, email_content)
return match.group(0) if match else None
def start_browser(self):
"""Start browser session."""
if not self.playwright:
self.playwright = sync_playwright().start()
self.browser = self.playwright.chromium.launch(headless=False)
self.context = self.browser.new_context(ignore_https_errors=True)
self.page = self.context.new_page()
def stop_browser(self):
"""Stop browser session."""
if self.page:
self.page.close()
if self.context:
self.context.close()
if self.browser:
self.browser.close()
if self.playwright:
self.playwright.stop()
self.page = None
self.context = None
self.browser = None
self.playwright = None
def test_01_signup(self):
"""Test user signup flow."""
self.start_browser()
try:
self.page.goto('https://localhost:5173/account/signup', wait_until='networkidle')
self.page.fill('[data-testid="signup-email"]', self.email)
self.page.fill('[data-testid="signup-password1"]', self.password)
self.page.fill('[data-testid="signup-password2"]', self.password)
self.page.click('[data-testid="signup-submit"]')
self.page.wait_for_url('**/account/verify-email', timeout=5000)
self.assertIn('verify-email', self.page.url, "Should redirect to verify-email page")
finally:
self.stop_browser()
def test_02_email_verification(self):
"""Test email verification flow."""
self.start_browser()
try:
# First signup
self.page.goto('https://localhost:5173/account/signup', wait_until='networkidle')
self.page.fill('[data-testid="signup-email"]', self.email)
self.page.fill('[data-testid="signup-password1"]', self.password)
self.page.fill('[data-testid="signup-password2"]', self.password)
self.page.click('[data-testid="signup-submit"]')
self.page.wait_for_url('**/account/verify-email', timeout=5000)
# Get verification email
email_content = self.get_latest_email_content()
self.assertIsNotNone(email_content, "Verification email should exist")
verification_code = self.extract_verification_code(email_content)
self.assertIsNotNone(verification_code, "Should extract verification code")
self.assertEqual(len(verification_code), 6, "Verification code should be 6 characters")
# Verify email with code
self.page.fill('[data-testid="verify-email-code-input"]', verification_code)
self.page.click('[data-testid="verify-email-code-submit"]')
self.page.wait_for_url('**/account/email', timeout=5000)
self.assertIn('email', self.page.url, "Should redirect to email management after verification")
finally:
self.stop_browser()
def test_03_password_login(self):
"""Test password-based login flow."""
self.start_browser()
try:
# Setup: signup and verify (user will be logged in after verification)
self._signup_and_verify()
# Logout first
self.page.goto('https://localhost:5173/account/logout', wait_until='networkidle')
time.sleep(1)
self.page.click('[data-testid="logout-submit"]')
time.sleep(2)
# Now login with password
self.page.goto('https://localhost:5173/account/login', wait_until='networkidle')
self.page.fill('[data-testid="login-email"]', self.email)
self.page.fill('[data-testid="login-password"]', self.password)
self.page.click('[data-testid="login-submit"]')
self.page.wait_for_url('https://localhost:5173/', timeout=5000)
# Verify logged in
logout_link = self.page.locator('a:has-text("Logout")')
self.assertGreater(logout_link.count(), 0, "Should see Logout link when logged in")
finally:
self.stop_browser()
def test_04_logout(self):
"""Test logout flow."""
self.start_browser()
try:
# Setup: login
self._login_user()
# Logout
self.page.goto('https://localhost:5173/account/logout', wait_until='networkidle')
time.sleep(1)
self.page.click('[data-testid="logout-submit"]')
self.page.wait_for_load_state('networkidle')
time.sleep(2)
# Verify logged out
self.page.goto('https://localhost:5173/', wait_until='networkidle')
time.sleep(1)
login_link = self.page.locator('a:has-text("Login")')
self.assertGreater(login_link.count(), 0, "Should see Login link when logged out")
finally:
self.stop_browser()
def test_05_code_login(self):
"""Test passwordless login with code flow."""
self.start_browser()
try:
# Setup: signup and verify (user will be logged in after verification)
self._signup_and_verify()
# Logout
self.page.goto('https://localhost:5173/account/logout', wait_until='networkidle')
time.sleep(1)
self.page.click('[data-testid="logout-submit"]')
time.sleep(2)
self.clear_email_folder()
# Request login code
self.page.goto('https://localhost:5173/account/login', wait_until='networkidle')
time.sleep(2)
self.page.click('a:has-text("Send me a sign-in code")')
self.page.wait_for_load_state('networkidle')
time.sleep(1)
self.page.fill('[data-testid="request-code-email"]', self.email)
self.page.click('[data-testid="request-code-submit"]')
self.page.wait_for_load_state('networkidle')
time.sleep(2)
# Get code from email
code_email = self.get_latest_email_content()
self.assertIsNotNone(code_email, "Login code email should exist")
login_code = self.extract_login_code(code_email)
self.assertIsNotNone(login_code, "Should extract login code")
self.assertEqual(len(login_code), 6, "Login code should be 6 characters")
# Enter code and login
self.page.fill('[data-testid="confirm-code-input"]', login_code)
self.page.click('[data-testid="confirm-code-submit"]')
self.page.wait_for_url('https://localhost:5173/', timeout=5000)
# Verify logged in
logout_link = self.page.locator('a:has-text("Logout")')
self.assertGreater(logout_link.count(), 0, "Should be logged in after code login")
finally:
self.stop_browser()
def test_06_password_reset(self):
"""Test password reset flow."""
self.start_browser()
try:
# Setup: signup and verify
self._signup_and_verify()
# Logout (should be at login page)
self.page.goto('https://localhost:5173/account/logout', wait_until='networkidle')
time.sleep(1)
if self.page.locator('[data-testid="logout-submit"]').count() > 0:
self.page.click('[data-testid="logout-submit"]')
time.sleep(2)
self.clear_email_folder()
# Request password reset
self.page.goto('https://localhost:5173/account/login', wait_until='networkidle')
time.sleep(1)
self.page.click('a:has-text("Forgot your password?")')
self.page.wait_for_load_state('networkidle')
time.sleep(1)
self.page.fill('[data-testid="password-reset-email"]', self.email)
self.page.click('[data-testid="password-reset-submit"]')
self.page.wait_for_load_state('networkidle')
time.sleep(2)
# Get reset email
reset_email = self.get_latest_email_content()
self.assertIsNotNone(reset_email, "Password reset email should exist")
reset_url = self.extract_password_reset_url(reset_email)
self.assertIsNotNone(reset_url, "Should extract password reset URL")
# Reset password
self.page.goto(reset_url)
self.page.wait_for_load_state('networkidle')
time.sleep(1)
self.page.fill('[data-testid="reset-password1"]', self.new_password)
self.page.fill('[data-testid="reset-password2"]', self.new_password)
self.page.click('[data-testid="reset-password-confirm"]')
self.page.wait_for_load_state('networkidle')
time.sleep(2)
# Password reset complete - now login with new password to verify it worked
# Navigate to login page
self.page.goto('https://localhost:5173/account/login', wait_until='networkidle')
time.sleep(1)
# Login with new password
self.page.fill('[data-testid="login-email"]', self.email)
self.page.fill('[data-testid="login-password"]', self.new_password)
self.page.click('[data-testid="login-submit"]')
self.page.wait_for_url('https://localhost:5173/', timeout=5000)
# Verify logged in with new password
logout_link = self.page.locator('a:has-text("Logout")')
self.assertGreater(logout_link.count(), 0, "Should be logged in with new password")
finally:
self.stop_browser()
# Helper methods
def _signup_and_verify(self):
"""Helper: signup and verify email."""
self.clear_email_folder()
self.page.goto('https://localhost:5173/account/signup', wait_until='networkidle')
self.page.fill('[data-testid="signup-email"]', self.email)
self.page.fill('[data-testid="signup-password1"]', self.password)
self.page.fill('[data-testid="signup-password2"]', self.password)
self.page.click('[data-testid="signup-submit"]')
self.page.wait_for_url('**/account/verify-email', timeout=5000)
email_content = self.get_latest_email_content()
verification_code = self.extract_verification_code(email_content)
self.page.fill('[data-testid="verify-email-code-input"]', verification_code)
self.page.click('[data-testid="verify-email-code-submit"]')
self.page.wait_for_url('**/account/email', timeout=5000)
# User is now logged in and on the email management page
def _login_user(self):
"""Helper: complete signup, verify, and login."""
self._signup_and_verify()
# User is already logged in after email verification
if __name__ == '__main__':
# Run tests with verbose output
unittest.main(verbosity=2)