Migrate Flask React template into Forge
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
# Architecture
|
||||
|
||||
`forge/` reserves a framework-independent core. `templates/` contains independent stack-specific packages; `flask-react/` is a reservation only. `skills/` is the canonical source for four future skills. `profiles/` holds minimal business and personal defaults. `scripts/` provides portable user-level skill distribution. `docs/specifications/` defines interfaces; integrations are optional.
|
||||
`forge/` holds framework-independent helpers. `templates/` contains independent stack-specific packages; `flask-react/` now includes a descriptor, source payload, fresh context boilerplate, optional GitHub workflow, and a standalone generator. `skills/` is the canonical source for four skills. `profiles/` holds business and personal defaults. `scripts/` provides portable user-level skill distribution. `docs/specifications/` defines interfaces; integrations are optional.
|
||||
|
||||
The context skill owns project records, tasks, worktrees, profiles, and design approvals. New delegates lifecycle setup to context. Contributor uses the context lifecycle with Captain/Commander authority and isolated testing. Design uses context for approvals and records. These are contracts, not active skill implementations.
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
# Current state
|
||||
|
||||
FORGE-F001, FORGE-F002, and FORGE-F007 were human accepted and are present on `codex`. FORGE-F004 and FORGE-F003 implementation candidates are merged into local `codex`, with their external validation and human acceptance pending. Explicit business/personal profile configuration is implemented. `bortstack-context`, `bortstack-contributor`, and `bortstack-design` packages are present; one skill directory remains reserved. The repository `testtask` entry point is provisioned but blocked because Forge has no application runtime or manual-test hook. No generator or active legacy-skill migration has been implemented. F006 is briefed but not engaged; its optional email/hosting and neutral-default boundary is accepted. Captain reports successful external validation of local Penpot 2.18 Docker and its integrated MCP connection, including editable shape/text creation and preservation of existing design elements during modification. The MCP container runs locally, but no Penpot connector or browser is exposed to this session, so current-session Penpot edits have not been verified. Windows and JJ's hands-on workflow have not been tested. Decisions FORGE-001 through FORGE-009 remain accepted. Captain has authorised direct `codex` work for future Forge tasks until further notice.
|
||||
FORGE-F001, FORGE-F002, and FORGE-F007 were human accepted and are present on `codex`. F003 and F004 candidates are merged with external validation and acceptance pending. F006 has an independent Flask/React template package and generator candidate directly on `codex`; human acceptance and some generated-project checks remain pending. Explicit business/personal profile configuration is implemented. `bortstack-context`, `bortstack-contributor`, and `bortstack-design` packages are present; one skill directory remains reserved. The repository `testtask` entry point is provisioned but blocked because Forge has no application runtime or manual-test hook. No cross-template generator or active legacy-skill migration has been implemented. Captain reports successful external validation of local Penpot 2.18 Docker and integrated MCP, but this session has no Penpot connector/browser. Windows and JJ's hands-on workflow have not been tested. Decisions FORGE-001 through FORGE-009 remain accepted. Captain has authorised direct `codex` work until further notice.
|
||||
|
||||
+5
-5
@@ -1,11 +1,11 @@
|
||||
# Handoff
|
||||
|
||||
Current work: FORGE-F007 was committed as `d3a88fd` on `codex` under FORGE-008's direct-branch policy and human accepted on 2026-11-17. F002 and F007 are Complete. The profile command writes only to an explicitly named target directory; validation used temporary projects, not external applications.
|
||||
Current work: FORGE-F006 migrated the tracked `flask-react-auth-base` source at `ff139bf5f28f4604b4a7108f4ee26608dea9924e` into Forge on `codex`, starting from `bc6b6d2`. The original source repository was read and remained clean/unchanged. F006 is Ready to Finalise for Captain review, not Complete. Direct `codex` work follows FORGE-008. No external application, provider, or production infrastructure was modified.
|
||||
|
||||
Implementation: `forge/profile_config.py` and `scripts/configure-profile.py` record a selected business or personal profile at `.bortstack/profile.yaml` with explicit owner, brand, contributor policy, testing, and deployment values. The command supports dry-run, refuses placeholder values and overwrites, and leaves existing project files intact. The profile contract and `bortstack-context` now describe the record. No new dependency, generator, provider integration, access grant, or deployment was added.
|
||||
Implementation: `templates/flask-react/` now contains a descriptor, independent source payload, Python generator, fresh neutral context boilerplate, and optional GitHub workflow. Generated projects do not need GitHub, SWAG, Resend, a production host, or Forge at runtime. Email is disabled by default, branding is project-specific, and optional SWAG uses a separate Compose overlay. Existing `roborto-*` skills and Forge distribution tooling are untouched.
|
||||
|
||||
Validation: `python3 -m unittest discover -s tests -v` passed 12 tests, including business and personal examples with different owners/brands and an existing-project preservation check. `python3 scripts/validate-skills.py` accepted three implemented packages; `git diff --check` passed. Windows invocation is documented but not exercised on Windows.
|
||||
Validation: Forge `python3 -m unittest discover -s tests -v` passed 15 tests and `python3 scripts/validate-skills.py` passed. A disposable `Orion Starter` generated at `/tmp/forge-f006-orion2` passed 14 backend tests in an ephemeral Docker container, SQLite migration upgrades, Compose configuration, and API/nginx image builds. A fresh `/tmp/forge-f006-orion3` passed base and optional SWAG-overlay Compose configuration, clean `npm ci`, 16 frontend tests, lint, and build in a Node container. A further disposable `/tmp/forge-f006-browser-trial` passed 23 Playwright checks with one intentional skip after Chromium OS libraries were installed in the ephemeral runner. Generator tests cover local-only mode, optional local Git, collision refusal, copied capabilities, neutral identity, and no active GitHub workflow. `git diff --check` passed.
|
||||
|
||||
Status: F007 is Complete by Captain acceptance. F003 remains merged with Captain design approval and Penpot/Windows/visual validation pending. F004 remains merged with JJ's external validation pending. The repository `testtask` remains blocked by lack of an application runtime. No push or deployment has occurred.
|
||||
Limitations: Host Python lacked Flask, so a direct host test failed; an initial network-disabled pip install and API build also failed on dependency resolution. Container validation succeeded using available dependency/image cache and normal Docker networking. Host npm was absent, but a clean generated-project `npm ci` and subsequent checks passed inside Node Docker. `npm ci` reported 14 advisories in development dependencies (5 moderate, 7 high, 2 critical); `npm audit --omit=dev` reported zero production advisories. The first Playwright attempt failed because the minimal runner lacked Chromium libraries; after installing those libraries inside an ephemeral container, the suite passed. MySQL runtime tests, Windows generation, and live email/hosting remain unverified. The existing bootstrap workflow must stay available until Captain acceptance. Forge `testtask` remains blocked because Forge has no application runtime.
|
||||
|
||||
Next action: F006 is the remaining independent prerequisite for F005. F006 has been briefed; Captain accepted the optional email/hosting and neutral-default boundary in FORGE-009, but implementation has not been engaged. The external `flask-react-auth-base` repository was inspected read-only and remains unchanged. Future Forge work stays on `codex` until Captain says otherwise.
|
||||
Next action: Captain reviews and accepts F006 or requests changes. F005 may use the descriptor and generator after F006 acceptance. F003 and F004 still await their separate external validation and acceptance. No push or deployment has occurred.
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
# Project overview
|
||||
|
||||
Bortstack Forge will manage a framework-independent core, independently maintained application templates, four canonical Codex skills, project profiles, and optional integrations. This repository is the canonical source for future Forge skills. FORGE-F001 established contracts and distribution. Flask/React code remains in its existing source repository. Penpot and repository-provider integrations are optional; Forge's design integration is not implemented. Captain reports a validated local Penpot 2.18 Docker deployment and integrated MCP connection outside this repository.
|
||||
Bortstack Forge manages a framework-independent core, independently maintained application templates, four canonical Codex skills, project profiles, and optional integrations. This repository is the canonical source for Forge skills. The Flask/React source has been copied into Forge's template package for F006; its original repository remains unchanged and operational. Penpot and repository-provider integrations are optional. Captain reports a validated local Penpot 2.18 Docker deployment and integrated MCP connection outside this repository.
|
||||
|
||||
+3
-1
@@ -52,7 +52,7 @@ Orchestrate technology-independent generation: template selection, project confi
|
||||
Acceptance: generate and validate a project from the migrated template with either profile and a local-only Git option.
|
||||
|
||||
## FORGE-F006 — Migrate Flask/React Bootstrap Template
|
||||
Status: Planned (briefed; implementation not yet engaged). Priority: High. Dependencies: FORGE-F001. Migration defaults accepted in FORGE-009.
|
||||
Status: Ready to Finalise (human acceptance pending). Priority: High. Dependencies: FORGE-F001. Implemented directly on `codex` under FORGE-008, starting from `bc6b6d2`. Migration defaults accepted in FORGE-009.
|
||||
|
||||
Migrate `flask-react-auth-base` into Forge's template architecture. Preserve Flask backend/authentication, React/Vite frontend, Docker configuration, database support, automated tests, and documentation. Remove mandatory GitHub and immediate production-deployment assumptions. Validate generated applications before retiring the existing bootstrap workflow. No additional framework templates yet.
|
||||
|
||||
@@ -60,6 +60,8 @@ Acceptance: a generated application passes relevant checks and retains the liste
|
||||
|
||||
Accepted migration boundary (2026-11-17): preserve email and hosting foundations as optional configuration with neutral project-specific defaults. Generation must work locally without GitHub or production infrastructure and must not publish or deploy. Keep the source `flask-react-auth-base` repository unchanged.
|
||||
|
||||
Implementation record (2026-11-17): Copied the tracked source at `ff139bf5f28f4604b4a7108f4ee26608dea9924e` into Forge's independent template package without changing the original repository. Added a descriptor and Python generator, fresh neutral project context, optional GitHub workflow and SWAG overlay, disabled email by default, and removed mandatory external-network and Roborto branding defaults. Generated projects passed 14 backend tests, 16 frontend tests, frontend lint/build, 23 Playwright checks (one intentional skip), SQLite migrations, Compose base/optional-overlay configuration, and API/nginx image builds. Forge's 15 tests and skill validation passed. A fresh generated frontend passed `npm ci`; the install reported 14 advisories in development dependencies, while `npm audit --omit=dev` reported zero production advisories. A clean host Python install, MySQL runtime test, and Windows generation remain unverified in this session; prior source-repository evidence does not substitute for those generated-project checks. Do not retire the existing bootstrap workflow or mark F006 Complete before human acceptance.
|
||||
|
||||
## FORGE-F007 — Implement Business/Personal Profiles
|
||||
Status: Complete; human acceptance received 2026-11-17. Priority: Medium. Dependencies: FORGE-F002. Implemented directly on `codex` under FORGE-008 in commit `d3a88fd`.
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# Template contract
|
||||
|
||||
A future template descriptor must identify template ID and version, supported project type, configuration variables, generation procedure, dependencies, development commands, validation/test commands, and optional capabilities. It must state platform requirements and how it produces initial context. No descriptor format or generation API is implemented yet.
|
||||
A template descriptor identifies template ID and version, supported project type, configuration variables, generation procedure, dependencies, development commands, validation/test commands, optional capabilities, platform requirements, and initial context behavior. `templates/flask-react/template.json` is the first implemented descriptor; `templates/flask-react/generate.py` is its standalone generation API. F005 will orchestrate selection and project profiles across templates. Generated projects have no Forge runtime dependency.
|
||||
|
||||
The first migration source is the existing `flask-react-auth-base` repository. Its documented `scripts/create-project.sh` accepts a project name, destination, and optional `--git-init`, and refuses existing destinations. It remains external and unchanged. Migration of its code or generator is a separate task.
|
||||
The migration source is the existing `flask-react-auth-base` repository at the commit recorded in the descriptor. It remains external and unchanged. Forge's generator accepts a project name, new destination, and optional `--git-init`; it refuses existing destinations and paths inside Forge. Email and hosting foundations are optional per FORGE-009, with no active GitHub workflow or automatic deployment in generated projects.
|
||||
|
||||
@@ -1,3 +1,15 @@
|
||||
# Flask/React template reservation
|
||||
# Flask/React template
|
||||
|
||||
Initial migration source: `/home/rob/projects/flask-react-auth-base` in the current development environment. Its `scripts/create-project.sh` generates a clean project copy and optionally initializes Git. This source has not been moved, copied, or rewritten here. The path is discovery evidence, not a portable dependency. See the [template contract](../../docs/specifications/template-contract.md).
|
||||
This independently maintained Forge template migrates the tracked source of `flask-react-auth-base` at commit `ff139bf5f28f4604b4a7108f4ee26608dea9924e`. The external source repository remains unchanged. The copied `source/` holds Flask authentication, SQLAlchemy migrations, React/Vite, Docker/nginx, and their tests. `boilerplate/` supplies fresh project context and neutral setup documentation. `template.json` is the descriptor consumed by future Forge orchestration.
|
||||
|
||||
Generate a project in a new directory:
|
||||
|
||||
```sh
|
||||
python3 templates/flask-react/generate.py "My Application" /tmp/my-application
|
||||
```
|
||||
|
||||
Add `--git-init` to initialize a local `main` branch. GitHub is not required. The generator refuses existing destinations and destinations inside Forge. It installs no packages, contacts no provider, and performs no deployment. It leaves profile selection to `bortstack-context`/F007; F005 will later orchestrate template and profile selection together.
|
||||
|
||||
The generated project has safe local/example configuration: SQLite is the development default, email is disabled, branding and project name are neutral, and Compose has no mandatory external SWAG network. Resend code, MySQL, Docker/nginx, an optional SWAG sample, and a GitHub CI/deployment example remain available. The GitHub workflow stays under `optional/github/` in Forge and is not generated as an active workflow. Enabling external services requires separate project decisions and configuration. See `boilerplate/docs/OPTIONAL_SERVICES.md`.
|
||||
|
||||
Linux generation was exercised. The Python generator is platform-neutral, but Windows generation and the full generated-project runtime matrix remain to be verified on Windows. The source package is a migration snapshot, not a live dependency on `/home/rob/projects/flask-react-auth-base`.
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
# Project instructions
|
||||
|
||||
Read `docs/PROJECT_OVERVIEW.md`, `docs/CURRENT_STATE.md`, `docs/DECISIONS.md`, `docs/TASKS.md`, and `docs/HANDOFF.md` before task work. Inspect Git status and relevant code. Record accepted decisions and task scope in this repository. Preserve unrelated work and never commit secrets. The project owner defines branch, review, deployment, and contributor permissions; no Forge runtime is required.
|
||||
@@ -0,0 +1,33 @@
|
||||
# __PROJECT_NAME__
|
||||
|
||||
This independent project was generated from Forge's Flask/React template. Define product requirements and choose a project profile before implementation. No GitHub account, production host, email provider, or Forge runtime is required for local development.
|
||||
|
||||
## Local development
|
||||
|
||||
```sh
|
||||
python3 -m venv api/.venv
|
||||
api/.venv/bin/python -m pip install -r api/config/requirements-dev.txt
|
||||
cd api && .venv/bin/flask --app api.py db upgrade && .venv/bin/flask --app api.py run
|
||||
```
|
||||
|
||||
In another terminal:
|
||||
|
||||
```sh
|
||||
cd react && npm ci && npm run dev
|
||||
```
|
||||
|
||||
Windows PowerShell: create the virtual environment with `py -3 -m venv api/.venv`, then use `api/.venv/Scripts/python.exe` and `api/.venv/Scripts/flask.exe` in place of the Unix paths. Run Node commands from `react/` on either platform.
|
||||
|
||||
## Validation
|
||||
|
||||
```sh
|
||||
cd api && .venv/bin/pytest
|
||||
cd react && npm run lint && npm test && npm run build
|
||||
docker compose --env-file .env.example config --quiet
|
||||
```
|
||||
|
||||
Playwright browser tests are optional and require `npx playwright install chromium` followed by `npm run test:e2e`. Docker is optional for local development. `.env.example` contains local/example values only; do not use its placeholder passwords in production or commit a populated `.env`.
|
||||
|
||||
## Project context
|
||||
|
||||
Read `AGENTS.md` and `docs/` before changing this project. The profile is deliberately unset; select business or personal and record owner, brand, contributor, testing, and deployment choices separately. Email delivery is disabled until a sender/provider is configured. See `docs/OPTIONAL_SERVICES.md` for optional hosting and email foundations.
|
||||
@@ -0,0 +1,3 @@
|
||||
# Current state
|
||||
|
||||
__PROJECT_NAME__ was generated from the Forge Flask/React template. Generation copied the files; dependency installation, tests, migrations, runtime health, and external services are unverified for this project. Inspect actual code/configuration and update this record after validation.
|
||||
@@ -0,0 +1,3 @@
|
||||
# Decisions
|
||||
|
||||
No product profile, owner, brand, email provider, repository provider, or hosting decision has been recorded yet. Preserve accepted decisions here with date, rationale, and consequences.
|
||||
@@ -0,0 +1,3 @@
|
||||
# Handoff
|
||||
|
||||
__PROJECT_NAME__ was generated from a Flask/React foundation. No product decisions or runtime validation are implied by generation. Read `AGENTS.md` and the context files, select a profile explicitly, then run the commands in `README.md` and record actual results. Keep secrets outside Git.
|
||||
@@ -0,0 +1,7 @@
|
||||
# Optional services
|
||||
|
||||
Local development needs no GitHub, production host, SWAG network, Resend account, or Cloudflare routing. Email delivery starts disabled. To enable it, choose and verify a project-specific sender/domain and contact destination, set `RESEND_API_KEY`, `EMAIL_FROM`, `CONTACT_EMAIL`, and `EMAIL_DELIVERY_ENABLED=true` in an untracked environment, then test account and contact flows. The code currently implements Resend outbound delivery; inbound routing is a separate operator choice.
|
||||
|
||||
`docker-compose.yml` provides MySQL, API, and nginx services with loopback diagnostic ports. It does not require an external reverse-proxy network. `ops/swag/` includes an optional Compose overlay and proxy sample for projects using SWAG; adapt networking and TLS separately before hosting. The Forge package retains a GitHub Actions CI/deployment example under `optional/github/`, but generation does not install an active workflow. Copying or enabling any deployment workflow is a separate project decision. Never use `.env.example` placeholder passwords or secrets in production.
|
||||
|
||||
Before production, choose a host and repository provider, configure external secrets, verify migrations/backup/rollback, review authentication and email policy, and run the project's required tests. Generation performs none of these actions.
|
||||
@@ -0,0 +1,3 @@
|
||||
# Project overview
|
||||
|
||||
__PROJECT_NAME__ is a newly generated Flask/React application foundation. Product purpose, intended users, ownership, branding, and deployment target are not yet selected. React/Vite lives under `react/`; Flask/SQLAlchemy and migrations live under `api/`. Development defaults to SQLite and disabled email. MySQL, Docker/nginx, Resend outbound email, SWAG, and GitHub automation are optional project choices. Generated code has no Forge runtime dependency.
|
||||
@@ -0,0 +1,6 @@
|
||||
# Tasks
|
||||
|
||||
## Initial project definition — __PROJECT_NAME__
|
||||
Status: Planned; implementation requires owner acceptance.
|
||||
|
||||
Define purpose, users, ownership, branding, business/personal profile, contributor permissions, testing expectations, and deployment expectations. Validate backend/frontend tests and migrations in this project. Email and hosting integrations remain optional; do not publish or deploy during initial setup.
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate an independent Flask/React project from Forge's migrated template."""
|
||||
import argparse
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
TOKEN_FILES = (".env.example", "docker-compose.yml", "react/index.html",
|
||||
"react/src/config/site.js", "react/src/components/Logo/Logo.jsx")
|
||||
|
||||
|
||||
def generate(name, destination, git_init=False):
|
||||
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9 _-]{0,79}", name):
|
||||
raise ValueError("project name must use letters, numbers, spaces, underscores or hyphens")
|
||||
slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
|
||||
if not slug:
|
||||
raise ValueError("project name needs a letter or number")
|
||||
target = Path(destination).expanduser().resolve()
|
||||
if target.exists() or target.is_symlink():
|
||||
raise FileExistsError(f"destination already exists: {target}")
|
||||
if target.is_relative_to(ROOT.parent.parent):
|
||||
raise ValueError("destination must be outside the Forge repository")
|
||||
if not target.parent.is_dir():
|
||||
raise ValueError("destination parent must already exist")
|
||||
target.mkdir()
|
||||
try:
|
||||
shutil.copytree(ROOT / "source", target, symlinks=False, dirs_exist_ok=True)
|
||||
shutil.copytree(ROOT / "boilerplate", target, dirs_exist_ok=True)
|
||||
values = {"__PROJECT_NAME__": name, "__APP_SLUG__": slug,
|
||||
"__DATABASE_NAME__": slug.replace("-", "_")}
|
||||
for relative in TOKEN_FILES:
|
||||
path = target / relative
|
||||
content = path.read_text(encoding="utf-8")
|
||||
for token, value in values.items():
|
||||
content = content.replace(token, value)
|
||||
path.write_text(content, encoding="utf-8")
|
||||
for relative in ("README.md", "docs/PROJECT_OVERVIEW.md", "docs/CURRENT_STATE.md",
|
||||
"docs/DECISIONS.md", "docs/TASKS.md", "docs/HANDOFF.md"):
|
||||
path = target / relative
|
||||
path.write_text(path.read_text(encoding="utf-8").replace("__PROJECT_NAME__", name), encoding="utf-8")
|
||||
if git_init:
|
||||
subprocess.run(["git", "-C", str(target), "init", "--initial-branch=main"], check=True, capture_output=True)
|
||||
except Exception:
|
||||
shutil.rmtree(target, ignore_errors=True)
|
||||
raise
|
||||
return target
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("project_name")
|
||||
parser.add_argument("destination")
|
||||
parser.add_argument("--git-init", action="store_true")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
print(f"Created {generate(args.project_name, args.destination, args.git_init)}")
|
||||
except (OSError, ValueError, subprocess.CalledProcessError) as exc:
|
||||
parser.exit(1, f"ERROR: {exc}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,237 @@
|
||||
name: CI and deployment
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [production]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
backend:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: api
|
||||
env:
|
||||
APP_ENV: testing
|
||||
SQLALCHEMY_DATABASE_URI: sqlite:///:memory:
|
||||
SECRET_KEY: ci-test-key
|
||||
REGISTRATION_MODE: open
|
||||
EMAIL_DELIVERY_ENABLED: "false"
|
||||
RATELIMIT_ENABLED: "false"
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- run: python -m pip install -r config/requirements-dev.txt
|
||||
- run: pytest --cov --cov-report=term-missing
|
||||
|
||||
backend-mysql:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: api
|
||||
services:
|
||||
mysql:
|
||||
image: mysql:8.4
|
||||
env:
|
||||
MYSQL_DATABASE: app_test
|
||||
MYSQL_USER: app_test
|
||||
MYSQL_PASSWORD: test-password
|
||||
MYSQL_ROOT_PASSWORD: root-test-password
|
||||
ports: ["3306:3306"]
|
||||
options: >-
|
||||
--health-cmd="mysqladmin ping -h localhost -uroot -proot-test-password --silent"
|
||||
--health-interval=10s
|
||||
--health-timeout=5s
|
||||
--health-retries=10
|
||||
env:
|
||||
APP_ENV: testing
|
||||
SQLALCHEMY_DATABASE_URI: mysql+pymysql://app_test:test-password@127.0.0.1:3306/app_test
|
||||
SECRET_KEY: ci-test-key
|
||||
REGISTRATION_MODE: open
|
||||
EMAIL_DELIVERY_ENABLED: "false"
|
||||
RATELIMIT_ENABLED: "false"
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- run: python -m pip install -r config/requirements-dev.txt
|
||||
- run: flask --app api.py db upgrade
|
||||
- run: pytest
|
||||
|
||||
frontend:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: react
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: npm
|
||||
cache-dependency-path: react/package-lock.json
|
||||
- run: npm ci
|
||||
- run: npm run lint
|
||||
- run: npm test
|
||||
- run: npm run build
|
||||
- run: npx playwright install --with-deps chromium
|
||||
- run: npm run test:e2e
|
||||
|
||||
publish-images:
|
||||
if: github.ref == 'refs/heads/production' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch')
|
||||
needs: [backend, backend-mysql, frontend]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
outputs:
|
||||
api_image: ${{ steps.images.outputs.api }}
|
||||
nginx_image: ${{ steps.images.outputs.nginx }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: docker/setup-buildx-action@v4
|
||||
- id: images
|
||||
name: Resolve immutable image names
|
||||
shell: bash
|
||||
run: |
|
||||
owner="$(printf '%s' "$GITHUB_REPOSITORY_OWNER" | tr '[:upper:]' '[:lower:]')"
|
||||
repository="${GITHUB_REPOSITORY#*/}"
|
||||
printf 'api=ghcr.io/%s/%s-api:%s\n' "$owner" "$repository" "$GITHUB_SHA" >> "$GITHUB_OUTPUT"
|
||||
printf 'nginx=ghcr.io/%s/%s-nginx:%s\n' "$owner" "$repository" "$GITHUB_SHA" >> "$GITHUB_OUTPUT"
|
||||
- uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: ./api
|
||||
file: ./api/Dockerfile
|
||||
push: true
|
||||
tags: ${{ steps.images.outputs.api }}
|
||||
labels: |
|
||||
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
|
||||
org.opencontainers.image.revision=${{ github.sha }}
|
||||
cache-from: type=gha,scope=api
|
||||
cache-to: type=gha,mode=max,scope=api
|
||||
- uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: ./nginx/Dockerfile
|
||||
push: true
|
||||
tags: ${{ steps.images.outputs.nginx }}
|
||||
labels: |
|
||||
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
|
||||
org.opencontainers.image.revision=${{ github.sha }}
|
||||
cache-from: type=gha,scope=nginx
|
||||
cache-to: type=gha,mode=max,scope=nginx
|
||||
- name: Scan API image
|
||||
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
|
||||
with:
|
||||
image-ref: ${{ steps.images.outputs.api }}
|
||||
format: table
|
||||
exit-code: "1"
|
||||
ignore-unfixed: true
|
||||
severity: CRITICAL,HIGH
|
||||
- name: Scan nginx image
|
||||
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
|
||||
with:
|
||||
image-ref: ${{ steps.images.outputs.nginx }}
|
||||
format: table
|
||||
exit-code: "1"
|
||||
ignore-unfixed: true
|
||||
severity: CRITICAL,HIGH
|
||||
|
||||
deploy-production:
|
||||
if: github.ref == 'refs/heads/production' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch')
|
||||
needs: [publish-images]
|
||||
runs-on: ubuntu-latest
|
||||
environment: production
|
||||
concurrency:
|
||||
group: production
|
||||
cancel-in-progress: false
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- name: Validate deployment configuration
|
||||
env:
|
||||
SSH_HOST: ${{ secrets.PRODUCTION_SSH_HOST }}
|
||||
SSH_USER: ${{ secrets.PRODUCTION_SSH_USER }}
|
||||
SSH_PRIVATE_KEY: ${{ secrets.PRODUCTION_SSH_PRIVATE_KEY }}
|
||||
SSH_KNOWN_HOSTS: ${{ secrets.PRODUCTION_SSH_KNOWN_HOSTS }}
|
||||
DEPLOY_PATH: ${{ vars.PRODUCTION_DEPLOY_PATH }}
|
||||
ENV_PATH: ${{ vars.PRODUCTION_ENV_PATH }}
|
||||
PUBLIC_URL: ${{ vars.PRODUCTION_PUBLIC_URL }}
|
||||
run: |
|
||||
test -n "$SSH_HOST"
|
||||
test -n "$SSH_USER"
|
||||
test -n "$SSH_PRIVATE_KEY"
|
||||
test -n "$SSH_KNOWN_HOSTS"
|
||||
test -n "$DEPLOY_PATH"
|
||||
test -n "$ENV_PATH"
|
||||
test -n "$PUBLIC_URL"
|
||||
- name: Configure SSH
|
||||
env:
|
||||
SSH_PRIVATE_KEY: ${{ secrets.PRODUCTION_SSH_PRIVATE_KEY }}
|
||||
SSH_KNOWN_HOSTS: ${{ secrets.PRODUCTION_SSH_KNOWN_HOSTS }}
|
||||
run: |
|
||||
install -m 700 -d ~/.ssh
|
||||
printf '%s\n' "$SSH_PRIVATE_KEY" > ~/.ssh/production
|
||||
chmod 600 ~/.ssh/production
|
||||
printf '%s\n' "$SSH_KNOWN_HOSTS" > ~/.ssh/known_hosts
|
||||
chmod 600 ~/.ssh/known_hosts
|
||||
- name: Deploy tested commit
|
||||
env:
|
||||
SSH_HOST: ${{ secrets.PRODUCTION_SSH_HOST }}
|
||||
SSH_USER: ${{ secrets.PRODUCTION_SSH_USER }}
|
||||
TARGET_COMMIT: ${{ github.sha }}
|
||||
API_IMAGE: ${{ needs.publish-images.outputs.api_image }}
|
||||
NGINX_IMAGE: ${{ needs.publish-images.outputs.nginx_image }}
|
||||
DEPLOY_PATH: ${{ vars.PRODUCTION_DEPLOY_PATH }}
|
||||
ENV_PATH: ${{ vars.PRODUCTION_ENV_PATH }}
|
||||
PUBLIC_URL: ${{ vars.PRODUCTION_PUBLIC_URL }}
|
||||
run: |
|
||||
ssh -i ~/.ssh/production -o BatchMode=yes -o IdentitiesOnly=yes \
|
||||
"$SSH_USER@$SSH_HOST" bash -se -- \
|
||||
"$TARGET_COMMIT" "$API_IMAGE" "$NGINX_IMAGE" \
|
||||
"$DEPLOY_PATH" "$ENV_PATH" "$PUBLIC_URL" <<'DEPLOY'
|
||||
set -Eeuo pipefail
|
||||
target_commit="$1"
|
||||
api_image="$2"
|
||||
nginx_image="$3"
|
||||
deploy_path="$4"
|
||||
env_path="$5"
|
||||
public_url="${6%/}"
|
||||
|
||||
cd "$deploy_path"
|
||||
test "$(git branch --show-current)" = production
|
||||
test -z "$(git status --porcelain)"
|
||||
test -r "$env_path"
|
||||
git fetch --quiet origin production
|
||||
git cat-file -e "${target_commit}^{commit}"
|
||||
git merge-base --is-ancestor "$target_commit" origin/production
|
||||
git merge --ff-only "$target_commit"
|
||||
test "$(git rev-parse HEAD)" = "$target_commit"
|
||||
|
||||
export APP_ENV_FILE="$env_path"
|
||||
export API_IMAGE="$api_image"
|
||||
export NGINX_IMAGE="$nginx_image"
|
||||
compose=(docker compose --env-file "$env_path")
|
||||
"${compose[@]}" config --quiet
|
||||
"${compose[@]}" pull api nginx
|
||||
"${compose[@]}" up -d mysql
|
||||
"${compose[@]}" run --rm --no-deps api flask --app api.py db upgrade
|
||||
"${compose[@]}" up -d --no-build api nginx
|
||||
"${compose[@]}" ps
|
||||
|
||||
curl --fail --silent --show-error --retry 12 --retry-all-errors \
|
||||
--retry-delay 5 --output /dev/null http://127.0.0.1:8081/
|
||||
curl --fail --silent --show-error --retry 12 --retry-all-errors \
|
||||
--retry-delay 5 --output /dev/null "$public_url/api/health/ready"
|
||||
DEPLOY
|
||||
@@ -0,0 +1,18 @@
|
||||
.git
|
||||
.github
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
AGENTS.md
|
||||
docs
|
||||
api/.venv
|
||||
api/__pycache__
|
||||
api/instance
|
||||
react/node_modules
|
||||
react/dist
|
||||
react/coverage
|
||||
react/docs
|
||||
react/e2e
|
||||
react/playwright-report
|
||||
react/test-results
|
||||
react/**/*.test.*
|
||||
@@ -0,0 +1,35 @@
|
||||
APP_ENV=development
|
||||
APP_URL=http://localhost:5173
|
||||
APP_SLUG=__APP_SLUG__
|
||||
REGISTRATION_MODE=open
|
||||
SECRET_KEY=replace-with-a-long-random-value
|
||||
|
||||
MYSQL_DATABASE=__DATABASE_NAME__
|
||||
MYSQL_USER=__DATABASE_NAME__
|
||||
MYSQL_PASSWORD=replace-with-a-strong-password
|
||||
MYSQL_ROOT_PASSWORD=replace-with-a-different-strong-password
|
||||
SQLALCHEMY_DATABASE_URI=mysql+pymysql://__DATABASE_NAME__:replace-with-a-strong-password@mysql:3306/__DATABASE_NAME__
|
||||
SQLALCHEMY_ECHO=false
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS=false
|
||||
|
||||
SESSION_COOKIE_SECURE=false
|
||||
SESSION_COOKIE_HTTPONLY=true
|
||||
SESSION_COOKIE_SAMESITE=Lax
|
||||
CORS_ORIGINS=http://localhost:5173
|
||||
|
||||
RESEND_API_KEY=
|
||||
EMAIL_FROM=
|
||||
CONTACT_EMAIL=
|
||||
EMAIL_DELIVERY_ENABLED=false
|
||||
RATELIMIT_ENABLED=true
|
||||
LOG_LEVEL=INFO
|
||||
MAX_CONTENT_LENGTH=1048576
|
||||
GUNICORN_WORKERS=2
|
||||
GUNICORN_TIMEOUT=30
|
||||
GUNICORN_GRACEFUL_TIMEOUT=30
|
||||
GUNICORN_KEEPALIVE=5
|
||||
|
||||
# Optional immutable image overrides supplied by separately configured deployment automation.
|
||||
# API_IMAGE=registry.example.invalid/example-api:COMMIT_SHA
|
||||
# NGINX_IMAGE=registry.example.invalid/example-nginx:COMMIT_SHA
|
||||
# APP_ENV_FILE=/opt/example-app/.env
|
||||
@@ -0,0 +1,21 @@
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.pytest_cache/
|
||||
.coverage
|
||||
htmlcov/
|
||||
.venv/
|
||||
venv/
|
||||
|
||||
node_modules/
|
||||
dist/
|
||||
coverage/
|
||||
playwright-report/
|
||||
test-results/
|
||||
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
*.db
|
||||
@@ -0,0 +1,10 @@
|
||||
[run]
|
||||
source = .
|
||||
omit =
|
||||
tests/*
|
||||
migrations/*
|
||||
import.py
|
||||
|
||||
[report]
|
||||
show_missing = true
|
||||
skip_covered = true
|
||||
@@ -0,0 +1,10 @@
|
||||
.env
|
||||
.env.*
|
||||
.venv
|
||||
__pycache__
|
||||
instance
|
||||
migrations/__pycache__
|
||||
tests
|
||||
*.pyc
|
||||
*.sqlite
|
||||
*.db
|
||||
@@ -0,0 +1,3 @@
|
||||
FLASK_APP=api.py
|
||||
FLASK_ENV=development
|
||||
FLASK_DEBUG=1
|
||||
@@ -0,0 +1,15 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
COPY config/requirements.txt ./config/requirements.txt
|
||||
RUN pip install --no-cache-dir -r ./config/requirements.txt \
|
||||
&& groupadd --gid 10001 app \
|
||||
&& useradd --uid 10001 --gid app --create-home --shell /usr/sbin/nologin app
|
||||
COPY . /app
|
||||
|
||||
ENV HOME=/home/app \
|
||||
PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1
|
||||
USER app:app
|
||||
EXPOSE 5000
|
||||
CMD ["gunicorn", "--config", "gunicorn.conf.py", "api:app"]
|
||||
@@ -0,0 +1,5 @@
|
||||
from flask import Flask
|
||||
from settings import app
|
||||
from models import AccountToken, User # noqa: F401
|
||||
|
||||
from routes.routes import *
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Auth."""
|
||||
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth
|
||||
from models import User
|
||||
from errors import error_response
|
||||
|
||||
basic_auth = HTTPBasicAuth()
|
||||
token_auth = HTTPTokenAuth()
|
||||
|
||||
|
||||
@basic_auth.verify_password
|
||||
def verify_password(email, password):
|
||||
"""Verify password."""
|
||||
user = User.query.filter_by(email=email).first()
|
||||
if user and user.check_password(password):
|
||||
return user
|
||||
|
||||
|
||||
@basic_auth.error_handler
|
||||
def basic_auth_error(status):
|
||||
"""Basic auth error."""
|
||||
return error_response(status)
|
||||
|
||||
|
||||
@token_auth.verify_token
|
||||
def verify_token(token):
|
||||
"""Verify token."""
|
||||
return User.check_token(token) if token else None
|
||||
|
||||
|
||||
@token_auth.error_handler
|
||||
def token_auth_error(status):
|
||||
"""Token auth error."""
|
||||
return error_response(status)
|
||||
@@ -0,0 +1,4 @@
|
||||
-r requirements.txt
|
||||
|
||||
pytest==9.1.1
|
||||
pytest-cov==7.1.0
|
||||
@@ -0,0 +1,10 @@
|
||||
Flask==3.1.3
|
||||
Flask-Migrate==4.1.0
|
||||
Flask-SQLAlchemy==3.1.1
|
||||
PyMySQL==1.2.0
|
||||
flask-cors==6.0.5
|
||||
python-dotenv==1.2.3
|
||||
Flask-HTTPAuth==4.8.1
|
||||
Flask-Limiter==4.1.1
|
||||
gunicorn==26.2.0
|
||||
resend==2.42.0
|
||||
@@ -0,0 +1,85 @@
|
||||
from html import escape
|
||||
|
||||
import resend
|
||||
from flask import current_app
|
||||
|
||||
|
||||
class EmailDeliveryError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def send_email(*, to, subject, html, text, reply_to=None):
|
||||
if not current_app.config["EMAIL_DELIVERY_ENABLED"]:
|
||||
return {"id": "email-delivery-disabled"}
|
||||
resend.api_key = current_app.config["RESEND_API_KEY"]
|
||||
payload = {
|
||||
"from": current_app.config["EMAIL_FROM"],
|
||||
"to": [to],
|
||||
"subject": subject,
|
||||
"html": html,
|
||||
"text": text,
|
||||
}
|
||||
if reply_to:
|
||||
payload["reply_to"] = reply_to
|
||||
try:
|
||||
return resend.Emails.send(payload)
|
||||
except Exception as error:
|
||||
raise EmailDeliveryError("Email delivery failed") from error
|
||||
|
||||
|
||||
def action_email(*, to, subject, heading, body, action_label, action_url):
|
||||
safe_heading = escape(heading)
|
||||
safe_body = escape(body)
|
||||
safe_label = escape(action_label)
|
||||
safe_url = escape(action_url, quote=True)
|
||||
html = (
|
||||
'<div style="font-family:Arial,sans-serif;max-width:600px;margin:auto">'
|
||||
f"<h1>{safe_heading}</h1><p>{safe_body}</p>"
|
||||
f'<p><a href="{safe_url}">{safe_label}</a></p>'
|
||||
f"<p>If the button does not work, copy this link:<br>{safe_url}</p></div>"
|
||||
)
|
||||
text = f"{heading}\n\n{body}\n\n{action_label}: {action_url}"
|
||||
return send_email(to=to, subject=subject, html=html, text=text)
|
||||
|
||||
|
||||
def send_verification_email(user, raw_token):
|
||||
url = f"{current_app.config['APP_URL']}/verify-email?token={raw_token}"
|
||||
return action_email(
|
||||
to=user.email,
|
||||
subject="Verify your email",
|
||||
heading="Verify your email",
|
||||
body="Confirm your email address to activate your account.",
|
||||
action_label="Verify email",
|
||||
action_url=url,
|
||||
)
|
||||
|
||||
|
||||
def send_password_reset_email(user, raw_token):
|
||||
url = f"{current_app.config['APP_URL']}/reset-password?token={raw_token}"
|
||||
return action_email(
|
||||
to=user.email,
|
||||
subject="Reset your password",
|
||||
heading="Reset your password",
|
||||
body="Use this secure link to choose a new password. If you did not request this, ignore this email.",
|
||||
action_label="Reset password",
|
||||
action_url=url,
|
||||
)
|
||||
|
||||
|
||||
def send_contact_email(*, name, email, subject, message):
|
||||
safe_name = escape(name)
|
||||
safe_email = escape(email)
|
||||
safe_subject = escape(subject)
|
||||
safe_message = escape(message).replace("\n", "<br>")
|
||||
return send_email(
|
||||
to=current_app.config["CONTACT_EMAIL"],
|
||||
subject=f"Website contact: {subject}",
|
||||
html=(
|
||||
"<h1>Contact form</h1>"
|
||||
f"<p><strong>From:</strong> {safe_name} ({safe_email})</p>"
|
||||
f"<p><strong>Subject:</strong> {safe_subject}</p>"
|
||||
f"<p>{safe_message}</p>"
|
||||
),
|
||||
text=f"From: {name} <{email}>\nSubject: {subject}\n\n{message}",
|
||||
reply_to=email,
|
||||
)
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Response errors."""
|
||||
from flask import jsonify
|
||||
from werkzeug.http import HTTP_STATUS_CODES
|
||||
|
||||
|
||||
def error_response(status_code, message=None):
|
||||
"""Error response."""
|
||||
payload = {"error": HTTP_STATUS_CODES.get(status_code, "Unknown error")}
|
||||
if message:
|
||||
payload["message"] = message
|
||||
response = jsonify(payload)
|
||||
response.status_code = status_code
|
||||
return response
|
||||
|
||||
|
||||
def bad_request(message):
|
||||
"""Bad request."""
|
||||
return error_response(400, message)
|
||||
@@ -0,0 +1,12 @@
|
||||
"""Environment-tunable Gunicorn defaults for the generic container."""
|
||||
|
||||
import os
|
||||
|
||||
bind = "0.0.0.0:5000"
|
||||
workers = int(os.environ.get("GUNICORN_WORKERS", "2"))
|
||||
timeout = int(os.environ.get("GUNICORN_TIMEOUT", "30"))
|
||||
graceful_timeout = int(os.environ.get("GUNICORN_GRACEFUL_TIMEOUT", "30"))
|
||||
keepalive = int(os.environ.get("GUNICORN_KEEPALIVE", "5"))
|
||||
errorlog = "-"
|
||||
accesslog = None # Query strings may contain verification/reset tokens.
|
||||
capture_output = False
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Minimal structured application logging without request payloads."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
class JsonFormatter(logging.Formatter):
|
||||
def format(self, record):
|
||||
payload = {
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"level": record.levelname,
|
||||
"logger": record.name,
|
||||
"message": record.getMessage(),
|
||||
}
|
||||
if record.exc_info:
|
||||
payload["exception"] = self.formatException(record.exc_info)
|
||||
return json.dumps(payload, ensure_ascii=False)
|
||||
|
||||
|
||||
def configure_logging(app):
|
||||
handler = logging.StreamHandler()
|
||||
handler.setFormatter(JsonFormatter())
|
||||
app.logger.handlers.clear()
|
||||
app.logger.addHandler(handler)
|
||||
app.logger.setLevel(app.config["LOG_LEVEL"])
|
||||
app.logger.propagate = False
|
||||
@@ -0,0 +1 @@
|
||||
Single-database configuration for Flask.
|
||||
@@ -0,0 +1,50 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# template used to generate migration files
|
||||
# file_template = %%(rev)s_%%(slug)s
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
|
||||
# Logging configuration
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic,flask_migrate
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[logger_flask_migrate]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = flask_migrate
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
@@ -0,0 +1,113 @@
|
||||
import logging
|
||||
from logging.config import fileConfig
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from alembic import context
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
fileConfig(config.config_file_name)
|
||||
logger = logging.getLogger('alembic.env')
|
||||
|
||||
|
||||
def get_engine():
|
||||
try:
|
||||
# this works with Flask-SQLAlchemy<3 and Alchemical
|
||||
return current_app.extensions['migrate'].db.get_engine()
|
||||
except (TypeError, AttributeError):
|
||||
# this works with Flask-SQLAlchemy>=3
|
||||
return current_app.extensions['migrate'].db.engine
|
||||
|
||||
|
||||
def get_engine_url():
|
||||
try:
|
||||
return get_engine().url.render_as_string(hide_password=False).replace(
|
||||
'%', '%%')
|
||||
except AttributeError:
|
||||
return str(get_engine().url).replace('%', '%%')
|
||||
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
# from myapp import mymodel
|
||||
# target_metadata = mymodel.Base.metadata
|
||||
config.set_main_option('sqlalchemy.url', get_engine_url())
|
||||
target_db = current_app.extensions['migrate'].db
|
||||
|
||||
# other values from the config, defined by the needs of env.py,
|
||||
# can be acquired:
|
||||
# my_important_option = config.get_main_option("my_important_option")
|
||||
# ... etc.
|
||||
|
||||
|
||||
def get_metadata():
|
||||
if hasattr(target_db, 'metadatas'):
|
||||
return target_db.metadatas[None]
|
||||
return target_db.metadata
|
||||
|
||||
|
||||
def run_migrations_offline():
|
||||
"""Run migrations in 'offline' mode.
|
||||
|
||||
This configures the context with just a URL
|
||||
and not an Engine, though an Engine is acceptable
|
||||
here as well. By skipping the Engine creation
|
||||
we don't even need a DBAPI to be available.
|
||||
|
||||
Calls to context.execute() here emit the given string to the
|
||||
script output.
|
||||
|
||||
"""
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url, target_metadata=get_metadata(), literal_binds=True
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online():
|
||||
"""Run migrations in 'online' mode.
|
||||
|
||||
In this scenario we need to create an Engine
|
||||
and associate a connection with the context.
|
||||
|
||||
"""
|
||||
|
||||
# this callback is used to prevent an auto-migration from being generated
|
||||
# when there are no changes to the schema
|
||||
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
|
||||
def process_revision_directives(context, revision, directives):
|
||||
if getattr(config.cmd_opts, 'autogenerate', False):
|
||||
script = directives[0]
|
||||
if script.upgrade_ops.is_empty():
|
||||
directives[:] = []
|
||||
logger.info('No changes in schema detected.')
|
||||
|
||||
conf_args = current_app.extensions['migrate'].configure_args
|
||||
if conf_args.get("process_revision_directives") is None:
|
||||
conf_args["process_revision_directives"] = process_revision_directives
|
||||
|
||||
connectable = get_engine()
|
||||
|
||||
with connectable.connect() as connection:
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=get_metadata(),
|
||||
**conf_args
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,24 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade():
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade():
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,55 @@
|
||||
"""user table
|
||||
|
||||
Revision ID: 0f62f2706427
|
||||
Revises:
|
||||
Create Date: 2023-12-04 12:52:57.863223
|
||||
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0f62f2706427"
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
|
||||
op.create_table(
|
||||
"user",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("email", sa.String(length=80), nullable=True),
|
||||
sa.Column("username", sa.String(length=100), nullable=True),
|
||||
sa.Column("password_hash", sa.String(length=255), nullable=True),
|
||||
sa.Column("token", sa.String(length=32), nullable=True),
|
||||
sa.Column("token_expiration", sa.DateTime(), nullable=True),
|
||||
sa.Column("refresh_token", sa.String(length=32), nullable=True),
|
||||
sa.Column("reset_password_code", sa.String(length=8), nullable=True),
|
||||
sa.Column("reset_password_expiration", sa.DateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("email"),
|
||||
)
|
||||
with op.batch_alter_table("user", schema=None) as batch_op:
|
||||
batch_op.create_index(
|
||||
batch_op.f("ix_user_refresh_token"), ["refresh_token"], unique=True
|
||||
)
|
||||
batch_op.create_index(
|
||||
batch_op.f("ix_user_reset_password_code"),
|
||||
["reset_password_code"],
|
||||
unique=True,
|
||||
)
|
||||
batch_op.create_index(
|
||||
batch_op.f("ix_user_token"), ["token"], unique=True
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table("user", schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f("ix_user_token"))
|
||||
batch_op.drop_index(batch_op.f("ix_user_reset_password_code"))
|
||||
batch_op.drop_index(batch_op.f("ix_user_refresh_token"))
|
||||
op.drop_table("user")
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
"""add account email tokens
|
||||
|
||||
Revision ID: 7a4e1b9c2d3f
|
||||
Revises: 0f62f2706427
|
||||
Create Date: 2026-08-28
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "7a4e1b9c2d3f"
|
||||
down_revision = "0f62f2706427"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
with op.batch_alter_table("user", schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column("email_verified_at", sa.DateTime(), nullable=True)
|
||||
)
|
||||
batch_op.drop_index(batch_op.f("ix_user_reset_password_code"))
|
||||
batch_op.drop_column("reset_password_expiration")
|
||||
batch_op.drop_column("reset_password_code")
|
||||
|
||||
op.create_table(
|
||||
"account_token",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||
sa.Column("purpose", sa.String(length=32), nullable=False),
|
||||
sa.Column("token_hash", sa.String(length=64), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("expires_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("used_at", sa.DateTime(), nullable=True),
|
||||
sa.ForeignKeyConstraint(["user_id"], ["user.id"]),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("token_hash"),
|
||||
)
|
||||
with op.batch_alter_table("account_token", schema=None) as batch_op:
|
||||
batch_op.create_index(
|
||||
batch_op.f("ix_account_token_expires_at"), ["expires_at"]
|
||||
)
|
||||
batch_op.create_index(
|
||||
batch_op.f("ix_account_token_purpose"), ["purpose"]
|
||||
)
|
||||
batch_op.create_index(
|
||||
batch_op.f("ix_account_token_user_id"), ["user_id"]
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table("account_token", schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f("ix_account_token_user_id"))
|
||||
batch_op.drop_index(batch_op.f("ix_account_token_purpose"))
|
||||
batch_op.drop_index(batch_op.f("ix_account_token_expires_at"))
|
||||
op.drop_table("account_token")
|
||||
with op.batch_alter_table("user", schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column("reset_password_code", sa.String(length=8), nullable=True)
|
||||
)
|
||||
batch_op.add_column(
|
||||
sa.Column("reset_password_expiration", sa.DateTime(), nullable=True)
|
||||
)
|
||||
batch_op.create_index(
|
||||
batch_op.f("ix_user_reset_password_code"),
|
||||
["reset_password_code"],
|
||||
unique=True,
|
||||
)
|
||||
batch_op.drop_column("email_verified_at")
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
from .user import User # noqa
|
||||
from .account_token import AccountToken # noqa
|
||||
@@ -0,0 +1,69 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from settings import db
|
||||
|
||||
|
||||
def utcnow():
|
||||
return datetime.utcnow()
|
||||
|
||||
|
||||
class AccountToken(db.Model):
|
||||
__tablename__ = "account_token"
|
||||
|
||||
PURPOSE_EMAIL_VERIFICATION = "email_verification"
|
||||
PURPOSE_PASSWORD_RESET = "password_reset"
|
||||
PURPOSES = {PURPOSE_EMAIL_VERIFICATION, PURPOSE_PASSWORD_RESET}
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
user_id = db.Column(
|
||||
db.Integer, db.ForeignKey("user.id"), nullable=False, index=True
|
||||
)
|
||||
purpose = db.Column(db.String(32), nullable=False, index=True)
|
||||
token_hash = db.Column(db.String(64), nullable=False, unique=True)
|
||||
created_at = db.Column(db.DateTime, nullable=False, default=utcnow)
|
||||
expires_at = db.Column(db.DateTime, nullable=False, index=True)
|
||||
used_at = db.Column(db.DateTime, nullable=True)
|
||||
user = db.relationship("User")
|
||||
|
||||
@staticmethod
|
||||
def hash_token(token, purpose):
|
||||
return hashlib.sha256(f"{purpose}:{token}".encode()).hexdigest()
|
||||
|
||||
@classmethod
|
||||
def issue(cls, user, purpose, lifetime):
|
||||
if purpose not in cls.PURPOSES:
|
||||
raise ValueError("Unsupported account token purpose")
|
||||
cls.query.filter_by(user_id=user.id, purpose=purpose, used_at=None).update(
|
||||
{"used_at": utcnow()}
|
||||
)
|
||||
raw_token = secrets.token_urlsafe(32)
|
||||
token = cls(
|
||||
user_id=user.id,
|
||||
purpose=purpose,
|
||||
token_hash=cls.hash_token(raw_token, purpose),
|
||||
expires_at=utcnow() + lifetime,
|
||||
)
|
||||
db.session.add(token)
|
||||
return token, raw_token
|
||||
|
||||
@classmethod
|
||||
def find_valid(cls, raw_token, purpose):
|
||||
if not isinstance(raw_token, str) or not raw_token or purpose not in cls.PURPOSES:
|
||||
return None
|
||||
candidate = cls.hash_token(raw_token, purpose)
|
||||
token = cls.query.filter_by(token_hash=candidate, purpose=purpose).first()
|
||||
if token is None or not hmac.compare_digest(token.token_hash, candidate):
|
||||
return None
|
||||
return token if token.is_valid else None
|
||||
|
||||
@property
|
||||
def is_valid(self):
|
||||
return self.used_at is None and self.expires_at > utcnow()
|
||||
|
||||
def consume(self):
|
||||
if not self.is_valid:
|
||||
raise ValueError("Token is invalid or expired")
|
||||
self.used_at = utcnow()
|
||||
@@ -0,0 +1,64 @@
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
from settings import db
|
||||
import base64
|
||||
from datetime import datetime, timedelta
|
||||
import os
|
||||
|
||||
|
||||
def normalize_email(email):
|
||||
return email.strip().casefold()
|
||||
|
||||
|
||||
class User(db.Model):
|
||||
__tablename__ = "user"
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
email = db.Column(db.String(80), unique=True)
|
||||
username = db.Column(db.String(100))
|
||||
password_hash = db.Column(db.String(255))
|
||||
token = db.Column(db.String(32), index=True, unique=True)
|
||||
token_expiration = db.Column(db.DateTime)
|
||||
refresh_token = db.Column(db.String(32), index=True, unique=True)
|
||||
email_verified_at = db.Column(db.DateTime, nullable=True)
|
||||
|
||||
def set_password(self, password):
|
||||
self.password_hash = generate_password_hash(password)
|
||||
|
||||
@staticmethod
|
||||
def normalize_email(email):
|
||||
return normalize_email(email)
|
||||
|
||||
def check_password(self, password):
|
||||
return check_password_hash(self.password_hash, password)
|
||||
|
||||
def __repr__(self):
|
||||
return "<User {}, {}>".format(self.id, self.username)
|
||||
|
||||
def to_dict(self):
|
||||
return {"id": self.id, "username": self.username}
|
||||
|
||||
def get_token(self, expires_in=3600):
|
||||
now = datetime.utcnow()
|
||||
if self.token and self.token_expiration > now + timedelta(seconds=60):
|
||||
return self.token
|
||||
self.token = base64.b64encode(os.urandom(24)).decode("utf-8")
|
||||
self.token_expiration = now + timedelta(seconds=expires_in)
|
||||
db.session.add(self)
|
||||
return self.token
|
||||
|
||||
def get_refresh_token(self):
|
||||
if self.refresh_token:
|
||||
return self.refresh_token
|
||||
self.refresh_token = base64.b64encode(os.urandom(24)).decode("utf-8")
|
||||
db.session.add(self)
|
||||
return self.refresh_token
|
||||
|
||||
def revoke_tokens(self):
|
||||
self.token_expiration = datetime.utcnow() - timedelta(seconds=1)
|
||||
self.refresh_token = None
|
||||
|
||||
@staticmethod
|
||||
def check_token(token):
|
||||
user = User.query.filter_by(token=token).first()
|
||||
if user is None or user.token_expiration < datetime.utcnow():
|
||||
return None
|
||||
return user
|
||||
@@ -0,0 +1,3 @@
|
||||
[pytest]
|
||||
testpaths = tests
|
||||
addopts = -q
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Generic contact-form endpoint."""
|
||||
|
||||
from email.utils import parseaddr
|
||||
|
||||
from flask import request
|
||||
|
||||
from email_service import EmailDeliveryError, send_contact_email
|
||||
from errors import error_response
|
||||
from settings import app, limiter
|
||||
|
||||
|
||||
def valid_email(value):
|
||||
return bool(
|
||||
value
|
||||
and "\r" not in value
|
||||
and "\n" not in value
|
||||
and parseaddr(value)[1] == value
|
||||
and "@" in value
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/contact")
|
||||
@limiter.limit("5 per hour")
|
||||
def contact():
|
||||
req = request.get_json(silent=True) or {}
|
||||
|
||||
# Quietly accept bot submissions that fill the hidden honeypot field.
|
||||
if req.get("website"):
|
||||
return {"success": True}
|
||||
|
||||
name = req.get("name", "").strip()
|
||||
email = req.get("email", "").strip()
|
||||
subject = req.get("subject", "").strip()
|
||||
message = req.get("message", "").strip()
|
||||
|
||||
if not (1 <= len(name) <= 100 and valid_email(email)):
|
||||
return error_response(400, "A valid name and email are required")
|
||||
if not (
|
||||
1 <= len(subject) <= 150
|
||||
and "\r" not in subject
|
||||
and "\n" not in subject
|
||||
and 10 <= len(message) <= 5000
|
||||
):
|
||||
return error_response(400, "A valid subject and message are required")
|
||||
|
||||
try:
|
||||
send_contact_email(
|
||||
name=name,
|
||||
email=email,
|
||||
subject=subject,
|
||||
message=message,
|
||||
)
|
||||
except EmailDeliveryError:
|
||||
app.logger.error("Contact email delivery failed")
|
||||
return error_response(503, "Unable to send message right now")
|
||||
return {"success": True}
|
||||
@@ -0,0 +1,34 @@
|
||||
from settings import app
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from settings import db
|
||||
from .token_routes import * # noqa: F401 F403
|
||||
from .user_routes import * # noqa: F401 F403
|
||||
from .contact_routes import * # noqa: F401 F403
|
||||
|
||||
|
||||
@app.route("/api/test")
|
||||
def test_route():
|
||||
"""Test."""
|
||||
return {"success": True}
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
def health():
|
||||
"""Backward-compatible liveness probe."""
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/api/health/live")
|
||||
def health_live():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/api/health/ready")
|
||||
def health_ready():
|
||||
try:
|
||||
db.session.execute(text("SELECT 1"))
|
||||
except SQLAlchemyError:
|
||||
app.logger.error("Database readiness check failed")
|
||||
return {"status": "unavailable"}, 503
|
||||
return {"status": "ready"}
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Token routes."""
|
||||
from flask import jsonify, make_response, request
|
||||
from settings import db, app
|
||||
from auth import token_auth, basic_auth
|
||||
from models.user import User
|
||||
from errors import error_response
|
||||
|
||||
# todo - put in basic_auth
|
||||
basic_auth.scheme = "Custom"
|
||||
basic_auth.realm = "Incorrect Credentials"
|
||||
|
||||
|
||||
@app.route("/api/auth/tokens", methods=["POST"])
|
||||
@basic_auth.login_required
|
||||
def get_token():
|
||||
"""Get token."""
|
||||
token = basic_auth.current_user().get_token()
|
||||
refresh_token = basic_auth.current_user().get_refresh_token()
|
||||
db.session.commit()
|
||||
response = make_response(
|
||||
jsonify(
|
||||
{
|
||||
"token": token,
|
||||
"username": basic_auth.current_user().username,
|
||||
"user_id": basic_auth.current_user().id,
|
||||
}
|
||||
)
|
||||
)
|
||||
response.set_cookie(
|
||||
"refresh_token",
|
||||
value=refresh_token,
|
||||
httponly=app.config["SESSION_COOKIE_HTTPONLY"],
|
||||
secure=app.config["SESSION_COOKIE_SECURE"],
|
||||
samesite=app.config["SESSION_COOKIE_SAMESITE"],
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
@app.route("/api/auth/tokens", methods=["DELETE"])
|
||||
@token_auth.login_required
|
||||
def revoke_token():
|
||||
"""Revoke token."""
|
||||
token_auth.current_user().revoke_tokens()
|
||||
db.session.commit()
|
||||
response = make_response(jsonify({"success": True}))
|
||||
response.delete_cookie(
|
||||
"refresh_token",
|
||||
httponly=app.config["SESSION_COOKIE_HTTPONLY"],
|
||||
secure=app.config["SESSION_COOKIE_SECURE"],
|
||||
samesite=app.config["SESSION_COOKIE_SAMESITE"],
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
@app.route("/api/auth/refresh", methods=["GET"])
|
||||
def refresh_token():
|
||||
"""Refresh token."""
|
||||
refresh_token = request.cookies.get("refresh_token")
|
||||
if refresh_token is None:
|
||||
return error_response(400, "Bad request, no refresh token")
|
||||
user = User.query.filter_by(refresh_token=refresh_token).first()
|
||||
if user is not None:
|
||||
access_token = user.get_token()
|
||||
db.session.commit()
|
||||
return {
|
||||
"token": access_token,
|
||||
"user_id": user.id,
|
||||
}
|
||||
return error_response(401, "Invalid refresh token")
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Generic account routes."""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from flask import request
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from auth import token_auth
|
||||
from email_service import (
|
||||
EmailDeliveryError,
|
||||
send_password_reset_email,
|
||||
send_verification_email,
|
||||
)
|
||||
from errors import error_response
|
||||
from models.account_token import AccountToken
|
||||
from models.user import User, normalize_email
|
||||
from settings import app, db, limiter
|
||||
|
||||
|
||||
@app.get("/api/user/registration-status")
|
||||
def registration_status():
|
||||
return {"mode": app.config["REGISTRATION_MODE"]}
|
||||
|
||||
|
||||
@app.get("/api/user/profile")
|
||||
@token_auth.login_required
|
||||
def get_user_profile():
|
||||
return token_auth.current_user().to_dict()
|
||||
|
||||
|
||||
@app.get("/api/user/current")
|
||||
@token_auth.login_required
|
||||
def get_current_user():
|
||||
return token_auth.current_user().to_dict()
|
||||
|
||||
|
||||
@app.post("/api/user/register")
|
||||
@limiter.limit("5 per hour")
|
||||
def register_user():
|
||||
if app.config["REGISTRATION_MODE"] == "closed":
|
||||
return error_response(403, "Registration is closed")
|
||||
|
||||
req = request.get_json(silent=True) or {}
|
||||
if not all(req.get(field) for field in ("email", "username", "password")):
|
||||
return error_response(400, "Email, username, and password are required")
|
||||
if len(req["password"]) < 8:
|
||||
return error_response(400, "Password must contain at least 8 characters")
|
||||
|
||||
email = normalize_email(req["email"])
|
||||
if User.query.filter(func.lower(User.email) == email).first() is not None:
|
||||
return error_response(409, "Email exists")
|
||||
|
||||
user = User(username=req["username"].strip(), email=email)
|
||||
user.set_password(req["password"])
|
||||
db.session.add(user)
|
||||
try:
|
||||
db.session.flush()
|
||||
_, raw_token = AccountToken.issue(
|
||||
user,
|
||||
AccountToken.PURPOSE_EMAIL_VERIFICATION,
|
||||
timedelta(hours=24),
|
||||
)
|
||||
db.session.commit()
|
||||
except IntegrityError:
|
||||
db.session.rollback()
|
||||
return error_response(409, "Unable to create account")
|
||||
|
||||
try:
|
||||
send_verification_email(user, raw_token)
|
||||
except EmailDeliveryError:
|
||||
app.logger.error("Verification email delivery failed")
|
||||
return {"success": True}, 201
|
||||
|
||||
|
||||
@app.post("/api/user/verify-email")
|
||||
@limiter.limit("20 per hour")
|
||||
def verify_email():
|
||||
req = request.get_json(silent=True) or {}
|
||||
token = AccountToken.find_valid(
|
||||
req.get("token"), AccountToken.PURPOSE_EMAIL_VERIFICATION
|
||||
)
|
||||
if token is None:
|
||||
return error_response(400, "Verification link is invalid or expired")
|
||||
token.user.email_verified_at = datetime.utcnow()
|
||||
token.consume()
|
||||
db.session.commit()
|
||||
return {"success": True}
|
||||
|
||||
|
||||
@app.post("/api/user/resend-verification")
|
||||
@limiter.limit("3 per hour")
|
||||
def resend_verification():
|
||||
req = request.get_json(silent=True) or {}
|
||||
email = normalize_email(req.get("email", ""))
|
||||
user = User.query.filter(func.lower(User.email) == email).first()
|
||||
if user is not None and user.email_verified_at is None:
|
||||
_, raw_token = AccountToken.issue(
|
||||
user,
|
||||
AccountToken.PURPOSE_EMAIL_VERIFICATION,
|
||||
timedelta(hours=24),
|
||||
)
|
||||
db.session.commit()
|
||||
try:
|
||||
send_verification_email(user, raw_token)
|
||||
except EmailDeliveryError:
|
||||
app.logger.error("Verification email delivery failed")
|
||||
return {"success": True}
|
||||
|
||||
|
||||
@app.post("/api/user/reset-password")
|
||||
@limiter.limit("3 per hour")
|
||||
def request_password_reset():
|
||||
req = request.get_json(silent=True) or {}
|
||||
email = normalize_email(req.get("email", ""))
|
||||
user = User.query.filter(func.lower(User.email) == email).first()
|
||||
if user is not None:
|
||||
_, raw_token = AccountToken.issue(
|
||||
user,
|
||||
AccountToken.PURPOSE_PASSWORD_RESET,
|
||||
timedelta(hours=1),
|
||||
)
|
||||
db.session.commit()
|
||||
try:
|
||||
send_password_reset_email(user, raw_token)
|
||||
except EmailDeliveryError:
|
||||
app.logger.error("Password reset email delivery failed")
|
||||
return {"success": True}
|
||||
|
||||
|
||||
@app.post("/api/user/update-password")
|
||||
@limiter.limit("10 per hour")
|
||||
def update_password():
|
||||
req = request.get_json(silent=True) or {}
|
||||
if len(req.get("password", "")) < 8:
|
||||
return error_response(400, "Password must contain at least 8 characters")
|
||||
token = AccountToken.find_valid(
|
||||
req.get("token"), AccountToken.PURPOSE_PASSWORD_RESET
|
||||
)
|
||||
if token is None:
|
||||
return error_response(400, "Reset link is invalid or expired")
|
||||
token.user.set_password(req["password"])
|
||||
token.user.revoke_tokens()
|
||||
token.consume()
|
||||
db.session.commit()
|
||||
return {"success": True}
|
||||
@@ -0,0 +1,116 @@
|
||||
import os
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from flask import Flask
|
||||
from flask_cors import CORS
|
||||
from flask_limiter import Limiter
|
||||
from flask_limiter.util import get_remote_address
|
||||
from flask_migrate import Migrate
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from sqlalchemy import MetaData
|
||||
from werkzeug.middleware.proxy_fix import ProxyFix
|
||||
|
||||
from logging_config import configure_logging
|
||||
|
||||
environment = os.environ.get("APP_ENV", "development").lower()
|
||||
if environment == "development":
|
||||
load_dotenv()
|
||||
environment = os.environ.get("APP_ENV", environment).lower()
|
||||
if environment not in {"development", "testing", "production"}:
|
||||
raise RuntimeError(
|
||||
"APP_ENV must be one of: development, testing, production"
|
||||
)
|
||||
|
||||
|
||||
def env_bool(name, default=False):
|
||||
value = os.environ.get(name)
|
||||
if value is None:
|
||||
return default
|
||||
return value.lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
convention = {
|
||||
"ix": "ix_%(column_0_label)s",
|
||||
"uq": "uq_%(table_name)s_%(column_0_name)s",
|
||||
"ck": "ck_%(table_name)s_%(constraint_name)s",
|
||||
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
|
||||
"pk": "pk_%(table_name)s",
|
||||
}
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config.update(
|
||||
{
|
||||
"APP_ENV": environment,
|
||||
"DEBUG": env_bool("DEBUG", environment == "development"),
|
||||
"TESTING": environment == "testing",
|
||||
"SECRET_KEY": os.environ.get("SECRET_KEY"),
|
||||
"SQLALCHEMY_DATABASE_URI": os.environ.get(
|
||||
"SQLALCHEMY_DATABASE_URI",
|
||||
"sqlite:///:memory:"
|
||||
if environment == "testing"
|
||||
else "sqlite:///mydatabase.sqlite",
|
||||
),
|
||||
"SQLALCHEMY_ECHO": env_bool("SQLALCHEMY_ECHO"),
|
||||
"SQLALCHEMY_TRACK_MODIFICATIONS": env_bool(
|
||||
"SQLALCHEMY_TRACK_MODIFICATIONS"
|
||||
),
|
||||
"APP_URL": os.environ.get("APP_URL", "http://localhost:8080").rstrip("/"),
|
||||
"CORS_ORIGINS": [
|
||||
origin.strip()
|
||||
for origin in os.environ.get("CORS_ORIGINS", "*").split(",")
|
||||
if origin.strip()
|
||||
],
|
||||
"REGISTRATION_MODE": os.environ.get("REGISTRATION_MODE", "open").lower(),
|
||||
"EMAIL_DELIVERY_ENABLED": env_bool(
|
||||
"EMAIL_DELIVERY_ENABLED", environment == "production"
|
||||
),
|
||||
"RESEND_API_KEY": os.environ.get("RESEND_API_KEY"),
|
||||
"EMAIL_FROM": os.environ.get("EMAIL_FROM"),
|
||||
"CONTACT_EMAIL": os.environ.get("CONTACT_EMAIL"),
|
||||
"LOG_LEVEL": os.environ.get("LOG_LEVEL", "INFO").upper(),
|
||||
"MAX_CONTENT_LENGTH": int(os.environ.get("MAX_CONTENT_LENGTH", 1_048_576)),
|
||||
"RATELIMIT_ENABLED": env_bool("RATELIMIT_ENABLED", True),
|
||||
"SESSION_COOKIE_SECURE": env_bool(
|
||||
"SESSION_COOKIE_SECURE", environment == "production"
|
||||
),
|
||||
"SESSION_COOKIE_HTTPONLY": env_bool("SESSION_COOKIE_HTTPONLY", True),
|
||||
"SESSION_COOKIE_SAMESITE": os.environ.get("SESSION_COOKIE_SAMESITE", "Lax"),
|
||||
}
|
||||
)
|
||||
|
||||
if app.config["REGISTRATION_MODE"] not in {"open", "closed"}:
|
||||
raise RuntimeError("REGISTRATION_MODE must be one of: open, closed")
|
||||
if environment == "production":
|
||||
required = ["SECRET_KEY", "SQLALCHEMY_DATABASE_URI", "CORS_ORIGINS"]
|
||||
if app.config["EMAIL_DELIVERY_ENABLED"]:
|
||||
required.extend(
|
||||
["RESEND_API_KEY", "EMAIL_FROM", "CONTACT_EMAIL", "APP_URL"]
|
||||
)
|
||||
missing = [name for name in required if not os.environ.get(name)]
|
||||
if missing:
|
||||
raise RuntimeError(
|
||||
"Missing required production configuration: " + ", ".join(missing)
|
||||
)
|
||||
if len(app.config["SECRET_KEY"]) < 32:
|
||||
raise RuntimeError("SECRET_KEY must contain at least 32 characters in production")
|
||||
if "*" in app.config["CORS_ORIGINS"]:
|
||||
raise RuntimeError("CORS_ORIGINS must not contain '*' in production")
|
||||
if app.config["SESSION_COOKIE_SAMESITE"].lower() == "none" and not app.config[
|
||||
"SESSION_COOKIE_SECURE"
|
||||
]:
|
||||
raise RuntimeError("SESSION_COOKIE_SAMESITE=None requires SESSION_COOKIE_SECURE=true")
|
||||
if app.config["SQLALCHEMY_ECHO"]:
|
||||
raise RuntimeError("SQLALCHEMY_ECHO must be disabled in production")
|
||||
|
||||
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)
|
||||
configure_logging(app)
|
||||
|
||||
metadata = MetaData(naming_convention=convention)
|
||||
db = SQLAlchemy(app, metadata=metadata)
|
||||
migrate = Migrate(app, db, render_as_batch=True)
|
||||
CORS(app, origins=app.config["CORS_ORIGINS"], supports_credentials=True)
|
||||
limiter = Limiter(
|
||||
get_remote_address,
|
||||
app=app,
|
||||
enabled=app.config["RATELIMIT_ENABLED"],
|
||||
storage_uri="memory://",
|
||||
)
|
||||
@@ -0,0 +1,32 @@
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
TEST_DEFAULTS = {
|
||||
"APP_ENV": "testing",
|
||||
"SQLALCHEMY_DATABASE_URI": "sqlite:///:memory:",
|
||||
"SECRET_KEY": "test-key",
|
||||
"REGISTRATION_MODE": "open",
|
||||
"EMAIL_DELIVERY_ENABLED": "false",
|
||||
"RATELIMIT_ENABLED": "true",
|
||||
}
|
||||
for name, value in TEST_DEFAULTS.items():
|
||||
os.environ.setdefault(name, value)
|
||||
|
||||
import pytest
|
||||
|
||||
from api import app
|
||||
from settings import db, limiter
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client():
|
||||
with app.app_context():
|
||||
limiter.reset()
|
||||
db.create_all()
|
||||
yield app.test_client()
|
||||
db.session.remove()
|
||||
db.drop_all()
|
||||
limiter.reset()
|
||||
@@ -0,0 +1,157 @@
|
||||
import base64
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from models.account_token import AccountToken
|
||||
from models.user import User
|
||||
from settings import app, db
|
||||
|
||||
|
||||
def register(client, **overrides):
|
||||
payload = {
|
||||
"email": "person@example.com",
|
||||
"username": "person",
|
||||
"password": "long-enough-password",
|
||||
**overrides,
|
||||
}
|
||||
return client.post("/api/user/register", json=payload)
|
||||
|
||||
|
||||
def basic_header(email="person@example.com", password="long-enough-password"):
|
||||
encoded = base64.b64encode(f"{email}:{password}".encode()).decode()
|
||||
return {"Authorization": f"Basic {encoded}"}
|
||||
|
||||
|
||||
def test_health_and_registration_status(client):
|
||||
assert client.get("/api/health").get_json() == {"status": "ok"}
|
||||
assert client.get("/api/health/live").get_json() == {"status": "ok"}
|
||||
assert client.get("/api/health/ready").get_json() == {"status": "ready"}
|
||||
assert client.get("/api/user/registration-status").get_json() == {
|
||||
"mode": "open"
|
||||
}
|
||||
|
||||
|
||||
def test_readiness_failure_is_generic(client, monkeypatch):
|
||||
from sqlalchemy.exc import OperationalError
|
||||
|
||||
def fail(_statement):
|
||||
raise OperationalError("SELECT 1", {}, RuntimeError("private database detail"))
|
||||
|
||||
monkeypatch.setattr("routes.routes.db.session.execute", fail)
|
||||
response = client.get("/api/health/ready")
|
||||
assert response.status_code == 503
|
||||
assert response.get_json() == {"status": "unavailable"}
|
||||
|
||||
|
||||
def test_registration_normalizes_email_and_hashes_one_time_token(client):
|
||||
response = register(client, email=" PERSON@Example.COM ")
|
||||
assert response.status_code == 201
|
||||
user = User.query.one()
|
||||
token = AccountToken.query.one()
|
||||
assert user.email == "person@example.com"
|
||||
assert user.password_hash != "long-enough-password"
|
||||
assert token.purpose == AccountToken.PURPOSE_EMAIL_VERIFICATION
|
||||
assert len(token.token_hash) == 64
|
||||
|
||||
|
||||
def test_registration_validates_input_and_duplicate_email(client):
|
||||
assert register(client, password="short").status_code == 400
|
||||
assert register(client).status_code == 201
|
||||
assert register(client, email="PERSON@example.com").status_code == 409
|
||||
|
||||
|
||||
def test_closed_registration_rejects_accounts(client):
|
||||
original = app.config["REGISTRATION_MODE"]
|
||||
app.config["REGISTRATION_MODE"] = "closed"
|
||||
try:
|
||||
assert register(client).status_code == 403
|
||||
finally:
|
||||
app.config["REGISTRATION_MODE"] = original
|
||||
|
||||
|
||||
def test_login_refresh_logout_cycle(client):
|
||||
assert register(client).status_code == 201
|
||||
login = client.post("/api/auth/tokens", headers=basic_header())
|
||||
assert login.status_code == 200
|
||||
token = login.get_json()["token"]
|
||||
refreshed = client.get("/api/auth/refresh")
|
||||
assert refreshed.status_code == 200
|
||||
assert refreshed.get_json()["user_id"] == login.get_json()["user_id"]
|
||||
logout = client.delete(
|
||||
"/api/auth/tokens", headers={"Authorization": f"Bearer {token}"}
|
||||
)
|
||||
assert logout.status_code == 200
|
||||
assert client.get("/api/auth/refresh").status_code == 400
|
||||
|
||||
|
||||
def test_password_reset_is_non_enumerating_and_single_use(client):
|
||||
assert register(client).status_code == 201
|
||||
assert client.post(
|
||||
"/api/user/reset-password", json={"email": "missing@example.com"}
|
||||
).status_code == 200
|
||||
assert client.post(
|
||||
"/api/user/reset-password", json={"email": "person@example.com"}
|
||||
).status_code == 200
|
||||
token = AccountToken.query.filter_by(
|
||||
purpose=AccountToken.PURPOSE_PASSWORD_RESET
|
||||
).one()
|
||||
assert token.token_hash
|
||||
assert client.post(
|
||||
"/api/user/update-password",
|
||||
json={"token": "not-the-token", "password": "new-password-value"},
|
||||
).status_code == 400
|
||||
|
||||
|
||||
def test_verification_and_password_reset_tokens_are_consumed(client, monkeypatch):
|
||||
captured = {}
|
||||
|
||||
def capture_verification(user, raw_token):
|
||||
captured["verification"] = raw_token
|
||||
|
||||
def capture_reset(user, raw_token):
|
||||
captured["reset"] = raw_token
|
||||
|
||||
monkeypatch.setattr("routes.user_routes.send_verification_email", capture_verification)
|
||||
monkeypatch.setattr("routes.user_routes.send_password_reset_email", capture_reset)
|
||||
assert register(client).status_code == 201
|
||||
assert client.post(
|
||||
"/api/user/verify-email", json={"token": captured["verification"]}
|
||||
).status_code == 200
|
||||
assert client.post(
|
||||
"/api/user/verify-email", json={"token": captured["verification"]}
|
||||
).status_code == 400
|
||||
|
||||
assert client.post(
|
||||
"/api/user/reset-password", json={"email": "person@example.com"}
|
||||
).status_code == 200
|
||||
assert client.post(
|
||||
"/api/user/update-password",
|
||||
json={"token": captured["reset"], "password": "replacement-password"},
|
||||
).status_code == 200
|
||||
assert client.post(
|
||||
"/api/user/update-password",
|
||||
json={"token": captured["reset"], "password": "another-password"},
|
||||
).status_code == 400
|
||||
assert client.post(
|
||||
"/api/auth/tokens",
|
||||
headers=basic_header(password="replacement-password"),
|
||||
).status_code == 200
|
||||
|
||||
|
||||
def test_expired_account_tokens_are_rejected(client, monkeypatch):
|
||||
captured = {}
|
||||
monkeypatch.setattr(
|
||||
"routes.user_routes.send_verification_email",
|
||||
lambda _user, raw_token: captured.update(verification=raw_token),
|
||||
)
|
||||
assert register(client).status_code == 201
|
||||
token = AccountToken.query.filter_by(
|
||||
purpose=AccountToken.PURPOSE_EMAIL_VERIFICATION
|
||||
).one()
|
||||
token.expires_at = datetime.utcnow() - timedelta(seconds=1)
|
||||
db.session.commit()
|
||||
|
||||
response = client.post(
|
||||
"/api/user/verify-email", json={"token": captured["verification"]}
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()["message"] == "Verification link is invalid or expired"
|
||||
@@ -0,0 +1,67 @@
|
||||
from email_service import EmailDeliveryError
|
||||
|
||||
|
||||
VALID_MESSAGE = {
|
||||
"name": "Example Person",
|
||||
"email": "person@example.com",
|
||||
"subject": "A useful question",
|
||||
"message": "This message is long enough to be accepted.",
|
||||
"website": "",
|
||||
}
|
||||
|
||||
|
||||
def test_contact_delivers_valid_message(client, monkeypatch):
|
||||
delivered = {}
|
||||
|
||||
def capture(**payload):
|
||||
delivered.update(payload)
|
||||
|
||||
monkeypatch.setattr("routes.contact_routes.send_contact_email", capture)
|
||||
response = client.post("/api/contact", json=VALID_MESSAGE)
|
||||
assert response.status_code == 200
|
||||
assert delivered == {
|
||||
key: VALID_MESSAGE[key] for key in ("name", "email", "subject", "message")
|
||||
}
|
||||
|
||||
|
||||
def test_contact_rejects_invalid_and_injection_input(client):
|
||||
assert client.post("/api/contact", json={}).status_code == 400
|
||||
assert client.post(
|
||||
"/api/contact",
|
||||
json={**VALID_MESSAGE, "email": "person@example.com\nBcc:test@example.com"},
|
||||
).status_code == 400
|
||||
assert client.post(
|
||||
"/api/contact",
|
||||
json={**VALID_MESSAGE, "subject": "Hello\r\nBcc: test@example.com"},
|
||||
).status_code == 400
|
||||
assert client.post(
|
||||
"/api/contact", json={**VALID_MESSAGE, "message": "short"}
|
||||
).status_code == 400
|
||||
|
||||
|
||||
def test_contact_honeypot_does_not_deliver(client, monkeypatch):
|
||||
def unexpected(**_payload):
|
||||
raise AssertionError("honeypot submission must not be delivered")
|
||||
|
||||
monkeypatch.setattr("routes.contact_routes.send_contact_email", unexpected)
|
||||
response = client.post(
|
||||
"/api/contact", json={**VALID_MESSAGE, "website": "https://bot.invalid"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
def test_contact_delivery_failure_is_generic(client, monkeypatch):
|
||||
def fail(**_payload):
|
||||
raise EmailDeliveryError("provider detail must not escape")
|
||||
|
||||
monkeypatch.setattr("routes.contact_routes.send_contact_email", fail)
|
||||
response = client.post("/api/contact", json=VALID_MESSAGE)
|
||||
assert response.status_code == 503
|
||||
assert response.get_json()["message"] == "Unable to send message right now"
|
||||
|
||||
|
||||
def test_contact_rate_limit_rejects_sixth_submission(client, monkeypatch):
|
||||
monkeypatch.setattr("routes.contact_routes.send_contact_email", lambda **_: None)
|
||||
responses = [client.post("/api/contact", json=VALID_MESSAGE) for _ in range(6)]
|
||||
assert [response.status_code for response in responses[:5]] == [200] * 5
|
||||
assert responses[5].status_code == 429
|
||||
@@ -0,0 +1,80 @@
|
||||
services:
|
||||
mysql:
|
||||
image: mysql:8.4
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
MYSQL_DATABASE: ${MYSQL_DATABASE:?MYSQL_DATABASE must be set}
|
||||
MYSQL_USER: ${MYSQL_USER:?MYSQL_USER must be set}
|
||||
MYSQL_PASSWORD: ${MYSQL_PASSWORD:?MYSQL_PASSWORD must be set}
|
||||
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:?MYSQL_ROOT_PASSWORD must be set}
|
||||
volumes:
|
||||
- db:/var/lib/mysql
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "mysqladmin ping -h localhost -uroot -p$$MYSQL_ROOT_PASSWORD --silent"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
start_period: 30s
|
||||
networks:
|
||||
- internal
|
||||
|
||||
api:
|
||||
image: ${API_IMAGE:-__APP_SLUG__-api:local}
|
||||
build:
|
||||
context: ./api
|
||||
restart: unless-stopped
|
||||
init: true
|
||||
stop_grace_period: 30s
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:size=64m,mode=1777
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
env_file:
|
||||
- ${APP_ENV_FILE:-.env.example}
|
||||
depends_on:
|
||||
mysql:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:5000/api/health/ready')"]
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 20s
|
||||
ports:
|
||||
- "127.0.0.1:5001:5000"
|
||||
networks:
|
||||
- internal
|
||||
|
||||
nginx:
|
||||
image: ${NGINX_IMAGE:-__APP_SLUG__-nginx:local}
|
||||
build:
|
||||
context: .
|
||||
dockerfile: nginx/Dockerfile
|
||||
restart: unless-stopped
|
||||
init: true
|
||||
stop_grace_period: 15s
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://127.0.0.1/"]
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 10s
|
||||
ports:
|
||||
- "127.0.0.1:8081:80"
|
||||
networks:
|
||||
- internal
|
||||
|
||||
networks:
|
||||
internal:
|
||||
internal: true
|
||||
|
||||
volumes:
|
||||
db:
|
||||
@@ -0,0 +1,12 @@
|
||||
FROM node:22-alpine AS frontend-build
|
||||
|
||||
WORKDIR /app
|
||||
COPY react/package.json react/package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY react/ ./
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:1.27-alpine
|
||||
COPY nginx/nginx.conf /etc/nginx/nginx.conf
|
||||
COPY --from=frontend-build /app/dist /usr/share/nginx/html
|
||||
EXPOSE 80
|
||||
@@ -0,0 +1,47 @@
|
||||
events {}
|
||||
|
||||
http {
|
||||
include /etc/nginx/mime.types;
|
||||
|
||||
map $http_x_forwarded_proto $upstream_forwarded_proto {
|
||||
default $http_x_forwarded_proto;
|
||||
"" $scheme;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://api:5000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $upstream_forwarded_proto;
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_connect_timeout 5s;
|
||||
proxy_read_timeout 30s;
|
||||
}
|
||||
|
||||
location = /index.html {
|
||||
add_header Cache-Control "no-cache";
|
||||
expires 0;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
location /assets/ {
|
||||
try_files $uri =404;
|
||||
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
# SWAG reverse-proxy integration
|
||||
|
||||
The default Compose stack does not require SWAG. If the project chooses this
|
||||
hosting pattern, combine `docker-compose.yml` with `ops/swag/docker-compose.swag.yml`
|
||||
after configuring the external network named by `SWAG_NETWORK` (default: `swagnet`). SWAG terminates TLS
|
||||
and proxies the public hostname to `nginx:80`; the application nginx container
|
||||
serves the React build and forwards `/api/` to the private API service.
|
||||
|
||||
Copy `app.subdomain.conf.sample` into the SWAG `nginx/proxy-confs/` directory,
|
||||
replace the placeholder domain settings using normal SWAG conventions, and
|
||||
restart or reload SWAG. The exact SWAG filesystem location is a server concern
|
||||
and is intentionally not encoded in this repository.
|
||||
|
||||
Do not expose MySQL publicly. The loopback API and frontend port mappings exist
|
||||
for server-local health diagnostics; SWAG should reach the frontend by Docker
|
||||
service name over the external network.
|
||||
@@ -0,0 +1,15 @@
|
||||
server {
|
||||
listen 443 ssl;
|
||||
listen [::]:443 ssl;
|
||||
|
||||
server_name app.*;
|
||||
include /config/nginx/ssl.conf;
|
||||
|
||||
location / {
|
||||
include /config/nginx/proxy.conf;
|
||||
include /config/nginx/resolver.conf;
|
||||
set $upstream_app nginx;
|
||||
set $upstream_port 80;
|
||||
proxy_pass http://$upstream_app:$upstream_port;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
# Optional overlay. Use only after configuring an external SWAG network.
|
||||
services:
|
||||
nginx:
|
||||
networks:
|
||||
- internal
|
||||
- swag
|
||||
|
||||
networks:
|
||||
swag:
|
||||
external: true
|
||||
name: ${SWAG_NETWORK:-swagnet}
|
||||
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,66 @@
|
||||
import AxeBuilder from '@axe-core/playwright'
|
||||
import { expect, test } from '@playwright/test'
|
||||
|
||||
const publicPages = [
|
||||
['/', 'Build your application from here'],
|
||||
['/contact', 'Contact'],
|
||||
['/privacy', 'Privacy policy'],
|
||||
['/terms', 'Terms of service'],
|
||||
['/login', 'Login'],
|
||||
['/register', 'Register'],
|
||||
['/forgot-password', 'Reset password'],
|
||||
]
|
||||
|
||||
for (const [path, heading] of publicPages) {
|
||||
test(`${path} renders without horizontal overflow`, async ({ page }) => {
|
||||
await page.goto(path)
|
||||
await expect(page.getByRole('heading', { name: heading, exact: true })).toBeVisible()
|
||||
const dimensions = await page.locator('html').evaluate((element) => ({
|
||||
viewport: element.clientWidth,
|
||||
content: element.scrollWidth,
|
||||
}))
|
||||
expect(dimensions.content).toBeLessThanOrEqual(dimensions.viewport)
|
||||
})
|
||||
}
|
||||
|
||||
test('public shell passes automated accessibility diagnostics', async ({ page }) => {
|
||||
await page.goto('/contact')
|
||||
const results = await new AxeBuilder({ page }).analyze()
|
||||
expect(results.violations).toEqual([])
|
||||
})
|
||||
|
||||
test('skip link is the first keyboard navigation target', async ({ page }) => {
|
||||
await page.goto('/')
|
||||
await page.keyboard.press('Tab')
|
||||
const skipLink = page.getByRole('link', { name: 'Skip to main content' })
|
||||
await expect(skipLink).toBeFocused()
|
||||
await expect(skipLink).toHaveAttribute('href', '#main-content')
|
||||
})
|
||||
|
||||
test('mobile navigation expands and exposes public destinations', async ({ page, isMobile }) => {
|
||||
test.skip(!isMobile, 'mobile navigation diagnostic')
|
||||
await page.goto('/')
|
||||
await page.getByRole('button', { name: 'Toggle navigation' }).click()
|
||||
await expect(page.getByRole('link', { name: 'Contact', exact: true }).first()).toBeVisible()
|
||||
await expect(page.getByRole('link', { name: 'Login', exact: true })).toBeVisible()
|
||||
})
|
||||
|
||||
test('contact form reports mocked delivery success', async ({ page }) => {
|
||||
await page.route('**/api/contact', async (route) => {
|
||||
await route.fulfill({ status: 200, contentType: 'application/json', body: '{"success":true}' })
|
||||
})
|
||||
await page.goto('/contact')
|
||||
await page.getByLabel('Name').fill('Example Person')
|
||||
await page.getByLabel('Email').fill('person@example.com')
|
||||
await page.getByLabel('Subject').fill('A useful question')
|
||||
await page.getByLabel('Message').fill('This message is long enough to be accepted.')
|
||||
await page.getByRole('button', { name: 'Send message' }).click()
|
||||
await expect(page.getByRole('status')).toContainText('message has been sent')
|
||||
})
|
||||
|
||||
test('protected dashboard with no session does not expose its content', async ({ page }) => {
|
||||
await page.goto('/dashboard')
|
||||
await expect(page.getByRole('heading', { name: 'Unauthorized' })).toBeVisible()
|
||||
await expect(page.getByText('Protected application workspace')).toHaveCount(0)
|
||||
await expect(page.locator('meta[name="robots"]')).toHaveAttribute('content', 'noindex, nofollow')
|
||||
})
|
||||
@@ -0,0 +1,42 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
|
||||
export default [
|
||||
{ ignores: ['dist', 'playwright-report', 'test-results'] },
|
||||
{
|
||||
files: ['e2e/**/*.{js,jsx}', 'playwright.config.js'],
|
||||
languageOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
globals: globals.node,
|
||||
parserOptions: { sourceType: 'module' },
|
||||
},
|
||||
rules: js.configs.recommended.rules,
|
||||
},
|
||||
{
|
||||
files: ['src/**/*.{js,jsx}'],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
parserOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
ecmaFeatures: { jsx: true },
|
||||
sourceType: 'module',
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
'react-hooks': reactHooks,
|
||||
'react-refresh': reactRefresh,
|
||||
},
|
||||
rules: {
|
||||
...js.configs.recommended.rules,
|
||||
...reactHooks.configs.recommended.rules,
|
||||
'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }],
|
||||
'react-refresh/only-export-components': [
|
||||
'warn',
|
||||
{ allowConstantExport: true },
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
@@ -0,0 +1,15 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="description" content="A reusable Flask and React web application foundation." />
|
||||
<meta name="robots" content="index, follow" />
|
||||
<meta name="theme-color" content="#343a40" />
|
||||
<title>__PROJECT_NAME__</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
+5725
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"name": "react",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"lint": "eslint .",
|
||||
"test": "vitest run",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"test:e2e": "playwright test",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"base-64": "^1.0.0",
|
||||
"bootstrap": "^5.3.5",
|
||||
"prop-types": "^15.8.1",
|
||||
"react": "^19.0.0",
|
||||
"react-bootstrap": "^2.10.9",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-icons": "^5.5.0",
|
||||
"react-router": "^7.5.3",
|
||||
"react-router-dom": "^7.5.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@axe-core/playwright": "^4.13.0",
|
||||
"@eslint/js": "^9.22.0",
|
||||
"@playwright/test": "^1.62.1",
|
||||
"@testing-library/jest-dom": "^6.6.3",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/react": "^19.0.10",
|
||||
"@types/react-dom": "^19.0.4",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"@vitest/coverage-v8": "^3.2.4",
|
||||
"eslint": "^9.22.0",
|
||||
"eslint-plugin-react-hooks": "^5.2.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.19",
|
||||
"globals": "^16.0.0",
|
||||
"jsdom": "^26.1.0",
|
||||
"sass": "^1.87.0",
|
||||
"vite": "^6.3.1",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { defineConfig, devices } from '@playwright/test'
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
fullyParallel: true,
|
||||
forbidOnly: Boolean(process.env.CI),
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
reporter: process.env.CI ? 'github' : 'list',
|
||||
use: {
|
||||
baseURL: 'http://127.0.0.1:4173',
|
||||
trace: 'retain-on-failure',
|
||||
},
|
||||
projects: [
|
||||
{ name: 'desktop-chromium', use: { ...devices['Desktop Chrome'] } },
|
||||
{ name: 'mobile-chromium', use: { ...devices['Pixel 5'] } },
|
||||
],
|
||||
webServer: {
|
||||
command: 'npm run dev -- --host 127.0.0.1 --port 4173',
|
||||
url: 'http://127.0.0.1:4173',
|
||||
reuseExistingServer: !process.env.CI,
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,5 @@
|
||||
User-agent: *
|
||||
Allow: /
|
||||
|
||||
# Add a production sitemap URL after the generated application's canonical
|
||||
# public origin and public-route policy have been confirmed.
|
||||
@@ -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="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -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;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user