Migrate Flask React template into Forge
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
import "./styles/custom.scss";
|
||||
|
||||
import { BrowserRouter, Routes, Route } from "react-router-dom";
|
||||
import { AuthProvider } from "./contexts/AuthContext";
|
||||
import ProtectedRoute from "./routing/ProtectedRoute";
|
||||
import PageNotFound from "./views/PageNotFound/PageNotFound";
|
||||
|
||||
import Login from "./views/Login/Login";
|
||||
import Register from "./views/Register/Register";
|
||||
import ForgotPassword from "./views/ForgotPassword/ForgotPassword";
|
||||
import ResetPassword from "./views/ResetPassword/ResetPassword";
|
||||
import VerifyEmail from "./views/VerifyEmail/VerifyEmail";
|
||||
import Contact from "./views/Contact/Contact";
|
||||
import Privacy from "./views/Legal/Privacy";
|
||||
import Terms from "./views/Legal/Terms";
|
||||
import Header from "./components/Header/Header";
|
||||
import Footer from "./components/Footer/Footer";
|
||||
import PageMeta from "./components/PageMeta/PageMeta";
|
||||
|
||||
import Homepage from "./views/Home/Homepage";
|
||||
import Dashboard from "./views/Dashboard/Dashboard";
|
||||
|
||||
|
||||
const App = () => {
|
||||
return (
|
||||
<div className="app" data-bs-theme="dark">
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<>
|
||||
<a className="skipLink" href="#main-content">Skip to main content</a>
|
||||
<Header />
|
||||
<div id="main-content" className="pageContent" tabIndex="-1">
|
||||
<Routes>
|
||||
<Route index element={<><PageMeta /><Homepage /></>} />
|
||||
<Route element={<ProtectedRoute />}>
|
||||
<Route path="dashboard" element={<><PageMeta title="Dashboard" noIndex /><Dashboard /></>} />
|
||||
</Route>
|
||||
<Route path="login" element={<><PageMeta title="Login" noIndex /><Login /></>} />
|
||||
<Route path="register" element={<><PageMeta title="Register" noIndex /><Register /></>} />
|
||||
<Route path="forgot-password" element={<><PageMeta title="Reset password" noIndex /><ForgotPassword /></>} />
|
||||
<Route path="reset-password" element={<><PageMeta title="Choose a password" noIndex /><ResetPassword /></>} />
|
||||
<Route path="verify-email" element={<><PageMeta title="Verify email" noIndex /><VerifyEmail /></>} />
|
||||
<Route path="contact" element={<><PageMeta title="Contact" description="Contact the application team." /><Contact /></>} />
|
||||
<Route path="privacy" element={<><PageMeta title="Privacy policy" /><Privacy /></>} />
|
||||
<Route path="terms" element={<><PageMeta title="Terms of service" /><Terms /></>} />
|
||||
<Route path="*" element={<><PageMeta title="Page not found" noIndex /><PageNotFound /></>} />
|
||||
</Routes>
|
||||
</div>
|
||||
<Footer />
|
||||
</>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default App;
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
@@ -0,0 +1,25 @@
|
||||
import styles from "./Footer.module.scss";
|
||||
import { NavLink } from "react-router-dom";
|
||||
import { site } from "../../config/site";
|
||||
|
||||
const Footer = () => {
|
||||
return (
|
||||
<footer className={styles.footer}>
|
||||
<nav className={styles.links} aria-label="Footer navigation">
|
||||
<NavLink to="/contact">Contact</NavLink>
|
||||
<NavLink to="/privacy">Privacy</NavLink>
|
||||
<NavLink to="/terms">Terms</NavLink>
|
||||
</nav>
|
||||
{site.developer && <div className={styles.developerSlot}>
|
||||
<a href={site.developer.url} aria-label={site.developer.linkLabel} rel="noreferrer">
|
||||
<img src={site.developer.logoPath} alt={site.developer.name} className={styles.developerLogo} />
|
||||
</a>
|
||||
</div>}
|
||||
<p className={styles.copyright}>
|
||||
© {new Date().getFullYear()} {site.name}
|
||||
</p>
|
||||
</footer>
|
||||
);
|
||||
};
|
||||
|
||||
export default Footer;
|
||||
@@ -0,0 +1,41 @@
|
||||
@use "sass:map";
|
||||
@use "../../styles/colors";
|
||||
|
||||
.footer {
|
||||
padding: 10px;
|
||||
min-height: 70px;
|
||||
background-color: map.get(colors.$theme-colors, "footer-bg");
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.links {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 1rem;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
}
|
||||
}
|
||||
|
||||
.developerSlot {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin: 0 auto 0.5rem;
|
||||
|
||||
a {
|
||||
display: inline-flex;
|
||||
border-radius: 0.25rem;
|
||||
}
|
||||
}
|
||||
|
||||
.developerLogo {
|
||||
display: block;
|
||||
width: min(210px, 70vw);
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.copyright {
|
||||
margin: 0;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import Footer from "./Footer";
|
||||
import { site } from "../../config/site";
|
||||
|
||||
describe("Footer", () => {
|
||||
it("keeps developer branding absent until configured", () => {
|
||||
render(<MemoryRouter><Footer /></MemoryRouter>);
|
||||
expect(screen.queryByRole("img")).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("contentinfo")).toHaveTextContent(site.name);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Nav } from "react-bootstrap";
|
||||
import { NavLink } from "react-router-dom";
|
||||
|
||||
const GuestNav = () => {
|
||||
return (
|
||||
<Nav>
|
||||
<Nav.Link as={NavLink} to="/contact">
|
||||
Contact
|
||||
</Nav.Link>
|
||||
<Nav.Link as={NavLink} to="/login">
|
||||
Login
|
||||
</Nav.Link>
|
||||
<Nav.Link as={NavLink} to="/register">
|
||||
Register
|
||||
</Nav.Link>
|
||||
</Nav>
|
||||
);
|
||||
};
|
||||
|
||||
export default GuestNav;
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Container, Navbar } from "react-bootstrap";
|
||||
import styles from "./Header.module.scss";
|
||||
import PageNav from "../PageNav/PageNav"
|
||||
import Logo from "../Logo/Logo"
|
||||
import { useAuth } from "../../contexts/AuthContext";
|
||||
import GuestNav from "../GuestNav/GuestNav";
|
||||
|
||||
|
||||
const Header = () => {
|
||||
const { user } = useAuth()
|
||||
|
||||
return (
|
||||
<Navbar expand="sm" className={styles.header} variant="dark">
|
||||
<Container>
|
||||
<Navbar.Brand as="div"><Logo /></Navbar.Brand>
|
||||
<Navbar.Toggle aria-controls="navbar-nav" />
|
||||
<Navbar.Collapse id="navbar-nav" className={styles.navbarCollapse}>
|
||||
{
|
||||
user ? <PageNav /> : <GuestNav />
|
||||
}
|
||||
|
||||
</Navbar.Collapse>
|
||||
</Container>
|
||||
</Navbar>
|
||||
)
|
||||
}
|
||||
|
||||
export default Header
|
||||
@@ -0,0 +1,12 @@
|
||||
@use "sass:map";
|
||||
@use "../../styles/colors";
|
||||
|
||||
.header {
|
||||
min-height: 70px;
|
||||
padding: 10px;
|
||||
background-color: map.get(colors.$theme-colors, "header-bg");
|
||||
}
|
||||
|
||||
.navbarCollapse {
|
||||
justify-content: flex-end !important;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import styles from "./Logo.module.scss";
|
||||
import { Link } from "react-router-dom";
|
||||
|
||||
function Logo() {
|
||||
return (
|
||||
<Link to="/" className={styles.link}>
|
||||
<span className={styles.logo}>__PROJECT_NAME__</span>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
export default Logo;
|
||||
@@ -0,0 +1,9 @@
|
||||
.link {
|
||||
text-decoration: none;
|
||||
color: unset;
|
||||
}
|
||||
|
||||
.logo {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useEffect } from "react";
|
||||
import PropTypes from "prop-types";
|
||||
import { pageTitle, site } from "../../config/site";
|
||||
|
||||
function upsertMeta(name, content) {
|
||||
let element = document.head.querySelector(`meta[name="${name}"]`);
|
||||
if (!element) {
|
||||
element = document.createElement("meta");
|
||||
element.setAttribute("name", name);
|
||||
document.head.appendChild(element);
|
||||
}
|
||||
element.setAttribute("content", content);
|
||||
}
|
||||
|
||||
export default function PageMeta({ title, description = site.description, noIndex = false }) {
|
||||
useEffect(() => {
|
||||
document.title = pageTitle(title);
|
||||
upsertMeta("description", description);
|
||||
upsertMeta("robots", noIndex ? "noindex, nofollow" : "index, follow");
|
||||
}, [description, noIndex, title]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
PageMeta.propTypes = {
|
||||
title: PropTypes.string,
|
||||
description: PropTypes.string,
|
||||
noIndex: PropTypes.bool,
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
import { render, waitFor } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import PageMeta from "./PageMeta";
|
||||
import { pageTitle } from "../../config/site";
|
||||
|
||||
describe("page metadata", () => {
|
||||
it("sets public page title, description, and indexing policy", async () => {
|
||||
render(<PageMeta title="Contact" description="Contact the application team." />);
|
||||
await waitFor(() => expect(document.title).toBe(pageTitle("Contact")));
|
||||
expect(document.head.querySelector('meta[name="description"]')).toHaveAttribute("content", "Contact the application team.");
|
||||
expect(document.head.querySelector('meta[name="robots"]')).toHaveAttribute("content", "index, follow");
|
||||
});
|
||||
|
||||
it("prevents indexing for account and protected pages", async () => {
|
||||
render(<PageMeta title="Dashboard" noIndex />);
|
||||
await waitFor(() => expect(document.title).toBe(pageTitle("Dashboard")));
|
||||
expect(document.head.querySelector('meta[name="robots"]')).toHaveAttribute("content", "noindex, nofollow");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { NavLink } from "react-router-dom";
|
||||
import { Nav } from "react-bootstrap";
|
||||
import { useAuth } from "../../contexts/AuthContext";
|
||||
|
||||
const PageNav = () => {
|
||||
const { logout } = useAuth();
|
||||
|
||||
return (
|
||||
<Nav>
|
||||
<Nav.Link as={NavLink} to="dashboard">
|
||||
Dashboard
|
||||
</Nav.Link>
|
||||
<Nav.Link as={NavLink} onClick={logout} to="/">
|
||||
Logout
|
||||
</Nav.Link>
|
||||
</Nav>
|
||||
);
|
||||
};
|
||||
|
||||
export default PageNav;
|
||||
@@ -0,0 +1,11 @@
|
||||
export const site = Object.freeze({
|
||||
name: "__PROJECT_NAME__",
|
||||
defaultTitle: "__PROJECT_NAME__",
|
||||
titleTemplate: "%s | __PROJECT_NAME__",
|
||||
description: "A reusable Flask and React web application foundation.",
|
||||
developer: null,
|
||||
});
|
||||
|
||||
export function pageTitle(title) {
|
||||
return title ? site.titleTemplate.replace("%s", title) : site.defaultTitle;
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
/* eslint-disable react-refresh/only-export-components */
|
||||
import { createContext, useContext, useReducer, useEffect } from "react";
|
||||
import PropTypes from "prop-types";
|
||||
import { encode as base64_encode } from "base-64";
|
||||
import { useLocalStorage } from "../hooks/useLocalStorage";
|
||||
import { useNavigate } from "react-router";
|
||||
|
||||
const AuthContext = createContext();
|
||||
const BASE_URL = "/api";
|
||||
|
||||
const initialState = {
|
||||
user: null,
|
||||
isAuthenticated: false,
|
||||
error: "",
|
||||
isLoading: false,
|
||||
};
|
||||
|
||||
function reducer(state, action) {
|
||||
const { type, payload } = action;
|
||||
|
||||
switch (type) {
|
||||
case "auth/login":
|
||||
return {
|
||||
...state,
|
||||
user: payload,
|
||||
isAuthenticated: true,
|
||||
error: "",
|
||||
};
|
||||
case "auth/logout":
|
||||
return { ...state, ...initialState };
|
||||
case "auth/error":
|
||||
return { ...state, error: payload };
|
||||
case "auth/preRequest":
|
||||
return { ...state, error: "", isLoading: true };
|
||||
case "auth/postRequest":
|
||||
return { ...state, isLoading: false };
|
||||
case "auth/updateToken":
|
||||
return { ...state, user: { ...state.user, token: payload } };
|
||||
default:
|
||||
throw new Error(`Unknown action type: ${action.type}`);
|
||||
}
|
||||
}
|
||||
|
||||
function AuthProvider({ children }) {
|
||||
const [{ user, isAuthenticated, isLoading, error }, dispatch] = useReducer(
|
||||
reducer,
|
||||
initialState
|
||||
);
|
||||
const { setLSItems, removeLSItems, getLSItems } = useLocalStorage();
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
const user = getLSItems(["user_id", "token", "username"]);
|
||||
if (!!user.user_id && !!user.token && !!user.username) {
|
||||
dispatch({ type: "auth/login", payload: user });
|
||||
}
|
||||
// Local-storage helpers are intentionally used only during initial hydration.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
async function login(email, password) {
|
||||
dispatch({ type: "auth/preRequest" });
|
||||
try {
|
||||
const res = await fetch(`${BASE_URL}/auth/tokens`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization:
|
||||
"Basic " + base64_encode(`${email}:${password}`),
|
||||
},
|
||||
});
|
||||
if (res.status === 200) {
|
||||
const data = await res.json();
|
||||
setLSItems(data);
|
||||
dispatch({ type: "auth/login", payload: data });
|
||||
}
|
||||
else if (res.status === 401) {
|
||||
throw new Error("Unauthorized");
|
||||
}
|
||||
else {
|
||||
throw new Error(res.statusText)
|
||||
}
|
||||
} catch (err) {
|
||||
dispatch({ type: "auth/error", payload: err.message });
|
||||
} finally {
|
||||
dispatch({ type: "auth/postRequest" });
|
||||
}
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
try {
|
||||
if (user?.token) await request("auth/tokens", { method: "DELETE" });
|
||||
} catch {
|
||||
// Local logout must complete even when server revocation fails.
|
||||
} finally {
|
||||
removeLSItems(["token", "username", "user_id"]);
|
||||
dispatch({ type: "auth/logout" });
|
||||
}
|
||||
}
|
||||
|
||||
async function register(email, password, username) {
|
||||
dispatch({ type: "auth/preRequest" });
|
||||
try {
|
||||
const res = await fetch(`${BASE_URL}/user/register`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({email, password, username})
|
||||
})
|
||||
if(res.status === 201) {
|
||||
return true
|
||||
}
|
||||
else{
|
||||
const data = await res.json()
|
||||
throw new Error(res.status === 409 ? "Email exists" : data.message)
|
||||
}
|
||||
} catch (err) {
|
||||
dispatch({ type: "auth/error", payload: err.message });
|
||||
} finally {
|
||||
dispatch({ type: "auth/postRequest" });
|
||||
}
|
||||
}
|
||||
|
||||
async function requestWithToken(url, token, options = {}) {
|
||||
const headers = new Headers();
|
||||
if (!token || token === "") {
|
||||
throw new Error("No bearer token");
|
||||
}
|
||||
headers.append("authorization", `Bearer ${token}`);
|
||||
headers.append("X-Requested-With", "XMLHttpRequest");
|
||||
if (options.headers) {
|
||||
Object.keys(options.headers).forEach((key) => {
|
||||
headers.append(key, options.headers[key]);
|
||||
});
|
||||
}
|
||||
const res = await fetch(
|
||||
`${BASE_URL}/${url}`,
|
||||
{
|
||||
...options,
|
||||
credentials: "include",
|
||||
headers,
|
||||
},
|
||||
true
|
||||
);
|
||||
return res;
|
||||
}
|
||||
|
||||
async function request(url, options = {}, reauth = false) {
|
||||
let token = user.token;
|
||||
if (reauth) {
|
||||
const res = await fetch(`${BASE_URL}/auth/refresh`);
|
||||
const data = await res.json();
|
||||
if (
|
||||
res.status == 400 &&
|
||||
data.message === "Bad request, no refresh token"
|
||||
) {
|
||||
dispatch({ type: "auth/logout" });
|
||||
navigate("/login");
|
||||
}
|
||||
if (`${data.user_id}` !== `${user.user_id}`)
|
||||
throw new Error(`Wrong user. ${data.user_id}, ${user.user_id}`);
|
||||
else if (res.status === 200) {
|
||||
token = data.token;
|
||||
setLSItems({ token });
|
||||
dispatch({ type: "auth/updateToken", payload: token });
|
||||
} else {
|
||||
throw new Error("Error refreshing token");
|
||||
}
|
||||
}
|
||||
const res = await requestWithToken(url, token, options);
|
||||
if (res.status == 401) {
|
||||
if (reauth) {
|
||||
throw new Error("Unauthorized");
|
||||
}
|
||||
return request(url, options, true);
|
||||
}
|
||||
if (!res.ok && !reauth) {
|
||||
throw new Error("Error fetching data");
|
||||
}
|
||||
const data = await res.json();
|
||||
return data;
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
login,
|
||||
logout,
|
||||
user,
|
||||
isAuthenticated,
|
||||
error,
|
||||
isLoading,
|
||||
request,
|
||||
register,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
const useAuth = () => {
|
||||
const context = useContext(AuthContext);
|
||||
if (context === undefined) {
|
||||
throw new Error("AuthContext used outside AuthProvider");
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
AuthProvider.propTypes = {
|
||||
children: PropTypes.object.isRequired,
|
||||
};
|
||||
|
||||
export { AuthProvider, useAuth };
|
||||
@@ -0,0 +1,16 @@
|
||||
const useLocalStorage = () => {
|
||||
const setLSItems = (items={}) => {
|
||||
Object.keys(items).forEach(key => localStorage.setItem(key, items[key]))
|
||||
}
|
||||
const removeLSItems = (keys=[]) => {
|
||||
keys.forEach(item => localStorage.removeItem(item))
|
||||
}
|
||||
const getLSItems = (keys=[]) => {
|
||||
let items = {}
|
||||
keys.forEach(key => items[key] = localStorage.getItem(key))
|
||||
return items
|
||||
}
|
||||
return {setLSItems, removeLSItems, getLSItems};
|
||||
}
|
||||
|
||||
export { useLocalStorage}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import App from './App.jsx'
|
||||
|
||||
createRoot(document.getElementById('root')).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,28 @@
|
||||
import { NavLink, Outlet } from 'react-router-dom'
|
||||
import { useAuth } from '../contexts/AuthContext'
|
||||
import PageMeta from '../components/PageMeta/PageMeta'
|
||||
|
||||
const ProtectedRoute = () => {
|
||||
const { user } = useAuth()
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<>
|
||||
<PageMeta title="Unauthorized" noIndex />
|
||||
<main style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
|
||||
<div style={{textAlign: 'center'}}>
|
||||
<h1>Unauthorized</h1>
|
||||
<h5>
|
||||
<span>
|
||||
<NavLink to='/login' style={{color: 'white'}}>Login</NavLink> to gain access
|
||||
</span>
|
||||
</h5>
|
||||
</div>
|
||||
</main>
|
||||
</>
|
||||
)
|
||||
}
|
||||
return <Outlet />
|
||||
}
|
||||
|
||||
export default ProtectedRoute
|
||||
@@ -0,0 +1,41 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { MemoryRouter, Route, Routes } from "react-router-dom";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import ProtectedRoute from "./ProtectedRoute";
|
||||
import { useAuth } from "../contexts/AuthContext";
|
||||
|
||||
vi.mock("../contexts/AuthContext", () => ({ useAuth: vi.fn() }));
|
||||
|
||||
describe("protected routes", () => {
|
||||
beforeEach(() => vi.mocked(useAuth).mockReset());
|
||||
|
||||
it("offers login instead of protected content to a guest", () => {
|
||||
vi.mocked(useAuth).mockReturnValue({ user: null });
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/dashboard"]}>
|
||||
<Routes>
|
||||
<Route element={<ProtectedRoute />}>
|
||||
<Route path="dashboard" element={<p>Protected dashboard</p>} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
);
|
||||
expect(screen.getByRole("heading", { name: "Unauthorized" })).toBeInTheDocument();
|
||||
expect(screen.queryByText("Protected dashboard")).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "Login" })).toHaveAttribute("href", "/login");
|
||||
});
|
||||
|
||||
it("renders protected content for an authenticated user", () => {
|
||||
vi.mocked(useAuth).mockReturnValue({ user: { user_id: 1 } });
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/dashboard"]}>
|
||||
<Routes>
|
||||
<Route element={<ProtectedRoute />}>
|
||||
<Route path="dashboard" element={<p>Protected dashboard</p>} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
);
|
||||
expect(screen.getByText("Protected dashboard")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
@use "./colors";
|
||||
|
||||
.app {
|
||||
display: flex;
|
||||
min-height: 100vh;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.pageContent {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
main {
|
||||
padding: 20px;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.skipLink {
|
||||
position: fixed;
|
||||
z-index: 2000;
|
||||
top: 0.5rem;
|
||||
left: 0.5rem;
|
||||
padding: 0.75rem 1rem;
|
||||
color: #111;
|
||||
background: #fff;
|
||||
transform: translateY(-200%);
|
||||
}
|
||||
|
||||
.skipLink:focus {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
:focus-visible {
|
||||
outline: 3px solid colors.$focus-ring;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
@media (max-width: 575.98px) {
|
||||
main {
|
||||
padding: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
scroll-behavior: auto !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
$body-bg: #222222;
|
||||
$body-color: white;
|
||||
$primary: #f99c00;
|
||||
$secondary: #005e49;
|
||||
$danger: red;
|
||||
$surface-header: #343a40;
|
||||
$surface-footer: #343a40;
|
||||
$focus-ring: #ffb84d;
|
||||
|
||||
$theme-colors: (
|
||||
"grey-dark": #222222,
|
||||
"grey-light": #d6f0e3,
|
||||
"grey": #343a40,
|
||||
"orange": #f99c00,
|
||||
"primary": $primary,
|
||||
"secondary": $secondary,
|
||||
"danger": $danger,
|
||||
"header-bg": $surface-header,
|
||||
"footer-bg": $surface-footer
|
||||
);
|
||||
@@ -0,0 +1,10 @@
|
||||
@use "./colors";
|
||||
@use "bootstrap/scss/bootstrap" with (
|
||||
$body-bg: colors.$body-bg,
|
||||
$body-color: colors.$body-color,
|
||||
$primary: colors.$primary,
|
||||
$secondary: colors.$secondary,
|
||||
$danger: colors.$danger,
|
||||
$theme-colors: colors.$theme-colors
|
||||
);
|
||||
@use "./app";
|
||||
@@ -0,0 +1 @@
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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" }),
|
||||
}));
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
const Dashboard = () => {
|
||||
return (
|
||||
<main>
|
||||
<section>
|
||||
<h1>Dashboard</h1>
|
||||
<p>
|
||||
This protected placeholder is ready for the generated
|
||||
project'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>
|
||||
);
|
||||
}
|
||||
@@ -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'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;
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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,9 @@
|
||||
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;
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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>;
|
||||
}
|
||||
Reference in New Issue
Block a user