BS-001 Initialize BortStack foundation and project workflow

This commit is contained in:
rob
2026-11-10 14:02:50 +00:00
parent 1ec90a082f
commit 52265961cb
119 changed files with 10298 additions and 64 deletions
+46
View File
@@ -0,0 +1,46 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { beforeEach, describe, expect, it, vi } from "vitest";
import Login from "./Login/Login";
import Register from "./Register/Register";
import { useAuth } from "../contexts/AuthContext";
vi.mock("../contexts/AuthContext", () => ({ useAuth: vi.fn() }));
describe("account entry forms", () => {
const login = vi.fn();
const register = vi.fn();
beforeEach(() => {
login.mockReset();
register.mockReset();
register.mockResolvedValue(false);
vi.mocked(useAuth).mockReturnValue({
login,
register,
isAuthenticated: false,
isLoading: false,
error: "",
});
});
it("submits labelled login credentials", () => {
render(<MemoryRouter><Login /></MemoryRouter>);
fireEvent.change(screen.getByLabelText("Email address"), { target: { value: "person@example.com" } });
fireEvent.change(screen.getByLabelText("Password"), { target: { value: "long-enough-password" } });
fireEvent.click(screen.getByRole("button", { name: "Login" }));
expect(login).toHaveBeenCalledWith("person@example.com", "long-enough-password");
expect(screen.getByRole("link", { name: "Forgot password?" })).toHaveAttribute("href", "/forgot-password");
});
it("does not register when passwords differ", () => {
render(<MemoryRouter><Register /></MemoryRouter>);
fireEvent.change(screen.getByLabelText("Email address"), { target: { value: "person@example.com" } });
fireEvent.change(screen.getByLabelText("Username"), { target: { value: "example-person" } });
fireEvent.change(screen.getByLabelText("Password"), { target: { value: "long-enough-password" } });
fireEvent.change(screen.getByLabelText("Confirm Password"), { target: { value: "different-password" } });
fireEvent.click(screen.getByRole("button", { name: "Register" }));
expect(register).not.toHaveBeenCalled();
expect(screen.getByText("Passwords do not match")).toBeInTheDocument();
});
});
+58
View File
@@ -0,0 +1,58 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { afterEach, describe, expect, it, vi } from "vitest";
import ForgotPassword from "./ForgotPassword/ForgotPassword";
import ResetPassword from "./ResetPassword/ResetPassword";
import VerifyEmail from "./VerifyEmail/VerifyEmail";
afterEach(() => vi.unstubAllGlobals());
describe("account recovery pages", () => {
it("renders the forgot-password form", () => {
render(<MemoryRouter><ForgotPassword /></MemoryRouter>);
expect(screen.getByRole("heading", { name: /reset password/i })).toBeInTheDocument();
expect(screen.getByLabelText("Email address")).toBeRequired();
});
it("renders the password update form", () => {
render(<MemoryRouter initialEntries={["/reset-password?token=test"]}><ResetPassword /></MemoryRouter>);
expect(screen.getByRole("heading", { name: /choose a password/i })).toBeInTheDocument();
expect(screen.getByLabelText("New password")).toHaveAttribute("minlength", "8");
});
it("uses a non-enumerating forgot-password success message", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true }));
render(<MemoryRouter><ForgotPassword /></MemoryRouter>);
fireEvent.change(screen.getByLabelText("Email address"), { target: { value: "person@example.com" } });
fireEvent.click(screen.getByRole("button", { name: "Send reset link" }));
await waitFor(() => expect(screen.getByText(/if that account exists/i)).toBeInTheDocument());
});
it("submits a reset token and reports success", async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ success: true }),
});
vi.stubGlobal("fetch", fetchMock);
render(<MemoryRouter initialEntries={["/reset-password?token=reset-token"]}><ResetPassword /></MemoryRouter>);
fireEvent.change(screen.getByLabelText("New password"), { target: { value: "replacement-password" } });
fireEvent.click(screen.getByRole("button", { name: "Update password" }));
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Password updated"));
expect(fetchMock).toHaveBeenCalledWith("/api/user/update-password", expect.objectContaining({
body: JSON.stringify({ token: "reset-token", password: "replacement-password" }),
}));
});
it("verifies an email token", async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ success: true }),
});
vi.stubGlobal("fetch", fetchMock);
render(<MemoryRouter initialEntries={["/verify-email?token=verify-token"]}><VerifyEmail /></MemoryRouter>);
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Email verified"));
expect(fetchMock).toHaveBeenCalledWith("/api/user/verify-email", expect.objectContaining({
body: JSON.stringify({ token: "verify-token" }),
}));
});
});
+82
View File
@@ -0,0 +1,82 @@
import { useState } from "react";
import { Button, Form } from "react-bootstrap";
import styles from "./Contact.module.scss";
const initialValues = {
name: "",
email: "",
subject: "",
message: "",
website: "",
};
export default function Contact() {
const [values, setValues] = useState(initialValues);
const [status, setStatus] = useState("idle");
const [error, setError] = useState("");
function update(field, value) {
setValues((current) => ({ ...current, [field]: value }));
}
async function submit(event) {
event.preventDefault();
setStatus("sending");
setError("");
try {
const response = await fetch("/api/contact", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || "Unable to send message");
}
setValues(initialValues);
setStatus("sent");
} catch (requestError) {
setError(requestError.message);
setStatus("error");
}
}
return (
<main className={styles.contact}>
<section>
<h1>Contact</h1>
<p>Use this form to contact the application team.</p>
{status === "sent" ? (
<p role="status">Your message has been sent.</p>
) : (
<Form onSubmit={submit}>
<Form.Group className={styles.field} controlId="contact-name">
<Form.Label>Name</Form.Label>
<Form.Control value={values.name} maxLength={100} onChange={(event) => update("name", event.target.value)} required />
</Form.Group>
<Form.Group className={styles.field} controlId="contact-email">
<Form.Label>Email</Form.Label>
<Form.Control type="email" value={values.email} onChange={(event) => update("email", event.target.value)} required />
</Form.Group>
<Form.Group className={styles.field} controlId="contact-subject">
<Form.Label>Subject</Form.Label>
<Form.Control value={values.subject} maxLength={150} onChange={(event) => update("subject", event.target.value)} required />
</Form.Group>
<Form.Group className={styles.field} controlId="contact-message">
<Form.Label>Message</Form.Label>
<Form.Control as="textarea" rows={6} minLength={10} maxLength={5000} value={values.message} onChange={(event) => update("message", event.target.value)} required />
</Form.Group>
<div className={styles.honeypot} aria-hidden="true">
<label htmlFor="contact-website">Website</label>
<input id="contact-website" name="website" tabIndex={-1} autoComplete="off" value={values.website} onChange={(event) => update("website", event.target.value)} />
</div>
{error && <p role="alert">{error}</p>}
<Button type="submit" disabled={status === "sending"}>
{status === "sending" ? "Sending…" : "Send message"}
</Button>
</Form>
)}
</section>
</main>
);
}
@@ -0,0 +1,20 @@
.contact {
display: grid;
place-items: center;
section {
width: min(100%, 36rem);
}
}
.field {
margin-bottom: 1rem;
}
.honeypot {
position: absolute;
left: -10000px;
width: 1px;
height: 1px;
overflow: hidden;
}
+15
View File
@@ -0,0 +1,15 @@
const Dashboard = () => {
return (
<main>
<section>
<h1>Dashboard</h1>
<p>
This protected placeholder is ready for the generated
project&apos;s authenticated workflow.
</p>
</section>
</main>
)
}
export default Dashboard
@@ -0,0 +1,45 @@
import { useState } from "react";
import { Button, Form } from "react-bootstrap";
import styles from "../Login/Login.module.scss";
export default function ForgotPassword() {
const [email, setEmail] = useState("");
const [sent, setSent] = useState(false);
const [error, setError] = useState("");
const [isLoading, setIsLoading] = useState(false);
async function submit(event) {
event.preventDefault();
setError("");
setIsLoading(true);
try {
const response = await fetch("/api/user/reset-password", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email }),
});
if (!response.ok) throw new Error("Unable to request a reset link");
setSent(true);
} catch (requestError) {
setError(requestError.message);
} finally {
setIsLoading(false);
}
}
return (
<main className={styles.login}>
{sent ? <p>If that account exists, a reset link has been sent.</p> : (
<Form className={styles.form} onSubmit={submit}>
<h1>Reset password</h1>
<Form.Label htmlFor="reset-email">Email address</Form.Label>
<Form.Control id="reset-email" type="email" value={email} onChange={(event) => setEmail(event.target.value)} required />
{error && <p role="alert">{error}</p>}
<Button type="submit" disabled={isLoading}>
{isLoading ? "Sending…" : "Send reset link"}
</Button>
</Form>
)}
</main>
);
}
+18
View File
@@ -0,0 +1,18 @@
import styles from "./Homepage.module.scss";
const Homepage = () => {
return (
<main className={styles.homepage}>
<section>
<p>Reusable Flask and React application foundation</p>
<h1>Build your application from here</h1>
<p>
Replace this placeholder with the generated project&apos;s
purpose, primary action, and product-specific content.
</p>
</section>
</main>
)
}
export default Homepage
@@ -0,0 +1,9 @@
.homepage {
display: grid;
place-items: center;
text-align: center;
section {
max-width: 44rem;
}
}
+14
View File
@@ -0,0 +1,14 @@
export default function Privacy() {
return (
<main>
<article>
<h1>Privacy policy</h1>
<p role="note">
This is a template placeholder. Replace it with a policy
reviewed for the generated application, its data handling,
providers, jurisdiction, and users before production.
</p>
</article>
</main>
);
}
+13
View File
@@ -0,0 +1,13 @@
export default function Terms() {
return (
<main>
<article>
<h1>Terms of service</h1>
<p role="note">
This is a template placeholder. Replace it with terms
reviewed for the generated application before production.
</p>
</article>
</main>
);
}
+83
View File
@@ -0,0 +1,83 @@
import styles from "./Login.module.scss";
import { useState, useEffect } from "react";
import { useAuth } from "../../contexts/AuthContext";
import { useNavigate } from "react-router-dom";
import { Form, Button } from "react-bootstrap";
const Login = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const { login, isAuthenticated, isLoading, error } = useAuth();
const navigate = useNavigate();
const [validated, setValidated] = useState(false);
useEffect(() => {
if(isAuthenticated) {
navigate("/dashboard")
}
}, [isAuthenticated, navigate])
function handleLogin(e) {
const form = e.currentTarget;
e.preventDefault();
e.stopPropagation();
const valid = form.checkValidity();
setValidated(true);
if (valid) {
login(email, password)
}
}
function updateForm(key, value) {
setValidated(false);
if (key === "email") {
setEmail(value);
} else if (key === "password") {
setPassword(value);
}
}
return (
<main className={styles.login}>
<Form className={styles.form} onSubmit={handleLogin}>
<h1>Login</h1>
<Form.Group className={styles.formGroup}>
<Form.Label htmlFor="email">Email address</Form.Label>
<Form.Control
type="email"
id="email"
onChange={(e) => updateForm("email", e.target.value)}
value={email}
required
isInvalid={validated && error === "Unauthorized"}
/>
<Form.Control.Feedback type="invalid" />
</Form.Group>
<Form.Group className={styles.formGroup}>
<Form.Label htmlFor="password">Password</Form.Label>
<Form.Control
type="password"
id="password"
onChange={(e) => updateForm("password", e.target.value)}
value={password}
required
isInvalid={validated && error === "Unauthorized"}
/>
<Form.Control.Feedback type="invalid">
{error}
</Form.Control.Feedback>
</Form.Group>
<Button
type="submit"
className={styles.btn}
disabled={isLoading}
>
Login
</Button>
<a href="/forgot-password">Forgot password?</a>
</Form>
</main>
);
};
export default Login;
+17
View File
@@ -0,0 +1,17 @@
.login {
display: flex;
justify-content: center;
align-items: center;
}
.form {
width: 240px;
}
.formGroup {
margin: 20px 0;
}
.btn {
float: right;
}
@@ -0,0 +1,10 @@
import styles from "./PageNotFound.module.scss";
export default function PageNotFound() {
return (
<main className={styles.pageNotFound}>
<h2>Page not found</h2>
</main>
);
}
@@ -0,0 +1,5 @@
.pageNotFound {
display: flex;
justify-content: center;
align-items: center;
}
+58
View File
@@ -0,0 +1,58 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { afterEach, describe, expect, it, vi } from "vitest";
import Contact from "./Contact/Contact";
import Homepage from "./Home/Homepage";
import Privacy from "./Legal/Privacy";
import Terms from "./Legal/Terms";
afterEach(() => vi.unstubAllGlobals());
describe("generic public pages", () => {
it("marks homepage content as replaceable", () => {
render(<MemoryRouter><Homepage /></MemoryRouter>);
expect(screen.getByRole("heading", { name: /build your application/i })).toBeInTheDocument();
});
it("marks legal pages as placeholders", () => {
const { rerender } = render(<Privacy />);
expect(screen.getByText(/template placeholder/i)).toBeInTheDocument();
rerender(<Terms />);
expect(screen.getByText(/template placeholder/i)).toBeInTheDocument();
});
it("submits the contact form and reports success", async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ success: true }),
});
vi.stubGlobal("fetch", fetchMock);
render(<MemoryRouter><Contact /></MemoryRouter>);
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Example Person" } });
fireEvent.change(screen.getByLabelText("Email"), { target: { value: "person@example.com" } });
fireEvent.change(screen.getByLabelText("Subject"), { target: { value: "A question" } });
fireEvent.change(screen.getByLabelText("Message"), { target: { value: "A message long enough to send." } });
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("message has been sent"));
expect(fetchMock).toHaveBeenCalledWith("/api/contact", expect.objectContaining({ method: "POST" }));
});
it("reports a contact delivery failure and restores the submit control", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
ok: false,
json: async () => ({ message: "Unable to send message right now" }),
}));
render(<MemoryRouter><Contact /></MemoryRouter>);
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Example Person" } });
fireEvent.change(screen.getByLabelText("Email"), { target: { value: "person@example.com" } });
fireEvent.change(screen.getByLabelText("Subject"), { target: { value: "A question" } });
fireEvent.change(screen.getByLabelText("Message"), { target: { value: "A message long enough to send." } });
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent("Unable to send message right now"));
expect(screen.getByRole("button", { name: "Send message" })).toBeEnabled();
});
});
+116
View File
@@ -0,0 +1,116 @@
import styles from "../Login/Login.module.scss";
import { useState } from "react";
import { useAuth } from "../../contexts/AuthContext";
import { useNavigate } from "react-router-dom";
import { Form, Button } from "react-bootstrap";
const Register = () => {
const [email, setEmail] = useState("");
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [passwordConfirm, setPasswordConfirm] = useState("");
const { register, isLoading, error } = useAuth();
const navigate = useNavigate();
const [validated, setValidated] = useState(false);
const handleRegister = (e) => {
const form = e.currentTarget;
e.preventDefault();
e.stopPropagation();
const valid = form.checkValidity() && password === passwordConfirm;
setValidated(true);
if (valid) {
register(email, password, username).then((success) => {
if(success) {
navigate("/login")
}
});
}
};
function updateForm(key, value) {
setValidated(false);
if (key === "email") {
setEmail(value);
} else if (key === "username") {
setUsername(value);
} else if (key === "password") {
setPassword(value);
} else if (key === "passwordConfirm") {
setPasswordConfirm(value);
}
}
return (
<main className={styles.login}>
<Form className={styles.form} onSubmit={handleRegister}>
<h1>Register</h1>
<Form.Group className={styles.formGroup}>
<Form.Label htmlFor="email">Email address</Form.Label>
<Form.Control
type="email"
id="email"
onChange={(e) => updateForm("email", e.target.value)}
value={email}
required
minLength={8}
isInvalid={validated && error === "Email exists"}
/>
<Form.Control.Feedback type="invalid">
Email already exists
</Form.Control.Feedback>
</Form.Group>
<Form.Group className={styles.formGroup}>
<Form.Label htmlFor="username">Username</Form.Label>
<Form.Control
id="username"
onChange={(e) => updateForm("username", e.target.value)}
value={username}
required
minLength={8}
/>
<Form.Control.Feedback type="invalid" />
</Form.Group>
<Form.Group className={styles.formGroup}>
<Form.Label htmlFor="password">Password</Form.Label>
<Form.Control
type="password"
id="password"
onChange={(e) => updateForm("password", e.target.value)}
value={password}
required
isInvalid={validated && passwordConfirm !== password}
/>
<Form.Control.Feedback type="invalid" />
</Form.Group>
<Form.Group className={styles.formGroup}>
<Form.Label htmlFor="confirm-password">
Confirm Password
</Form.Label>
<Form.Control
type="password"
id="confirm-password"
onChange={(e) =>
updateForm("passwordConfirm", e.target.value)
}
value={passwordConfirm}
required
isInvalid={validated && passwordConfirm !== password}
/>
<Form.Control.Feedback type="invalid">
Passwords do not match
</Form.Control.Feedback>
</Form.Group>
<Button
type="submit"
className={styles.btn}
disabled={isLoading}
>
Register
</Button>
</Form>
</main>
);
};
export default Register;
@@ -0,0 +1,43 @@
import { useState } from "react";
import { Button, Form } from "react-bootstrap";
import { useSearchParams } from "react-router-dom";
import styles from "../Login/Login.module.scss";
export default function ResetPassword() {
const [params] = useSearchParams();
const [password, setPassword] = useState("");
const [message, setMessage] = useState("");
const [isLoading, setIsLoading] = useState(false);
async function submit(event) {
event.preventDefault();
setIsLoading(true);
try {
const response = await fetch("/api/user/update-password", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token: params.get("token"), password }),
});
const data = await response.json();
setMessage(response.ok ? "Password updated. You can now log in." : data.message || "Unable to update password");
} catch {
setMessage("Unable to update password");
} finally {
setIsLoading(false);
}
}
return (
<main className={styles.login}>
<Form className={styles.form} onSubmit={submit}>
<h1>Choose a password</h1>
<Form.Label htmlFor="new-password">New password</Form.Label>
<Form.Control id="new-password" type="password" minLength={8} value={password} onChange={(event) => setPassword(event.target.value)} required />
{message && <p role="status">{message}</p>}
<Button type="submit" disabled={isLoading}>
{isLoading ? "Updating…" : "Update password"}
</Button>
</Form>
</main>
);
}
@@ -0,0 +1,21 @@
import { useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
export default function VerifyEmail() {
const [params] = useSearchParams();
const token = params.get("token");
const [message, setMessage] = useState("Verifying email…");
useEffect(() => {
fetch("/api/user/verify-email", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token }),
}).then(async (response) => {
const data = await response.json();
setMessage(response.ok ? "Email verified. You can now log in." : data.message || "Unable to verify email");
}).catch(() => setMessage("Unable to verify email"));
}, [token]);
return <main><p role="status">{message}</p></main>;
}