Compare commits
3 commits
b49497cc59
...
a6c66d4607
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a6c66d4607 | ||
|
|
e4c7e165d1 | ||
|
|
0cc2a3f721 |
67 changed files with 3773 additions and 353 deletions
|
|
@ -40,6 +40,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
|
|||
- Speed: nginx must gzip JS/CSS/JSON/SVG and speak HTTP/2; page HTML is `no-cache`; uploads get a `-640.webp` small copy made at upload and at boot: `docs/performance.md`.
|
||||
- Security headers: the API sends them (Hono `secureHeaders()`, plus a CSRF check on `/api` writes); nginx sends HSTS on everything and must pass `Host` and `X-Forwarded-For` to the API: `docs/security-headers.md`.
|
||||
- Request form (`/request`): files go to the "Requests" folder of a Google shared drive and new-request emails go out through Gmail, both via a service account (`server/src/googleService.js`). `driveUpload(folder, ...)` finds or makes the named folder in the shared drive, so other uses get their own folder. Tools → Media → Files uploads to "Media" and shares each file as anyone-with-the-link (`server/src/routes/files.js`, migration 048); link fields with `files: true` pick from it ("Choose a file"), and link cards take its first-page preview. Needs a `/api/admin/files` nginx block (51m). Off until `GOOGLE_SERVICE_ACCOUNT` plus `GOOGLE_SHARED_DRIVE` (the bare id, not a URL) / `GOOGLE_MAIL_FROM` are set. Needs its own nginx block. Setup: `docs/google-drive-and-mail.md`.
|
||||
- Profile accounts (migration 076): admins invite an email (Data → Profile accounts), the person sets a password from the link or signs in with any Google account under that email, claims their People record (an admin approves), then edits it and hides parts at `/account`. Public reads of people go through the `v_people_public` view, never `people`. Discord linking is off until `DISCORD_CLIENT_ID` and `DISCORD_CLIENT_SECRET` are set: `docs/profile-accounts.md`.
|
||||
- Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Accounts made by admin-cli get in; with access groups set (Site settings → Access, plus `GOOGLE_DIRECTORY_AS`), anyone in one gets a Google-only account whose role follows the group, rechecked at sign-in, hourly and by Panel → Re-sync now (`server/src/accessGroups.js`); superadmins and admin-cli accounts are never changed by groups. Passwords still work. Setup: `docs/google-sign-in.md`.
|
||||
|
||||
## Git workflow
|
||||
|
|
@ -61,13 +62,13 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
|
|||
- All pages use `PageShell.tsx` as the wrapper unless explicitly noted otherwise.
|
||||
- Pages live in `src/pages/`; section-level components go in `src/pages/sections/`.
|
||||
- `src/data/` holds only hardcoded data shared across multiple section files (e.g. `historyDecades.ts`, map grid). Everything else comes from SQLite, through hooks in `src/lib/`.
|
||||
- `navConfig.ts` is the single source of truth for navigation, routes, and actions (header, footer, pages).
|
||||
- Navigation (header and footer links, page titles and intros, hidden pages) is edited in Pages → Navigation (`site_nav*` tables, `server/src/siteNav.js`, read through `src/lib/useSiteNav.ts`). `navConfig.ts` only holds the defaults the app starts from before that loads. Routes are in `App.tsx`; a static page's default title and intro in `site.json`'s `pages`. A hidden page answers Not found below viewer (server and app both).
|
||||
- `api.ts` is the shared caching client used by frontend data hooks.
|
||||
- `docs/updating-data-in-code.md`: where content that isn't in the database lives (admin dropdown labels, fixed value lists, nav, banner, decades, map grid) and how to change it. Keep it current when adding a dropdown or code-owned content.
|
||||
- Images: every record image (logos, photos, backgrounds, block images) is an upload, in a folder by use: `/uploads/logos/`, `/uploads/images/`, `/uploads/thumbnails/` (saved previews), `/uploads/captions/` (videos' .vtt files); a logo or icon image field sets `folder: "logos"` (`docs/media-uploads.md`, Folders). A bare filename resolves to `/uploads/<file>` (`src/lib/media.ts`, and `server/src/pageMeta.js` for previews). Only the site's own chosen assets, the NGU logos in the nav, footer and admin, are bundled from `src/assets/logos/`. Logo images hide themselves on load error (`onError`).
|
||||
|
||||
## Rules and gotchas
|
||||
- **Role checks must use ladder comparisons, never equality.** Roles rank viewer → editor → admin → superadmin. Use the minimum-rank helpers from `src/lib/roles.ts` (`canWrite`, `canDelete`, `isSuper`, `atLeast`). Where a local variable shadows the name, import with an alias, e.g. `canWrite as roleCanWrite`. `role === "admin"` silently excludes higher roles and has caused repeated bugs.
|
||||
- **Role checks must use ladder comparisons, never equality.** Roles rank member → viewer → editor → admin → superadmin (member is a profile account: the site and its own profile, never the admin; `/api/admin` needs viewer, `requireStaff`). Use the minimum-rank helpers from `src/lib/roles.ts` (`canWrite`, `canDelete`, `isSuper`, `isStaff`, `atLeast`). Where a local variable shadows the name, import with an alias, e.g. `canWrite as roleCanWrite`. `role === "admin"` silently excludes higher roles and has caused repeated bugs.
|
||||
- **Imports need explicit extensions** (`.ts`, `.tsx`, `.js`) everywhere.
|
||||
- **Vite resolves `.js` before `.ts`**, so a `.js` and `.ts` file with the same base name will import the wrong one. Give new hooks distinct names.
|
||||
- **Don't use `fallback: EMPTY` in api.ts hooks.** It silently returns empty arrays and hides server errors; let the error state surface.
|
||||
|
|
@ -87,6 +88,7 @@ Descriptor-driven: `server/src/admin-crud.js` and `server/src/admin-schema/` (se
|
|||
- The `OMIT` sentinel distinguishes unsent fields from deliberate clears.
|
||||
- `admin-schema-sync.js` runs at boot and throws if descriptors don't match live `PRAGMA table_info`. If boot fails after a schema change, update the descriptor or migration so they agree.
|
||||
- `admin-cli.js` imports `ROLES` and `destroyAllSessionsFor` from `auth.js`. Keep it that way to prevent drift.
|
||||
- Drafts (migration 077, `server/src/drafts.js`, `docs/drafts.md`): any existing record can be saved as a draft (one per record), previewed on the real page and published (the ordinary PATCH, which drops the draft). Checking and previewing apply the draft in a transaction that is rolled back; `tx()` nests as a savepoint for that, so never call `BEGIN` by hand. A new entity with a public page adds its path to `PREVIEW_PATHS` in `src/lib/adminSchema.ts`.
|
||||
|
||||
## Migrations
|
||||
- `server/src/migrations/066_schema.sql` is the baseline: the whole schema, consolidated on 2026-10-04 from the old 023–066 (generated from the live schema, so the comments are the ones inside each table). `066_seed.sql` runs right after it with the least a new database needs (single rows, event scopes, the site pages' sections, the Musicians tag); content is typed in through the admin. Both only run on an empty database; the runner refuses a database between v1 and v65 (bring it to v66 with a release from before the consolidation first). It's the place to read the schema, not to change it: a database that already exists never re-runs it.
|
||||
|
|
|
|||
82
TODO.md
82
TODO.md
|
|
@ -13,8 +13,7 @@
|
|||
- [ ] Are these three tabs, three sections (each in the side nav), or a filter over one list? Answer:
|
||||
- [ ] Does each resource belong to exactly one audience, or can it be in several (eg. a tag per audience)? Answer:
|
||||
- [ ] What happens to the page's current sections: move under an audience, or replaced? Answer:
|
||||
- [ ] **Library (New Thought Nexus)**: a library for NGUers.
|
||||
- [ ] Which name: Library, New Thought Nexus, or both (Nexus as the page, Library as a section)? Answer:
|
||||
- [ ] **Library**: a library for NGUers.
|
||||
- [ ] What goes in it: links out, uploaded files (Drive "Media"), books, videos, our own articles? Answer:
|
||||
- [ ] Public, or only for NGUers? If only NGUers, how do they sign in (there are only admin accounts today)? Answer:
|
||||
- [ ] Is the metaphysics dictionary / Metaphysical Bible Dictionary part of it (see Future: Poetry Builder needs the same import)? Answer:
|
||||
|
|
@ -53,27 +52,24 @@
|
|||
- [ ] Is this a section to build (eg. on Organization or Partners), or a question to answer in a blog post? Answer:
|
||||
|
||||
## Page Features
|
||||
- [ ] **Full profiles**: people get full profile pages.
|
||||
- [ ] **Full profiles**: people get full profile pages. Profile accounts, claiming and visibility are done (Part 2, Accounts); what's left is the page itself.
|
||||
- [ ] What is missing from a person's page today that makes it "full": bio, more photos, links, events they spoke at, groups, blog posts they wrote? Answer:
|
||||
- [ ] Do people edit their own profile (they'd need accounts), or do admins edit them? Answer:
|
||||
- [ ] Every person, or only those with a profile switched on (privacy)? Answer:
|
||||
- [ ] Ties to Planning Center sync (Data) and the gamification below? Answer:
|
||||
- [ ] **Page preview images per page**: the event's banner on event pages, the person's photo on theirs, the org's logo on org pages.
|
||||
- Already done in `server/src/pageMeta.js`: events use the event photo, then the event logo, then its org's logo; people their photo; orgs, teams and awards their logo; blog posts their cover. SVG logos are skipped (social sites don't show them).
|
||||
- [ ] Which page showed the wrong picture, and where (Discord, iMessage, Facebook)? Answer:
|
||||
- [ ] Is it production (not deployed yet?) or the SVG skip? Should an SVG logo get a PNG copy made at upload for previews? Answer:
|
||||
- [ ] Should event pages prefer the card background ("banner") over the event photo? Answer:
|
||||
- [ ] **Blog page tabs**: a blog index with tabs (there is no /blog index page today, only /blog/<id>).
|
||||
- [ ] Tabs by tag, by author, or fixed kinds (eg. News, Stories, Guides, Website updates)? Answer:
|
||||
- [ ] A new /blog page in the nav, or tabs on the Community blog section? Answer:
|
||||
- [ ] **Gamification synced to Discord**: points, badges or levels on the site, synced to Discord.
|
||||
- [ ] What earns points: going to events, writing for the blog, volunteering, Discord activity? Answer:
|
||||
- [ ] Where are they shown: on full profiles, a leaderboard, only in Discord? Answer:
|
||||
- [ ] Which way does it sync: site → Discord roles, Discord → site, or both? Is there a Discord bot already (or only the reports webhook)? Answer:
|
||||
- [ ] How do we match a person to their Discord account (they link it themselves)? Answer:
|
||||
- [ ] **Blog page tabs**: tabs within a blog post, at the top.
|
||||
- [ ] each tab would switch the active display of content and table of contents, there could be some title/intro content above the tabs.
|
||||
- [ ] **Gamification synced to Discord**: points, badges or levels on the site, synced to Discord. Linking a profile to Discord is done (Part 2, Accounts); the bot, points and badges are next.
|
||||
- [ ] What earns points: going to events, writing for the blog, volunteering, Discord activity? Answer: all of the above, we could create badges on profiles.
|
||||
- [ ] Where are they shown: on full profiles, a leaderboard, only in Discord? Answer: shown on profiles when logged in, no leaderboard for now, and when using a command in discord. this content would not show on the public bio section of a user when viewing from a people tile.
|
||||
- [ ] Which way does it sync: site → Discord roles, Discord → site, or both? Is there a Discord bot already (or only the reports webhook)? Answer: would like a bot built, for if things in discord update or affect gamification shown on the website. most things will be assigned to users by moderators.
|
||||
- [ ] How do we match a person to their Discord account (they link it themselves)? Answer: they can link it, admins can overwrite and update/set
|
||||
- [ ] **Site version names**: each update gets a name, "The ___ Update", Minecraft style.
|
||||
- [ ] Shown where: the footer next to the version, the changelog, both? Answer:
|
||||
- [ ] Does the tag suffix become the name (v1.13.2-region-cards → "The Region Cards Update"), or a name of its own? Answer:
|
||||
- [ ] Shown where: the footer next to the version, the changelog, both? Answer: both
|
||||
- [ ] Does the tag suffix become the name (v1.13.2-region-cards → "The Region Cards Update"), or a name of its own? Answer: yeah the tag.
|
||||
|
||||
## Accessibility Features
|
||||
- [ ] Check the mobile fixes on a real phone (or the browser's phone view at 320, 375 and 430px), light and dark: every page, the menu, the hero, the retreat carousel, people tiles and their details, the community map, schedule blocks, the banner.
|
||||
|
|
@ -84,48 +80,31 @@
|
|||
|
||||
## Mobile
|
||||
- [ ] **Featured event label on the front page**: where it sits doesn't make sense, at least on mobile.
|
||||
- [ ] Where should it go: above the card, on the card's photo, or dropped on mobile? Answer:
|
||||
- [ ] Same change on desktop? [ ] yes
|
||||
- [ ] Where should it go: above the card, on the card's photo, or dropped on mobile? Answer: droppd on mobile
|
||||
- [ ] Same change on desktop? move above the section on the right displaying the featured event.
|
||||
|
||||
## Page Editing
|
||||
- [ ] **Draft edits of sections and pages**: change a page or section without publishing it straight away.
|
||||
- [ ] Which editors: Pages (Front page, Retreats, Community...) only, or every record (events, people...) too? Answer:
|
||||
- [ ] Preview the draft on the real page before publishing? [ ] yes
|
||||
- [ ] Can editors save drafts and only admins publish (an approval step), or does anyone who can edit publish? Answer:
|
||||
- [ ] One draft per page at a time, or several? Answer:
|
||||
|
||||
## Admin
|
||||
|
||||
## Data
|
||||
- [ ] **Planning Center sync to People**: Planning Center People into the site's people records.
|
||||
- [ ] One way (Planning Center → site), or both? Answer:
|
||||
- [ ] Who gets synced: everyone, or a Planning Center list or tag (eg. "Website")? Most people in Planning Center shouldn't have a public page. Answer:
|
||||
- [ ] One way (Planning Center → site), or both? Answer: to site only
|
||||
- [ ] Who gets synced: everyone, or a Planning Center list or tag (eg. "Website")? Most people in Planning Center shouldn't have a public page. Answer:a specific list
|
||||
- [ ] Which fields: name, photo, email, phone, birthday? Which win when both sides differ? Answer:
|
||||
- [ ] How often: a button in Data, hourly, nightly? Answer:
|
||||
- [ ] Is there a Planning Center API app (personal access token) we can use, and which account owns it? Answer:
|
||||
- [ ] **New Thought young adult directory**: authors and TikTok and Instagram creators (faceless but organic).
|
||||
- [ ] People records with a new People tag (like Musicians), or a separate list of links (they aren't NGU people)? Answer:
|
||||
- [ ] What does "faceless but organic" mean for what's shown: no photo, only their handle and a link? Answer:
|
||||
- [ ] Do they agree to be listed, or is it a public list of public accounts? Answer:
|
||||
- [ ] Where does it show: Resources (For Young Adults), the Library, Community? Answer:
|
||||
- [ ] How often: a button in Data, hourly, nightly? Answer: manually only
|
||||
- [ ] Is there a Planning Center API app (personal access token) we can use, and which account owns it? Answer: use the API
|
||||
- [ ] **New Thought young adult directory**: things like authors and TikTok and Instagram creators.
|
||||
- [ ] section in the community page, Directories. tabs with different people lists, we have musicians already.
|
||||
- [ ] Do they agree to be listed, or is it a public list of public accounts? Answer: we add them to the list as admins
|
||||
|
||||
## Navigation
|
||||
- [ ] **Shop button** at the top right of the header.
|
||||
- [ ] Where does it go: an existing store (which URL), or a shop we build? Answer:
|
||||
- [ ] Shown on mobile too (in the menu, or beside it)? Answer:
|
||||
- [ ] **Manage the nav, sitemap and page headers from the admin**, so pages that aren't done can be hidden.
|
||||
- [ ] Hidden means: out of the nav and sitemap only (the address still works, like Unlisted), or the page returns Not found to non-admins? Answer:
|
||||
- [ ] What else is editable: link order, labels, which header menu a link is in, page titles and their blurbs? Answer:
|
||||
- [ ] `navConfig.ts` is the source of truth today; OK to move the editable parts into the database with navConfig as the defaults? [ ] yes
|
||||
|
||||
## Tools
|
||||
- [ ] **File conversion**: a simple tool, eg. WebP to JPG.
|
||||
- [ ] Which conversions: images only (WebP, JPG, PNG, HEIC?), or also documents (Word to PDF) and video? Answer:
|
||||
- [ ] In the browser (nothing uploaded, images only), or on the server (more formats)? Answer:
|
||||
- [ ] Which conversions: images only (WebP, JPG, PNG, HEIC?), or also documents (Word to PDF) and video? Answer: image converson
|
||||
- [ ] In the browser (nothing uploaded, images only), or on the server (more formats)? Answer: images only.
|
||||
- [ ] Also a "Download as JPG" on files in the Media library? [ ] yes
|
||||
- [ ] **What is needed for SEE**: list it.
|
||||
- [ ] What is SEE (an event, a program, a system)? Answer:
|
||||
- [ ] Is the list a page on the site, a TODO here, or a document? Answer:
|
||||
|
||||
## Content
|
||||
- [ ] **Newsletter: featured partners and new partnerships**, maybe as a blog post.
|
||||
|
|
@ -154,6 +133,23 @@
|
|||
|
||||
|
||||
# Part 2: Done
|
||||
## Page Editing (branch `nav-access`, no PR yet; migration 077)
|
||||
- [x] **Drafts of every record** (migration 077, `docs/drafts.md`): an existing record of any kind (events, people, organizations, blog posts, the front page, the site pages, Navigation, Site settings...) can be saved as a draft instead of going live. One draft per record; anyone who can edit it can save, preview, publish or discard it. Opening a record with a draft opens the draft, saying who saved it and when, and warning when the live record was saved since. Lists mark records with a draft.
|
||||
- [x] **Preview on the real page**: Preview saves the draft and opens the record's page in a new tab with it applied, under an amber "Previewing a draft" bar, for signed-in admin accounts only; anyone else sees the live page. The server answers that tab's reads from a second connection holding the draft in a transaction it rolls back, so no page needed code of its own.
|
||||
- [ ] Check in a browser: save a draft of an event, a site page (a section's title) and Navigation (a link), preview each, publish one, discard one; open the same address signed out.
|
||||
|
||||
## Accounts (branch `nav-access`, no PR yet; migration 076, back up the database before deploying)
|
||||
- [x] **Profile accounts** (migration 076, `docs/profile-accounts.md`): a member role below viewer, signed in to the site and their own profile, never the admin (`/api/admin` now refuses anything under viewer). By invite only: Data → Profile accounts (admins and up) adds an email and shows its link once; Email invite sends a fresh one through Gmail. The link (`/account/welcome`) sets a password, or they sign in with Google under that email, any Google account. A New sign-in link on the account doubles as a password reset.
|
||||
- [x] **Claiming a People record**: on `/account` (Your profile; the footer's Sign in link) they ask to be a record; admins approve or decline it under Claims, or set it directly on the account.
|
||||
- [x] **Editing it and choosing what shows**: with a record, they edit its pronouns, tagline, location, public email and phone, bio and photo, and hide any of photo, pronouns, tagline, bio, email, phone, location, links. Hidden parts stay in the record (the People editor shows the same switches) and are left out everywhere on the site: every public read of people goes through the new `v_people_public` view, and the views that read people were rebuilt over it.
|
||||
- [x] **Discord linking**: a profile links its Discord account (identify scope: id and name) from `/account`; an admin can set or clear it on the account. Off until `DISCORD_CLIENT_ID` and `DISCORD_CLIENT_SECRET` are set on the service.
|
||||
- [ ] Check in a browser: invite (copy link and Email invite), the welcome page with a password and with a non-org Google account, a claim and its approval, editing and hiding (then the person's page, a team page and a people tile signed out), Discord linking once it's set up, a member opening /admin.
|
||||
|
||||
## Navigation (branch `nav-access`, no PR yet; migration 075, back up the database before deploying)
|
||||
- [x] **Pages → Navigation** (migration 075): the header's pages and buttons, the footer's Get in Touch and bottom row, edited in the admin (admins and up): place, order, label, link (a page, a #section or an address elsewhere), a header page set under another page's menu (after its sections), a filled button (Give's style, also beside the footer's logo), new tab. `navConfig.ts` is now only the defaults the app starts from before the nav loads. Page titles and intros moved here from Site settings (the old rows came along).
|
||||
- [x] **Hidden pages**: a page ticked Hidden in Navigation answers Not found (404, noindex) to everyone below viewer, server and app both, and is out of the menus, the sitemap and the not-found page's suggestions; links to it are only sent to viewers and up. Signed in, it shows with a bar saying it's hidden. Its sections aren't cached (`server/src/siteNav.js`, `GET /api/nav`).
|
||||
- [x] **Shop**: a Shop page of sections at `/shop` (Pages → Shop, empty for now), starting hidden, with a Shop button in the header (beside Contact Us and Give, and in the phone menu's list with them). Unhide it in Navigation once it has content; its sections can link out to the Bonfire store.
|
||||
- [ ] Check in a browser: the header and phone menu, a page set under another's menu, the footer, signed out and signed in (the hidden bar, Shop showing), light and dark.
|
||||
## Feature updates (branch `feature-updates`, v1.13.x, no PR yet; migrations 069 to 071, back up the database before deploying)
|
||||
- [x] **Partner cards, logo first**: the organization cards (Partners, Ministries) lead with the logo, large and centered, the name under it as a small line (still the heading); with no logo, its initials. Cards sit raised with a shadow and an accent top edge.
|
||||
- [x] **Frame a photo on upload**: photo fields (people, event photo and card background, blog cover and guest photo, hero photos, link card pictures, block images, schedule graphics and map images; not logos) open Frame the photo for a JPEG, PNG or WebP: drag (or arrow keys) to place, zoom slider, a shape menu (the field's own first; As uploaded keeps the photo's). The framed part is what uploads; Upload as is skips. Nothing stored beside the picture, so re-framing is uploading again.
|
||||
|
|
|
|||
46
docs/drafts.md
Normal file
46
docs/drafts.md
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
# Drafts
|
||||
|
||||
Any record the admin edits (events, people, organizations, blog posts,
|
||||
the front page, the site pages, Navigation, Site settings...) can be
|
||||
saved as a draft instead of going live (migration 077). One draft per
|
||||
record; anyone who can edit the record can save, preview, publish or
|
||||
discard it.
|
||||
|
||||
## In the editor
|
||||
|
||||
- **Save draft** keeps the form as the record's draft. It's checked the
|
||||
way a save is (same field errors), but nothing on the site changes.
|
||||
- **Preview** saves the draft and opens the record's page in a new tab
|
||||
showing it, with an amber bar ("Previewing a draft"). Only a
|
||||
signed-in admin account (viewer and up) sees the draft; anyone else
|
||||
opening that address sees the live page. Stop previewing in the bar
|
||||
returns the tab to the live site.
|
||||
- **Publish** (the Save button, while there's a draft) saves it for
|
||||
real and drops the draft.
|
||||
- **Discard draft** throws it away; the live version is untouched.
|
||||
|
||||
Opening a record that has a draft opens the draft, with a note saying
|
||||
who saved it and when. If the live record was saved after the draft was
|
||||
started, the note says so: publishing replaces those changes. Lists
|
||||
mark records with a draft.
|
||||
|
||||
Records not yet created have no drafts: Create is the only save (leave
|
||||
them unpublished until they're ready).
|
||||
|
||||
## How it works
|
||||
|
||||
`server/src/drafts.js`. A draft is the editor's whole form, as a save
|
||||
would send it. Saving one applies it inside a transaction that is
|
||||
always rolled back (`rolledBackSync` in `server/src/db.js`), so it's
|
||||
validated without being written. A preview is a public API read sent
|
||||
with `X-Draft-Preview: <entity>/<id>` (`src/lib/api.ts` adds it in a tab
|
||||
opened with `?preview=`): the server opens a second connection to the
|
||||
database, applies the draft in a transaction there, answers the read
|
||||
from it, and rolls back. WAL keeps those writes unseen by every other
|
||||
request. Public reads carry `Vary: X-Draft-Preview`, so a browser never
|
||||
mixes a cached live answer with a preview.
|
||||
|
||||
`tx()` nests as a savepoint, which is what lets a save run inside the
|
||||
rolled-back transaction. Where each entity's page is: `PREVIEW_PATHS` in
|
||||
`src/lib/adminSchema.ts` (an entity without one has drafts but no
|
||||
Preview button).
|
||||
|
|
@ -6,12 +6,16 @@ off until the service has an OAuth client ID and secret.
|
|||
|
||||
## Who gets in
|
||||
|
||||
Two kinds of account can sign in with Google:
|
||||
Three kinds of account can sign in with Google:
|
||||
|
||||
- **Group accounts**, when access groups are set up (below): anyone in
|
||||
one of the site's Workspace groups. Their account is made at their
|
||||
first sign-in, and their role follows the group.
|
||||
- **Accounts made with admin-cli**, as before.
|
||||
- **Profile accounts** (members, `docs/profile-accounts.md`), invited
|
||||
from Data → Profile accounts. These are the one case outside the
|
||||
Workspace: any Google account under the invited email, from the
|
||||
site's `/sign-in` page or the invite's welcome page.
|
||||
|
||||
Created with
|
||||
`admin-cli.js add <email>` (the password it asks for stays as a way in
|
||||
|
|
@ -23,7 +27,8 @@ changes. `admin-cli.js list` shows which accounts are linked.
|
|||
Refused, with a message on the login page: no admin account for that
|
||||
email (and in no access group), an email already linked to a different Google account, a
|
||||
disabled account, any account outside the Workspace domain (checked by
|
||||
Google's `hd` claim, not just the email), an unverified email.
|
||||
Google's `hd` claim, not just the email) unless it's a profile account's,
|
||||
an unverified email.
|
||||
|
||||
Code: `server/src/googleAuth.js` (the Google side),
|
||||
`server/src/routes/auth.js` (matching and linking accounts) and
|
||||
|
|
|
|||
78
docs/profile-accounts.md
Normal file
78
docs/profile-accounts.md
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
# Profile accounts
|
||||
|
||||
People can have an account on the site for their own profile (migration
|
||||
076). Nobody signs up: an admin invites them.
|
||||
|
||||
## How it goes
|
||||
|
||||
1. **Invite.** Data → Profile accounts → Invite someone (admins and up):
|
||||
an email, and a name if you like. That makes a *member* account with
|
||||
no password, and shows its invite link once, for 14 days. Copy it to
|
||||
send yourself, or press Email invite to send a fresh one through
|
||||
Gmail (needs Gmail set up, `docs/google-drive-and-mail.md`; the link
|
||||
shown before stops working).
|
||||
2. **Sign up.** The link opens `/account/welcome`: they set a password,
|
||||
or continue with Google under the invited email (any Google account,
|
||||
not only @nextgenerationofunity.org, when Google sign-in is on,
|
||||
`docs/google-sign-in.md`). Either takes up the invite.
|
||||
3. **Claim.** On `/account` (Your profile, also the footer's Sign in
|
||||
link) they pick the People record that's them and send the request.
|
||||
It waits under Claims on Data → Profile accounts until an admin
|
||||
approves or declines it. An admin can also set an account's record
|
||||
directly there.
|
||||
4. **Edit.** With a record, they edit its pronouns, tagline, location,
|
||||
public email and phone, bio and photo, and tick what to hide on the
|
||||
site. Their name, publishing and everything else stay the admin's.
|
||||
Changes are live as soon as they save.
|
||||
|
||||
A member is below viewer: signed in to the site, never to the admin
|
||||
(`/api/admin` refuses anything under viewer, `requireStaff` in
|
||||
`server/src/auth.js`). Staff accounts can claim a record too, from
|
||||
`/account`.
|
||||
|
||||
Forgotten password: on the account's row, New sign-in link (or Email a
|
||||
sign-in link); opening it sets a new password.
|
||||
|
||||
Turn off stops an account signing in and ends its sessions. Remove
|
||||
deletes the account; its People record stays.
|
||||
|
||||
## What "hidden" does
|
||||
|
||||
Each hidden part (photo, pronouns, tagline, bio, public email, public
|
||||
phone, location, links) stays in the record, and the admin's People
|
||||
editor shows the same switches (Hidden on the site). The site never
|
||||
shows it: every public read goes through the `v_people_public` view,
|
||||
which nulls hidden fields, and person links are left out when links are
|
||||
hidden (`loadLinks` in `server/src/shape.js`). When adding a public
|
||||
query on people, read `v_people_public`, not `people`.
|
||||
|
||||
## Discord
|
||||
|
||||
A profile can link its Discord account (the `identify` scope only: the
|
||||
Discord user id and name), kept for the gamification to come. Off until
|
||||
the service has a Discord application:
|
||||
|
||||
1. https://discord.com/developers/applications → New Application.
|
||||
2. OAuth2 → Redirects: add `https://nextgenerationofunity.org/api/account/discord/callback`
|
||||
(and the dev server's address, if you test there).
|
||||
3. Copy the Client ID and Client Secret into the service's environment
|
||||
(`systemctl edit ngu-api`):
|
||||
|
||||
```
|
||||
[Service]
|
||||
Environment=DISCORD_CLIENT_ID=...
|
||||
Environment=DISCORD_CLIENT_SECRET=...
|
||||
```
|
||||
|
||||
`DISCORD_REDIRECT_URI` overrides the return address (default: site.json's
|
||||
`url` plus `/api/account/discord/callback`).
|
||||
4. `systemctl restart ngu-api`.
|
||||
|
||||
An admin can set or clear an account's Discord id by hand on its row
|
||||
(the long number from Discord: Developer Mode, then Copy User ID).
|
||||
|
||||
Code: `server/src/invites.js`, `server/src/discordAuth.js`,
|
||||
`server/src/routes/account.js` (the member's own routes),
|
||||
`server/src/routes/profiles.js` (the admin's), `src/pages/Account.tsx`,
|
||||
`src/pages/AccountWelcome.tsx`, `src/pages/SignIn.tsx`,
|
||||
`src/pages/admin/AdminProfiles.tsx`.
|
||||
|
|
@ -247,8 +247,8 @@ const FRONT_PAGE_SECTIONS = [
|
|||
The subnav links jump to each band by its anchor: the `id` passed in
|
||||
each band's `render` in `Home.tsx` (`#retreats`, `#calendar`,
|
||||
`#numbers`, `#connect`, and `#hero` for the hero). If you rename a
|
||||
subnav label in `navConfig.ts`, leave its `hash` alone unless you also
|
||||
change the band's `id`.
|
||||
heading in Front page → Sections, its anchor stays: leave the band's
|
||||
`id` alone unless you mean to break links to it.
|
||||
|
||||
**Adding a new kind of band** (not just renaming one) is a feature,
|
||||
not a relabel: it needs a component, an entry in `SECTIONS` in
|
||||
|
|
@ -278,7 +278,7 @@ The numbers band's "Number Source" dropdown works the same way:
|
|||
|
||||
| What | File | Notes |
|
||||
| --- | --- | --- |
|
||||
| Header and footer navigation, each page's sections (the header dropdowns, mobile menu and footer site map) | `src/navConfig.ts` | `PAGE_LINKS` (order), `NAV_ACTIONS`. Each page's sections aren't listed there: they follow the page itself, through `src/lib/navSections.ts` (the site pages' sections from Admin → Pages; the front page's bands it shows, with `src/lib/frontPageBands.ts` giving each band's anchor and default heading). A new page also needs a route in `src/App.tsx`. |
|
||||
| Header and footer navigation, each page's sections (the header dropdowns, mobile menu and footer site map) | Admin → Pages → Navigation (the database, `075_site_nav.sql`); `src/navConfig.ts` is only the defaults the app starts from before it loads | Links: where each shows (header pages, header buttons, footer Get in Touch, footer bottom row), order, label, a header page set under another's menu, a filled button, new tab. Pages: title, intro and Hidden (Not found below viewer, out of the menus and the sitemap; `server/src/siteNav.js`). Each page's sections aren't listed there: they follow the page itself, through `src/lib/navSections.ts` (the site pages' sections from Admin → Pages; the front page's bands it shows, with `src/lib/frontPageBands.ts` giving each band's anchor and default heading). A new static page needs a route in `src/App.tsx` and an entry in `site.json`'s `pages` (its default title and intro, and what Navigation's Page select offers); a new page of sections also needs its id in `site_pages`' CHECK and a descriptor in both admin schemas, like Shop (075). |
|
||||
| Section titles, blurbs and colors on Feedback, Privacy, Terms | the page file in `src/pages/` | the `SECTIONS` array at the top. |
|
||||
| Site-wide announcement banner | `src/data/bannerConfig.ts` | `enabled: false` hides it. Bump `id` when the message changes, so people who dismissed the old one see the new one. |
|
||||
| History page decade headers | `src/data/historyDecades.ts` | Title, tagline and blurb per decade. |
|
||||
|
|
|
|||
|
|
@ -53,6 +53,7 @@ import { timeline } from "./admin-schema/timeline.js";
|
|||
import { frontPage } from "./admin-schema/frontPage.js";
|
||||
import { blogPosts } from "./admin-schema/blog.js";
|
||||
import { siteSettings } from "./admin-schema/siteSettings.js";
|
||||
import { siteNav } from "./admin-schema/siteNav.js";
|
||||
import { newsletters } from "./admin-schema/newsletters.js";
|
||||
import { personTagTypes } from "./admin-schema/personTags.js";
|
||||
import { tags } from "./admin-schema/tags.js";
|
||||
|
|
@ -64,6 +65,7 @@ import {
|
|||
resourcesPage,
|
||||
organizationPage,
|
||||
historyPage,
|
||||
shopPage,
|
||||
} from "./admin-schema/sitePages.js";
|
||||
|
||||
export const ENTITIES = {
|
||||
|
|
@ -84,6 +86,8 @@ export const ENTITIES = {
|
|||
resources_page: resourcesPage,
|
||||
organization_page: organizationPage,
|
||||
history_page: historyPage,
|
||||
shop_page: shopPage,
|
||||
navigation: siteNav,
|
||||
site_settings: siteSettings,
|
||||
newsletters,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -42,6 +42,9 @@ export const people = {
|
|||
text("location_label"),
|
||||
bool("is_published"),
|
||||
bool("is_listed"),
|
||||
// What's taken off the site (076): its owner's choice on their
|
||||
// profile, or an admin's. v_people_public applies it.
|
||||
...["photo", "pronouns", "tagline", "bio", "email", "phone", "location", "links"].map((key) => bool(`hide_${key}`)),
|
||||
],
|
||||
|
||||
extensions: [
|
||||
|
|
|
|||
44
server/src/admin-schema/siteNav.js
Normal file
44
server/src/admin-schema/siteNav.js
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { text, bool, enumeration } from "./columns.js";
|
||||
|
||||
/* ── Navigation (075_site_nav.sql) ───────────────────────────────
|
||||
Pages → Navigation: the header's and footer's links, in order,
|
||||
and each static page's title, intro and whether it's hidden
|
||||
(siteNav.js reads it for the site). Admins and up: it can take a
|
||||
page off the site. */
|
||||
export const siteNav = {
|
||||
key: "navigation",
|
||||
table: "site_nav",
|
||||
idColumn: "id",
|
||||
idKind: "slug",
|
||||
singleton: "site",
|
||||
concurrency: "updated_at",
|
||||
writeRole: "admin",
|
||||
|
||||
list: { columns: ["id", "updated_at"], filters: [], search: [], order: "id" },
|
||||
|
||||
columns: [],
|
||||
|
||||
children: [
|
||||
{
|
||||
key: "links",
|
||||
table: "site_nav_links",
|
||||
owner: { column: "nav_id" },
|
||||
order: "sort_order",
|
||||
columns: [
|
||||
enumeration("place", ["main", "action", "footer", "legal"], { required: true }),
|
||||
text("label", { required: true }),
|
||||
text("path", { required: true }),
|
||||
text("parent_path"),
|
||||
enumeration("style", ["filled"]),
|
||||
bool("new_tab"),
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "pages",
|
||||
table: "site_nav_pages",
|
||||
owner: { column: "nav_id" },
|
||||
order: "sort_order",
|
||||
columns: [text("path", { required: true }), text("title"), text("description"), bool("is_hidden")],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
|
@ -2,7 +2,8 @@ import { text, url, int, enumeration, featuredCardsChild, blocksChild } from "./
|
|||
|
||||
/* ── The site's own pages (056_site_pages.sql) ───────────────────
|
||||
|
||||
Community, Retreats, Resources, Organization and History: one
|
||||
Community, Retreats, Resources, Organization, History and Shop
|
||||
(075): one
|
||||
site_pages row each, edited as its own singleton, with its
|
||||
sections nested under it and each section's blocks under that
|
||||
(the blocks' items under them, as on any record). A section is
|
||||
|
|
@ -106,3 +107,4 @@ export const retreatsPage = sitePage("retreats");
|
|||
export const resourcesPage = sitePage("resources");
|
||||
export const organizationPage = sitePage("organization");
|
||||
export const historyPage = sitePage("history");
|
||||
export const shopPage = sitePage("shop");
|
||||
|
|
|
|||
|
|
@ -3,8 +3,9 @@ import { text, enumeration } from "./columns.js";
|
|||
|
||||
/* ── Site settings (035_site_settings.sql) ──────────────────────
|
||||
A singleton of overrides for what site.json says: name,
|
||||
description, preview image, icons, search indexing, and static
|
||||
pages' titles and intros. Superadmins only. pageMeta.js merges it
|
||||
description, preview image, icons and search indexing (static
|
||||
pages' titles and intros are Pages → Navigation's, siteNav.js).
|
||||
Superadmins only. pageMeta.js merges it
|
||||
over site.json. */
|
||||
export const siteSettings = {
|
||||
key: "site_settings",
|
||||
|
|
@ -39,13 +40,6 @@ export const siteSettings = {
|
|||
],
|
||||
|
||||
children: [
|
||||
{
|
||||
key: "pages",
|
||||
table: "site_setting_pages",
|
||||
owner: { column: "settings_id" },
|
||||
order: "sort_order",
|
||||
columns: [text("path", { required: true }), text("title"), text("description")],
|
||||
},
|
||||
{
|
||||
key: "colors",
|
||||
table: "site_setting_colors",
|
||||
|
|
|
|||
|
|
@ -219,14 +219,27 @@ export async function requireAuth(c, next) {
|
|||
await next();
|
||||
}
|
||||
|
||||
export const ROLES = ["viewer", "editor", "admin", "superadmin"];
|
||||
const RANK = { viewer: 1, editor: 2, admin: 3, superadmin: 4 };
|
||||
/* member is a profile account (076): signed in to the site and their
|
||||
own profile, below every admin role, so it passes no admin check.
|
||||
/api/admin as a whole needs viewer (index.js, requireStaff). */
|
||||
export const ROLES = ["member", "viewer", "editor", "admin", "superadmin"];
|
||||
const RANK = { member: 1, viewer: 2, editor: 3, admin: 4, superadmin: 5 };
|
||||
|
||||
/* Whether a user is at least this rank. A ladder, never equality. */
|
||||
export function hasRole(user, role) {
|
||||
return (RANK[user?.role] ?? 0) >= (RANK[role] ?? Infinity);
|
||||
}
|
||||
|
||||
/* Anyone who uses the admin: a signed-in account of viewer and up.
|
||||
A profile account (member) is signed in but gets 403 here. */
|
||||
export async function requireStaff(c, next) {
|
||||
const user = currentUser(c.get("db"), c);
|
||||
if (!user) return c.json({ error: "Not signed in." }, 401);
|
||||
if (!hasRole(user, "viewer")) return c.json({ error: "Not allowed." }, 403);
|
||||
c.set("user", user);
|
||||
await next();
|
||||
}
|
||||
|
||||
export function requireRole(...roles) {
|
||||
const need = Math.min(...roles.map((r) => RANK[r] ?? Infinity));
|
||||
return async (c, next) => {
|
||||
|
|
|
|||
|
|
@ -36,27 +36,67 @@ export async function openDatabase(path) {
|
|||
db.exec("PRAGMA busy_timeout = 5000");
|
||||
|
||||
db.driverName = "node:sqlite";
|
||||
// A draft's preview opens its own connection to the same file (drafts.js).
|
||||
db.path = path;
|
||||
return db;
|
||||
}
|
||||
|
||||
/* ── Transactions ──────────────────────────────────────────────
|
||||
node:sqlite has no db.transaction(), so do it by hand. Runs
|
||||
fn() and commits, or rolls back and rethrows.
|
||||
fn() and commits, or rolls back and rethrows. Inside another
|
||||
tx() (or rolledBack(), below) it's a savepoint instead, so a
|
||||
save can run inside a transaction that's then thrown away:
|
||||
how a draft is checked and previewed (drafts.js).
|
||||
───────────────────────────────────────────────────────────── */
|
||||
|
||||
export function tx(db, fn) {
|
||||
db.exec("BEGIN");
|
||||
const depth = db.txDepth ?? 0;
|
||||
const savepoint = `tx_${depth}`;
|
||||
db.exec(depth ? `SAVEPOINT ${savepoint}` : "BEGIN");
|
||||
db.txDepth = depth + 1;
|
||||
try {
|
||||
const result = fn();
|
||||
db.exec("COMMIT");
|
||||
db.exec(depth ? `RELEASE ${savepoint}` : "COMMIT");
|
||||
return result;
|
||||
} catch (err) {
|
||||
try {
|
||||
db.exec("ROLLBACK");
|
||||
db.exec(depth ? `ROLLBACK TO ${savepoint}; RELEASE ${savepoint}` : "ROLLBACK");
|
||||
} catch {
|
||||
/* already rolled back */
|
||||
}
|
||||
throw err;
|
||||
} finally {
|
||||
db.txDepth = depth;
|
||||
}
|
||||
}
|
||||
|
||||
/* Runs fn() in a transaction that is always rolled back, whatever
|
||||
fn() does: its writes are seen only by fn() itself. fn() may wait,
|
||||
so only on a connection of its own (a draft's preview, drafts.js):
|
||||
on the main one, another request would see the writes meanwhile. */
|
||||
export async function rolledBack(db, fn) {
|
||||
if (db.txDepth) throw new Error("rolledBack() can't run inside a transaction.");
|
||||
db.exec("BEGIN");
|
||||
db.txDepth = 1;
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
db.txDepth = 0;
|
||||
db.exec("ROLLBACK");
|
||||
}
|
||||
}
|
||||
|
||||
/* The same for a synchronous fn(), which nothing else can run
|
||||
during, so the main connection is fine (checking a draft). */
|
||||
export function rolledBackSync(db, fn) {
|
||||
if (db.txDepth) throw new Error("rolledBackSync() can't run inside a transaction.");
|
||||
db.exec("BEGIN");
|
||||
db.txDepth = 1;
|
||||
try {
|
||||
return fn();
|
||||
} finally {
|
||||
db.txDepth = 0;
|
||||
db.exec("ROLLBACK");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
84
server/src/discordAuth.js
Normal file
84
server/src/discordAuth.js
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
DISCORD LINKING
|
||||
|
||||
A profile account links its Discord account (076): OAuth 2.0 with
|
||||
the identify scope only, which gives the Discord user's id and
|
||||
name and nothing else (no servers, no messages). The routes are in
|
||||
routes/account.js; an admin can also set or clear it by hand
|
||||
(routes/profiles.js). Kept for the gamification to come, which
|
||||
matches Discord members to people by this id.
|
||||
|
||||
DISCORD_CLIENT_ID from the Discord developer portal
|
||||
DISCORD_CLIENT_SECRET the same; never in the repo
|
||||
DISCORD_REDIRECT_URI default <site.json url>/api/account/discord/callback
|
||||
|
||||
With no client id or secret it's off: the profile page doesn't
|
||||
offer it and the routes answer 404. Setup: docs/profile-accounts.md.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { randomBytes } from "node:crypto";
|
||||
|
||||
import { loadSite } from "./pageMeta.js";
|
||||
|
||||
const AUTHORIZE = "https://discord.com/oauth2/authorize";
|
||||
const TOKEN = "https://discord.com/api/oauth2/token";
|
||||
const ME = "https://discord.com/api/users/@me";
|
||||
|
||||
export function discordConfig() {
|
||||
const clientId = process.env.DISCORD_CLIENT_ID;
|
||||
const clientSecret = process.env.DISCORD_CLIENT_SECRET;
|
||||
if (!clientId || !clientSecret) return null;
|
||||
|
||||
let redirectUri = process.env.DISCORD_REDIRECT_URI ?? null;
|
||||
if (!redirectUri) {
|
||||
try {
|
||||
const origin = (loadSite().url ?? "").replace(/\/$/, "");
|
||||
if (origin) redirectUri = `${origin}/api/account/discord/callback`;
|
||||
} catch {
|
||||
redirectUri = null;
|
||||
}
|
||||
}
|
||||
return { clientId, clientSecret, redirectUri };
|
||||
}
|
||||
|
||||
/* Where to send the browser, and the state to keep until it's back. */
|
||||
export function startLink(config) {
|
||||
const state = randomBytes(24).toString("base64url");
|
||||
const url = new URL(AUTHORIZE);
|
||||
url.search = new URLSearchParams({
|
||||
client_id: config.clientId,
|
||||
redirect_uri: config.redirectUri,
|
||||
response_type: "code",
|
||||
scope: "identify",
|
||||
state,
|
||||
prompt: "consent",
|
||||
});
|
||||
return { url: url.toString(), state };
|
||||
}
|
||||
|
||||
/* Trade the code for a token, then ask who it is. Returns
|
||||
{ id, name } or throws. */
|
||||
export async function finishLink(config, code) {
|
||||
const res = await fetch(TOKEN, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({
|
||||
client_id: config.clientId,
|
||||
client_secret: config.clientSecret,
|
||||
grant_type: "authorization_code",
|
||||
code,
|
||||
redirect_uri: config.redirectUri,
|
||||
}),
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
const token = await res.json().catch(() => ({}));
|
||||
if (!res.ok || !token.access_token) throw new Error(`Discord didn't accept the link (${res.status}).`);
|
||||
|
||||
const me = await fetch(ME, {
|
||||
headers: { Authorization: `Bearer ${token.access_token}` },
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
const user = await me.json().catch(() => ({}));
|
||||
if (!me.ok || !user.id) throw new Error(`Discord didn't say who you are (${me.status}).`);
|
||||
return { id: String(user.id), name: String(user.global_name || user.username || "").slice(0, 100) || null };
|
||||
}
|
||||
156
server/src/drafts.js
Normal file
156
server/src/drafts.js
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
DRAFTS (077_drafts.sql)
|
||||
|
||||
A record's changes saved without going live: one per record, of
|
||||
any entity the admin edits. The draft is the editor's whole form,
|
||||
exactly what a save would send, so publishing is that save
|
||||
(PATCH, routes/admin-entities.js), which then drops the draft.
|
||||
|
||||
Nothing applies a draft for real until it's published. Twice it's
|
||||
applied and thrown away:
|
||||
|
||||
checking when it's saved, in a transaction on the main
|
||||
connection that's always rolled back
|
||||
(rolledBackSync): updateRow is synchronous, so no
|
||||
other request can see it, and a draft that a save
|
||||
would refuse is refused now, with the same errors
|
||||
|
||||
preview a public API read sent with X-Draft-Preview:
|
||||
<entity>/<id> by a signed-in viewer and up runs on a
|
||||
connection of its own (the same file), inside a
|
||||
transaction holding the applied draft, rolled back
|
||||
when the answer is made (previewDrafts). The site
|
||||
draws the real page from it, with no code of its own
|
||||
for previews. WAL keeps that connection's writes
|
||||
unseen by everyone else; it holds the write lock
|
||||
meanwhile, a few milliseconds, which other writes
|
||||
wait out (busy_timeout).
|
||||
|
||||
The draft is applied over the live record as it is now, so a
|
||||
save made since the draft was started is overwritten when it's
|
||||
published; the editor says when that's so (stale).
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { currentUser, hasRole } from "./auth.js";
|
||||
import { openDatabase, rolledBack, rolledBackSync } from "./db.js";
|
||||
import { HttpError, normalizeId, updateRow } from "./admin-crud.js";
|
||||
import { ENTITIES } from "./admin-schema.js";
|
||||
|
||||
/* Who may preview a draft: anyone who can read the admin. */
|
||||
export const PREVIEWS = "viewer";
|
||||
|
||||
export const entityNamed = (key) => (Object.hasOwn(ENTITIES, key) ? ENTITIES[key] : null);
|
||||
|
||||
const liveStamp = (db, entity, id) =>
|
||||
entity.concurrency
|
||||
? db
|
||||
.prepare(`SELECT ${entity.concurrency} AS stamp FROM ${entity.table} WHERE ${entity.idColumn} = ?`)
|
||||
.get(normalizeId(entity, id))?.stamp
|
||||
: undefined;
|
||||
|
||||
/* Writes the draft over the live record, its concurrency stamp taken
|
||||
from the live row so the check passes. Call inside a rolled-back
|
||||
transaction, or as the real publish. */
|
||||
function apply(db, entity, id, payload) {
|
||||
const stamp = liveStamp(db, entity, id);
|
||||
return updateRow(db, entity, id, entity.concurrency ? { ...payload, [entity.concurrency]: stamp } : payload);
|
||||
}
|
||||
|
||||
export function readDraft(db, key, id) {
|
||||
const entity = entityNamed(key);
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT d.*, u.name AS updated_by_name, u.email AS updated_by_email
|
||||
FROM drafts d LEFT JOIN admin_users u ON u.id = d.updated_by
|
||||
WHERE d.entity = ? AND d.record_id = ?`,
|
||||
)
|
||||
.get(key, String(id));
|
||||
if (!row) return null;
|
||||
const live = entity ? liveStamp(db, entity, id) : undefined;
|
||||
return {
|
||||
payload: JSON.parse(row.payload),
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
updated_by: row.updated_by_name ?? row.updated_by_email ?? null,
|
||||
// The live record was saved after the draft was started.
|
||||
stale: Boolean(entity?.concurrency && row.base_updated_at && live && live !== row.base_updated_at),
|
||||
};
|
||||
}
|
||||
|
||||
/* The ids of an entity's records that have a draft, for its list. */
|
||||
export const draftIds = (db, key) =>
|
||||
db.prepare(`SELECT record_id FROM drafts WHERE entity = ?`).all(key).map((row) => row.record_id);
|
||||
|
||||
/* Checks the draft by applying it and throwing that away, then keeps
|
||||
it. An HttpError from the check (422 with fields, say) refuses it. */
|
||||
export function saveDraft(db, key, id, payload, userId) {
|
||||
const entity = entityNamed(key);
|
||||
if (!entity) throw new HttpError(404, "Unknown entity.");
|
||||
if (!payload || typeof payload !== "object") throw new HttpError(400, "Expected the record's form.");
|
||||
rolledBackSync(db, () => apply(db, entity, id, payload));
|
||||
|
||||
const existing = db.prepare(`SELECT base_updated_at FROM drafts WHERE entity = ? AND record_id = ?`).get(key, String(id));
|
||||
const base = existing ? existing.base_updated_at : (payload[entity.concurrency] ?? null);
|
||||
db.prepare(
|
||||
`INSERT INTO drafts (entity, record_id, payload, base_updated_at, created_by, updated_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT (entity, record_id) DO UPDATE
|
||||
SET payload = excluded.payload, updated_by = excluded.updated_by, updated_at = datetime('now')`,
|
||||
).run(key, String(id), JSON.stringify(payload), base, userId, userId);
|
||||
return readDraft(db, key, id);
|
||||
}
|
||||
|
||||
export function dropDraft(db, key, id) {
|
||||
db.prepare(`DELETE FROM drafts WHERE entity = ? AND record_id = ?`).run(key, String(id));
|
||||
}
|
||||
|
||||
/* Middleware for the public API: a GET carrying X-Draft-Preview from
|
||||
a signed-in viewer and up is answered with that draft applied. Any
|
||||
other request, or a draft that isn't there, goes on as usual. */
|
||||
export async function previewDrafts(c, next) {
|
||||
if (c.req.method !== "GET" || /^\/api\/(admin|auth|account)(\/|$)/.test(c.req.path)) return next();
|
||||
await answer(c, next);
|
||||
// A public read may be kept a minute (shape.js, CACHE): never hand
|
||||
// the live copy to a preview tab, or a preview's to anyone.
|
||||
c.res.headers.append("Vary", "X-Draft-Preview");
|
||||
}
|
||||
|
||||
async function answer(c, next) {
|
||||
const wanted = c.req.header("x-draft-preview");
|
||||
if (!wanted) return next();
|
||||
|
||||
const main = c.get("db");
|
||||
if (!hasRole(currentUser(main, c), PREVIEWS)) return next();
|
||||
|
||||
const slash = wanted.indexOf("/");
|
||||
const key = wanted.slice(0, slash);
|
||||
let id;
|
||||
try {
|
||||
id = decodeURIComponent(wanted.slice(slash + 1));
|
||||
} catch {
|
||||
return next();
|
||||
}
|
||||
const entity = entityNamed(key);
|
||||
const draft = slash > 0 && entity ? readDraft(main, key, id) : null;
|
||||
if (!draft) return next();
|
||||
|
||||
const db = await openDatabase(main.path);
|
||||
try {
|
||||
await rolledBack(db, async () => {
|
||||
// A draft the record has outgrown (a field it no longer has,
|
||||
// say) shows the live page rather than an error; saving it in
|
||||
// the editor says what's wrong.
|
||||
try {
|
||||
apply(db, entity, id, draft.payload);
|
||||
} catch (err) {
|
||||
console.warn(`draft preview ${key}/${id} not applied: ${err.message}`);
|
||||
}
|
||||
c.set("db", db);
|
||||
await next();
|
||||
});
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
// Only for this tab, never kept.
|
||||
c.res.headers.set("Cache-Control", "no-store");
|
||||
}
|
||||
|
|
@ -30,6 +30,12 @@
|
|||
Nothing here creates an account. A Google login is only let in
|
||||
if admin-cli has already made one for that email (see auth.js
|
||||
routes), and is linked to it on first use.
|
||||
|
||||
Profile accounts (076) are the one case outside the domain: an
|
||||
invited member may sign in with any Google account under the
|
||||
invited email. finishLogin says whether the identity is in the
|
||||
Workspace domain (inDomain) instead of refusing it, and the
|
||||
callback lets an outside identity reach a member account only.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
|
|
@ -70,8 +76,10 @@ export function googleConfig() {
|
|||
}
|
||||
|
||||
/* The first leg: where to send the browser, and the state and PKCE
|
||||
verifier to keep (in a short-lived cookie) until it comes back. */
|
||||
export function startLogin(config) {
|
||||
verifier to keep (in a short-lived cookie) until it comes back.
|
||||
anyDomain: a profile account's sign-in, so the account chooser
|
||||
isn't narrowed to the Workspace. */
|
||||
export function startLogin(config, { anyDomain = false } = {}) {
|
||||
const state = base64url(randomBytes(24));
|
||||
const verifier = base64url(randomBytes(48));
|
||||
const challenge = base64url(createHash("sha256").update(verifier).digest());
|
||||
|
|
@ -87,7 +95,7 @@ export function startLogin(config) {
|
|||
code_challenge_method: "S256",
|
||||
// Only a hint to Google's account chooser; the hd claim is what's
|
||||
// actually checked on the way back.
|
||||
hd: config.domain,
|
||||
...(anyDomain ? {} : { hd: config.domain }),
|
||||
prompt: "select_account",
|
||||
});
|
||||
|
||||
|
|
@ -102,7 +110,7 @@ export class GoogleLoginError extends Error {
|
|||
}
|
||||
|
||||
/* The second leg: trade the code for tokens and check the identity.
|
||||
Returns { sub, email, name } or throws GoogleLoginError. */
|
||||
Returns { sub, email, name, inDomain } or throws GoogleLoginError. */
|
||||
export async function finishLogin(config, code, verifier) {
|
||||
let res;
|
||||
try {
|
||||
|
|
@ -145,9 +153,7 @@ export async function finishLogin(config, code, verifier) {
|
|||
if (!claims.email_verified || !email) {
|
||||
throw new GoogleLoginError("unverified", "That Google account's email isn't verified.");
|
||||
}
|
||||
if (String(claims.hd ?? "").toLowerCase() !== config.domain || !email.endsWith(`@${config.domain}`)) {
|
||||
throw new GoogleLoginError("wrong_domain", `Use your @${config.domain} account.`);
|
||||
}
|
||||
const inDomain = String(claims.hd ?? "").toLowerCase() === config.domain && email.endsWith(`@${config.domain}`);
|
||||
|
||||
return { sub: String(claims.sub), email, name: claims.name ?? null };
|
||||
return { sub: String(claims.sub), email, name: claims.name ?? null, inDomain };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -32,6 +32,8 @@ import pages from "./routes/pages.js";
|
|||
import feedback from "./routes/feedback.js";
|
||||
import requests from "./routes/requests.js";
|
||||
import auth from "./routes/auth.js";
|
||||
import account from "./routes/account.js";
|
||||
import profiles from "./routes/profiles.js";
|
||||
import admin from "./routes/admin.js";
|
||||
import panel from "./routes/panel.js";
|
||||
import adminEntities from "./routes/admin-entities.js";
|
||||
|
|
@ -43,11 +45,12 @@ import countdown from "./routes/countdown.js";
|
|||
import redirects from "./routes/redirects.js";
|
||||
import { CLIPS_DIR, startClipWorker } from "./clips.js";
|
||||
import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
|
||||
import { logSafe, startSessionSweeper } from "./auth.js";
|
||||
import { logSafe, requireStaff, startSessionSweeper } from "./auth.js";
|
||||
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
|
||||
import { startGroupSync } from "./accessGroups.js";
|
||||
import { startAnalyticsReports } from "./analyticsReport.js";
|
||||
import { ENTITIES } from "./admin-schema.js";
|
||||
import { previewDrafts } from "./drafts.js";
|
||||
|
||||
const HOST = process.env.HOST ?? "127.0.0.1";
|
||||
const PORT = Number(process.env.PORT ?? 3001);
|
||||
|
|
@ -134,7 +137,7 @@ app.use(
|
|||
so each is capped well above its longest real body (a 5000
|
||||
character message) and far below nginx's limit. */
|
||||
const smallBody = bodyLimit({ maxSize: 64 * 1024, onError: (c) => c.json({ error: "That's too long." }, 413) });
|
||||
for (const path of ["/api/csp-report", "/api/feedback", "/api/auth/login"]) app.use(path, smallBody);
|
||||
for (const path of ["/api/csp-report", "/api/feedback", "/api/auth/login", "/api/account/accept", "/api/account/claim", "/api/account/profile"]) app.use(path, smallBody);
|
||||
|
||||
/* What the policy above would have blocked. Browsers post these on
|
||||
their own; a short line per report is plenty to go on. */
|
||||
|
|
@ -178,6 +181,10 @@ app.use("*", async (c, next) => {
|
|||
await next();
|
||||
});
|
||||
|
||||
// A draft's preview (drafts.js): a public read from a signed-in
|
||||
// viewer with X-Draft-Preview answers with that draft applied.
|
||||
app.use("/api/*", previewDrafts);
|
||||
|
||||
app.get("/api/health", (c) =>
|
||||
c.json({ ok: true, schema: version, driver: db.driverName }),
|
||||
);
|
||||
|
|
@ -206,9 +213,18 @@ app.use("/api/auth/login", rateLimit({ windowMs: 15 * 60_000, max: 10 }));
|
|||
// Looser than a password guess: each Google sign-in is two requests,
|
||||
// and Google has already checked the person by the second.
|
||||
app.use("/api/auth/google/*", rateLimit({ windowMs: 15 * 60_000, max: 40 }));
|
||||
// The whole admin is for viewer and up; a profile account (member)
|
||||
// is signed in but kept out. Each router still checks its own.
|
||||
app.use("/api/admin/*", requireStaff);
|
||||
app.route("/api/admin/panel", panel);
|
||||
app.route("/api/auth", auth);
|
||||
// A profile account's own page (076); setting a password from an
|
||||
// invite is held to the login's pace.
|
||||
app.use("/api/account/accept", rateLimit({ windowMs: 15 * 60_000, max: 10 }));
|
||||
app.use("/api/account/photo", rateLimit({ windowMs: 15 * 60_000, max: 20 }));
|
||||
app.route("/api/account", account);
|
||||
app.route("/api/admin", admin);
|
||||
app.route("/api/admin", profiles);
|
||||
// Before the entity routes, whose /:entity would claim /media.
|
||||
app.route("/api/admin", media);
|
||||
app.route("/api/admin", imports);
|
||||
|
|
|
|||
89
server/src/invites.js
Normal file
89
server/src/invites.js
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
INVITES: how a profile account (076) comes to exist
|
||||
|
||||
Nobody signs up. An admin adds an email (Data → Profile
|
||||
accounts, routes/profiles.js), which makes a member account with
|
||||
no password, and issues an invite: a link to /account/welcome
|
||||
with a random token. The token itself is shown once, to the
|
||||
admin, and emailed if they press Email invite; the database
|
||||
keeps only its SHA-256, like a session's. Issuing a new one
|
||||
replaces the old, so a link sent to the wrong place can be
|
||||
killed by sending another.
|
||||
|
||||
The link lets its holder set a password (routes/account.js).
|
||||
Signing in with Google under the invited email takes it up too
|
||||
(routes/auth.js). Either way the token is cleared.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
|
||||
import { loadSite } from "./pageMeta.js";
|
||||
import { mailReady, sendMail } from "./googleService.js";
|
||||
|
||||
export const INVITE_DAYS = 14;
|
||||
|
||||
const sha256 = (value) => createHash("sha256").update(value).digest("hex");
|
||||
|
||||
/* A new invite for this account, replacing any before it. Returns
|
||||
the link, which is never stored. */
|
||||
export function issueInvite(db, accountId, invitedBy) {
|
||||
const token = randomBytes(32).toString("base64url");
|
||||
db.prepare(
|
||||
`UPDATE admin_users
|
||||
SET invite_hash = ?, invite_expires_at = datetime('now', ?),
|
||||
invited_at = datetime('now'), invited_by = ?
|
||||
WHERE id = ?`,
|
||||
).run(sha256(token), `+${INVITE_DAYS} days`, invitedBy, accountId);
|
||||
return inviteLink(token);
|
||||
}
|
||||
|
||||
export function inviteLink(token) {
|
||||
let origin = "";
|
||||
try {
|
||||
origin = (loadSite().url ?? "").replace(/\/$/, "");
|
||||
} catch {
|
||||
origin = "";
|
||||
}
|
||||
return `${origin}/account/welcome?token=${encodeURIComponent(token)}`;
|
||||
}
|
||||
|
||||
/* The account an unexpired invite token belongs to, or null. */
|
||||
export function accountForInvite(db, token) {
|
||||
if (typeof token !== "string" || token.length < 20 || token.length > 100) return null;
|
||||
return (
|
||||
db
|
||||
.prepare(
|
||||
`SELECT id, email, name, role, is_active
|
||||
FROM admin_users
|
||||
WHERE invite_hash = ? AND invite_expires_at > datetime('now') AND is_active = 1`,
|
||||
)
|
||||
.get(sha256(token)) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
/* The invite as an email, through Gmail (googleService.js). */
|
||||
export async function emailInvite(db, account, link) {
|
||||
if (!mailReady()) throw new Error("Gmail isn't set up on the server (docs/google-drive-and-mail.md).");
|
||||
let site = { title: "Next Generation of Unity" };
|
||||
try {
|
||||
site = loadSite();
|
||||
} catch {
|
||||
// The default name will do.
|
||||
}
|
||||
const hello = account.name ? `Hi ${account.name},` : "Hi,";
|
||||
await sendMail({
|
||||
to: account.email,
|
||||
subject: `Your ${site.title} profile`,
|
||||
text: [
|
||||
hello,
|
||||
"",
|
||||
`You're invited to make a profile account on the ${site.title} website. Open this link to set a password, or to sign in with Google under this email:`,
|
||||
"",
|
||||
link,
|
||||
"",
|
||||
`The link works once, for ${INVITE_DAYS} days. Once you're in, you can find your profile on the site, ask to claim it, and choose what of it shows.`,
|
||||
"",
|
||||
"If you weren't expecting this, you can ignore it.",
|
||||
].join("\n"),
|
||||
});
|
||||
}
|
||||
122
server/src/migrations/075_site_nav.sql
Normal file
122
server/src/migrations/075_site_nav.sql
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
-- ═══════════════════════════════════════════════════════════════
|
||||
-- 075 SITE NAVIGATION
|
||||
--
|
||||
-- Pages → Navigation edits what navConfig.ts used to fix in code:
|
||||
-- the header's links and buttons, the footer's, and each page's
|
||||
-- title, intro and whether it is hidden. navConfig.ts stays as the
|
||||
-- defaults the app starts from before this arrives.
|
||||
--
|
||||
-- site_nav the editor's one row ('site')
|
||||
-- site_nav_links every link, in order, by where it shows:
|
||||
-- main the header's pages (sections drop
|
||||
-- down under each); with a parent, in
|
||||
-- that page's dropdown instead
|
||||
-- action the header's buttons, right side
|
||||
-- (and the phone menu's list under
|
||||
-- the pages); a filled one also sits
|
||||
-- beside the footer's logo
|
||||
-- footer the footer's Get in Touch list
|
||||
-- legal the footer's bottom row
|
||||
-- site_nav_pages a static page's title and intro (the page's
|
||||
-- heading and its search text) over site.json's,
|
||||
-- and is_hidden: a hidden page is out of the nav
|
||||
-- and the sitemap and answers Not found to anyone
|
||||
-- below viewer (pageMeta.js, siteNav.js)
|
||||
--
|
||||
-- site_setting_pages (Site settings → Page titles and intros) moves
|
||||
-- into site_nav_pages and is dropped.
|
||||
--
|
||||
-- The Shop page: site_pages takes 'shop' (a page of sections like
|
||||
-- the others), rebuilt since its CHECK can't change in place. It
|
||||
-- starts hidden, with its header button.
|
||||
-- ═══════════════════════════════════════════════════════════════
|
||||
|
||||
CREATE TABLE site_nav (
|
||||
id TEXT PRIMARY KEY CHECK (id = 'site'),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
) STRICT;
|
||||
|
||||
INSERT INTO site_nav (id) VALUES ('site');
|
||||
|
||||
CREATE TABLE site_nav_links (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
nav_id TEXT NOT NULL REFERENCES site_nav (id) ON DELETE CASCADE,
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
place TEXT NOT NULL CHECK (place IN ('main', 'action', 'footer', 'legal')),
|
||||
label TEXT NOT NULL,
|
||||
-- '/retreats', '/organization#contact', or an https:// address
|
||||
path TEXT NOT NULL,
|
||||
-- main links only: the page whose dropdown it sits in
|
||||
parent_path TEXT,
|
||||
-- action links only: null is the outlined button
|
||||
style TEXT CHECK (style IN ('filled')),
|
||||
new_tab INTEGER NOT NULL DEFAULT 0 CHECK (new_tab IN (0, 1))
|
||||
) STRICT;
|
||||
CREATE INDEX site_nav_links_order_idx ON site_nav_links (nav_id, sort_order);
|
||||
|
||||
INSERT INTO site_nav_links (nav_id, sort_order, place, label, path, parent_path, style, new_tab) VALUES
|
||||
('site', 0, 'main', 'Home', '/', NULL, NULL, 0),
|
||||
('site', 1, 'main', 'Retreats', '/retreats', NULL, NULL, 0),
|
||||
('site', 2, 'main', 'Community', '/community', NULL, NULL, 0),
|
||||
('site', 3, 'main', 'Resources', '/resources', NULL, NULL, 0),
|
||||
('site', 4, 'main', 'Organization', '/organization', NULL, NULL, 0),
|
||||
('site', 5, 'main', 'History', '/history', NULL, NULL, 0),
|
||||
('site', 6, 'action', 'Shop', '/shop', NULL, NULL, 0),
|
||||
('site', 7, 'action', 'Contact Us', '/organization#contact', NULL, NULL, 0),
|
||||
('site', 8, 'action', 'Give', '/give', NULL, 'filled', 1),
|
||||
('site', 9, 'footer', 'Feedback', '/feedback', NULL, NULL, 0),
|
||||
('site', 10, 'footer', 'Request', '/request', NULL, NULL, 0),
|
||||
('site', 11, 'footer', 'Contact Us', '/organization#contact', NULL, NULL, 0),
|
||||
('site', 12, 'legal', 'Privacy Policy', '/privacy', NULL, NULL, 0),
|
||||
('site', 13, 'legal', 'Terms of Service', '/terms', NULL, NULL, 0);
|
||||
|
||||
CREATE TABLE site_nav_pages (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
nav_id TEXT NOT NULL REFERENCES site_nav (id) ON DELETE CASCADE,
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
path TEXT NOT NULL, -- '/retreats', a key of site.json's pages
|
||||
title TEXT, -- null: site.json's
|
||||
description TEXT, -- null: site.json's
|
||||
is_hidden INTEGER NOT NULL DEFAULT 0 CHECK (is_hidden IN (0, 1)),
|
||||
UNIQUE (nav_id, path)
|
||||
) STRICT;
|
||||
|
||||
INSERT INTO site_nav_pages (nav_id, sort_order, path, title, description)
|
||||
SELECT 'site', sort_order, path, title, description
|
||||
FROM site_setting_pages WHERE settings_id = 'site';
|
||||
|
||||
INSERT INTO site_nav_pages (nav_id, sort_order, path, is_hidden)
|
||||
VALUES ('site', (SELECT coalesce(max(sort_order) + 1, 0) FROM site_nav_pages), '/shop', 1);
|
||||
|
||||
DROP TABLE site_setting_pages;
|
||||
|
||||
-- site_pages, with 'shop'.
|
||||
CREATE TABLE site_pages_new (
|
||||
id TEXT PRIMARY KEY
|
||||
CHECK (id IN ('community', 'retreats', 'resources', 'organization', 'history', 'shop')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
) STRICT;
|
||||
|
||||
INSERT INTO site_pages_new (id, updated_at) SELECT id, updated_at FROM site_pages;
|
||||
INSERT INTO site_pages_new (id) VALUES ('shop');
|
||||
|
||||
-- page_sections names site_pages; legacy mode leaves it alone
|
||||
-- through the rename.
|
||||
PRAGMA legacy_alter_table = ON;
|
||||
DROP TABLE site_pages;
|
||||
ALTER TABLE site_pages_new RENAME TO site_pages;
|
||||
PRAGMA legacy_alter_table = OFF;
|
||||
|
||||
CREATE TRIGGER site_nav_touch
|
||||
AFTER UPDATE ON site_nav
|
||||
FOR EACH ROW WHEN new.updated_at = old.updated_at
|
||||
BEGIN
|
||||
UPDATE site_nav SET updated_at = datetime('now') WHERE id = new.id;
|
||||
END;
|
||||
|
||||
CREATE TRIGGER site_pages_touch
|
||||
AFTER UPDATE ON site_pages
|
||||
FOR EACH ROW WHEN new.updated_at = old.updated_at
|
||||
BEGIN
|
||||
UPDATE site_pages SET updated_at = datetime('now') WHERE id = new.id;
|
||||
END;
|
||||
264
server/src/migrations/076_profile_accounts.sql
Normal file
264
server/src/migrations/076_profile_accounts.sql
Normal file
|
|
@ -0,0 +1,264 @@
|
|||
-- ═══════════════════════════════════════════════════════════════
|
||||
-- 076 PROFILE ACCOUNTS
|
||||
--
|
||||
-- Accounts for people, not only for the admin. An admin invites an
|
||||
-- email (Data → Profile accounts); nobody signs up on their own. The
|
||||
-- invite's link lets them set a password, or they sign in with
|
||||
-- Google under that email, any Google account, not only
|
||||
-- @nextgenerationofunity.org. Then they claim their People record,
|
||||
-- an admin approves it, and they edit their profile and choose what
|
||||
-- of it shows.
|
||||
--
|
||||
-- admin_users is rebuilt (its CHECKs can't change in place):
|
||||
-- role takes 'member', below viewer: signs in to the
|
||||
-- site and their own profile, never to the admin
|
||||
-- access_source takes 'invite', an account made by an invite
|
||||
-- person_id the People record it claimed (one account each)
|
||||
-- invite_hash SHA-256 of the invite link's token, until used
|
||||
-- invite_expires_at, invited_at, invited_by
|
||||
-- discord_id, discord_name the linked Discord account, set by
|
||||
-- its owner through Discord or by an admin
|
||||
--
|
||||
-- person_claims: a request to be a People record, approved or
|
||||
-- declined by an admin.
|
||||
--
|
||||
-- people.hide_*: what its owner (or an admin) took off the site.
|
||||
-- The value stays, for the admin; v_people_public is the record as
|
||||
-- the site shows it, the hidden fields null, and every public read
|
||||
-- goes through it, the views below included.
|
||||
-- ═══════════════════════════════════════════════════════════════
|
||||
|
||||
CREATE TABLE admin_users_new (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
|
||||
-- Stored lowercased. The application lowercases on every read
|
||||
-- and write, so the UNIQUE index is genuinely case-insensitive
|
||||
-- without depending on a collation.
|
||||
email TEXT NOT NULL UNIQUE,
|
||||
name TEXT,
|
||||
|
||||
-- Null for a Google-only account, or an invite not yet taken up.
|
||||
-- A row with both can use either route in.
|
||||
password_hash TEXT,
|
||||
|
||||
-- Google's stable subject id. Nullable, unique when present,
|
||||
-- SQLite allows any number of NULLs in a unique index.
|
||||
google_sub TEXT UNIQUE,
|
||||
|
||||
-- Listed low to high. The application treats these as a ladder,
|
||||
-- not a set: each one passes every check the one below it
|
||||
-- passes. The default stays 'admin' so no existing tooling
|
||||
-- starts creating accounts with different powers than it did
|
||||
-- yesterday.
|
||||
--
|
||||
-- member their own profile, on the site; no admin
|
||||
-- viewer read the admin
|
||||
-- editor + create and update
|
||||
-- admin + delete, invite members, approve claims
|
||||
-- superadmin + accounts, roles and sessions
|
||||
role TEXT NOT NULL DEFAULT 'admin'
|
||||
CHECK (role IN ('member', 'viewer', 'editor', 'admin', 'superadmin')),
|
||||
is_active INTEGER NOT NULL DEFAULT 1 CHECK (is_active IN (0, 1)),
|
||||
last_login_at TEXT,
|
||||
access_source TEXT NOT NULL DEFAULT 'manual'
|
||||
CHECK (access_source IN ('manual', 'group', 'invite')),
|
||||
group_disabled INTEGER NOT NULL DEFAULT 0 CHECK (group_disabled IN (0, 1)),
|
||||
groups_checked_at TEXT,
|
||||
|
||||
person_id TEXT UNIQUE REFERENCES people (id) ON DELETE SET NULL,
|
||||
invite_hash TEXT UNIQUE,
|
||||
invite_expires_at TEXT,
|
||||
invited_at TEXT,
|
||||
invited_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
|
||||
discord_id TEXT UNIQUE,
|
||||
discord_name TEXT
|
||||
) STRICT;
|
||||
|
||||
INSERT INTO admin_users_new
|
||||
(id, created_at, email, name, password_hash, google_sub, role, is_active, last_login_at,
|
||||
access_source, group_disabled, groups_checked_at)
|
||||
SELECT id, created_at, email, name, password_hash, google_sub, role, is_active, last_login_at,
|
||||
access_source, group_disabled, groups_checked_at
|
||||
FROM admin_users;
|
||||
|
||||
-- sessions, media, clip_jobs and drive_files name admin_users;
|
||||
-- legacy mode leaves them alone through the rename.
|
||||
PRAGMA legacy_alter_table = ON;
|
||||
DROP TABLE admin_users;
|
||||
ALTER TABLE admin_users_new RENAME TO admin_users;
|
||||
PRAGMA legacy_alter_table = OFF;
|
||||
|
||||
CREATE TABLE person_claims (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account_id INTEGER NOT NULL REFERENCES admin_users (id) ON DELETE CASCADE,
|
||||
person_id TEXT NOT NULL REFERENCES people (id) ON DELETE CASCADE,
|
||||
message TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'pending'
|
||||
CHECK (status IN ('pending', 'approved', 'declined')),
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
decided_at TEXT,
|
||||
decided_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL
|
||||
) STRICT;
|
||||
CREATE INDEX person_claims_status_idx ON person_claims (status, created_at);
|
||||
CREATE INDEX person_claims_account_idx ON person_claims (account_id);
|
||||
-- One open request per account.
|
||||
CREATE UNIQUE INDEX person_claims_one_pending ON person_claims (account_id) WHERE status = 'pending';
|
||||
|
||||
ALTER TABLE people ADD COLUMN hide_photo INTEGER NOT NULL DEFAULT 0 CHECK (hide_photo IN (0, 1));
|
||||
ALTER TABLE people ADD COLUMN hide_pronouns INTEGER NOT NULL DEFAULT 0 CHECK (hide_pronouns IN (0, 1));
|
||||
ALTER TABLE people ADD COLUMN hide_tagline INTEGER NOT NULL DEFAULT 0 CHECK (hide_tagline IN (0, 1));
|
||||
ALTER TABLE people ADD COLUMN hide_bio INTEGER NOT NULL DEFAULT 0 CHECK (hide_bio IN (0, 1));
|
||||
ALTER TABLE people ADD COLUMN hide_email INTEGER NOT NULL DEFAULT 0 CHECK (hide_email IN (0, 1));
|
||||
ALTER TABLE people ADD COLUMN hide_phone INTEGER NOT NULL DEFAULT 0 CHECK (hide_phone IN (0, 1));
|
||||
ALTER TABLE people ADD COLUMN hide_location INTEGER NOT NULL DEFAULT 0 CHECK (hide_location IN (0, 1));
|
||||
ALTER TABLE people ADD COLUMN hide_links INTEGER NOT NULL DEFAULT 0 CHECK (hide_links IN (0, 1));
|
||||
|
||||
-- A person as the site shows them. Every public read uses this, not
|
||||
-- people; the admin reads people.
|
||||
CREATE VIEW v_people_public AS
|
||||
SELECT
|
||||
id,
|
||||
display_name,
|
||||
sort_name,
|
||||
CASE WHEN hide_pronouns = 0 THEN pronouns END AS pronouns,
|
||||
CASE WHEN hide_tagline = 0 THEN tagline END AS tagline,
|
||||
CASE WHEN hide_photo = 0 THEN photo END AS photo,
|
||||
CASE WHEN hide_email = 0 THEN public_email END AS public_email,
|
||||
CASE WHEN hide_phone = 0 THEN public_phone END AS public_phone,
|
||||
CASE WHEN hide_location = 0 THEN locality END AS locality,
|
||||
CASE WHEN hide_location = 0 THEN state_code END AS state_code,
|
||||
country,
|
||||
CASE WHEN hide_location = 0 THEN location_label END AS location_label,
|
||||
is_published,
|
||||
created_at,
|
||||
updated_at,
|
||||
CASE WHEN hide_bio = 0 THEN bio END AS bio,
|
||||
primary_org_id,
|
||||
is_listed,
|
||||
specialty,
|
||||
hide_links
|
||||
FROM people;
|
||||
|
||||
-- The views that read people's public fields, over v_people_public.
|
||||
|
||||
DROP VIEW v_event_people;
|
||||
CREATE VIEW v_event_people AS
|
||||
SELECT
|
||||
ep.event_id, ep.person_id, ep.role, ep.title, ep.sort_order,
|
||||
p.display_name, p.pronouns, p.tagline, p.photo
|
||||
FROM event_people ep
|
||||
JOIN v_people_public p ON p.id = ep.person_id AND p.is_published = 1
|
||||
WHERE ep.is_public = 1;
|
||||
|
||||
DROP VIEW v_timeline;
|
||||
CREATE VIEW v_timeline AS
|
||||
SELECT
|
||||
t.id,
|
||||
t.kind,
|
||||
t.ref_kind,
|
||||
t.ref_id,
|
||||
t.precision,
|
||||
t.is_featured,
|
||||
t.is_published,
|
||||
t.sort_order,
|
||||
|
||||
COALESCE(t.occurred_on, e.starts_on, pa.awarded_on) AS effective_date,
|
||||
|
||||
COALESCE(
|
||||
t.title,
|
||||
e.title,
|
||||
o.name,
|
||||
aw.name,
|
||||
p.display_name,
|
||||
tm.name
|
||||
) AS effective_title,
|
||||
|
||||
COALESCE(t.blurb, e.tagline, o.tagline, aw.description, p.tagline, tm.tagline)
|
||||
AS effective_blurb,
|
||||
t.meta,
|
||||
t.link_url,
|
||||
|
||||
-- Filename only. The directory is the frontend's business.
|
||||
COALESCE(e.event_logo, e.org_logo, o.logo, aw.logo, p.photo, tm.logo)
|
||||
AS effective_logo,
|
||||
|
||||
o.kind AS org_kind,
|
||||
tm.org_id AS team_org_id,
|
||||
tm.name AS team_name,
|
||||
|
||||
-- Whether the referenced record is itself visible. An entry must not
|
||||
-- outlive the thing it points at being unpublished, a draft event
|
||||
-- would otherwise leak its title and date onto a public page. Null
|
||||
-- for a standalone milestone, which answers to nothing but its own
|
||||
-- is_published.
|
||||
CASE t.ref_kind
|
||||
WHEN 'event' THEN e.is_published
|
||||
WHEN 'organization' THEN o.is_published
|
||||
WHEN 'person' THEN p.is_published
|
||||
WHEN 'team' THEN tm.is_published
|
||||
ELSE NULL
|
||||
END AS ref_is_published,
|
||||
t.occurred_on,
|
||||
t.title AS title_override
|
||||
FROM timeline_entries t
|
||||
LEFT JOIN events e ON t.ref_kind = 'event' AND e.id = t.ref_id
|
||||
LEFT JOIN organizations o ON t.ref_kind = 'organization' AND o.id = t.ref_id
|
||||
LEFT JOIN awards aw ON t.ref_kind = 'award' AND aw.id = t.ref_id
|
||||
LEFT JOIN v_people_public p ON t.ref_kind = 'person' AND p.id = t.ref_id
|
||||
LEFT JOIN teams tm ON t.ref_kind = 'team' AND tm.id = t.ref_id
|
||||
LEFT JOIN person_awards pa ON t.ref_kind = 'award' AND pa.award_id = t.ref_id
|
||||
AND pa.id = (SELECT MIN(id) FROM person_awards
|
||||
WHERE award_id = t.ref_id);
|
||||
|
||||
DROP VIEW v_org_leadership;
|
||||
CREATE VIEW v_org_leadership AS
|
||||
SELECT
|
||||
a.org_id,
|
||||
a.team_id,
|
||||
t.name AS team_name,
|
||||
t.sort_order AS team_sort_order,
|
||||
a.person_id,
|
||||
a.title,
|
||||
a.role,
|
||||
a.is_owner,
|
||||
a.sort_order,
|
||||
p.display_name,
|
||||
p.sort_name,
|
||||
p.pronouns,
|
||||
p.tagline,
|
||||
p.photo,
|
||||
p.public_email,
|
||||
p.location_label,
|
||||
p.bio,
|
||||
o.id AS primary_org_id,
|
||||
o.name AS primary_org_name
|
||||
FROM affiliations a
|
||||
JOIN v_people_public p ON p.id = a.person_id AND p.is_published = 1
|
||||
LEFT JOIN teams t ON t.id = a.team_id
|
||||
LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1
|
||||
WHERE a.is_public = 1
|
||||
AND a.ended_on IS NULL
|
||||
ORDER BY a.org_id, a.is_owner DESC, a.sort_order, p.sort_name;
|
||||
|
||||
DROP VIEW v_event_hosts;
|
||||
CREATE VIEW v_event_hosts AS
|
||||
SELECT
|
||||
eh.id,
|
||||
eh.event_id,
|
||||
eh.sort_order,
|
||||
CASE WHEN eh.person_id IS NULL THEN 'organization' ELSE 'person' END
|
||||
AS host_kind,
|
||||
COALESCE(eh.org_id, eh.person_id) AS host_id,
|
||||
COALESCE(o.name, p.display_name) AS host_name,
|
||||
o.kind AS host_org_kind,
|
||||
o.logo AS host_logo,
|
||||
o.color AS host_color,
|
||||
p.photo AS host_photo,
|
||||
COALESCE(o.is_published, p.is_published) AS host_is_published,
|
||||
t.id AS host_team_id,
|
||||
t.name AS host_team_name
|
||||
FROM event_hosts eh
|
||||
LEFT JOIN organizations o ON o.id = eh.org_id
|
||||
LEFT JOIN v_people_public p ON p.id = eh.person_id
|
||||
LEFT JOIN teams t ON t.id = eh.team_id AND eh.org_id IS NOT NULL AND t.is_published = 1;
|
||||
25
server/src/migrations/077_drafts.sql
Normal file
25
server/src/migrations/077_drafts.sql
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
-- ═══════════════════════════════════════════════════════════════
|
||||
-- 077 DRAFTS
|
||||
--
|
||||
-- A record's changes saved without going live: one draft per
|
||||
-- record, of any entity the admin edits (events, people, pages,
|
||||
-- Navigation...). payload is the editor's whole form, as a save
|
||||
-- would send it; publishing is that save, which then drops the
|
||||
-- draft. Anyone who can edit the record can save, preview, publish
|
||||
-- or discard it (drafts.js).
|
||||
--
|
||||
-- base_updated_at is the record's updated_at when the draft was
|
||||
-- started, so the editor can say the live record changed since.
|
||||
-- ═══════════════════════════════════════════════════════════════
|
||||
|
||||
CREATE TABLE drafts (
|
||||
entity TEXT NOT NULL, -- the descriptor key, eg. 'events'
|
||||
record_id TEXT NOT NULL,
|
||||
payload TEXT NOT NULL CHECK (json_valid(payload)),
|
||||
base_updated_at TEXT,
|
||||
created_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
PRIMARY KEY (entity, record_id)
|
||||
) STRICT;
|
||||
|
|
@ -15,7 +15,8 @@
|
|||
/site.json (SITE_CONFIG): the site's name, address, default
|
||||
description and image, icons, and each static page's title and
|
||||
description. Laid over it: Panel → Site settings (the
|
||||
site_settings table, 035), where anything set wins and anything
|
||||
site_settings table, 035) and Pages → Navigation's page titles
|
||||
(site_nav_pages, 075), where anything set wins and anything
|
||||
blank falls back to site.json. siteFor(db) does the merge. The
|
||||
pages read the same merged values (renderPage writes them into
|
||||
the HTML as window.__SITE__, see src/lib/site.ts), so a
|
||||
|
|
@ -28,6 +29,8 @@
|
|||
published, listed indexed, in the sitemap
|
||||
published, unlisted noindex: reachable by link, not by search
|
||||
unpublished, missing 404 and noindex, with the site defaults
|
||||
a hidden static page 404 and noindex below viewer, out of the
|
||||
sitemap (siteNav.js)
|
||||
/admin noindex
|
||||
|
||||
Image paths resolve like src/lib/media.ts does: a bare filename
|
||||
|
|
@ -44,6 +47,7 @@ import { fileURLToPath } from "node:url";
|
|||
import { loadBlocks, paragraphs } from "./shape.js";
|
||||
import { themeCss } from "./theme.js";
|
||||
import { driveReady } from "./googleService.js";
|
||||
import { hiddenFrom, hiddenPaths, navFor } from "./siteNav.js";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
|
|
@ -71,15 +75,15 @@ const origin = (site) => (site.url ?? "").replace(/\/$/, "");
|
|||
|
||||
/* site.json with the admin's Site settings laid over it: a value set
|
||||
there wins, a blank one falls back. indexing 'on' / 'off' overrides
|
||||
robots.index for this database only. Page overrides apply only to
|
||||
pages site.json knows. */
|
||||
robots.index for this database only. Page overrides (Pages →
|
||||
Navigation) apply only to pages site.json knows. */
|
||||
export function siteFor(db) {
|
||||
const base = loadSite();
|
||||
const row = db.prepare(`SELECT * FROM site_settings WHERE id = 'site'`).get() ?? {};
|
||||
|
||||
const pages = { ...(base.pages ?? {}) };
|
||||
const overrides = db
|
||||
.prepare(`SELECT path, title, description FROM site_setting_pages WHERE settings_id = 'site'`)
|
||||
.prepare(`SELECT path, title, description FROM site_nav_pages WHERE nav_id = 'site'`)
|
||||
.all();
|
||||
for (const page of overrides) {
|
||||
const known = pages[page.path];
|
||||
|
|
@ -112,13 +116,15 @@ export function siteFor(db) {
|
|||
};
|
||||
}
|
||||
|
||||
/* What the browser app reads for headings and titles. */
|
||||
// requestFiles: whether the Request form can take files (Drive set up).
|
||||
const forBrowser = (site) => ({
|
||||
/* What the browser app reads for headings, titles and its menus.
|
||||
requestFiles: whether the Request form can take files (Drive set
|
||||
up). nav: this visitor's links and the hidden pages (siteNav.js). */
|
||||
const forBrowser = (site, nav) => ({
|
||||
title: site.title,
|
||||
pages: site.pages,
|
||||
privacyEmail: site.privacyEmail,
|
||||
requestFiles: driveReady(),
|
||||
nav,
|
||||
});
|
||||
|
||||
/* robots.txt for this database's setting, as the build writes it. */
|
||||
|
|
@ -296,7 +302,7 @@ function awardMeta(site, db, id, meta) {
|
|||
}
|
||||
|
||||
function personMeta(site, db, id, meta) {
|
||||
const row = db.prepare(`SELECT * FROM people WHERE id = ? AND is_published = 1`).get(id);
|
||||
const row = db.prepare(`SELECT * FROM v_people_public WHERE id = ? AND is_published = 1`).get(id);
|
||||
if (!row) return notFound(meta);
|
||||
return {
|
||||
...meta,
|
||||
|
|
@ -326,7 +332,7 @@ function blogMeta(site, db, id, meta) {
|
|||
.prepare(
|
||||
`SELECT p.display_name AS name
|
||||
FROM blog_post_authors a
|
||||
JOIN people p ON p.id = a.person_id AND p.is_published = 1
|
||||
JOIN v_people_public p ON p.id = a.person_id AND p.is_published = 1
|
||||
WHERE a.post_id = ? ORDER BY a.sort_order`,
|
||||
)
|
||||
.all(id)
|
||||
|
|
@ -358,12 +364,17 @@ function blogMeta(site, db, id, meta) {
|
|||
};
|
||||
}
|
||||
|
||||
/* The metadata for one request path. */
|
||||
export function metaFor(db, rawPath) {
|
||||
/* The profile account pages and their titles (src/pages/SignIn.tsx,
|
||||
Account.tsx, AccountWelcome.tsx say the same). */
|
||||
const ACCOUNT_PAGES = { "/sign-in": "Sign in", "/account": "Your profile", "/account/welcome": "Welcome" };
|
||||
|
||||
/* The metadata for one request path, for this visitor (the signed-in
|
||||
user or null, who decides whether a hidden page is there). */
|
||||
export function metaFor(db, rawPath, user = null) {
|
||||
const site = siteFor(db);
|
||||
// Canonical form: no trailing slash (but "/" itself), no query.
|
||||
const pathname = rawPath.split(/[?#]/)[0].replace(/(.)\/+$/, "$1") || "/";
|
||||
const meta = defaults(site, db, pathname);
|
||||
const meta = { ...defaults(site, db, pathname), nav: navFor(db, user) };
|
||||
|
||||
if (pathname === "/") {
|
||||
// The home page's data, and its first hero photo when the hero is
|
||||
|
|
@ -395,7 +406,12 @@ export function metaFor(db, rawPath) {
|
|||
|
||||
if (/^\/admin(\/|$)/.test(pathname)) return { ...meta, title: `Admin | ${site.title}`, noindex: true };
|
||||
|
||||
// A profile account's pages (076): there for anyone, about no one
|
||||
// in particular, so never indexed or in the sitemap.
|
||||
if (ACCOUNT_PAGES[pathname]) return { ...meta, title: titled(site, ACCOUNT_PAGES[pathname]), noindex: true };
|
||||
|
||||
const page = site.pages?.[pathname];
|
||||
if (page && hiddenFrom(db, user, pathname)) return notFound(meta);
|
||||
if (page) {
|
||||
return { ...meta, title: titled(site, page.title), description: plainText(page.description) ?? meta.description };
|
||||
}
|
||||
|
|
@ -520,7 +536,7 @@ export function renderPage(html, meta) {
|
|||
),
|
||||
// Read by src/lib/site.ts before the app's module runs (a plain
|
||||
// script in the head runs during parsing; modules wait).
|
||||
`<script>window.__SITE__ = ${scriptJson(forBrowser(site))}</script>`,
|
||||
`<script>window.__SITE__ = ${scriptJson(forBrowser(site, meta.nav))}</script>`,
|
||||
site.themeCss && `<style id="site-colors">${site.themeCss}</style>`,
|
||||
analyticsTag(site),
|
||||
].filter(Boolean);
|
||||
|
|
@ -542,10 +558,13 @@ export function sitemap(db) {
|
|||
const site = siteFor(db);
|
||||
const base = origin(site);
|
||||
const day = (value) => (value ? String(value).slice(0, 10) : null);
|
||||
const hidden = hiddenPaths(db);
|
||||
|
||||
const entries = [
|
||||
{ loc: "/" },
|
||||
...Object.keys(site.pages ?? {}).map((loc) => ({ loc })),
|
||||
...Object.keys(site.pages ?? {})
|
||||
.filter((loc) => !hidden.has(loc))
|
||||
.map((loc) => ({ loc })),
|
||||
...db
|
||||
.prepare(`SELECT id, updated_at FROM events WHERE is_published = 1 AND is_listed = 1`)
|
||||
.all()
|
||||
|
|
|
|||
333
server/src/routes/account.js
Normal file
333
server/src/routes/account.js
Normal file
|
|
@ -0,0 +1,333 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
ACCOUNT ROUTES: a profile account's own page (076), mounted
|
||||
under /api/account
|
||||
|
||||
GET /invite?token= who an invite link is for (welcome page)
|
||||
POST /accept { token, password }: set the password,
|
||||
sign in, take up the invite
|
||||
GET / me: the account, my person (as I edit
|
||||
it), my claim, Discord
|
||||
GET /people the People records I could claim
|
||||
POST /claim { person_id, message }: ask to be one
|
||||
DELETE /claim take back the open request
|
||||
PATCH /profile my person's text and what of it shows
|
||||
POST /photo my person's photo (multipart, `file`)
|
||||
GET /discord off to Discord to link it
|
||||
GET /discord/callback back from it
|
||||
DELETE /discord unlink it
|
||||
|
||||
Every route but the first two needs a session; any role will do,
|
||||
so an admin with a claimed record has a profile too. Only the
|
||||
account's own person is ever written, and only the fields in
|
||||
PROFILE_FIELDS: name, published and listed stay the admin's.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { Hono } from "hono";
|
||||
import { bodyLimit } from "hono/body-limit";
|
||||
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
|
||||
|
||||
import { SECURE_COOKIE, createSession, currentUser, hashPassword } from "../auth.js";
|
||||
import { accountForInvite } from "../invites.js";
|
||||
import { discordConfig, finishLink, startLink } from "../discordAuth.js";
|
||||
import { googleConfig } from "../googleAuth.js";
|
||||
import { MAX_UPLOAD_BYTES, MediaError, publicPath } from "../media.js";
|
||||
import { addToLibrary } from "./media.js";
|
||||
import { NO_STORE } from "../shape.js";
|
||||
|
||||
const account = new Hono();
|
||||
|
||||
const MIN_PASSWORD = 12;
|
||||
|
||||
/* What an owner edits on their own record, and its longest. */
|
||||
const PROFILE_FIELDS = {
|
||||
pronouns: 40,
|
||||
tagline: 160,
|
||||
bio: 4000,
|
||||
public_email: 254,
|
||||
public_phone: 40,
|
||||
location_label: 120,
|
||||
};
|
||||
|
||||
/* What an owner can take off the site (people.hide_*). */
|
||||
export const HIDE_FIELDS = ["photo", "pronouns", "tagline", "bio", "email", "phone", "location", "links"];
|
||||
|
||||
async function body(c) {
|
||||
try {
|
||||
return (await c.req.json()) ?? {};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Invites ─────────────────────────────────────────────────── */
|
||||
|
||||
account.get("/invite", (c) => {
|
||||
const invited = accountForInvite(c.get("db"), c.req.query("token"));
|
||||
if (!invited) return c.json({ error: "This invite link has expired or was already used." }, 404, NO_STORE);
|
||||
return c.json({ invite: { email: invited.email, name: invited.name, google: Boolean(googleConfig()) } }, 200, NO_STORE);
|
||||
});
|
||||
|
||||
account.post("/accept", async (c) => {
|
||||
const data = await body(c);
|
||||
if (!data) return c.json({ error: "Expected a JSON body." }, 400);
|
||||
|
||||
const db = c.get("db");
|
||||
const invited = accountForInvite(db, data.token);
|
||||
if (!invited) return c.json({ error: "This invite link has expired or was already used." }, 404);
|
||||
|
||||
const password = String(data.password ?? "");
|
||||
if (password.length < MIN_PASSWORD) {
|
||||
return c.json({ error: `Use at least ${MIN_PASSWORD} characters.`, fields: { password: "Too short." } }, 422);
|
||||
}
|
||||
if (password.length > 200) return c.json({ error: "That password is too long." }, 422);
|
||||
|
||||
db.prepare(
|
||||
`UPDATE admin_users
|
||||
SET password_hash = ?, invite_hash = NULL, invite_expires_at = NULL, last_login_at = datetime('now')
|
||||
WHERE id = ?`,
|
||||
).run(hashPassword(password), invited.id);
|
||||
createSession(db, c, invited.id);
|
||||
console.log(`invite taken up by ${invited.email}`);
|
||||
|
||||
return c.json({ user: { id: invited.id, email: invited.email, name: invited.name, role: invited.role } }, 200, NO_STORE);
|
||||
});
|
||||
|
||||
/* ── Signed in from here ─────────────────────────────────────── */
|
||||
|
||||
account.use("*", async (c, next) => {
|
||||
const path = c.req.path;
|
||||
if (path.endsWith("/invite") || path.endsWith("/accept")) return next();
|
||||
const user = currentUser(c.get("db"), c);
|
||||
if (!user) return c.json({ error: "Not signed in." }, 401, NO_STORE);
|
||||
c.set("user", user);
|
||||
await next();
|
||||
});
|
||||
|
||||
/* My person as I edit it: the stored values, not the public view,
|
||||
with what's hidden said separately. */
|
||||
function myPerson(db, accountId) {
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT p.* FROM people p JOIN admin_users u ON u.person_id = p.id WHERE u.id = ?`,
|
||||
)
|
||||
.get(accountId);
|
||||
if (!row) return null;
|
||||
return {
|
||||
id: row.id,
|
||||
display_name: row.display_name,
|
||||
is_published: row.is_published === 1,
|
||||
photo: row.photo,
|
||||
...Object.fromEntries(Object.keys(PROFILE_FIELDS).map((key) => [key, row[key]])),
|
||||
hidden: Object.fromEntries(HIDE_FIELDS.map((key) => [key, row[`hide_${key}`] === 1])),
|
||||
};
|
||||
}
|
||||
|
||||
account.get("/", (c) => {
|
||||
const db = c.get("db");
|
||||
const user = c.get("user");
|
||||
const row = db.prepare(`SELECT discord_id, discord_name FROM admin_users WHERE id = ?`).get(user.id);
|
||||
const claim = db
|
||||
.prepare(
|
||||
`SELECT c.id, c.person_id, p.display_name, c.status, c.created_at, c.decided_at
|
||||
FROM person_claims c JOIN people p ON p.id = c.person_id
|
||||
WHERE c.account_id = ? ORDER BY c.id DESC LIMIT 1`,
|
||||
)
|
||||
.get(user.id);
|
||||
|
||||
return c.json(
|
||||
{
|
||||
account: {
|
||||
user,
|
||||
person: myPerson(db, user.id),
|
||||
claim: claim ?? null,
|
||||
discord: { enabled: Boolean(discordConfig()), id: row?.discord_id ?? null, name: row?.discord_name ?? null },
|
||||
},
|
||||
},
|
||||
200,
|
||||
NO_STORE,
|
||||
);
|
||||
});
|
||||
|
||||
/* Published records nobody has claimed, to pick from. */
|
||||
account.get("/people", (c) => {
|
||||
const people = c
|
||||
.get("db")
|
||||
.prepare(
|
||||
`SELECT p.id, p.display_name AS name
|
||||
FROM people p
|
||||
WHERE p.is_published = 1
|
||||
AND NOT EXISTS (SELECT 1 FROM admin_users u WHERE u.person_id = p.id)
|
||||
ORDER BY COALESCE(p.sort_name, p.display_name)`,
|
||||
)
|
||||
.all();
|
||||
return c.json({ people }, 200, NO_STORE);
|
||||
});
|
||||
|
||||
account.post("/claim", async (c) => {
|
||||
const data = await body(c);
|
||||
if (!data) return c.json({ error: "Expected a JSON body." }, 400);
|
||||
const db = c.get("db");
|
||||
const user = c.get("user");
|
||||
|
||||
if (db.prepare(`SELECT person_id FROM admin_users WHERE id = ?`).get(user.id)?.person_id) {
|
||||
return c.json({ error: "Your account already has a profile." }, 409);
|
||||
}
|
||||
const personId = String(data.person_id ?? "");
|
||||
const person = db.prepare(`SELECT id FROM people WHERE id = ? AND is_published = 1`).get(personId);
|
||||
if (!person) return c.json({ error: "Pick a person from the list.", fields: { person_id: "Pick one." } }, 422);
|
||||
if (db.prepare(`SELECT 1 FROM admin_users WHERE person_id = ?`).get(personId)) {
|
||||
return c.json({ error: "Someone has already claimed that profile." }, 409);
|
||||
}
|
||||
|
||||
const message = String(data.message ?? "").trim().slice(0, 1000) || null;
|
||||
try {
|
||||
db.prepare(`INSERT INTO person_claims (account_id, person_id, message) VALUES (?, ?, ?)`).run(
|
||||
user.id,
|
||||
personId,
|
||||
message,
|
||||
);
|
||||
} catch (err) {
|
||||
if (/UNIQUE/.test(err.message)) return c.json({ error: "You already have a request waiting." }, 409);
|
||||
throw err;
|
||||
}
|
||||
console.log(`claim: ${user.email} asked for ${personId}`);
|
||||
return c.body(null, 204);
|
||||
});
|
||||
|
||||
account.delete("/claim", (c) => {
|
||||
c.get("db")
|
||||
.prepare(`DELETE FROM person_claims WHERE account_id = ? AND status = 'pending'`)
|
||||
.run(c.get("user").id);
|
||||
return c.body(null, 204);
|
||||
});
|
||||
|
||||
account.patch("/profile", async (c) => {
|
||||
const data = await body(c);
|
||||
if (!data) return c.json({ error: "Expected a JSON body." }, 400);
|
||||
const db = c.get("db");
|
||||
const person = myPerson(db, c.get("user").id);
|
||||
if (!person) return c.json({ error: "Your account has no profile yet." }, 409);
|
||||
|
||||
const sets = [];
|
||||
const values = [];
|
||||
const fields = {};
|
||||
for (const [key, max] of Object.entries(PROFILE_FIELDS)) {
|
||||
if (!(key in data)) continue;
|
||||
const value = data[key] == null ? "" : String(data[key]).trim();
|
||||
if (value.length > max) fields[key] = `Up to ${max} characters.`;
|
||||
sets.push(`${key} = ?`);
|
||||
values.push(value || null);
|
||||
}
|
||||
if (data.public_email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(data.public_email).trim())) {
|
||||
fields.public_email = "That doesn't look like an email address.";
|
||||
}
|
||||
if (Object.keys(fields).length) return c.json({ error: "Check the highlighted fields.", fields }, 422);
|
||||
|
||||
for (const key of HIDE_FIELDS) {
|
||||
if (data.hidden && key in data.hidden) {
|
||||
sets.push(`hide_${key} = ?`);
|
||||
values.push(data.hidden[key] ? 1 : 0);
|
||||
}
|
||||
}
|
||||
if (sets.length) {
|
||||
db.prepare(`UPDATE people SET ${sets.join(", ")}, updated_at = datetime('now') WHERE id = ?`).run(
|
||||
...values,
|
||||
person.id,
|
||||
);
|
||||
console.log(`profile ${person.id} updated by ${c.get("user").email}`);
|
||||
}
|
||||
return c.json({ person: myPerson(db, c.get("user").id) }, 200, NO_STORE);
|
||||
});
|
||||
|
||||
account.post(
|
||||
"/photo",
|
||||
bodyLimit({ maxSize: MAX_UPLOAD_BYTES + 64 * 1024, onError: (c) => c.json({ error: "That file is too large." }, 413) }),
|
||||
async (c) => {
|
||||
const db = c.get("db");
|
||||
const user = c.get("user");
|
||||
const person = myPerson(db, user.id);
|
||||
if (!person) return c.json({ error: "Your account has no profile yet." }, 409);
|
||||
|
||||
let form;
|
||||
try {
|
||||
form = await c.req.parseBody();
|
||||
} catch {
|
||||
return c.json({ error: "Expected a file upload." }, 400);
|
||||
}
|
||||
const file = form.file;
|
||||
if (!(file instanceof File)) return c.json({ error: "No file was sent." }, 400);
|
||||
if (!/^image\/(jpeg|png|webp)$/.test(file.type)) {
|
||||
return c.json({ error: "Use a JPEG, PNG or WebP photo." }, 415);
|
||||
}
|
||||
|
||||
let row;
|
||||
try {
|
||||
row = await addToLibrary(db, Buffer.from(await file.arrayBuffer()), {
|
||||
originalName: person.display_name,
|
||||
folder: "images",
|
||||
userId: user.id,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof MediaError) return c.json({ error: err.message }, err.status ?? 422);
|
||||
throw err;
|
||||
}
|
||||
db.prepare(`UPDATE people SET photo = ?, updated_at = datetime('now') WHERE id = ?`).run(
|
||||
publicPath(row.filename),
|
||||
person.id,
|
||||
);
|
||||
console.log(`profile ${person.id} photo ${row.filename} by ${user.email}`);
|
||||
return c.json({ person: myPerson(db, user.id) }, 200, NO_STORE);
|
||||
},
|
||||
);
|
||||
|
||||
/* ── Discord ─────────────────────────────────────────────────── */
|
||||
|
||||
const DISCORD_COOKIE = SECURE_COOKIE ? "__Host-site_discord" : "site_discord";
|
||||
const DISCORD_COOKIE_OPTIONS = { httpOnly: true, secure: SECURE_COOKIE, sameSite: "Lax", path: "/" };
|
||||
const backToAccount = (c, result) => c.redirect(`/account?discord=${encodeURIComponent(result)}`, 302);
|
||||
|
||||
account.get("/discord", (c) => {
|
||||
const config = discordConfig();
|
||||
if (!config) return c.json({ error: "Discord linking isn't set up." }, 404);
|
||||
if (!config.redirectUri) {
|
||||
console.error("discord link: no return address. Set DISCORD_REDIRECT_URI, or SITE_CONFIG to a site.json with a url.");
|
||||
return backToAccount(c, "failed");
|
||||
}
|
||||
const { url, state } = startLink(config);
|
||||
setCookie(c, DISCORD_COOKIE, state, { ...DISCORD_COOKIE_OPTIONS, maxAge: 600 });
|
||||
return c.redirect(url, 302);
|
||||
});
|
||||
|
||||
account.get("/discord/callback", async (c) => {
|
||||
const config = discordConfig();
|
||||
if (!config) return c.json({ error: "Discord linking isn't set up." }, 404);
|
||||
const state = getCookie(c, DISCORD_COOKIE);
|
||||
deleteCookie(c, DISCORD_COOKIE, DISCORD_COOKIE_OPTIONS);
|
||||
|
||||
if (c.req.query("error")) return backToAccount(c, "canceled");
|
||||
const code = c.req.query("code");
|
||||
if (!state || !code || c.req.query("state") !== state) return backToAccount(c, "expired");
|
||||
|
||||
let who;
|
||||
try {
|
||||
who = await finishLink(config, code);
|
||||
} catch (err) {
|
||||
console.warn(`discord link failed: ${err.message}`);
|
||||
return backToAccount(c, "failed");
|
||||
}
|
||||
|
||||
const db = c.get("db");
|
||||
const user = c.get("user");
|
||||
const taken = db.prepare(`SELECT id FROM admin_users WHERE discord_id = ? AND id <> ?`).get(who.id, user.id);
|
||||
if (taken) return backToAccount(c, "taken");
|
||||
db.prepare(`UPDATE admin_users SET discord_id = ?, discord_name = ? WHERE id = ?`).run(who.id, who.name, user.id);
|
||||
console.log(`discord ${who.id} linked to ${user.email}`);
|
||||
return backToAccount(c, "linked");
|
||||
});
|
||||
|
||||
account.delete("/discord", (c) => {
|
||||
c.get("db").prepare(`UPDATE admin_users SET discord_id = NULL, discord_name = NULL WHERE id = ?`).run(c.get("user").id);
|
||||
return c.body(null, 204);
|
||||
});
|
||||
|
||||
export default account;
|
||||
|
|
@ -6,7 +6,11 @@
|
|||
GET /api/admin/:entity/:id row with side tables and children
|
||||
POST /api/admin/:entity create
|
||||
PATCH /api/admin/:entity/:id replace the row and its children
|
||||
(publishing a draft too: it's dropped)
|
||||
DELETE /api/admin/:entity/:id
|
||||
GET /api/admin/:entity/:id/draft its draft, or null (drafts.js)
|
||||
PUT /api/admin/:entity/:id/draft save the form as its draft
|
||||
DELETE /api/admin/:entity/:id/draft discard it
|
||||
|
||||
Mounted alongside the existing admin router, which keeps the
|
||||
feedback routes. Both sit under the same requireAuth.
|
||||
|
|
@ -29,6 +33,7 @@ import {
|
|||
deleteRow,
|
||||
} from "../admin-crud.js";
|
||||
import { NO_STORE } from "../shape.js";
|
||||
import { draftIds, dropDraft, readDraft, saveDraft } from "../drafts.js";
|
||||
|
||||
const entities = new Hono();
|
||||
|
||||
|
|
@ -84,7 +89,8 @@ entities.get("/options", (c) => {
|
|||
entities.get("/:entity", (c) => {
|
||||
const entity = entityOr404(c);
|
||||
const { rows, total } = listRows(c.get("db"), entity, c.req.query());
|
||||
return c.json({ rows, total }, 200, NO_STORE);
|
||||
// Which of them have a draft waiting, for the list to mark.
|
||||
return c.json({ rows, total, drafts: draftIds(c.get("db"), entity.key) }, 200, NO_STORE);
|
||||
});
|
||||
|
||||
entities.get("/:entity/:id", (c) => {
|
||||
|
|
@ -103,6 +109,8 @@ entities.patch("/:entity/:id", requireRole("editor"), async (c) => {
|
|||
const entity = entityForWrite(c);
|
||||
const id = c.req.param("id");
|
||||
const row = visible(c, entity, updateRow(c.get("db"), entity, id, await json(c)));
|
||||
// Saved for real: any draft of it is published, or overtaken.
|
||||
dropDraft(c.get("db"), entity.key, id);
|
||||
console.log(`${entity.key} ${id} updated by ${c.get("user").email}`);
|
||||
return c.json({ row }, 200, NO_STORE);
|
||||
});
|
||||
|
|
@ -111,10 +119,34 @@ entities.delete("/:entity/:id", requireRole("admin"), (c) => {
|
|||
const entity = entityOr404(c);
|
||||
const id = c.req.param("id");
|
||||
deleteRow(c.get("db"), entity, id);
|
||||
dropDraft(c.get("db"), entity.key, id);
|
||||
console.log(`${entity.key} ${id} deleted by ${c.get("user").email}`);
|
||||
return c.body(null, 204);
|
||||
});
|
||||
|
||||
/* ── Drafts (drafts.js) ──────────────────────────────────────── */
|
||||
|
||||
entities.get("/:entity/:id/draft", (c) => {
|
||||
const entity = entityOr404(c);
|
||||
return c.json({ draft: readDraft(c.get("db"), entity.key, c.req.param("id")) }, 200, NO_STORE);
|
||||
});
|
||||
|
||||
entities.put("/:entity/:id/draft", requireRole("editor"), async (c) => {
|
||||
const entity = entityForWrite(c);
|
||||
const id = c.req.param("id");
|
||||
const draft = saveDraft(c.get("db"), entity.key, id, await json(c), c.get("user").id);
|
||||
console.log(`${entity.key} ${id} draft saved by ${c.get("user").email}`);
|
||||
return c.json({ draft }, 200, NO_STORE);
|
||||
});
|
||||
|
||||
entities.delete("/:entity/:id/draft", requireRole("editor"), (c) => {
|
||||
const entity = entityForWrite(c);
|
||||
const id = c.req.param("id");
|
||||
dropDraft(c.get("db"), entity.key, id);
|
||||
console.log(`${entity.key} ${id} draft discarded by ${c.get("user").email}`);
|
||||
return c.body(null, 204);
|
||||
});
|
||||
|
||||
async function json(c) {
|
||||
try {
|
||||
return await c.req.json();
|
||||
|
|
|
|||
|
|
@ -5,7 +5,9 @@
|
|||
POST /api/auth/logout deletes the session row and cookie
|
||||
GET /api/auth/me who am I, or 401
|
||||
GET /api/auth/providers which ways in are switched on
|
||||
GET /api/auth/google off to Google's account chooser
|
||||
GET /api/auth/google off to Google's account chooser;
|
||||
?for=account from the site's sign-in
|
||||
page (any Google account, back there)
|
||||
GET /api/auth/google/callback back from it: sign in, or
|
||||
back to the login page with ?error=
|
||||
|
||||
|
|
@ -27,6 +29,11 @@
|
|||
email, which then links it. A matching email already linked to a
|
||||
different Google account is refused rather than relinked.
|
||||
googleAuth.js checks the identity itself.
|
||||
|
||||
Profile accounts (076) are made by an admin's invite
|
||||
(routes/profiles.js). One may sign in with a Google account
|
||||
outside the Workspace, under the invited email; an outside
|
||||
identity reaches nothing else. Signing in takes up the invite.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { Hono } from "hono";
|
||||
|
|
@ -153,7 +160,11 @@ const OAUTH_COOKIE_OPTIONS = {
|
|||
const safeNext = (value) =>
|
||||
typeof value === "string" && /^\/admin(\/[\w\-/]*)?$/.test(value) ? value : "/admin/home";
|
||||
|
||||
const backToLogin = (c, code) => c.redirect(`/admin/login?error=${encodeURIComponent(code)}`, 302);
|
||||
// The page a sign-in started from: the admin's, or the site's
|
||||
// (/sign-in, for profile accounts) when `from` is 'account'.
|
||||
const SIGN_IN_PAGES = { admin: "/admin/login", account: "/sign-in" };
|
||||
const backToLogin = (c, code, from = "admin") =>
|
||||
c.redirect(`${SIGN_IN_PAGES[from] ?? SIGN_IN_PAGES.admin}?error=${encodeURIComponent(code)}`, 302);
|
||||
|
||||
auth.get("/providers", (c) =>
|
||||
c.json({ password: true, google: Boolean(googleConfig()) }, 200, NO_STORE),
|
||||
|
|
@ -162,17 +173,18 @@ auth.get("/providers", (c) =>
|
|||
auth.get("/google", (c) => {
|
||||
const config = googleConfig();
|
||||
if (!config) return c.json({ error: "Google sign-in isn't set up." }, 404);
|
||||
const from = c.req.query("for") === "account" ? "account" : "admin";
|
||||
if (!config.redirectUri) {
|
||||
// Said in the log, where whoever runs the box will look; the
|
||||
// person at the login page just learns it didn't work.
|
||||
console.error(
|
||||
"google login: no return address. Set GOOGLE_REDIRECT_URI, or SITE_CONFIG to a site.json with a url.",
|
||||
);
|
||||
return backToLogin(c, "google_failed");
|
||||
return backToLogin(c, "google_failed", from);
|
||||
}
|
||||
|
||||
const { url, state, verifier } = startLogin(config);
|
||||
setCookie(c, OAUTH_COOKIE, JSON.stringify({ state, verifier, next: safeNext(c.req.query("next")) }), {
|
||||
const { url, state, verifier } = startLogin(config, { anyDomain: from === "account" });
|
||||
setCookie(c, OAUTH_COOKIE, JSON.stringify({ state, verifier, from, next: safeNext(c.req.query("next")) }), {
|
||||
...OAUTH_COOKIE_OPTIONS,
|
||||
maxAge: 600,
|
||||
});
|
||||
|
|
@ -190,13 +202,15 @@ auth.get("/google/callback", async (c) => {
|
|||
saved = null;
|
||||
}
|
||||
deleteCookie(c, OAUTH_COOKIE, OAUTH_COOKIE_OPTIONS);
|
||||
const from = saved?.from === "account" ? "account" : "admin";
|
||||
const back = (code) => backToLogin(c, code, from);
|
||||
|
||||
// Pressing Cancel on Google's screen comes back as ?error=.
|
||||
if (c.req.query("error")) return backToLogin(c, "canceled");
|
||||
if (c.req.query("error")) return back("canceled");
|
||||
|
||||
const code = c.req.query("code");
|
||||
if (!saved?.state || !code || c.req.query("state") !== saved.state) {
|
||||
return backToLogin(c, "expired");
|
||||
return back("expired");
|
||||
}
|
||||
|
||||
let identity;
|
||||
|
|
@ -205,7 +219,7 @@ auth.get("/google/callback", async (c) => {
|
|||
} catch (err) {
|
||||
if (err instanceof GoogleLoginError) {
|
||||
console.warn(`google login refused: ${err.code}`);
|
||||
return backToLogin(c, err.code);
|
||||
return back(err.code);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
|
@ -215,6 +229,20 @@ auth.get("/google/callback", async (c) => {
|
|||
const byId = (id) => db.prepare(`SELECT ${columns} FROM admin_users WHERE id = ?`).get(id);
|
||||
let user = db.prepare(`SELECT ${columns} FROM admin_users WHERE google_sub = ?`).get(identity.sub);
|
||||
|
||||
// From outside the Workspace, only a profile account: by its
|
||||
// linked Google id, or its invited email.
|
||||
if (!identity.inDomain) {
|
||||
user ??= db.prepare(`SELECT ${columns} FROM admin_users WHERE email = ?`).get(identity.email);
|
||||
if (!user || user.role !== "member") {
|
||||
console.warn(`google login: ${identity.email} is outside the Workspace and has no profile account`);
|
||||
return back(user ? "wrong_domain" : "no_account");
|
||||
}
|
||||
if (user.google_sub && user.google_sub !== identity.sub) {
|
||||
console.warn(`google login: ${identity.email} is linked to another Google account`);
|
||||
return back("linked_elsewhere");
|
||||
}
|
||||
}
|
||||
|
||||
// What the access groups give this person (accessGroups.js), asked
|
||||
// only when it matters. Unanswerable is a refusal: a sign-in has to
|
||||
// be shown to be allowed.
|
||||
|
|
@ -232,14 +260,14 @@ auth.get("/google/callback", async (c) => {
|
|||
if (!byEmail) {
|
||||
if (!accessEnabled(db)) {
|
||||
console.warn(`google login: no account for ${identity.email}`);
|
||||
return backToLogin(c, "no_account");
|
||||
return back("no_account");
|
||||
}
|
||||
// In an access group: the account is made now, Google only.
|
||||
const found = await roleFromGroups();
|
||||
if (found.failed) return backToLogin(c, "groups_unreachable");
|
||||
if (found.failed) return back("groups_unreachable");
|
||||
if (!found.role) {
|
||||
console.warn(`google login: ${identity.email} is in no access group`);
|
||||
return backToLogin(c, "not_in_group");
|
||||
return back("not_in_group");
|
||||
}
|
||||
const id = db
|
||||
.prepare(
|
||||
|
|
@ -251,10 +279,10 @@ auth.get("/google/callback", async (c) => {
|
|||
user = byId(id);
|
||||
} else if (byEmail.google_sub) {
|
||||
console.warn(`google login: ${identity.email} is linked to another Google account`);
|
||||
return backToLogin(c, "linked_elsewhere");
|
||||
return back("linked_elsewhere");
|
||||
} else {
|
||||
// Before linking: a refused sign-in mustn't change the account.
|
||||
if (byEmail.is_active !== 1) return backToLogin(c, "disabled");
|
||||
if (byEmail.is_active !== 1) return back("disabled");
|
||||
db.prepare(`UPDATE admin_users SET google_sub = ? WHERE id = ?`).run(identity.sub, byEmail.id);
|
||||
console.log(`google account linked to ${byEmail.email}`);
|
||||
user = byEmail;
|
||||
|
|
@ -266,23 +294,30 @@ auth.get("/google/callback", async (c) => {
|
|||
// and with access groups switched off none gets in (it can't be
|
||||
// rechecked, so it would keep its last role for good).
|
||||
if (user.access_source === "group" && user.role !== "superadmin") {
|
||||
if (!accessEnabled(db)) return backToLogin(c, "not_in_group");
|
||||
if (user.is_active !== 1 && user.group_disabled !== 1) return backToLogin(c, "disabled");
|
||||
if (!accessEnabled(db)) return back("not_in_group");
|
||||
if (user.is_active !== 1 && user.group_disabled !== 1) return back("disabled");
|
||||
const found = await roleFromGroups();
|
||||
if (found.failed) return backToLogin(c, "groups_unreachable");
|
||||
if (found.failed) return back("groups_unreachable");
|
||||
applyGroupRole(db, user, found.role);
|
||||
if (!found.role) return backToLogin(c, "not_in_group");
|
||||
if (!found.role) return back("not_in_group");
|
||||
user = byId(user.id);
|
||||
}
|
||||
|
||||
if (user.is_active !== 1) return backToLogin(c, "disabled");
|
||||
if (user.is_active !== 1) return back("disabled");
|
||||
|
||||
createSession(db, c, user.id);
|
||||
// The invite is taken up: its link stops working.
|
||||
db.prepare(
|
||||
`UPDATE admin_users SET last_login_at = datetime('now'), name = COALESCE(name, ?) WHERE id = ?`,
|
||||
).run(identity.name, user.id);
|
||||
`UPDATE admin_users
|
||||
SET last_login_at = datetime('now'), name = COALESCE(name, ?), google_sub = COALESCE(google_sub, ?),
|
||||
invite_hash = NULL, invite_expires_at = NULL
|
||||
WHERE id = ?`,
|
||||
).run(identity.name, identity.sub, user.id);
|
||||
console.log(`login ${user.email} (google)`);
|
||||
|
||||
// A profile account, or a sign-in from the site, goes to the
|
||||
// profile page; the admin's goes back where it was headed.
|
||||
if (user.role === "member" || from === "account") return c.redirect("/account", 302);
|
||||
// Checked again: the cookie came back from the browser.
|
||||
return c.redirect(safeNext(saved.next), 302);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ function loadAuthors(db, ids) {
|
|||
.prepare(
|
||||
`SELECT a.post_id, p.id, p.display_name, p.pronouns, p.tagline, p.photo
|
||||
FROM blog_post_authors a
|
||||
JOIN people p ON p.id = a.person_id AND p.is_published = 1
|
||||
JOIN v_people_public p ON p.id = a.person_id AND p.is_published = 1
|
||||
WHERE a.post_id IN (${marks(ids.length)})
|
||||
ORDER BY a.post_id, a.sort_order`,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -437,7 +437,7 @@ function attachAwards(db, orgs) {
|
|||
`SELECT a.id, a.org_id, a.name, a.description, a.logo,
|
||||
(SELECT COUNT(*)
|
||||
FROM person_awards pa
|
||||
JOIN people p ON p.id = pa.person_id AND p.is_published = 1
|
||||
JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
|
||||
WHERE pa.award_id = a.id AND pa.is_public = 1) AS recipient_count
|
||||
FROM awards a
|
||||
WHERE a.org_id IN (${marks(ids.length)}) AND a.is_published = 1 AND a.is_listed = 1
|
||||
|
|
@ -579,7 +579,7 @@ content.get("/events/:id", (c) => {
|
|||
pa.person_id, p.display_name, p.photo
|
||||
FROM person_awards pa
|
||||
JOIN awards a ON a.id = pa.award_id AND a.is_published = 1
|
||||
JOIN people p ON p.id = pa.person_id AND p.is_published = 1
|
||||
JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
|
||||
WHERE pa.event_id = ? AND pa.is_public = 1
|
||||
ORDER BY a.sort_order, a.name, COALESCE(p.sort_name, p.display_name)`,
|
||||
)
|
||||
|
|
@ -774,7 +774,7 @@ content.get("/awards", (c) => {
|
|||
`SELECT a.*, o.name AS org_name, o.kind AS org_kind,
|
||||
(SELECT COUNT(*)
|
||||
FROM person_awards pa
|
||||
JOIN people p ON p.id = pa.person_id AND p.is_published = 1
|
||||
JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
|
||||
WHERE pa.award_id = a.id AND pa.is_public = 1) AS recipient_count
|
||||
FROM awards a
|
||||
LEFT JOIN organizations o ON o.id = a.org_id AND o.is_published = 1
|
||||
|
|
@ -818,7 +818,7 @@ content.get("/awards/:id", (c) => {
|
|||
p.display_name, p.photo, p.tagline,
|
||||
e.id AS event_id, e.title AS event_title
|
||||
FROM person_awards pa
|
||||
JOIN people p ON p.id = pa.person_id AND p.is_published = 1
|
||||
JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
|
||||
LEFT JOIN events e ON e.id = pa.event_id AND e.is_published = 1
|
||||
WHERE pa.award_id = ? AND pa.is_public = 1
|
||||
ORDER BY pa.awarded_on DESC, COALESCE(p.sort_name, p.display_name)`,
|
||||
|
|
|
|||
|
|
@ -188,7 +188,7 @@ function loadRosters(db, rows) {
|
|||
`SELECT tep.entry_id, tep.person_id, tep.note,
|
||||
p.display_name, p.photo
|
||||
FROM timeline_entry_people tep
|
||||
JOIN people p ON p.id = tep.person_id AND p.is_published = 1
|
||||
JOIN v_people_public p ON p.id = tep.person_id AND p.is_published = 1
|
||||
WHERE tep.entry_id IN (${marks(ids.length)})
|
||||
ORDER BY tep.entry_id, tep.sort_order`,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -66,7 +66,7 @@ const STAT_QUERIES = {
|
|||
people: `SELECT COUNT(*) AS n FROM people WHERE is_published = 1 AND is_listed = 1`,
|
||||
awards_given: `SELECT COUNT(*) AS n
|
||||
FROM person_awards pa
|
||||
JOIN people p ON p.id = pa.person_id AND p.is_published = 1
|
||||
JOIN v_people_public p ON p.id = pa.person_id AND p.is_published = 1
|
||||
JOIN awards a ON a.id = pa.award_id AND a.is_published = 1
|
||||
WHERE pa.is_public = 1`,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -7,7 +7,8 @@
|
|||
can say no while production says yes
|
||||
GET /anything the built index.html, its title, description,
|
||||
preview image, canonical link and structured
|
||||
data filled in for that path (pageMeta.js)
|
||||
data filled in for that path (pageMeta.js),
|
||||
and this visitor's menus (siteNav.js)
|
||||
|
||||
In production nginx serves files that exist (the JS, CSS,
|
||||
uploads) itself and sends everything else here, so a shared link
|
||||
|
|
@ -35,6 +36,7 @@ import { fileURLToPath } from "node:url";
|
|||
|
||||
import { Hono } from "hono";
|
||||
|
||||
import { currentUser } from "../auth.js";
|
||||
import { metaFor, renderPage, robotsTxt, siteFor, sitemap } from "../pageMeta.js";
|
||||
import { CACHE, NO_STORE } from "../shape.js";
|
||||
|
||||
|
|
@ -109,7 +111,8 @@ pages.get("*", (c, next) => {
|
|||
let meta;
|
||||
let page;
|
||||
try {
|
||||
meta = metaFor(c.get("db"), pathname);
|
||||
// Who's asking decides whether a hidden page is there (siteNav.js).
|
||||
meta = metaFor(c.get("db"), pathname, currentUser(c.get("db"), c));
|
||||
page = renderPage(html, meta);
|
||||
} catch (err) {
|
||||
warnOnce(
|
||||
|
|
|
|||
|
|
@ -129,7 +129,7 @@ people.get("/people", (c) => {
|
|||
p.bio,
|
||||
o.id AS primary_org_id,
|
||||
o.name AS primary_org_name
|
||||
FROM people p
|
||||
FROM v_people_public p
|
||||
LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1
|
||||
WHERE p.id IN (${marks(ids.length)})
|
||||
AND p.is_published = 1`,
|
||||
|
|
@ -167,7 +167,7 @@ people.get("/directories/:tag", (c) => {
|
|||
o.id AS primary_org_id,
|
||||
o.name AS primary_org_name
|
||||
FROM person_tags t
|
||||
JOIN people p ON p.id = t.person_id AND p.is_published = 1 AND p.is_listed = 1
|
||||
JOIN v_people_public p ON p.id = t.person_id AND p.is_published = 1 AND p.is_listed = 1
|
||||
LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1
|
||||
WHERE t.tag_id = ?
|
||||
ORDER BY COALESCE(p.sort_name, p.display_name)`,
|
||||
|
|
@ -221,7 +221,7 @@ people.get("/people/:id", (c) => {
|
|||
o.id AS primary_org_id,
|
||||
o.name AS primary_org_name,
|
||||
o.kind AS primary_org_kind
|
||||
FROM people p
|
||||
FROM v_people_public p
|
||||
LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1
|
||||
WHERE p.id = ? AND p.is_published = 1`,
|
||||
)
|
||||
|
|
|
|||
198
server/src/routes/profiles.js
Normal file
198
server/src/routes/profiles.js
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
PROFILE ACCOUNT ROUTES (076): Data → Profile accounts, mounted
|
||||
under /api/admin, admins and up
|
||||
|
||||
GET /profiles every profile account, and the
|
||||
claims waiting
|
||||
POST /profiles { email, name }: a new account,
|
||||
invited (its link comes back)
|
||||
POST /profiles/:id/invite a new link, replacing the old;
|
||||
{ email: true } also emails it
|
||||
PATCH /profiles/:id { person_id, discord_id,
|
||||
discord_name, is_active }: an
|
||||
admin's own say
|
||||
DELETE /profiles/:id remove the account
|
||||
POST /profiles/claims/:id/approve the request's person is theirs
|
||||
POST /profiles/claims/:id/decline
|
||||
|
||||
Only member accounts are listed or changed here. The admin roles
|
||||
are the Panel's (superadmins), so an admin can't make or touch
|
||||
another admin from this page.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { Hono } from "hono";
|
||||
|
||||
import { destroyAllSessionsFor, logSafe, requireRole } from "../auth.js";
|
||||
import { tx } from "../db.js";
|
||||
import { emailInvite, issueInvite } from "../invites.js";
|
||||
import { mailReady } from "../googleService.js";
|
||||
import { NO_STORE } from "../shape.js";
|
||||
|
||||
const profiles = new Hono();
|
||||
|
||||
profiles.use("/profiles", requireRole("admin"));
|
||||
profiles.use("/profiles/*", requireRole("admin"));
|
||||
|
||||
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
|
||||
async function body(c) {
|
||||
try {
|
||||
return (await c.req.json()) ?? {};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const member = (db, id) =>
|
||||
db.prepare(`SELECT * FROM admin_users WHERE id = ? AND role = 'member'`).get(Number(id)) ?? null;
|
||||
|
||||
profiles.get("/profiles", (c) => {
|
||||
const db = c.get("db");
|
||||
const accounts = db
|
||||
.prepare(
|
||||
`SELECT u.id, u.email, u.name, u.is_active, u.created_at, u.last_login_at,
|
||||
u.invited_at, u.invite_expires_at,
|
||||
(u.invite_hash IS NOT NULL AND u.invite_expires_at > datetime('now')) AS invite_open,
|
||||
(u.password_hash IS NOT NULL OR u.google_sub IS NOT NULL) AS signed_up,
|
||||
u.person_id, p.display_name AS person_name,
|
||||
u.discord_id, u.discord_name
|
||||
FROM admin_users u
|
||||
LEFT JOIN people p ON p.id = u.person_id
|
||||
WHERE u.role = 'member'
|
||||
ORDER BY u.created_at DESC, u.id DESC`,
|
||||
)
|
||||
.all();
|
||||
const claims = db
|
||||
.prepare(
|
||||
`SELECT c.id, c.account_id, u.email, u.name, c.person_id, p.display_name AS person_name,
|
||||
c.message, c.created_at
|
||||
FROM person_claims c
|
||||
JOIN admin_users u ON u.id = c.account_id
|
||||
JOIN people p ON p.id = c.person_id
|
||||
WHERE c.status = 'pending'
|
||||
ORDER BY c.created_at`,
|
||||
)
|
||||
.all();
|
||||
return c.json({ accounts, claims, mail: mailReady() }, 200, NO_STORE);
|
||||
});
|
||||
|
||||
profiles.post("/profiles", async (c) => {
|
||||
const data = await body(c);
|
||||
if (!data) return c.json({ error: "Expected a JSON body." }, 400);
|
||||
const db = c.get("db");
|
||||
const email = String(data.email ?? "").trim().toLowerCase().slice(0, 254);
|
||||
const name = String(data.name ?? "").trim().slice(0, 120) || null;
|
||||
if (!EMAIL.test(email)) return c.json({ error: "Enter an email address.", fields: { email: "Needed." } }, 422);
|
||||
if (db.prepare(`SELECT 1 FROM admin_users WHERE email = ?`).get(email)) {
|
||||
return c.json({ error: "That email already has an account.", fields: { email: "Already has one." } }, 409);
|
||||
}
|
||||
|
||||
const id = db
|
||||
.prepare(
|
||||
`INSERT INTO admin_users (email, name, role, access_source) VALUES (?, ?, 'member', 'invite')`,
|
||||
)
|
||||
.run(email, name).lastInsertRowid;
|
||||
const link = issueInvite(db, id, c.get("user").id);
|
||||
console.log(`profile account ${logSafe(email)} invited by ${c.get("user").email}`);
|
||||
return c.json({ id: Number(id), link }, 201, NO_STORE);
|
||||
});
|
||||
|
||||
profiles.post("/profiles/:id/invite", async (c) => {
|
||||
const db = c.get("db");
|
||||
const account = member(db, c.req.param("id"));
|
||||
if (!account) return c.json({ error: "No such profile account." }, 404);
|
||||
const data = (await body(c)) ?? {};
|
||||
|
||||
const link = issueInvite(db, account.id, c.get("user").id);
|
||||
if (data.email) {
|
||||
try {
|
||||
await emailInvite(db, account, link);
|
||||
} catch (err) {
|
||||
console.warn(`invite email to ${account.email} failed: ${err.message}`);
|
||||
return c.json({ link, emailed: false, error: `The email didn't go: ${err.message}` }, 502, NO_STORE);
|
||||
}
|
||||
}
|
||||
console.log(`invite for ${account.email} ${data.email ? "emailed" : "issued"} by ${c.get("user").email}`);
|
||||
return c.json({ link, emailed: Boolean(data.email) }, 200, NO_STORE);
|
||||
});
|
||||
|
||||
profiles.patch("/profiles/:id", async (c) => {
|
||||
const db = c.get("db");
|
||||
const account = member(db, c.req.param("id"));
|
||||
if (!account) return c.json({ error: "No such profile account." }, 404);
|
||||
const data = await body(c);
|
||||
if (!data) return c.json({ error: "Expected a JSON body." }, 400);
|
||||
|
||||
const sets = [];
|
||||
const values = [];
|
||||
if ("person_id" in data) {
|
||||
const personId = data.person_id ? String(data.person_id) : null;
|
||||
if (personId) {
|
||||
if (!db.prepare(`SELECT 1 FROM people WHERE id = ?`).get(personId)) {
|
||||
return c.json({ error: "No such person.", fields: { person_id: "Pick one." } }, 422);
|
||||
}
|
||||
const holder = db.prepare(`SELECT email FROM admin_users WHERE person_id = ? AND id <> ?`).get(personId, account.id);
|
||||
if (holder) return c.json({ error: `${holder.email} already has that profile.` }, 409);
|
||||
}
|
||||
sets.push("person_id = ?");
|
||||
values.push(personId);
|
||||
}
|
||||
if ("discord_id" in data) {
|
||||
const discordId = data.discord_id ? String(data.discord_id).trim() : null;
|
||||
if (discordId && !/^\d{5,25}$/.test(discordId)) {
|
||||
return c.json({ error: "A Discord id is the long number (Developer Mode → Copy User ID).", fields: { discord_id: "Digits only." } }, 422);
|
||||
}
|
||||
if (discordId && db.prepare(`SELECT 1 FROM admin_users WHERE discord_id = ? AND id <> ?`).get(discordId, account.id)) {
|
||||
return c.json({ error: "Another account has that Discord id." }, 409);
|
||||
}
|
||||
sets.push("discord_id = ?", "discord_name = ?");
|
||||
values.push(discordId, discordId ? String(data.discord_name ?? "").trim().slice(0, 100) || null : null);
|
||||
}
|
||||
if ("is_active" in data) {
|
||||
sets.push("is_active = ?");
|
||||
values.push(data.is_active ? 1 : 0);
|
||||
}
|
||||
if (!sets.length) return c.json({ error: "Nothing to change." }, 422);
|
||||
|
||||
db.prepare(`UPDATE admin_users SET ${sets.join(", ")} WHERE id = ?`).run(...values, account.id);
|
||||
if ("is_active" in data && !data.is_active) destroyAllSessionsFor(db, account.id);
|
||||
console.log(`profile account ${account.email} changed by ${c.get("user").email}`);
|
||||
return c.body(null, 204);
|
||||
});
|
||||
|
||||
profiles.delete("/profiles/:id", (c) => {
|
||||
const db = c.get("db");
|
||||
const account = member(db, c.req.param("id"));
|
||||
if (!account) return c.json({ error: "No such profile account." }, 404);
|
||||
db.prepare(`DELETE FROM admin_users WHERE id = ?`).run(account.id);
|
||||
console.log(`profile account ${account.email} removed by ${c.get("user").email}`);
|
||||
return c.body(null, 204);
|
||||
});
|
||||
|
||||
function decide(c, approve) {
|
||||
const db = c.get("db");
|
||||
const claim = db
|
||||
.prepare(`SELECT * FROM person_claims WHERE id = ? AND status = 'pending'`)
|
||||
.get(Number(c.req.param("id")));
|
||||
if (!claim) return c.json({ error: "That request was already answered." }, 404);
|
||||
|
||||
const taken = tx(db, () => {
|
||||
if (approve) {
|
||||
const holder = db.prepare(`SELECT email FROM admin_users WHERE person_id = ?`).get(claim.person_id);
|
||||
if (holder) return holder.email;
|
||||
db.prepare(`UPDATE admin_users SET person_id = ? WHERE id = ?`).run(claim.person_id, claim.account_id);
|
||||
}
|
||||
db.prepare(
|
||||
`UPDATE person_claims SET status = ?, decided_at = datetime('now'), decided_by = ? WHERE id = ?`,
|
||||
).run(approve ? "approved" : "declined", c.get("user").id, claim.id);
|
||||
return null;
|
||||
});
|
||||
if (taken) return c.json({ error: `${taken} already has that profile. Decline this one.` }, 409);
|
||||
console.log(`claim ${claim.id} (${claim.person_id}) ${approve ? "approved" : "declined"} by ${c.get("user").email}`);
|
||||
return c.body(null, 204);
|
||||
}
|
||||
|
||||
profiles.post("/profiles/claims/:id/approve", (c) => decide(c, true));
|
||||
profiles.post("/profiles/claims/:id/decline", (c) => decide(c, false));
|
||||
|
||||
export default profiles;
|
||||
|
|
@ -1,11 +1,15 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
SITE PAGE ROUTES: read-only, mounted under /api
|
||||
|
||||
GET /nav this visitor's header and footer links and
|
||||
the hidden pages (siteNav.js); not cached,
|
||||
since it depends on who's signed in
|
||||
GET /site-pages every site page's section headings, for
|
||||
the header's dropdowns and the side nav
|
||||
GET /site-pages/:id one page's sections, in order: heading,
|
||||
accent, preset (and an events preset's
|
||||
filter and view), and its blocks
|
||||
filter and view), and its blocks; Not
|
||||
found for a hidden page, below viewer
|
||||
|
||||
Edited in the admin as Pages → each page
|
||||
(admin-schema/sitePages.js). Blocks are shaped as on any record
|
||||
|
|
@ -13,10 +17,17 @@
|
|||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { Hono } from "hono";
|
||||
import { json, loadBlocks } from "../shape.js";
|
||||
import { currentUser } from "../auth.js";
|
||||
import { hiddenPaths, navFor, seesHidden } from "../siteNav.js";
|
||||
import { NO_STORE, json, loadBlocks } from "../shape.js";
|
||||
|
||||
const sitePages = new Hono();
|
||||
|
||||
sitePages.get("/nav", (c) => {
|
||||
const db = c.get("db");
|
||||
return c.json({ nav: navFor(db, currentUser(db, c)) }, 200, NO_STORE);
|
||||
});
|
||||
|
||||
sitePages.get("/site-pages", (c) => {
|
||||
const rows = c
|
||||
.get("db")
|
||||
|
|
@ -31,7 +42,8 @@ sitePages.get("/site-pages", (c) => {
|
|||
sitePages.get("/site-pages/:id", (c) => {
|
||||
const db = c.get("db");
|
||||
const id = c.req.param("id");
|
||||
if (!db.prepare(`SELECT 1 FROM site_pages WHERE id = ?`).get(id)) {
|
||||
const hidden = hiddenPaths(db).has(`/${id}`);
|
||||
if (!db.prepare(`SELECT 1 FROM site_pages WHERE id = ?`).get(id) || (hidden && !seesHidden(currentUser(db, c)))) {
|
||||
return c.json({ error: "No such page." }, 404);
|
||||
}
|
||||
|
||||
|
|
@ -53,7 +65,9 @@ sitePages.get("/site-pages/:id", (c) => {
|
|||
picked.set(section_id, [...(picked.get(section_id) ?? []), org_id]);
|
||||
}
|
||||
|
||||
return json(c, {
|
||||
// A hidden page is only for those signed in: never kept.
|
||||
const send = hidden ? (body) => c.json(body, 200, NO_STORE) : (body) => json(c, body);
|
||||
return send({
|
||||
page: {
|
||||
id,
|
||||
sections: rows.map(({ id: sectionId, ...section }) => ({
|
||||
|
|
|
|||
|
|
@ -27,11 +27,14 @@ export function loadLinks(db, ownerKind, ids) {
|
|||
const out = new Map();
|
||||
if (ids.length === 0) return out;
|
||||
|
||||
// A person who took their links off the site (people.hide_links,
|
||||
// 076) has none here.
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT owner_id, kind, platform, label, url, is_primary
|
||||
FROM links
|
||||
WHERE owner_kind = ? AND owner_id IN (${placeholders(ids.length)})
|
||||
AND NOT (owner_kind = 'person' AND owner_id IN (SELECT id FROM people WHERE hide_links = 1))
|
||||
ORDER BY owner_id, sort_order`,
|
||||
)
|
||||
.all(ownerKind, ...ids);
|
||||
|
|
@ -106,7 +109,7 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") {
|
|||
p.id AS person_id, p.display_name AS person_name,
|
||||
p.photo AS person_photo, p.tagline AS person_tagline
|
||||
FROM content_block_items i
|
||||
LEFT JOIN people p ON p.id = i.person_id AND p.is_published = 1
|
||||
LEFT JOIN v_people_public p ON p.id = i.person_id AND p.is_published = 1
|
||||
WHERE i.block_id IN (${placeholders(blockIds.length)})
|
||||
ORDER BY i.block_id, i.sort_order`,
|
||||
)
|
||||
|
|
@ -266,7 +269,7 @@ const FEATURED_REFS = {
|
|||
person: {
|
||||
sql: (marks) =>
|
||||
`SELECT id, display_name AS title, tagline AS blurb, photo
|
||||
FROM people WHERE is_published = 1 AND id IN (${marks})`,
|
||||
FROM v_people_public WHERE is_published = 1 AND id IN (${marks})`,
|
||||
image: (row) => (row.photo ? { file: row.photo, kind: "person" } : null),
|
||||
},
|
||||
team: {
|
||||
|
|
|
|||
65
server/src/siteNav.js
Normal file
65
server/src/siteNav.js
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
SITE NAVIGATION
|
||||
|
||||
Pages → Navigation (075_site_nav.sql): the header's and footer's
|
||||
links, and which static pages are hidden. Read by pageMeta.js
|
||||
(window.__SITE__, the page's status, the sitemap) and served as
|
||||
GET /api/nav for the app (routes/sitePages.js).
|
||||
|
||||
A hidden page answers Not found to anyone below viewer, and its
|
||||
links are left out of what they're sent; a viewer and up sees
|
||||
both, and the page says it's hidden (Layout.tsx). Who's asking
|
||||
is the session cookie, so the same page can be hidden from one
|
||||
visitor and shown to the next: the HTML is no-cache already.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { hasRole } from "./auth.js";
|
||||
|
||||
/* Who sees hidden pages. */
|
||||
export const SEES_HIDDEN = "viewer";
|
||||
|
||||
export const seesHidden = (user) => hasRole(user, SEES_HIDDEN);
|
||||
|
||||
/* The paths whose pages are hidden, eg. '/shop'. */
|
||||
export function hiddenPaths(db) {
|
||||
return new Set(
|
||||
db
|
||||
.prepare(`SELECT path FROM site_nav_pages WHERE nav_id = 'site' AND is_hidden = 1`)
|
||||
.all()
|
||||
.map((row) => row.path),
|
||||
);
|
||||
}
|
||||
|
||||
/* A link's page: its path without the #section or ?query, or null
|
||||
for an address off the site. */
|
||||
const pageOf = (href) => (/^\//.test(href) ? href.split(/[?#]/)[0].replace(/(.)\/+$/, "$1") : null);
|
||||
|
||||
/* Whether this path's page is one the user can't see. */
|
||||
export function hiddenFrom(db, user, pathname) {
|
||||
return !seesHidden(user) && hiddenPaths(db).has(pageOf(pathname));
|
||||
}
|
||||
|
||||
/* What the app draws its menus from: every link this user may
|
||||
follow, and the hidden pages' paths (so the app can answer Not
|
||||
found, or say a page is hidden, without asking again). */
|
||||
export function navFor(db, user) {
|
||||
const hidden = hiddenPaths(db);
|
||||
const sees = seesHidden(user);
|
||||
const links = db
|
||||
.prepare(
|
||||
`SELECT place, label, path, parent_path, style, new_tab
|
||||
FROM site_nav_links WHERE nav_id = 'site' ORDER BY sort_order, id`,
|
||||
)
|
||||
.all()
|
||||
.filter((link) => sees || !hidden.has(pageOf(link.path)))
|
||||
.map((link) => ({
|
||||
place: link.place,
|
||||
label: link.label,
|
||||
path: link.path,
|
||||
parent: link.parent_path || null,
|
||||
filled: link.style === "filled",
|
||||
newTab: link.new_tab === 1,
|
||||
}));
|
||||
|
||||
return { links, hidden: [...hidden], seesHidden: sees };
|
||||
}
|
||||
|
|
@ -54,6 +54,10 @@
|
|||
"title": "Privacy Policy",
|
||||
"description": "How Next Generation of Unity collects, uses, and protects your information."
|
||||
},
|
||||
"/shop": {
|
||||
"title": "Shop",
|
||||
"description": "Shirts, stickers and more from Next Generation of Unity. Every purchase supports our retreats and programs."
|
||||
},
|
||||
"/terms": {
|
||||
"title": "Terms of Service",
|
||||
"description": "The terms that apply when you use this site and our programs."
|
||||
|
|
|
|||
25
src/App.tsx
25
src/App.tsx
|
|
@ -49,8 +49,8 @@ const lazyPage = (load) =>
|
|||
throw err
|
||||
}),
|
||||
)
|
||||
// Community, Retreats, Resources, Organization and History: each
|
||||
// built in the admin from sections.
|
||||
// Community, Retreats, Resources, Organization, History and Shop:
|
||||
// each built in the admin from sections.
|
||||
const SitePage = lazyPage(() => import("./pages/SitePage.tsx"))
|
||||
const Feedback = lazyPage(() => import("./pages/Feedback.tsx"))
|
||||
const Request = lazyPage(() => import("./pages/Request.tsx"))
|
||||
|
|
@ -59,6 +59,10 @@ const QrCodes = lazyPage(() => import("./pages/QrCodes.tsx"))
|
|||
const Privacy = lazyPage(() => import("./pages/Privacy.tsx"))
|
||||
const Terms = lazyPage(() => import("./pages/Terms.tsx"))
|
||||
const NotFound = lazyPage(() => import("./pages/NotFound.tsx"))
|
||||
// Profile accounts (076): signing in, an invite's welcome, the profile.
|
||||
const SignIn = lazyPage(() => import("./pages/SignIn.tsx"))
|
||||
const AccountWelcome = lazyPage(() => import("./pages/AccountWelcome.tsx"))
|
||||
const Account = lazyPage(() => import("./pages/Account.tsx"))
|
||||
|
||||
/*Entity Pages*/
|
||||
const EventDetail = lazyPage(() => import("./pages/EventDetail.tsx"))
|
||||
|
|
@ -82,12 +86,15 @@ const AdminMedia = lazyPage(() => import("./pages/admin/AdminMedia.tsx"))
|
|||
const AdminClips = lazyPage(() => import("./pages/admin/AdminClips.tsx"))
|
||||
const AdminVideoFrames = lazyPage(() => import("./pages/admin/AdminVideoFrames.tsx"))
|
||||
const AdminNewsletter = lazyPage(() => import("./pages/admin/AdminNewsletter.tsx"))
|
||||
const AdminProfiles = lazyPage(() => import("./pages/admin/AdminProfiles.tsx"))
|
||||
const EntityList = lazyPage(() => import("./pages/admin/EntityList.tsx"))
|
||||
const EntityEdit = lazyPage(() => import("./pages/admin/EntityEdit.tsx"))
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
{/* The whole app: the site shows a profile link and hidden pages by who's signed in. */}
|
||||
<AuthProvider>
|
||||
<Routes>
|
||||
{/* Layout renders the nav once and swaps page content into <Outlet /> */}
|
||||
<Route element={<Layout />}>
|
||||
|
|
@ -107,12 +114,16 @@ export default function App() {
|
|||
<Route path="organization" element={<SitePage key="organization" id="organization" />} />
|
||||
<Route path="resources" element={<SitePage key="resources" id="resources" />} />
|
||||
<Route path="history" element={<SitePage key="history" id="history" />} />
|
||||
<Route path="shop" element={<SitePage key="shop" id="shop" />} />
|
||||
<Route path="feedback" element={<Feedback />} />
|
||||
<Route path="request" element={<Request />} />
|
||||
<Route path="qr" element={<QrCodes />} />
|
||||
<Route path="give" element={<Giving />} />
|
||||
<Route path="privacy" element={<Privacy />} />
|
||||
<Route path="terms" element={<Terms />} />
|
||||
<Route path="sign-in" element={<SignIn />} />
|
||||
<Route path="account" element={<Account />} />
|
||||
<Route path="account/welcome" element={<AccountWelcome />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Route>
|
||||
{/* A schedule as a slideshow for a screen: full screen, no Layout. */}
|
||||
|
|
@ -126,11 +137,9 @@ export default function App() {
|
|||
/>
|
||||
<Route
|
||||
element={
|
||||
<AuthProvider>
|
||||
<Suspense fallback={null}>
|
||||
<Outlet />
|
||||
</Suspense>
|
||||
</AuthProvider>
|
||||
<Suspense fallback={null}>
|
||||
<Outlet />
|
||||
</Suspense>
|
||||
}
|
||||
>
|
||||
<Route path="/admin/login" element={<AdminLogin />} />
|
||||
|
|
@ -151,6 +160,7 @@ export default function App() {
|
|||
</Route>
|
||||
<Route element={<RequireRole role="admin" />}>
|
||||
<Route path="clips" element={<AdminClips />} />
|
||||
<Route path="profiles" element={<AdminProfiles />} />
|
||||
</Route>
|
||||
<Route path=":entity" element={<EntityList />} />
|
||||
<Route path=":entity/:id" element={<EntityEdit />} />
|
||||
|
|
@ -158,6 +168,7 @@ export default function App() {
|
|||
</Route>
|
||||
</Route>
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,31 +1,18 @@
|
|||
import { Link } from "react-router-dom";
|
||||
import { PAGE_LINKS, NAV_ACTIONS } from "../navConfig.ts";
|
||||
import { useNavSections } from "../lib/navSections.ts";
|
||||
import { useSiteNav } from "../lib/useSiteNav.ts";
|
||||
import { useAuth } from "../lib/auth.tsx";
|
||||
import SiteLink from "./SiteLink.tsx";
|
||||
import siteLogo from "../assets/logos/NGU_Logo.svg";
|
||||
import PlatformIcon from "./PlatformIcon.tsx";
|
||||
import { ORGANIZATION_DETAILS as Organization_Details } from "../data/organizationDetails.ts";
|
||||
import { SOCIAL_LINKS } from "../data/socialLinks.ts";
|
||||
|
||||
// Give's destination lives in navConfig so the footer and the nav can't drift.
|
||||
// Only the label differs down here.
|
||||
const giveAction = NAV_ACTIONS.find((a) => a.variant === "fancy");
|
||||
|
||||
/* An internal route, or an off-site address opened in a new tab. */
|
||||
type TouchLink = { label: string } & (
|
||||
| { external?: false; to: string }
|
||||
| { external: true; href: string }
|
||||
);
|
||||
|
||||
const Get_In_Touch: TouchLink[] = [
|
||||
{ label: "Feedback", to: "/feedback"},
|
||||
{ label: "Request", to: "/request" },
|
||||
{ label: "Contact Us", to: "/organization#contact" },
|
||||
];
|
||||
|
||||
const Footer_Links = [
|
||||
{ label: "Privacy Policy", to: "/privacy" },
|
||||
{ label: "Terms of Service", to: "/terms" },
|
||||
];
|
||||
/* Every link here is Pages → Navigation's (useSiteNav): the filled
|
||||
header buttons (Give) beside the logo, Get in Touch, the site map
|
||||
(the header's pages, their sections and the pages set under them)
|
||||
and the bottom row. The bottom row ends with the profile account's
|
||||
way in (076): Sign in, or Your profile once signed in. */
|
||||
|
||||
const footerLinkClass =
|
||||
"text-white/65 hover:text-[var(--pal-green-2)] text-sm transition-colors";
|
||||
|
|
@ -41,6 +28,8 @@ const headingClass = "text-white/90 text-sm font-semibold mb-4";
|
|||
|
||||
export default function Footer() {
|
||||
const sectionsOf = useNavSections();
|
||||
const nav = useSiteNav();
|
||||
const { user } = useAuth();
|
||||
return (
|
||||
<footer className="py-16 px-6" style={{ background: "#001011" }}>
|
||||
<div className="max-w-6xl mx-auto">
|
||||
|
|
@ -53,17 +42,18 @@ export default function Footer() {
|
|||
<Link to="/" className="inline-block">
|
||||
<img src={siteLogo} alt="Next Generation of Unity" className="h-14 w-auto" />
|
||||
</Link>
|
||||
{giveAction && (
|
||||
<a
|
||||
href={giveAction.to}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="btn inline-block whitespace-nowrap px-6 py-2.5 text-sm text-white transition-transform duration-200 hover:-translate-y-0.5"
|
||||
style={{ background: "var(--color-action)" }}
|
||||
>
|
||||
{giveAction.label}
|
||||
</a>
|
||||
)}
|
||||
{nav.actions
|
||||
.filter((action) => action.filled)
|
||||
.map((action) => (
|
||||
<SiteLink
|
||||
key={`${action.label}${action.path}`}
|
||||
link={action}
|
||||
className="btn inline-block whitespace-nowrap px-6 py-2.5 text-sm text-white transition-transform duration-200 hover:-translate-y-0.5"
|
||||
style={{ background: "var(--color-action)" }}
|
||||
>
|
||||
{action.label}
|
||||
</SiteLink>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<address className="mt-5 not-italic text-sm leading-relaxed text-white/60">
|
||||
|
|
@ -100,22 +90,11 @@ export default function Footer() {
|
|||
|
||||
<h2 className={headingClass}>Get in Touch</h2>
|
||||
<ul className="flex flex-col gap-3">
|
||||
{Get_In_Touch.map((link) => (
|
||||
<li key={link.label}>
|
||||
{link.external ? (
|
||||
<a
|
||||
href={link.href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className={pageLinkClass}
|
||||
>
|
||||
{link.label}
|
||||
</a>
|
||||
) : (
|
||||
<Link to={link.to} className={pageLinkClass}>
|
||||
{link.label}
|
||||
</Link>
|
||||
)}
|
||||
{nav.footer.map((link) => (
|
||||
<li key={`${link.label}${link.path}`}>
|
||||
<SiteLink link={link} className={pageLinkClass}>
|
||||
{link.label}
|
||||
</SiteLink>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
|
@ -126,13 +105,25 @@ export default function Footer() {
|
|||
<nav aria-label="Site map" className="mb-12 border-t border-white/10 pt-10">
|
||||
<h2 className={headingClass}>Site Map</h2>
|
||||
<ul className="grid grid-cols-2 gap-x-6 gap-y-6 sm:grid-cols-3 lg:grid-cols-6">
|
||||
{PAGE_LINKS.map((page) => {
|
||||
{nav.main.map((page) => {
|
||||
const sections = sectionsOf(page.path);
|
||||
return (
|
||||
<li key={page.path}>
|
||||
<Link to={page.path} className={pageLinkClass}>
|
||||
<SiteLink link={page} className={pageLinkClass}>
|
||||
{page.label}
|
||||
</Link>
|
||||
</SiteLink>
|
||||
|
||||
{page.children.length > 0 && (
|
||||
<ul className="flex flex-col">
|
||||
{page.children.map((child) => (
|
||||
<li key={child.path}>
|
||||
<SiteLink link={child} className={pageLinkClass}>
|
||||
{child.label}
|
||||
</SiteLink>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{sections.length > 0 && (
|
||||
<ul className="mt-1 flex flex-col">
|
||||
|
|
@ -156,12 +147,15 @@ export default function Footer() {
|
|||
|
||||
<div className="border-t border-white/10 pt-8 flex flex-col md:flex-row items-center justify-between gap-4">
|
||||
<p className="text-white/65 text-sm">© 2026 Next Generation of Unity. All rights reserved.</p>
|
||||
<div className="flex gap-6">
|
||||
{Footer_Links.map((link) => (
|
||||
<Link key={link.label} to={link.to} className={footerLinkClass}>
|
||||
<div className="flex flex-wrap justify-center gap-x-6 gap-y-2">
|
||||
{nav.legal.map((link) => (
|
||||
<SiteLink key={`${link.label}${link.path}`} link={link} className={footerLinkClass}>
|
||||
{link.label}
|
||||
</Link>
|
||||
</SiteLink>
|
||||
))}
|
||||
<Link to={user ? "/account" : "/sign-in"} className={footerLinkClass}>
|
||||
{user ? "Your profile" : "Sign in"}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
12
src/components/GoogleLogo.tsx
Normal file
12
src/components/GoogleLogo.tsx
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
/* Google's "G", for the Sign in with Google buttons: a brand mark,
|
||||
so drawn as Google gives it rather than as a Phosphor icon. */
|
||||
export default function GoogleLogo({ className = 'h-5 w-5' }: { className?: string }) {
|
||||
return (
|
||||
<svg viewBox="0 0 48 48" className={className} aria-hidden="true">
|
||||
<path fill="#FFC107" d="M43.6 20.5H42V20H24v8h11.3C33.7 32.7 29.2 36 24 36c-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7C34 6.1 29.3 4 24 4 12.9 4 4 12.9 4 24s8.9 20 20 20 20-8.9 20-20c0-1.3-.1-2.4-.4-3.5z" />
|
||||
<path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.7 15.1 19 12 24 12c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7C34 6.1 29.3 4 24 4 16.3 4 9.7 8.3 6.3 14.7z" />
|
||||
<path fill="#4CAF50" d="M24 44c5.2 0 9.9-2 13.4-5.2l-6.2-5.2C29.2 35.1 26.7 36 24 36c-5.2 0-9.6-3.3-11.3-8l-6.5 5C9.5 39.6 16.2 44 24 44z" />
|
||||
<path fill="#1976D2" d="M43.6 20.5H42V20H24v8h11.3c-.8 2.2-2.2 4.2-4.1 5.6l6.2 5.2C37 39.2 44 34 44 24c0-1.3-.1-2.4-.4-3.5z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,8 +1,10 @@
|
|||
import { X, List } from "@phosphor-icons/react";
|
||||
import { Suspense, useState, useEffect, useRef } from "react";
|
||||
import { X, List, EyeSlash, PencilSimple } from "@phosphor-icons/react";
|
||||
import { lazy, Suspense, useState, useEffect, useRef } from "react";
|
||||
import { NavLink, Link, Outlet, useLocation } from "react-router-dom";
|
||||
import { PAGE_LINKS, NAV_ACTIONS } from "../navConfig.ts";
|
||||
import type { NavLink as NavLinkItem } from "../navConfig.ts";
|
||||
import { useNavSections } from "../lib/navSections.ts";
|
||||
import { useSiteNav } from "../lib/useSiteNav.ts";
|
||||
import SiteLink from "./SiteLink.tsx";
|
||||
import Banner from "./Banner.tsx";
|
||||
import siteLogo from "../assets/logos/NGU_Logo.svg";
|
||||
import Footer from "./Footer.tsx";
|
||||
|
|
@ -13,26 +15,22 @@ import ReaderView from "./ReaderView.tsx";
|
|||
import ThemeToggle from "./ThemeToggle.tsx";
|
||||
import { jumpTo } from "../lib/focus.ts";
|
||||
import { useReadingMode } from "../lib/readingMode.ts";
|
||||
import { draftPreview, stopPreview } from "../lib/api.ts";
|
||||
|
||||
const NotFound = lazy(() => import("../pages/NotFound.tsx"));
|
||||
|
||||
/* ── Right-side nav actions ──────────────────────────────── */
|
||||
|
||||
type NavActionItem = {
|
||||
label: string;
|
||||
to: string;
|
||||
variant: string;
|
||||
external?: boolean;
|
||||
};
|
||||
|
||||
const ACTION_VARIANTS: Record<
|
||||
string,
|
||||
{ className: string; style: React.CSSProperties }
|
||||
> = {
|
||||
ghost: {
|
||||
outline: {
|
||||
className:
|
||||
"font-semibold border border-white/30 text-white/85 hover:border-white/60 hover:text-white hover:bg-white/10",
|
||||
style: {},
|
||||
},
|
||||
fancy: {
|
||||
filled: {
|
||||
className: "font-bold text-white hover:scale-105",
|
||||
style: { background: "var(--color-action)" },
|
||||
},
|
||||
|
|
@ -48,33 +46,20 @@ function NavAction({
|
|||
size = "desktop",
|
||||
onClick,
|
||||
}: {
|
||||
item: NavActionItem;
|
||||
item: NavLinkItem;
|
||||
size?: keyof typeof ACTION_SIZES;
|
||||
onClick?: () => void;
|
||||
}) {
|
||||
const v = ACTION_VARIANTS[item.variant] ?? ACTION_VARIANTS.ghost;
|
||||
const v = ACTION_VARIANTS[item.filled ? "filled" : "outline"];
|
||||
const className = `inline-block whitespace-nowrap btn transition-all duration-200 active:scale-[0.98] ${ACTION_SIZES[size]} ${v.className}`;
|
||||
|
||||
return item.external ? (
|
||||
<a
|
||||
href={item.to}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className={className}
|
||||
style={v.style}
|
||||
onClick={onClick}
|
||||
>
|
||||
return (
|
||||
<SiteLink link={item} className={className} style={v.style} onClick={onClick}>
|
||||
{item.label}
|
||||
</a>
|
||||
) : (
|
||||
<Link to={item.to} className={className} style={v.style} onClick={onClick}>
|
||||
{item.label}
|
||||
</Link>
|
||||
</SiteLink>
|
||||
);
|
||||
}
|
||||
|
||||
const navActions = NAV_ACTIONS as NavActionItem[];
|
||||
|
||||
/* ── Layout ──────────────────────────────────────────────── */
|
||||
|
||||
export default function Layout() {
|
||||
|
|
@ -95,6 +80,31 @@ export default function Layout() {
|
|||
const pageRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const sectionsOf = useNavSections();
|
||||
const nav = useSiteNav();
|
||||
// A hidden page (Pages → Navigation) is Not found below viewer; a
|
||||
// viewer and up sees it, under a bar saying so. The server answers
|
||||
// the same (server/src/siteNav.js); this covers the app's own moves.
|
||||
const hiddenHere = nav.isHidden(location.pathname);
|
||||
const page = (
|
||||
<Suspense fallback={null}>{hiddenHere && !nav.seesHidden ? <NotFound /> : <Outlet />}</Suspense>
|
||||
);
|
||||
// A draft's preview tab (api.ts): the page as it would be with the
|
||||
// draft published, for signed-in admin accounts.
|
||||
const previewBar = draftPreview && (
|
||||
<p className="flex flex-wrap items-center justify-center gap-x-3 gap-y-1 bg-[var(--pal-amber-3)] px-6 py-2 text-center text-sm text-[var(--pal-amber-1)] print:hidden">
|
||||
<PencilSimple size={18} weight="bold" aria-hidden="true" />
|
||||
Previewing a draft: this is how it will look once published. Nobody else sees it.
|
||||
<button type="button" onClick={stopPreview} className="font-semibold underline">
|
||||
Stop previewing
|
||||
</button>
|
||||
</p>
|
||||
);
|
||||
const hiddenBar = hiddenHere && nav.seesHidden && (
|
||||
<p className="flex items-center justify-center gap-2 bg-tint px-6 py-2 text-center text-sm text-ink print:hidden">
|
||||
<EyeSlash size={18} weight="bold" aria-hidden="true" />
|
||||
This page is hidden: only signed-in admin accounts can see it. Show it in Pages → Navigation.
|
||||
</p>
|
||||
);
|
||||
|
||||
// Close the mobile menu whenever the route changes
|
||||
useEffect(() => {
|
||||
|
|
@ -177,9 +187,7 @@ export default function Layout() {
|
|||
<main id="main" tabIndex={-1} className="outline-none">
|
||||
<ReaderView source={pageRef} />
|
||||
<div ref={pageRef} hidden>
|
||||
<Suspense fallback={null}>
|
||||
<Outlet />
|
||||
</Suspense>
|
||||
{page}
|
||||
</div>
|
||||
</main>
|
||||
<AccessibilityPanel />
|
||||
|
|
@ -221,14 +229,15 @@ export default function Layout() {
|
|||
none: it's the logo's link too, and its bands are one
|
||||
scroll away. */}
|
||||
<div className="hidden lg:flex items-center gap-6">
|
||||
{PAGE_LINKS.map((page) => {
|
||||
{nav.main.map((page) => {
|
||||
const pageSections = page.path === "/" ? [] : sectionsOf(page.path);
|
||||
const hasMenu = pageSections.length > 0 || page.children.length > 0;
|
||||
return (
|
||||
<div
|
||||
key={page.path}
|
||||
className="group relative"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key !== "Escape" || pageSections.length === 0) return;
|
||||
if (e.key !== "Escape" || !hasMenu) return;
|
||||
setDismissed(page.path);
|
||||
e.currentTarget.querySelector("a")?.focus();
|
||||
}}
|
||||
|
|
@ -250,7 +259,7 @@ export default function Layout() {
|
|||
>
|
||||
{page.label}
|
||||
</NavLink>
|
||||
{pageSections.length > 0 && (
|
||||
{hasMenu && (
|
||||
// pt-3 is the bridge the pointer crosses from the
|
||||
// link into the menu without it closing. Keyboard
|
||||
// focus opens it too, but only keyboard focus
|
||||
|
|
@ -276,6 +285,17 @@ export default function Layout() {
|
|||
</Link>
|
||||
</li>
|
||||
))}
|
||||
{/* Pages set under this one (Pages → Navigation), after its sections. */}
|
||||
{page.children.map((child) => (
|
||||
<li key={child.path}>
|
||||
<SiteLink
|
||||
link={child}
|
||||
className="block px-4 py-2 text-sm font-semibold text-white/90 transition-colors hover:bg-white/10 hover:text-[var(--pal-amber-2)] focus-visible:bg-white/10"
|
||||
>
|
||||
{child.label}
|
||||
</SiteLink>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
|
@ -287,8 +307,8 @@ export default function Layout() {
|
|||
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="hidden lg:flex items-center gap-3">
|
||||
{navActions.map((item) => (
|
||||
<NavAction key={item.label} item={item} />
|
||||
{nav.actions.map((item) => (
|
||||
<NavAction key={`${item.label}${item.path}`} item={item} />
|
||||
))}
|
||||
</div>
|
||||
|
||||
|
|
@ -315,9 +335,9 @@ export default function Layout() {
|
|||
|
||||
{/* Page content */}
|
||||
<main id="main" tabIndex={-1} className="outline-none" inert={mobileMenuOpen}>
|
||||
<Suspense fallback={null}>
|
||||
<Outlet />
|
||||
</Suspense>
|
||||
{previewBar}
|
||||
{hiddenBar}
|
||||
{page}
|
||||
</main>
|
||||
|
||||
{/*Site Footer applied to every page*/}
|
||||
|
|
@ -346,7 +366,7 @@ export default function Layout() {
|
|||
</button>
|
||||
|
||||
<div className="w-64">
|
||||
{PAGE_LINKS.map((page) => {
|
||||
{nav.main.map((page) => {
|
||||
const pageSections = sectionsOf(page.path);
|
||||
const isActive = location.pathname === page.path;
|
||||
|
||||
|
|
@ -364,6 +384,22 @@ export default function Layout() {
|
|||
{page.label}
|
||||
</NavLink>
|
||||
|
||||
{/* Pages set under this one (Pages → Navigation) */}
|
||||
{page.children.length > 0 && (
|
||||
<div className="ml-3 pl-4 mb-2 flex flex-col">
|
||||
{page.children.map((child) => (
|
||||
<SiteLink
|
||||
key={child.path}
|
||||
link={child}
|
||||
className="text-white text-xl font-bold py-2 hover:text-[var(--pal-amber-2)] transition-colors"
|
||||
onClick={() => setMobileMenuOpen(false)}
|
||||
>
|
||||
{child.label}
|
||||
</SiteLink>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Sections nest under the page they belong to */}
|
||||
{isActive && pageSections.length > 0 && (
|
||||
<div
|
||||
|
|
@ -388,9 +424,9 @@ export default function Layout() {
|
|||
</div>
|
||||
|
||||
<div className="mt-8 flex flex-col items-center gap-3">
|
||||
{navActions.map((item) => (
|
||||
{nav.actions.map((item) => (
|
||||
<NavAction
|
||||
key={item.label}
|
||||
key={`${item.label}${item.path}`}
|
||||
item={item}
|
||||
size="mobile"
|
||||
onClick={() => setMobileMenuOpen(false)}
|
||||
|
|
|
|||
|
|
@ -40,7 +40,7 @@
|
|||
import { Fragment, useEffect, useState, type ReactNode, type RefObject } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
|
||||
import { PAGE_LINKS } from '../navConfig.ts'
|
||||
import { useSiteNav } from '../lib/useSiteNav.ts'
|
||||
|
||||
type Inline = string | { href: string; children: Inline[] }
|
||||
|
||||
|
|
@ -240,6 +240,7 @@ function Anchor({ href, children }: { href: string; children: ReactNode }) {
|
|||
|
||||
export default function ReaderView({ source }: { source: RefObject<HTMLElement | null> }) {
|
||||
const [blocks, setBlocks] = useState<Block[]>([])
|
||||
const { main: pages } = useSiteNav()
|
||||
|
||||
useEffect(() => {
|
||||
const root = source.current
|
||||
|
|
@ -264,7 +265,7 @@ export default function ReaderView({ source }: { source: RefObject<HTMLElement |
|
|||
return (
|
||||
<article className="reader">
|
||||
<p>
|
||||
{PAGE_LINKS.map((page, i) => (
|
||||
{pages.map((page, i) => (
|
||||
<span key={page.path}>
|
||||
{i > 0 && ' · '}
|
||||
<Link to={page.path}>{page.label}</Link>
|
||||
|
|
|
|||
30
src/components/SiteLink.tsx
Normal file
30
src/components/SiteLink.tsx
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { Link } from 'react-router-dom'
|
||||
|
||||
import type { NavLink } from '../navConfig.ts'
|
||||
|
||||
/* A nav link (Pages → Navigation): a route on the site, or a plain
|
||||
link for an address off it or one set to open in a new tab. */
|
||||
export default function SiteLink({
|
||||
link,
|
||||
children,
|
||||
...rest
|
||||
}: {
|
||||
link: NavLink
|
||||
children: React.ReactNode
|
||||
className?: string
|
||||
style?: React.CSSProperties
|
||||
onClick?: () => void
|
||||
}) {
|
||||
if (!link.path.startsWith('/') || link.newTab) {
|
||||
return (
|
||||
<a href={link.path} {...(link.newTab ? { target: '_blank', rel: 'noopener noreferrer' } : {})} {...rest}>
|
||||
{children}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<Link to={link.path} {...rest}>
|
||||
{children}
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
|
|
@ -18,6 +18,7 @@
|
|||
and never fills in reads as real input instead of being skipped.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { awardHref, blogHref, eventHref, orgHref, personHref, teamHref } from "./hrefs.ts";
|
||||
import { organizations } from "./adminSchema/organizations.ts";
|
||||
import { events } from "./adminSchema/events.ts";
|
||||
import { people } from "./adminSchema/people.ts";
|
||||
|
|
@ -27,6 +28,7 @@ import { timeline } from "./adminSchema/timeline.ts";
|
|||
import { frontPage } from "./adminSchema/frontPage.ts";
|
||||
import { blogPosts } from "./adminSchema/blog.ts";
|
||||
import { siteSettings } from "./adminSchema/siteSettings.ts";
|
||||
import { siteNav } from "./adminSchema/siteNav.ts";
|
||||
import { personTagTypes } from "./adminSchema/personTags.ts";
|
||||
import { tags } from "./adminSchema/tags.ts";
|
||||
import { contactTypes } from "./adminSchema/contactTypes.ts";
|
||||
|
|
@ -37,6 +39,7 @@ import {
|
|||
resourcesPage,
|
||||
organizationPage,
|
||||
historyPage,
|
||||
shopPage,
|
||||
} from "./adminSchema/sitePages.ts";
|
||||
|
||||
export const ADMIN_ENTITIES: Record<string, any> = {
|
||||
|
|
@ -57,9 +60,36 @@ export const ADMIN_ENTITIES: Record<string, any> = {
|
|||
resources_page: resourcesPage,
|
||||
organization_page: organizationPage,
|
||||
history_page: historyPage,
|
||||
shop_page: shopPage,
|
||||
navigation: siteNav,
|
||||
site_settings: siteSettings,
|
||||
};
|
||||
|
||||
/* Where each entity's record shows on the site, for its draft's
|
||||
Preview (EntityEdit.tsx opens it with ?preview=, which api.ts sends
|
||||
on as X-Draft-Preview; server/src/drafts.js). An entity without
|
||||
one has drafts but nothing to preview them on. */
|
||||
export const PREVIEW_PATHS: Record<string, (row: any) => string | null> = {
|
||||
organizations: (row) => (row.kind === "ministry" ? null : orgHref(row.id, row.kind)),
|
||||
events: (row) => eventHref(row.id),
|
||||
people: (row) => personHref(row.id),
|
||||
person_tag_types: (row) => `/directory/${encodeURIComponent(row.id)}`,
|
||||
teams: (row) => teamHref(row.id),
|
||||
awards: (row) => awardHref(row.id),
|
||||
timeline: () => "/history",
|
||||
front_page: () => "/",
|
||||
blog_posts: (row) => blogHref(row.id),
|
||||
community_page: () => "/community",
|
||||
retreats_page: () => "/retreats",
|
||||
resources_page: () => "/resources",
|
||||
organization_page: () => "/organization",
|
||||
history_page: () => "/history",
|
||||
shop_page: () => "/shop",
|
||||
// The menus are on every page.
|
||||
navigation: () => "/",
|
||||
site_settings: () => "/",
|
||||
};
|
||||
|
||||
/* The /admin/options request for the option lists `part` of a
|
||||
manifest names (any `optionsFrom` inside it, at any depth), so a
|
||||
form gets only the lists its selects use. An empty request would
|
||||
|
|
|
|||
|
|
@ -83,6 +83,20 @@ export const people = {
|
|||
note: "Unpublished people are invisible everywhere.",
|
||||
fields: [PUBLISHED_FIELD, LISTED_FIELD],
|
||||
},
|
||||
{
|
||||
legend: "Hidden on the site",
|
||||
note: "Ticked parts stay here but don't show anywhere on the site. Someone with a profile account who has claimed this person sets these on their profile too (Data → Profile accounts).",
|
||||
fields: [
|
||||
["photo", "Photo"],
|
||||
["pronouns", "Pronouns"],
|
||||
["tagline", "Tagline"],
|
||||
["bio", "Bio"],
|
||||
["email", "Public email"],
|
||||
["phone", "Public phone"],
|
||||
["location", "Location"],
|
||||
["links", "Links"],
|
||||
].map(([key, label]) => ({ path: `hide_${key}`, label: `Hide ${label.toLowerCase()}`, widget: "checkbox" })),
|
||||
},
|
||||
],
|
||||
|
||||
children: [
|
||||
|
|
|
|||
104
src/lib/adminSchema/siteNav.ts
Normal file
104
src/lib/adminSchema/siteNav.ts
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
import siteConfiguration from "../../../site.json";
|
||||
|
||||
/* ── Navigation (075_site_nav.sql) ───────────────────────────────
|
||||
Pages → Navigation: the header's and footer's links, and each
|
||||
static page's title, intro and whether it's hidden. Admins and up
|
||||
save it, since hiding takes a page off the site. Server side:
|
||||
server/src/admin-schema/siteNav.js; the site reads it through
|
||||
server/src/siteNav.js and src/lib/useSiteNav.ts. */
|
||||
|
||||
const SITE_PAGES: [string, string][] = Object.entries(siteConfiguration.pages).map(
|
||||
([path, page]) => [path, `${page.title} (${path})`],
|
||||
);
|
||||
|
||||
const PLACES: [string, string][] = [
|
||||
["main", "Header: pages"],
|
||||
["action", "Header: buttons"],
|
||||
["footer", "Footer: Get in Touch"],
|
||||
["legal", "Footer: bottom row"],
|
||||
];
|
||||
|
||||
const placeLabel = (place) => PLACES.find(([key]) => key === place)?.[1];
|
||||
|
||||
export const siteNav = {
|
||||
key: "navigation",
|
||||
label: "Navigation",
|
||||
singular: "navigation",
|
||||
idLabel: "Navigation",
|
||||
singleton: "site",
|
||||
writeRole: "admin",
|
||||
|
||||
list: { columns: [], filters: [] },
|
||||
|
||||
groups: [],
|
||||
|
||||
children: [
|
||||
{
|
||||
key: "links",
|
||||
label: "Links",
|
||||
note: "Top to bottom, in the order each place shows them. A link to a hidden page is only shown to signed-in admin accounts. A header page lists its sections under it by itself (Pages → the page).",
|
||||
addLabel: "Add link",
|
||||
title: (row) => (row.label ? `${row.label} · ${placeLabel(row.place) ?? "No place"}` : "New link"),
|
||||
blank: { place: "", label: "", path: "", parent_path: "", style: "", new_tab: 0 },
|
||||
fields: [
|
||||
{ path: "place", label: "Shows in", widget: "select", options: PLACES, required: true },
|
||||
{ path: "label", label: "Label", required: true, help: "eg. Shop" },
|
||||
{
|
||||
path: "path",
|
||||
label: "Link",
|
||||
required: true,
|
||||
full: true,
|
||||
help: "A page on the site, a section of one, or an address elsewhere, eg. /shop, /organization#contact or https://www.bonfire.com/store/…",
|
||||
},
|
||||
{
|
||||
path: "parent_path",
|
||||
label: "Under page",
|
||||
widget: "select",
|
||||
options: [["/", "Home (/)"], ...SITE_PAGES],
|
||||
blankLabel: "Default: its own place in the header",
|
||||
help: "Lists it in that page's menu, after its sections, instead of in the header's row",
|
||||
when: { path: "place", value: "main" },
|
||||
},
|
||||
{
|
||||
path: "style",
|
||||
label: "Style",
|
||||
widget: "select",
|
||||
options: [["filled", "Filled, like Give (also beside the footer's logo)"]],
|
||||
blankLabel: "Default: outlined",
|
||||
when: { path: "place", value: "action" },
|
||||
},
|
||||
{ path: "new_tab", label: "Opens in a new tab", widget: "checkbox" },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "pages",
|
||||
label: "Pages",
|
||||
note: "A page's heading and intro (also its search title and description), and whether it's hidden. A hidden page is out of the menus and the sitemap and says Not found to everyone but signed-in admin accounts, who see it with a bar saying it's hidden. Blank fields keep site.json's. A page not listed here shows as site.json has it.",
|
||||
addLabel: "Add page",
|
||||
title: (row) =>
|
||||
`${SITE_PAGES.find(([path]) => path === row.path)?.[1] ?? "New page"}${row.is_hidden ? " · Hidden" : ""}`,
|
||||
blank: { path: "", title: "", description: "", is_hidden: 0 },
|
||||
fields: [
|
||||
{ path: "path", label: "Page", widget: "select", options: SITE_PAGES, required: true },
|
||||
{
|
||||
path: "is_hidden",
|
||||
label: "Hidden",
|
||||
widget: "checkbox",
|
||||
help: "Not found to everyone but signed-in admin accounts, eg. a page that isn't done",
|
||||
},
|
||||
{
|
||||
path: "title",
|
||||
label: "Title",
|
||||
help: (row) => (row?.path ? `Default: ${siteConfiguration.pages[row.path]?.title ?? ""}` : undefined),
|
||||
},
|
||||
{
|
||||
path: "description",
|
||||
label: "Intro",
|
||||
widget: "textarea",
|
||||
full: true,
|
||||
help: (row) => (row?.path ? `Default: ${siteConfiguration.pages[row.path]?.description ?? ""}` : undefined),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
/* ── The site's own pages (056_site_pages.sql) ───────────────────
|
||||
Pages → Community, Retreats, Resources, Organization, History:
|
||||
Pages → Community, Retreats, Resources, Organization, History,
|
||||
Shop (075):
|
||||
each page is its sections, in order, and each section is its
|
||||
heading and its own content blocks, then a preset if it has one
|
||||
(a prebuilt part of the site, drawn under the blocks). Server
|
||||
|
|
@ -254,3 +255,4 @@ export const retreatsPage = sitePage("retreats", "Retreats page", ["events"]);
|
|||
export const resourcesPage = sitePage("resources", "Resources page", ["people_directory"]);
|
||||
export const organizationPage = sitePage("organization", "Organization page", ["people_directory"]);
|
||||
export const historyPage = sitePage("history", "History page", ["timeline"]);
|
||||
export const shopPage = sitePage("shop", "Shop page", []);
|
||||
|
|
|
|||
|
|
@ -4,10 +4,8 @@ import { THEME_DEFAULTS } from "../../../server/src/themeDefaults.js";
|
|||
|
||||
/* ── Site settings (035_site_settings.sql) ───────────────────────
|
||||
Overrides for site.json, superadmins only: every blank falls back
|
||||
to what site.json says, which is shown as the default. */
|
||||
const SITE_PAGES: [string, string][] = Object.entries(siteConfiguration.pages).map(
|
||||
([path, page]) => [path, `${page.title} (${path})`],
|
||||
);
|
||||
to what site.json says, which is shown as the default. Page titles
|
||||
and intros are Pages → Navigation's (siteNav.ts). */
|
||||
|
||||
/* The palette an admin can change, in the order the dropdown lists
|
||||
it: token and label. The defaults come from the server's list
|
||||
|
|
@ -218,28 +216,5 @@ export const siteSettings = {
|
|||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "pages",
|
||||
label: "Page titles and intros",
|
||||
note: "Change a static page's heading and intro, which are also its search title and description. Blank fields keep site.json's.",
|
||||
addLabel: "Change a page",
|
||||
title: (row) => SITE_PAGES.find(([path]) => path === row.path)?.[1] ?? "New page",
|
||||
blank: { path: "", title: "", description: "" },
|
||||
fields: [
|
||||
{ path: "path", label: "Page", widget: "select", options: SITE_PAGES, required: true },
|
||||
{
|
||||
path: "title",
|
||||
label: "Title",
|
||||
help: (row) => (row?.path ? `Default: ${siteConfiguration.pages[row.path]?.title ?? ""}` : undefined),
|
||||
},
|
||||
{
|
||||
path: "description",
|
||||
label: "Intro",
|
||||
widget: "textarea",
|
||||
full: true,
|
||||
help: (row) => (row?.path ? `Default: ${siteConfiguration.pages[row.path]?.description ?? ""}` : undefined),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
|
|
|||
|
|
@ -21,6 +21,36 @@ import { visionColor } from "./color.ts";
|
|||
const BASE = import.meta.env?.VITE_API_BASE ?? "/api";
|
||||
const DEFAULT_TTL = 60_000;
|
||||
|
||||
/* A draft's preview (server/src/drafts.js): a tab opened from the
|
||||
editor's Preview with ?preview=<entity>/<id> sends it with every
|
||||
read of the site's data, for as long as the tab lasts, and the
|
||||
server answers with that draft applied (to a signed-in viewer and
|
||||
up; anyone else gets the live site). Never for the admin's own
|
||||
reads. */
|
||||
const PREVIEW_KEY = "site-draft-preview";
|
||||
|
||||
export const draftPreview: string | null = (() => {
|
||||
if (typeof window === "undefined") return null;
|
||||
try {
|
||||
const asked = new URLSearchParams(window.location.search).get("preview");
|
||||
if (asked) sessionStorage.setItem(PREVIEW_KEY, asked);
|
||||
return asked ?? sessionStorage.getItem(PREVIEW_KEY);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
|
||||
export function stopPreview() {
|
||||
try {
|
||||
sessionStorage.removeItem(PREVIEW_KEY);
|
||||
} catch {
|
||||
// Nothing kept to clear.
|
||||
}
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.delete("preview");
|
||||
window.location.replace(url.toString());
|
||||
}
|
||||
|
||||
const cache = new Map(); // path → { at, promise }
|
||||
const settled = new Map(); // path → the last body it answered with
|
||||
|
||||
|
|
@ -44,9 +74,11 @@ const NOT_THE_API: Record<number, string> = {
|
|||
};
|
||||
|
||||
async function request(path, options: RequestInit = {}) {
|
||||
const preview: Record<string, string> =
|
||||
draftPreview && !String(path).startsWith("/admin") ? { "X-Draft-Preview": draftPreview } : {};
|
||||
const response = await fetch(`${BASE}${path}`, {
|
||||
...options,
|
||||
headers: { Accept: "application/json", ...options.headers },
|
||||
headers: { Accept: "application/json", ...preview, ...(options.headers as Record<string, string>) },
|
||||
});
|
||||
|
||||
if (response.status === 204) return null;
|
||||
|
|
@ -123,7 +155,7 @@ export function peek(path) {
|
|||
return settled.get(path);
|
||||
}
|
||||
|
||||
export function invalidate(path) {
|
||||
export function invalidate(path?: string) {
|
||||
if (path) {
|
||||
cache.delete(path);
|
||||
settled.delete(path);
|
||||
|
|
@ -151,6 +183,14 @@ export function patch(path, data) {
|
|||
});
|
||||
}
|
||||
|
||||
export function put(path, data) {
|
||||
return request(path, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
export function del(path) {
|
||||
return request(path, { method: "DELETE" });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,13 +10,19 @@
|
|||
RequireAuth guards routes. Worth being clear about what that
|
||||
does and doesn't do: it hides the interface, not the data. The
|
||||
protection is the 401 from /api/admin, this only stops someone
|
||||
staring at an empty table.
|
||||
staring at an empty table. A profile account (member) is signed
|
||||
in but has no admin, so it's sent to its page on the site.
|
||||
|
||||
The provider wraps the whole app, since the site shows a profile
|
||||
link and hidden pages by who's signed in. Signing in or out drops
|
||||
the API cache: the nav and hidden pages depend on it.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { createContext, useCallback, useContext, useEffect, useState } from "react";
|
||||
import { Navigate, Outlet, useLocation } from "react-router-dom";
|
||||
|
||||
import { get, post, ApiError } from "./api.ts";
|
||||
import { get, invalidate, post, ApiError } from "./api.ts";
|
||||
import { isStaff } from "./roles.ts";
|
||||
|
||||
const AuthContext = createContext<any>(null);
|
||||
|
||||
|
|
@ -45,6 +51,7 @@ export function AuthProvider({ children }) {
|
|||
|
||||
const login = useCallback(async (email, password) => {
|
||||
const data = await post("/auth/login", { email, password });
|
||||
invalidate();
|
||||
setUser(data.user);
|
||||
return data.user;
|
||||
}, []);
|
||||
|
|
@ -54,12 +61,19 @@ export function AuthProvider({ children }) {
|
|||
await post("/auth/logout", {});
|
||||
} finally {
|
||||
// Whatever the server said, this browser is done.
|
||||
invalidate();
|
||||
setUser(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// After a sign-in the server did itself (an invite's password).
|
||||
const signedIn = useCallback((next) => {
|
||||
invalidate();
|
||||
setUser(next);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, loading, login, logout }}>
|
||||
<AuthContext.Provider value={{ user, loading, login, logout, signedIn }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
|
|
@ -94,5 +108,7 @@ export function RequireAuth() {
|
|||
return <Navigate to="/admin/login" state={{ from: location }} replace />;
|
||||
}
|
||||
|
||||
if (!isStaff(user)) return <Navigate to="/account" replace />;
|
||||
|
||||
return <Outlet />;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@
|
|||
table, so there is one answer to "where does an event live" and
|
||||
changing it is changing EVENT_BASE below.
|
||||
|
||||
navConfig.ts stays the source of truth for the *nav*: these are
|
||||
The nav is Pages → Navigation's (useSiteNav.ts): these are
|
||||
record routes, which never appear in it.
|
||||
|
||||
── On missing ids ──
|
||||
|
|
|
|||
|
|
@ -14,18 +14,22 @@
|
|||
role to be added, and there's now a fourth.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
export const ROLES = ["viewer", "editor", "admin", "superadmin"] as const;
|
||||
/* member is a profile account (076): the site and their own profile,
|
||||
never the admin. */
|
||||
export const ROLES = ["member", "viewer", "editor", "admin", "superadmin"] as const;
|
||||
|
||||
export type Role = (typeof ROLES)[number];
|
||||
|
||||
export const ROLE_RANK: Record<Role, number> = {
|
||||
viewer: 1,
|
||||
editor: 2,
|
||||
admin: 3,
|
||||
superadmin: 4,
|
||||
member: 1,
|
||||
viewer: 2,
|
||||
editor: 3,
|
||||
admin: 4,
|
||||
superadmin: 5,
|
||||
};
|
||||
|
||||
export const ROLE_LABELS: Record<Role, string> = {
|
||||
member: "Profile",
|
||||
viewer: "Viewer",
|
||||
editor: "Editor",
|
||||
admin: "Admin",
|
||||
|
|
@ -35,9 +39,10 @@ export const ROLE_LABELS: Record<Role, string> = {
|
|||
/* Each line is what that role adds to the one above it in the
|
||||
list. Read top to bottom, they describe the whole ladder. */
|
||||
export const ROLE_NOTES: Record<Role, string> = {
|
||||
member: "Signs in to the site to edit their own profile. No admin.",
|
||||
viewer: "Can read everything in the CMS and change nothing.",
|
||||
editor: "Can create and update records. Can't delete anything.",
|
||||
admin: "Can delete records, including feedback.",
|
||||
admin: "Can delete records, including feedback. Invites profile accounts and approves their claims.",
|
||||
superadmin: "Can manage accounts, roles and sessions.",
|
||||
};
|
||||
|
||||
|
|
@ -55,3 +60,5 @@ export function atLeast(user: MaybeUser, role: Role): boolean {
|
|||
export const canWrite = (user: MaybeUser) => atLeast(user, "editor");
|
||||
export const canDelete = (user: MaybeUser) => atLeast(user, "admin");
|
||||
export const isSuper = (user: MaybeUser) => atLeast(user, "superadmin");
|
||||
/* Uses the admin at all: a profile account (member) doesn't. */
|
||||
export const isStaff = (user: MaybeUser) => atLeast(user, "viewer");
|
||||
|
|
|
|||
44
src/lib/useAccount.ts
Normal file
44
src/lib/useAccount.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
/* A profile account's own page (server/src/routes/account.js): the
|
||||
account, the People record it has (as its owner edits it), its
|
||||
claim, and Discord. Not cached: it changes as they edit it. */
|
||||
|
||||
import { useRecord, type Resource } from './useRecord.ts'
|
||||
|
||||
/* What an owner can take off the site (people.hide_*), in the order
|
||||
the profile page lists them. */
|
||||
export const HIDE_FIELDS = [
|
||||
['photo', 'Photo'],
|
||||
['pronouns', 'Pronouns'],
|
||||
['tagline', 'Tagline'],
|
||||
['bio', 'Bio'],
|
||||
['email', 'Public email'],
|
||||
['phone', 'Public phone'],
|
||||
['location', 'Location'],
|
||||
['links', 'Links'],
|
||||
] as const
|
||||
|
||||
export type HideField = (typeof HIDE_FIELDS)[number][0]
|
||||
|
||||
export type MyPerson = {
|
||||
id: string
|
||||
display_name: string
|
||||
is_published: boolean
|
||||
photo: string | null
|
||||
pronouns: string | null
|
||||
tagline: string | null
|
||||
bio: string | null
|
||||
public_email: string | null
|
||||
public_phone: string | null
|
||||
location_label: string | null
|
||||
hidden: Record<HideField, boolean>
|
||||
}
|
||||
|
||||
export type MyAccount = {
|
||||
user: { id: number; email: string; name: string | null; role: string }
|
||||
person: MyPerson | null
|
||||
claim: { id: number; person_id: string; display_name: string; status: 'pending' | 'approved' | 'declined' } | null
|
||||
discord: { enabled: boolean; id: string | null; name: string | null }
|
||||
}
|
||||
|
||||
export const useMyAccount = (enabled: boolean): Resource<MyAccount> =>
|
||||
useRecord(enabled ? '/account' : null, 'account')
|
||||
56
src/lib/useSiteNav.ts
Normal file
56
src/lib/useSiteNav.ts
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
SITE NAV: the header's and footer's links, and the hidden pages
|
||||
|
||||
Pages → Navigation, for this visitor (server/src/siteNav.js): a
|
||||
link to a hidden page is only sent to a viewer and up. The page
|
||||
HTML carries it (window.__SITE__.nav), so the menus draw on the
|
||||
first paint; GET /api/nav asks again, which is also how the dev
|
||||
server (no page metadata) and a sign-in in another tab get it.
|
||||
Until either answers, navConfig.ts's defaults.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { useMemo } from 'react'
|
||||
|
||||
import { NAV_DEFAULTS, type NavLink } from '../navConfig.ts'
|
||||
import { useRecord } from './useRecord.ts'
|
||||
|
||||
export type SiteNav = {
|
||||
links: NavLink[]
|
||||
/** Paths of hidden pages, eg. '/shop'. */
|
||||
hidden: string[]
|
||||
/** This visitor sees hidden pages (signed in, viewer and up). */
|
||||
seesHidden: boolean
|
||||
}
|
||||
|
||||
const fromPage: SiteNav | undefined =
|
||||
typeof window !== 'undefined' ? (window as unknown as { __SITE__?: { nav?: SiteNav } }).__SITE__?.nav : undefined
|
||||
|
||||
const DEFAULTS: SiteNav = { links: NAV_DEFAULTS, hidden: [], seesHidden: false }
|
||||
|
||||
/** A path's page: no #section or ?query, no trailing slash. */
|
||||
export const pageOf = (path: string): string => path.split(/[?#]/)[0].replace(/(.)\/+$/, '$1') || '/'
|
||||
|
||||
export function useSiteNav() {
|
||||
const { data } = useRecord<SiteNav>('/nav', 'nav')
|
||||
const nav = data ?? fromPage ?? DEFAULTS
|
||||
|
||||
return useMemo(() => {
|
||||
const main = nav.links.filter((l) => l.place === 'main')
|
||||
const top = main.filter((l) => !l.parent)
|
||||
const tops = new Set(top.map((l) => pageOf(l.path)))
|
||||
return {
|
||||
...nav,
|
||||
/** The header's pages, each with the links set under it. */
|
||||
main: top.map((page) => ({
|
||||
...page,
|
||||
children: main.filter((l) => l.parent && l.parent === pageOf(page.path)),
|
||||
})),
|
||||
/** Every main link, children included, for lists of the site's pages. */
|
||||
pages: main.filter((l) => !l.parent || tops.has(l.parent)),
|
||||
actions: nav.links.filter((l) => l.place === 'action'),
|
||||
footer: nav.links.filter((l) => l.place === 'footer'),
|
||||
legal: nav.links.filter((l) => l.place === 'legal'),
|
||||
isHidden: (path: string) => nav.hidden.includes(pageOf(path)),
|
||||
}
|
||||
}, [nav])
|
||||
}
|
||||
|
|
@ -1,22 +1,56 @@
|
|||
// Single source of truth for navigation.
|
||||
// Add a page here and in App.jsx, and both tiers of the nav update.
|
||||
/* ═══════════════════════════════════════════════════════════════
|
||||
NAV DEFAULTS
|
||||
|
||||
export const PAGE_LINKS = [
|
||||
{ label: "Home", path: "/" },
|
||||
{ label: "Retreats", path: "/retreats" },
|
||||
{ label: "Community", path: "/community" },
|
||||
{ label: "Resources", path: "/resources" },
|
||||
{ label: "Organization", path: "/organization" },
|
||||
{ label: "History", path: "/history" },
|
||||
];
|
||||
The header's and footer's links are edited in Pages → Navigation
|
||||
(075_site_nav.sql) and reach the app through useSiteNav
|
||||
(src/lib/useSiteNav.ts). This is what the app starts from before
|
||||
they arrive: the same links the migration seeded, so a dev server
|
||||
with no page metadata, or a moment before /api/nav answers, still
|
||||
has a menu. Change the menus in the admin, not here.
|
||||
|
||||
// Right-side actions. `variant` picks the styling, not the destination.
|
||||
export const NAV_ACTIONS = [
|
||||
{ label: "Contact Us", to: "/organization#contact", variant: "ghost" },
|
||||
{
|
||||
label: "Give",
|
||||
to: "/give",
|
||||
variant: "fancy",
|
||||
external: true,
|
||||
},
|
||||
];
|
||||
place: main the header's pages (sections drop down under
|
||||
each); with a parent, in that page's dropdown
|
||||
action the header's buttons (filled: the Give style,
|
||||
also beside the footer's logo)
|
||||
footer the footer's Get in Touch list
|
||||
legal the footer's bottom row
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
export type NavPlace = 'main' | 'action' | 'footer' | 'legal'
|
||||
|
||||
export type NavLink = {
|
||||
place: NavPlace
|
||||
label: string
|
||||
/** '/retreats', '/organization#contact', or an https:// address. */
|
||||
path: string
|
||||
/** A main link's page whose dropdown it sits in. */
|
||||
parent: string | null
|
||||
filled: boolean
|
||||
newTab: boolean
|
||||
}
|
||||
|
||||
const link = (place: NavPlace, label: string, path: string, more: Partial<NavLink> = {}): NavLink => ({
|
||||
place,
|
||||
label,
|
||||
path,
|
||||
parent: null,
|
||||
filled: false,
|
||||
newTab: false,
|
||||
...more,
|
||||
})
|
||||
|
||||
export const NAV_DEFAULTS: NavLink[] = [
|
||||
link('main', 'Home', '/'),
|
||||
link('main', 'Retreats', '/retreats'),
|
||||
link('main', 'Community', '/community'),
|
||||
link('main', 'Resources', '/resources'),
|
||||
link('main', 'Organization', '/organization'),
|
||||
link('main', 'History', '/history'),
|
||||
link('action', 'Contact Us', '/organization#contact'),
|
||||
link('action', 'Give', '/give', { filled: true, newTab: true }),
|
||||
link('footer', 'Feedback', '/feedback'),
|
||||
link('footer', 'Request', '/request'),
|
||||
link('footer', 'Contact Us', '/organization#contact'),
|
||||
link('legal', 'Privacy Policy', '/privacy'),
|
||||
link('legal', 'Terms of Service', '/terms'),
|
||||
]
|
||||
|
|
|
|||
416
src/pages/Account.tsx
Normal file
416
src/pages/Account.tsx
Normal file
|
|
@ -0,0 +1,416 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
YOUR PROFILE: /account, a profile account's page (076)
|
||||
|
||||
Your account who's signed in, sign out (and the admin, for
|
||||
an admin account)
|
||||
Your profile before a record is theirs: ask to claim one (an
|
||||
admin approves it); after: edit its text and
|
||||
photo, and choose what of it shows on the site
|
||||
Discord link it (or unlink), for the gamification to come
|
||||
|
||||
Signed out, it's the sign-in page's job. Everything is saved
|
||||
through routes/account.js, which only ever writes the account's
|
||||
own person.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Link, Navigate, useSearchParams } from 'react-router-dom'
|
||||
import { ArrowSquareOut, SignOut } from '@phosphor-icons/react'
|
||||
|
||||
import PageShell from '../components/PageShell.tsx'
|
||||
import { useAuth } from '../lib/auth.tsx'
|
||||
import { ApiError, del, get, patch, post, upload } from '../lib/api.ts'
|
||||
import { ACCENTS, BRAND } from '../lib/color.ts'
|
||||
import { mediaUrl } from '../lib/media.ts'
|
||||
import { personHref } from '../lib/hrefs.ts'
|
||||
import { ROLE_LABELS, isStaff, type Role } from '../lib/roles.ts'
|
||||
import { HIDE_FIELDS, useMyAccount, type MyAccount, type MyPerson } from '../lib/useAccount.ts'
|
||||
import { fieldClass, primaryButton } from './SignIn.tsx'
|
||||
|
||||
const quietButton =
|
||||
'btn border border-brand px-5 py-2.5 text-link transition-colors hover:bg-tint focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/40 disabled:cursor-not-allowed disabled:opacity-60'
|
||||
|
||||
/* What ?discord= says after the trip to Discord (routes/account.js). */
|
||||
const DISCORD_RESULTS: Record<string, string> = {
|
||||
linked: 'Your Discord account is linked.',
|
||||
canceled: 'Linking Discord was canceled.',
|
||||
expired: 'That took too long. Try again.',
|
||||
taken: 'That Discord account is already linked to another profile.',
|
||||
failed: "Discord didn't link. Try again in a moment.",
|
||||
}
|
||||
|
||||
const message = (err: unknown) =>
|
||||
err instanceof ApiError ? err.message : "Couldn't reach the server. Try again in a moment."
|
||||
|
||||
function Alert({ children, tone = 'danger' }: { children: React.ReactNode; tone?: 'danger' | 'ok' }) {
|
||||
return (
|
||||
<p
|
||||
role={tone === 'danger' ? 'alert' : 'status'}
|
||||
className={`mt-4 px-4 py-3 text-sm ${
|
||||
tone === 'danger' ? 'border border-danger/30 bg-danger-tint text-danger' : 'border border-brand/30 bg-tint text-body'
|
||||
}`}
|
||||
>
|
||||
{children}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
export default function Account() {
|
||||
const { user, loading, logout } = useAuth()
|
||||
const { data, error, reload } = useMyAccount(Boolean(user))
|
||||
|
||||
if (loading) return null
|
||||
if (!user) return <Navigate to="/sign-in" replace />
|
||||
|
||||
const content = (part: React.ReactNode) => <div className="mx-auto max-w-3xl px-6">{part}</div>
|
||||
|
||||
return (
|
||||
<PageShell
|
||||
title="Your profile"
|
||||
intro="Your account on the site, the profile that's yours, and what of it shows."
|
||||
sections={[
|
||||
{
|
||||
id: 'account',
|
||||
title: 'Your account',
|
||||
accent: BRAND,
|
||||
content: content(
|
||||
<div className="flex flex-wrap items-center justify-between gap-4 bg-raised p-6 shadow-md">
|
||||
<div>
|
||||
<p className="font-semibold text-ink">{user.name || user.email}</p>
|
||||
<p className="text-sm text-muted">
|
||||
{user.email} · {ROLE_LABELS[user.role as Role] ?? user.role}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{isStaff(user) && (
|
||||
<Link to="/admin/home" className={quietButton}>
|
||||
Admin
|
||||
</Link>
|
||||
)}
|
||||
<button type="button" onClick={logout} className={`${quietButton} inline-flex items-center gap-2`}>
|
||||
<SignOut size={18} weight="bold" aria-hidden="true" />
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
</div>,
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'profile',
|
||||
title: 'Your profile',
|
||||
blurb: 'Your page on the site, eg. on a team or an event. Ask for yours, then edit it here.',
|
||||
accent: ACCENTS.green,
|
||||
content: content(
|
||||
error ? (
|
||||
<p className="text-danger">Couldn't load your profile. {error}</p>
|
||||
) : !data ? (
|
||||
<div className="skeleton !min-h-40" aria-label="Loading your profile" />
|
||||
) : data.person ? (
|
||||
<ProfileEditor key={data.person.id} person={data.person} onSaved={reload} />
|
||||
) : (
|
||||
<Claim account={data} onChange={reload} />
|
||||
),
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'discord',
|
||||
title: 'Discord',
|
||||
blurb: 'Link your Discord account so what you do there can count here.',
|
||||
accent: ACCENTS.amber,
|
||||
content: content(data ? <Discord account={data} onChange={reload} /> : null),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/* ── Claiming a record ───────────────────────────────────────── */
|
||||
|
||||
function Claim({ account, onChange }: { account: MyAccount; onChange: () => void }) {
|
||||
const [people, setPeople] = useState<{ id: string; name: string }[] | null>(null)
|
||||
const [personId, setPersonId] = useState('')
|
||||
const [note, setNote] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const pending = account.claim?.status === 'pending' ? account.claim : null
|
||||
|
||||
useEffect(() => {
|
||||
if (pending) return
|
||||
get('/account/people', { ttl: 0 })
|
||||
.then((data) => setPeople(data.people))
|
||||
.catch((err) => setError(message(err)))
|
||||
}, [pending])
|
||||
|
||||
async function run(action: () => Promise<unknown>) {
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
try {
|
||||
await action()
|
||||
onChange()
|
||||
} catch (err) {
|
||||
setError(message(err))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (pending) {
|
||||
return (
|
||||
<div className="notice p-5">
|
||||
<p className="text-body">
|
||||
You asked to be <strong>{pending.display_name}</strong>. An admin will look at it soon.
|
||||
</p>
|
||||
<button type="button" disabled={busy} onClick={() => run(() => del('/account/claim'))} className={`mt-4 ${quietButton}`}>
|
||||
Take back the request
|
||||
</button>
|
||||
{error && <Alert>{error}</Alert>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
run(() => post('/account/claim', { person_id: personId, message: note }))
|
||||
}}
|
||||
className="bg-raised p-6 shadow-md"
|
||||
>
|
||||
{account.claim?.status === 'declined' && (
|
||||
<p className="mb-4 text-sm text-muted">
|
||||
Your request to be {account.claim.display_name} wasn't approved. Pick again, or say more in the note.
|
||||
</p>
|
||||
)}
|
||||
<label htmlFor="claim-person" className="block text-sm font-medium text-body">
|
||||
Which person on the site is you?
|
||||
</label>
|
||||
<select
|
||||
id="claim-person"
|
||||
value={personId}
|
||||
onChange={(e) => setPersonId(e.target.value)}
|
||||
className={`mt-2 ${fieldClass}`}
|
||||
disabled={!people}
|
||||
>
|
||||
<option value="">{people ? 'Choose your name' : 'Loading…'}</option>
|
||||
{people?.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<p className="mt-1 text-xs text-muted">Not listed? Ask us through the Request page to add you.</p>
|
||||
<label htmlFor="claim-note" className="mt-5 block text-sm font-medium text-body">
|
||||
A note for the admin <span className="font-normal text-muted">(optional)</span>
|
||||
</label>
|
||||
<textarea
|
||||
id="claim-note"
|
||||
rows={3}
|
||||
maxLength={1000}
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
className={`mt-2 ${fieldClass}`}
|
||||
/>
|
||||
{error && <Alert>{error}</Alert>}
|
||||
<button type="submit" disabled={busy || !personId} className={`mt-6 ${primaryButton}`}>
|
||||
{busy ? 'Sending…' : 'Ask for this profile'}
|
||||
</button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
/* ── Editing it ──────────────────────────────────────────────── */
|
||||
|
||||
const TEXT_FIELDS: { key: keyof MyPerson; label: string; help?: string; long?: boolean; type?: string }[] = [
|
||||
{ key: 'pronouns', label: 'Pronouns', help: 'eg. she/her' },
|
||||
{ key: 'tagline', label: 'Tagline', help: 'A line under your name when you have no title, eg. Musician and youth leader' },
|
||||
{ key: 'location_label', label: 'Location', help: 'eg. Kansas City, MO' },
|
||||
{ key: 'public_email', label: 'Public email', type: 'email', help: 'Shown on your page. Leave it blank for none.' },
|
||||
{ key: 'public_phone', label: 'Public phone', type: 'tel' },
|
||||
{ key: 'bio', label: 'Bio', long: true, help: 'A blank line starts a new paragraph.' },
|
||||
]
|
||||
|
||||
function ProfileEditor({ person, onSaved }: { person: MyPerson; onSaved: () => void }) {
|
||||
const [values, setValues] = useState(() =>
|
||||
Object.fromEntries(TEXT_FIELDS.map(({ key }) => [key, (person[key] as string | null) ?? ''])),
|
||||
)
|
||||
const [hidden, setHidden] = useState(person.hidden)
|
||||
const [photo, setPhoto] = useState(person.photo)
|
||||
const [fields, setFields] = useState<Record<string, string>>({})
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [saved, setSaved] = useState(false)
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
async function save(event: React.FormEvent) {
|
||||
event.preventDefault()
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
setFields({})
|
||||
setSaved(false)
|
||||
try {
|
||||
await patch('/account/profile', { ...values, hidden })
|
||||
setSaved(true)
|
||||
onSaved()
|
||||
} catch (err) {
|
||||
setError(message(err))
|
||||
if (err instanceof ApiError && err.fields) setFields(err.fields)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function sendPhoto(file: File | undefined) {
|
||||
if (!file) return
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
try {
|
||||
const form = new FormData()
|
||||
form.append('file', file)
|
||||
const data = await upload('/account/photo', form)
|
||||
setPhoto(data.person.photo)
|
||||
} catch (err) {
|
||||
setError(message(err))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={save} noValidate className="bg-raised p-6 shadow-md sm:p-8">
|
||||
<div className="flex flex-wrap items-center gap-5">
|
||||
{photo ? (
|
||||
<img src={mediaUrl(photo) ?? undefined} alt="" className="h-24 w-24 object-cover" />
|
||||
) : (
|
||||
<div className="flex h-24 w-24 items-center justify-center bg-tint text-sm text-muted">No photo</div>
|
||||
)}
|
||||
<div>
|
||||
<p className="text-xl font-bold text-ink">{person.display_name}</p>
|
||||
{person.is_published ? (
|
||||
<Link to={personHref(person.id)} className="inline-flex items-center gap-1 text-sm text-link underline">
|
||||
Your page on the site
|
||||
<ArrowSquareOut size={14} weight="bold" aria-hidden="true" />
|
||||
</Link>
|
||||
) : (
|
||||
<p className="text-sm text-muted">Your page isn't on the site yet.</p>
|
||||
)}
|
||||
<label className={`mt-3 inline-block cursor-pointer ${quietButton}`}>
|
||||
{photo ? 'Change photo' : 'Add a photo'}
|
||||
<input
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp"
|
||||
className="sr-only"
|
||||
disabled={busy}
|
||||
onChange={(e) => sendPhoto(e.target.files?.[0])}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<p className="mt-3 text-xs text-muted">Your name is changed by an admin: ask through the Request page.</p>
|
||||
|
||||
<div className="mt-8 grid gap-5 sm:grid-cols-2">
|
||||
{TEXT_FIELDS.map(({ key, label, help, long, type }) => (
|
||||
<div key={key} className={long ? 'sm:col-span-2' : ''}>
|
||||
<label htmlFor={`profile-${key}`} className="block text-sm font-medium text-body">
|
||||
{label}
|
||||
</label>
|
||||
{long ? (
|
||||
<textarea
|
||||
id={`profile-${key}`}
|
||||
rows={6}
|
||||
value={values[key]}
|
||||
onChange={(e) => setValues({ ...values, [key]: e.target.value })}
|
||||
aria-describedby={help ? `profile-${key}-help` : undefined}
|
||||
className={`mt-2 ${fieldClass}`}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
id={`profile-${key}`}
|
||||
type={type ?? 'text'}
|
||||
value={values[key]}
|
||||
onChange={(e) => setValues({ ...values, [key]: e.target.value })}
|
||||
aria-describedby={help ? `profile-${key}-help` : undefined}
|
||||
aria-invalid={Boolean(fields[key])}
|
||||
className={`mt-2 ${fieldClass}`}
|
||||
/>
|
||||
)}
|
||||
{fields[key] && <p className="mt-1 text-sm text-danger">{fields[key]}</p>}
|
||||
{help && (
|
||||
<p id={`profile-${key}-help`} className="mt-1 text-xs text-muted">
|
||||
{help}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<fieldset className="mt-8">
|
||||
<legend className="text-base font-semibold text-body">Hide on the site</legend>
|
||||
<p className="mt-1 text-sm text-muted">
|
||||
Ticked parts stay saved but don't show anywhere on the site: your page, team and event lists, people tiles.
|
||||
</p>
|
||||
<div className="mt-3 grid gap-2 sm:grid-cols-2">
|
||||
{HIDE_FIELDS.map(([key, label]) => (
|
||||
<label key={key} className="flex items-center gap-3 text-body">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={hidden[key]}
|
||||
onChange={(e) => setHidden({ ...hidden, [key]: e.target.checked })}
|
||||
className="h-4 w-4 accent-[var(--color-action)]"
|
||||
/>
|
||||
Hide {label.toLowerCase()}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
{error && <Alert>{error}</Alert>}
|
||||
{saved && !error && <Alert tone="ok">Saved. It's on the site now.</Alert>}
|
||||
<button type="submit" disabled={busy} className={`mt-6 ${primaryButton}`}>
|
||||
{busy ? 'Saving…' : 'Save profile'}
|
||||
</button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
/* ── Discord ─────────────────────────────────────────────────── */
|
||||
|
||||
function Discord({ account, onChange }: { account: MyAccount; onChange: () => void }) {
|
||||
const [searchParams] = useSearchParams()
|
||||
const result = searchParams.get('discord')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const { discord } = account
|
||||
|
||||
async function unlink() {
|
||||
setError(null)
|
||||
try {
|
||||
await del('/account/discord')
|
||||
onChange()
|
||||
} catch (err) {
|
||||
setError(message(err))
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-raised p-6 shadow-md">
|
||||
{discord.id ? (
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<p className="text-body">
|
||||
Linked to <strong>{discord.name ?? discord.id}</strong>.
|
||||
</p>
|
||||
<button type="button" onClick={unlink} className={quietButton}>
|
||||
Unlink
|
||||
</button>
|
||||
</div>
|
||||
) : discord.enabled ? (
|
||||
<a href="/api/account/discord" className={`inline-block ${primaryButton}`}>
|
||||
Link Discord
|
||||
</a>
|
||||
) : (
|
||||
<p className="text-muted">Linking Discord isn't switched on yet. An admin can link it for you.</p>
|
||||
)}
|
||||
{result && DISCORD_RESULTS[result] && (
|
||||
<Alert tone={result === 'linked' ? 'ok' : 'danger'}>{DISCORD_RESULTS[result]}</Alert>
|
||||
)}
|
||||
{error && <Alert>{error}</Alert>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
142
src/pages/AccountWelcome.tsx
Normal file
142
src/pages/AccountWelcome.tsx
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
WELCOME: /account/welcome?token=…, an invite's link (076)
|
||||
|
||||
Who the invite is for, then a password to set, or Google under the
|
||||
invited email. Either takes up the invite: the link stops working
|
||||
and the account is signed in (routes/account.js, routes/auth.js).
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
|
||||
|
||||
import PageShell from '../components/PageShell.tsx'
|
||||
import { useAuth } from '../lib/auth.tsx'
|
||||
import { ApiError, get, post } from '../lib/api.ts'
|
||||
import { BRAND } from '../lib/color.ts'
|
||||
import { GoogleButton, fieldClass, primaryButton } from './SignIn.tsx'
|
||||
|
||||
const MIN_PASSWORD = 12
|
||||
|
||||
type Invite = { email: string; name: string | null; google: boolean }
|
||||
|
||||
export default function AccountWelcome() {
|
||||
const [searchParams] = useSearchParams()
|
||||
const token = searchParams.get('token') ?? ''
|
||||
const navigate = useNavigate()
|
||||
const { signedIn } = useAuth()
|
||||
|
||||
const [invite, setInvite] = useState<Invite | null>(null)
|
||||
const [problem, setProblem] = useState<string | null>(null)
|
||||
const [password, setPassword] = useState('')
|
||||
const [again, setAgain] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) {
|
||||
setProblem('This page needs the link from your invite email.')
|
||||
return
|
||||
}
|
||||
get(`/account/invite?token=${encodeURIComponent(token)}`, { ttl: 0 })
|
||||
.then((data) => setInvite(data.invite))
|
||||
.catch((err) => setProblem(err instanceof ApiError ? err.message : "Couldn't reach the server. Try again in a moment."))
|
||||
}, [token])
|
||||
|
||||
async function submit(event: React.FormEvent) {
|
||||
event.preventDefault()
|
||||
if (busy) return
|
||||
if (password.length < MIN_PASSWORD) return setError(`Use at least ${MIN_PASSWORD} characters.`)
|
||||
if (password !== again) return setError("The two passwords don't match.")
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
try {
|
||||
const data = await post('/account/accept', { token, password })
|
||||
signedIn(data.user)
|
||||
navigate('/account', { replace: true })
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : "Couldn't reach the server. Try again in a moment.")
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<PageShell
|
||||
title="Welcome"
|
||||
intro="You've been invited to make a profile account."
|
||||
sections={[
|
||||
{
|
||||
id: 'welcome',
|
||||
title: invite?.name ? `Hi, ${invite.name}` : 'Your account',
|
||||
accent: BRAND,
|
||||
content: (
|
||||
<div className="mx-auto max-w-md px-6">
|
||||
{problem ? (
|
||||
<div className="notice p-5">
|
||||
<p className="text-body">{problem}</p>
|
||||
<p className="mt-2 text-sm text-muted">
|
||||
Already set up? <Link to="/sign-in" className="text-link underline">Sign in</Link>. Otherwise ask whoever invited you for a new link.
|
||||
</p>
|
||||
</div>
|
||||
) : !invite ? (
|
||||
<div className="skeleton !min-h-40" aria-label="Checking your invite" />
|
||||
) : (
|
||||
<form onSubmit={submit} noValidate className="bg-raised p-6 shadow-md sm:p-8">
|
||||
<p className="text-sm text-muted">
|
||||
Your account is <strong className="text-body">{invite.email}</strong>.
|
||||
</p>
|
||||
{invite.google && (
|
||||
<>
|
||||
<div className="mt-5">
|
||||
<GoogleButton label="Continue with Google" />
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-muted">Sign in to Google as {invite.email}.</p>
|
||||
<div className="my-6 flex items-center gap-3 text-xs text-muted">
|
||||
<span className="h-px flex-1 bg-muted/20" />
|
||||
or set a password
|
||||
<span className="h-px flex-1 bg-muted/20" />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<label htmlFor="welcome-password" className={`${invite.google ? '' : 'mt-5 '}block text-sm font-medium text-body`}>
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="welcome-password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
aria-describedby="welcome-password-help"
|
||||
className={`mt-2 ${fieldClass}`}
|
||||
/>
|
||||
<p id="welcome-password-help" className="mt-1 text-xs text-muted">
|
||||
At least {MIN_PASSWORD} characters.
|
||||
</p>
|
||||
<label htmlFor="welcome-again" className="mt-5 block text-sm font-medium text-body">
|
||||
Password again
|
||||
</label>
|
||||
<input
|
||||
id="welcome-again"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={again}
|
||||
onChange={(e) => setAgain(e.target.value)}
|
||||
className={`mt-2 ${fieldClass}`}
|
||||
/>
|
||||
{error && (
|
||||
<p role="alert" className="mt-5 border border-danger/30 bg-danger-tint px-4 py-3 text-sm text-danger">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button type="submit" disabled={busy || !password || !again} className={`mt-6 w-full ${primaryButton}`}>
|
||||
{busy ? 'Setting up…' : 'Set password and sign in'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
|
@ -18,7 +18,7 @@ import { useMemo } from 'react'
|
|||
import { Link, useLocation } from 'react-router-dom'
|
||||
|
||||
import PageShell from '../components/PageShell.tsx'
|
||||
import { PAGE_LINKS } from '../navConfig.ts'
|
||||
import { useSiteNav } from '../lib/useSiteNav.ts'
|
||||
import { SITE_PAGES } from '../lib/site.ts'
|
||||
import { useDirectory, type Directory } from '../lib/useContent.ts'
|
||||
import { blogHref, eventHref, orgHref, personHref, teamHref, awardHref } from '../lib/hrefs.ts'
|
||||
|
|
@ -33,10 +33,11 @@ const ORG_KIND_LABEL: Record<string, string> = {
|
|||
partner: 'Partner',
|
||||
}
|
||||
|
||||
/* Everything an address could have meant: the static pages, then
|
||||
each kind of record, with the words to match it by. */
|
||||
function candidates(directory: Directory | null): Candidate[] {
|
||||
const pages: Candidate[] = Object.entries(SITE_PAGES).map(([path, page]) => ({
|
||||
/* Everything an address could have meant: the static pages (not the
|
||||
hidden ones), then each kind of record, with the words to match
|
||||
it by. */
|
||||
function candidates(directory: Directory | null, isHidden: (path: string) => boolean): Candidate[] {
|
||||
const pages: Candidate[] = Object.entries(SITE_PAGES).filter(([path]) => !isHidden(path)).map(([path, page]) => ({
|
||||
href: path,
|
||||
label: page.title,
|
||||
detail: 'Page',
|
||||
|
|
@ -65,7 +66,11 @@ function candidates(directory: Directory | null): Candidate[] {
|
|||
export default function NotFound() {
|
||||
const { pathname } = useLocation()
|
||||
const { data: directory, loading } = useDirectory()
|
||||
const matches = useMemo(() => suggest(pathname, candidates(directory ?? null)), [pathname, directory])
|
||||
const { main: pages, isHidden } = useSiteNav()
|
||||
const matches = useMemo(
|
||||
() => suggest(pathname, candidates(directory ?? null, isHidden)),
|
||||
[pathname, directory, isHidden],
|
||||
)
|
||||
const reading = useReadingMode()
|
||||
|
||||
return (
|
||||
|
|
@ -118,7 +123,7 @@ export default function NotFound() {
|
|||
accent: ACCENTS.green,
|
||||
content: (
|
||||
<div className="mx-auto flex max-w-6xl flex-wrap gap-3 px-6">
|
||||
{PAGE_LINKS.map((page) => (
|
||||
{pages.map((page) => (
|
||||
<Link
|
||||
key={page.path}
|
||||
to={page.path}
|
||||
|
|
|
|||
|
|
@ -10,8 +10,8 @@ const PAGE = sitePage('/qr')
|
|||
QR CODES PAGE: /qr
|
||||
|
||||
A QR code for any page on the site, for flyers, slides and
|
||||
signs. Unlisted: not in navConfig, so neither the header nor the
|
||||
footer links here. It lists only published records, so there is
|
||||
signs. Unlisted: not in Pages → Navigation's links, so neither
|
||||
the header nor the footer links here. It lists only published records, so there is
|
||||
nothing on it a visitor couldn't already reach.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
|
|
|
|||
157
src/pages/SignIn.tsx
Normal file
157
src/pages/SignIn.tsx
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
SIGN IN: /sign-in, for profile accounts (076)
|
||||
|
||||
Accounts are by invite only (Data → Profile accounts), so there's
|
||||
no sign-up here: an invite's link (/account/welcome) sets the
|
||||
password, or the invited email signs in with Google, any Google
|
||||
account. The admin's own login (/admin/login) is the same accounts
|
||||
through another door; either lands an admin where they asked.
|
||||
|
||||
A Google refusal comes back here as ?error=<code> (routes/auth.js).
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Navigate, useNavigate, useSearchParams } from 'react-router-dom'
|
||||
|
||||
import PageShell from '../components/PageShell.tsx'
|
||||
import GoogleLogo from '../components/GoogleLogo.tsx'
|
||||
import { useAuth } from '../lib/auth.tsx'
|
||||
import { ApiError, get } from '../lib/api.ts'
|
||||
import { BRAND } from '../lib/color.ts'
|
||||
|
||||
export const SIGN_IN_TITLE = 'Sign in'
|
||||
|
||||
const GOOGLE_ERRORS: Record<string, string> = {
|
||||
canceled: 'Google sign-in was canceled.',
|
||||
expired: 'That sign-in took too long or was already used. Try again.',
|
||||
no_account: "There's no profile account for that Google account. Accounts are by invite: ask us to invite your email.",
|
||||
linked_elsewhere: "That email's account is linked to a different Google account.",
|
||||
disabled: 'That account has been turned off.',
|
||||
wrong_domain: 'Use your @nextgenerationofunity.org Google account for that one.',
|
||||
unverified: "That Google account's email isn't verified.",
|
||||
google_unreachable: "Couldn't reach Google. Try again in a moment.",
|
||||
google_failed: "Google sign-in didn't work. Try again, or use your password.",
|
||||
not_in_group: "That Google account isn't in a website access group.",
|
||||
groups_unreachable: "Couldn't check your Google groups just now. Try again in a moment.",
|
||||
}
|
||||
|
||||
export const fieldClass =
|
||||
'w-full border border-muted/50 bg-surface px-4 py-3 text-body outline-none transition-colors focus:border-brand focus:ring-2 focus:ring-brand/25'
|
||||
|
||||
export const primaryButton =
|
||||
'btn bg-action px-6 py-3 text-white transition-colors hover:bg-action-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/40 disabled:cursor-not-allowed disabled:bg-muted/25'
|
||||
|
||||
export function GoogleButton({ label = 'Sign in with Google' }: { label?: string }) {
|
||||
return (
|
||||
<a
|
||||
href="/api/auth/google?for=account"
|
||||
className="flex items-center justify-center gap-3 btn border border-muted/30 px-6 py-3 text-body transition-colors hover:bg-tint"
|
||||
>
|
||||
<GoogleLogo />
|
||||
{label}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
/* Whether the server has Google sign-in switched on. */
|
||||
export function useGoogleSignIn(): boolean {
|
||||
const [google, setGoogle] = useState(false)
|
||||
useEffect(() => {
|
||||
get('/auth/providers', { ttl: 0 })
|
||||
.then((data) => setGoogle(Boolean(data.google)))
|
||||
.catch(() => setGoogle(false))
|
||||
}, [])
|
||||
return google
|
||||
}
|
||||
|
||||
export default function SignIn() {
|
||||
const { user, loading, login } = useAuth()
|
||||
const navigate = useNavigate()
|
||||
const [searchParams] = useSearchParams()
|
||||
const googleError = searchParams.get('error')
|
||||
const google = useGoogleSignIn()
|
||||
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState<string | null>(
|
||||
googleError ? (GOOGLE_ERRORS[googleError] ?? GOOGLE_ERRORS.google_failed) : null,
|
||||
)
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
if (!loading && user) return <Navigate to="/account" replace />
|
||||
|
||||
async function submit(event: React.FormEvent) {
|
||||
event.preventDefault()
|
||||
if (busy) return
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
try {
|
||||
await login(email.trim(), password)
|
||||
navigate('/account', { replace: true })
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : "Couldn't reach the server. Try again in a moment.")
|
||||
setPassword('')
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<PageShell
|
||||
title={SIGN_IN_TITLE}
|
||||
intro="For people with a profile account. Accounts are by invite: if you'd like one, ask us through the Request page."
|
||||
sections={[
|
||||
{
|
||||
id: 'sign-in',
|
||||
title: 'Your account',
|
||||
accent: BRAND,
|
||||
content: (
|
||||
<div className="mx-auto max-w-md px-6">
|
||||
<form onSubmit={submit} noValidate className="bg-raised p-6 shadow-md sm:p-8">
|
||||
{google && (
|
||||
<>
|
||||
<GoogleButton />
|
||||
<div className="my-6 flex items-center gap-3 text-xs text-muted">
|
||||
<span className="h-px flex-1 bg-muted/20" />
|
||||
or with a password
|
||||
<span className="h-px flex-1 bg-muted/20" />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<label htmlFor="sign-in-email" className="block text-sm font-medium text-body">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="sign-in-email"
|
||||
type="email"
|
||||
autoComplete="username"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className={`mt-2 ${fieldClass}`}
|
||||
/>
|
||||
<label htmlFor="sign-in-password" className="mt-5 block text-sm font-medium text-body">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="sign-in-password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className={`mt-2 ${fieldClass}`}
|
||||
/>
|
||||
{error && (
|
||||
<p role="alert" className="mt-5 border border-danger/30 bg-danger-tint px-4 py-3 text-sm text-danger">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button type="submit" disabled={busy || !email || !password} className={`mt-6 w-full ${primaryButton}`}>
|
||||
{busy ? 'Signing in…' : 'Sign in'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
|
@ -3,7 +3,7 @@
|
|||
|
||||
Bare on purpose. No PageShell, no announcement banner, no
|
||||
footer site map. None of that belongs around a staff tool, and
|
||||
/admin should never appear in navConfig.
|
||||
/admin should never appear in Pages → Navigation.
|
||||
|
||||
Three areas share this chrome: Home, the CMS and the Panel. The
|
||||
wordmark names whichever one you're in, and from anywhere but
|
||||
|
|
|
|||
|
|
@ -18,6 +18,8 @@ import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
|
|||
|
||||
import { useAuth } from "../../lib/auth.tsx";
|
||||
import { ApiError, get } from "../../lib/api.ts";
|
||||
import { isStaff } from "../../lib/roles.ts";
|
||||
import GoogleLogo from "../../components/GoogleLogo.tsx";
|
||||
|
||||
/* What a ?error= from the Google callback means, in the words the
|
||||
person at the login page needs. */
|
||||
|
|
@ -74,8 +76,9 @@ export default function AdminLogin() {
|
|||
setError(null);
|
||||
|
||||
try {
|
||||
await login(email.trim(), password);
|
||||
navigate(destination, { replace: true });
|
||||
const user = await login(email.trim(), password);
|
||||
// A profile account has no admin: its page is on the site.
|
||||
navigate(isStaff(user) ? destination : "/account", { replace: true });
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof ApiError
|
||||
|
|
@ -106,12 +109,7 @@ export default function AdminLogin() {
|
|||
href={`/api/auth/google?next=${encodeURIComponent(destination)}`}
|
||||
className="flex items-center justify-center gap-3 btn border border-muted/30 px-6 py-3 text-body transition-colors hover:bg-tint"
|
||||
>
|
||||
<svg viewBox="0 0 48 48" className="h-5 w-5" aria-hidden="true">
|
||||
<path fill="#FFC107" d="M43.6 20.5H42V20H24v8h11.3C33.7 32.7 29.2 36 24 36c-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7C34 6.1 29.3 4 24 4 12.9 4 4 12.9 4 24s8.9 20 20 20 20-8.9 20-20c0-1.3-.1-2.4-.4-3.5z" />
|
||||
<path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.7 15.1 19 12 24 12c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7C34 6.1 29.3 4 24 4 16.3 4 9.7 8.3 6.3 14.7z" />
|
||||
<path fill="#4CAF50" d="M24 44c5.2 0 9.9-2 13.4-5.2l-6.2-5.2C29.2 35.1 26.7 36 24 36c-5.2 0-9.6-3.3-11.3-8l-6.5 5C9.5 39.6 16.2 44 24 44z" />
|
||||
<path fill="#1976D2" d="M43.6 20.5H42V20H24v8h11.3c-.8 2.2-2.2 4.2-4.1 5.6l6.2 5.2C37 39.2 44 34 44 24c0-1.3-.1-2.4-.4-3.5z" />
|
||||
</svg>
|
||||
<GoogleLogo />
|
||||
Sign in with Google
|
||||
</a>
|
||||
<div className="my-6 flex items-center gap-3 text-xs text-muted">
|
||||
|
|
|
|||
450
src/pages/admin/AdminProfiles.tsx
Normal file
450
src/pages/admin/AdminProfiles.tsx
Normal file
|
|
@ -0,0 +1,450 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
ADMIN: PROFILE ACCOUNTS (Data → Profile accounts, admins and up)
|
||||
|
||||
Profile accounts (076) are by invite: an email added here gets an
|
||||
account with no password and a link to set one (or to sign in
|
||||
with Google under that email). The link is shown once, to copy;
|
||||
Email invite sends a fresh one through Gmail and shows it too
|
||||
(the one before stops working). For an account already set up,
|
||||
the same link is a way back in when a password is forgotten.
|
||||
|
||||
Then: the claims waiting (someone asking to be a People record),
|
||||
and each account's record, Discord and whether it's on. Server
|
||||
side: server/src/routes/profiles.js. Admin accounts (viewer and
|
||||
up) are the Panel's, not this page's.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { useCallback, useEffect, useId, useState, type FormEvent } from "react";
|
||||
|
||||
import { ApiError, del, get, patch, post } from "../../lib/api.ts";
|
||||
import { preview } from "../../lib/text.ts";
|
||||
|
||||
const MUTED = "var(--color-muted)";
|
||||
|
||||
const button =
|
||||
"btn border border-brand px-3 py-1.5 text-sm text-link transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50";
|
||||
const primary =
|
||||
"btn bg-action px-5 py-2.5 text-white transition-colors hover:bg-action-hover disabled:bg-muted/25";
|
||||
const danger =
|
||||
"btn border border-danger/40 px-3 py-1.5 text-sm text-danger transition-colors hover:bg-danger-tint disabled:opacity-50";
|
||||
const input =
|
||||
"w-full border border-muted/25 bg-surface px-3 py-2 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25";
|
||||
|
||||
type Account = {
|
||||
id: number;
|
||||
email: string;
|
||||
name: string | null;
|
||||
is_active: number;
|
||||
created_at: string;
|
||||
last_login_at: string | null;
|
||||
invited_at: string | null;
|
||||
invite_expires_at: string | null;
|
||||
invite_open: number;
|
||||
signed_up: number;
|
||||
person_id: string | null;
|
||||
person_name: string | null;
|
||||
discord_id: string | null;
|
||||
discord_name: string | null;
|
||||
};
|
||||
|
||||
type Claim = {
|
||||
id: number;
|
||||
account_id: number;
|
||||
email: string;
|
||||
name: string | null;
|
||||
person_id: string;
|
||||
person_name: string;
|
||||
message: string | null;
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
const message = (err: unknown) => (err instanceof ApiError ? err.message : "Couldn't reach the server.");
|
||||
const day = (value: string | null) => (value ? value.slice(0, 10) : "-");
|
||||
|
||||
/* A link to copy, shown once. */
|
||||
function LinkBox({ link, note }: { link: string; note: string }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
return (
|
||||
<div className="mt-3 border border-brand/20 bg-tint p-3">
|
||||
<p className="text-xs" style={{ color: MUTED }}>
|
||||
{note}
|
||||
</p>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-2">
|
||||
<code className="min-w-0 flex-1 break-all text-xs text-body">{link}</code>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(link);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 1500);
|
||||
} catch {
|
||||
setCopied(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{copied ? "Copied" : "Copy link"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AdminProfiles() {
|
||||
const [data, setData] = useState<{ accounts: Account[]; claims: Claim[]; mail: boolean } | null>(null);
|
||||
const [people, setPeople] = useState<{ id: string; label: string }[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(() => {
|
||||
get("/admin/profiles", { ttl: 0 })
|
||||
.then(setData)
|
||||
.catch((err) => setError(message(err)));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
get("/admin/options?only=people", { ttl: 0 })
|
||||
.then((body) => setPeople(body.options.people))
|
||||
.catch(() => setPeople([]));
|
||||
}, [load]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex flex-wrap items-baseline gap-3">
|
||||
<h1 className="text-2xl font-bold text-link">Profile accounts</h1>
|
||||
<p className="text-sm" style={{ color: MUTED }}>
|
||||
People with an account on the site for their own profile. By invite only.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Invite mail={Boolean(data?.mail)} onDone={load} />
|
||||
|
||||
{error && <p className="mt-6 text-danger">{error}</p>}
|
||||
|
||||
<section className="mt-8">
|
||||
<h2 className="text-lg font-bold text-ink">Claims waiting</h2>
|
||||
{!data ? null : data.claims.length === 0 ? (
|
||||
<p className="notice mt-3 p-4 text-sm">Nobody is waiting.</p>
|
||||
) : (
|
||||
<ul className="mt-3 space-y-3">
|
||||
{data.claims.map((claim) => (
|
||||
<ClaimRow key={claim.id} claim={claim} onDone={load} />
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="mt-8">
|
||||
<h2 className="text-lg font-bold text-ink">Accounts</h2>
|
||||
{!data ? (
|
||||
<div className="skeleton mt-3 !min-h-40" aria-label="Loading the accounts" />
|
||||
) : data.accounts.length === 0 ? (
|
||||
<p className="notice mt-3 p-4 text-sm">No profile accounts yet. Invite someone above.</p>
|
||||
) : (
|
||||
<ul className="mt-3 space-y-3">
|
||||
{data.accounts.map((account) => (
|
||||
<AccountRow key={account.id} account={account} people={people} mail={data.mail} onDone={load} />
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Invite({ mail, onDone }: { mail: boolean; onDone: () => void }) {
|
||||
const emailId = useId();
|
||||
const nameId = useId();
|
||||
const [email, setEmail] = useState("");
|
||||
const [name, setName] = useState("");
|
||||
const [made, setMade] = useState<{ id: number; email: string; link: string } | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function submit(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await post("/admin/profiles", { email, name });
|
||||
setMade({ id: result.id, email: email.trim().toLowerCase(), link: result.link });
|
||||
setEmail("");
|
||||
setName("");
|
||||
onDone();
|
||||
} catch (err) {
|
||||
setError(message(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="mt-6 bg-raised p-5 shadow-md">
|
||||
<h2 className="text-lg font-bold text-ink">Invite someone</h2>
|
||||
<form onSubmit={submit} className="mt-3 flex flex-wrap items-end gap-3">
|
||||
<div className="min-w-56 flex-1">
|
||||
<label htmlFor={emailId} className="block text-sm font-medium text-body">
|
||||
Email
|
||||
</label>
|
||||
<input id={emailId} type="email" value={email} onChange={(e) => setEmail(e.target.value)} className={`mt-1 ${input}`} />
|
||||
</div>
|
||||
<div className="min-w-48 flex-1">
|
||||
<label htmlFor={nameId} className="block text-sm font-medium text-body">
|
||||
Name <span className="font-normal" style={{ color: MUTED }}>(optional)</span>
|
||||
</label>
|
||||
<input id={nameId} value={name} onChange={(e) => setName(e.target.value)} className={`mt-1 ${input}`} />
|
||||
</div>
|
||||
<button type="submit" disabled={busy || !email.trim()} className={primary}>
|
||||
{busy ? "Inviting…" : "Invite"}
|
||||
</button>
|
||||
</form>
|
||||
<p className="mt-2 text-xs" style={{ color: MUTED }}>
|
||||
They can sign in with a password from the link, or with Google under this email (any Google account).
|
||||
</p>
|
||||
{error && <p className="mt-3 text-sm text-danger">{error}</p>}
|
||||
{made && (
|
||||
<>
|
||||
<LinkBox
|
||||
link={made.link}
|
||||
note={`${made.email}'s invite link, for 14 days. Shown once: copy it, or email it from the account below.`}
|
||||
/>
|
||||
{mail && <EmailInvite id={made.id} label="Email this invite" onDone={(link) => setMade({ ...made, link })} />}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/* Email a fresh link (the last one stops working). */
|
||||
function EmailInvite({ id, label, onDone }: { id: number; label: string; onDone: (link: string) => void }) {
|
||||
const [state, setState] = useState<"idle" | "busy" | "sent" | string>("idle");
|
||||
return (
|
||||
<div className="mt-3 flex flex-wrap items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={state === "busy"}
|
||||
onClick={async () => {
|
||||
setState("busy");
|
||||
try {
|
||||
const result = await post(`/admin/profiles/${id}/invite`, { email: true });
|
||||
onDone(result.link);
|
||||
setState("sent");
|
||||
} catch (err) {
|
||||
setState(message(err));
|
||||
}
|
||||
}}
|
||||
>
|
||||
{state === "busy" ? "Sending…" : label}
|
||||
</button>
|
||||
{state === "sent" && <span className="text-sm text-body">Sent. The link above is the one in the email.</span>}
|
||||
{!["idle", "busy", "sent"].includes(state) && <span className="text-sm text-danger">{state}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ClaimRow({ claim, onDone }: { claim: Claim; onDone: () => void }) {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function decide(answer: "approve" | "decline") {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await post(`/admin/profiles/claims/${claim.id}/${answer}`, {});
|
||||
onDone();
|
||||
} catch (err) {
|
||||
setError(message(err));
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<li className="bg-raised p-4 shadow-sm">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<p className="text-body">
|
||||
<strong>{claim.name || claim.email}</strong>
|
||||
{claim.name && <span style={{ color: MUTED }}> ({claim.email})</span>} asks to be{" "}
|
||||
<a href={`/admin/people/${encodeURIComponent(claim.person_id)}`} className="text-link underline">
|
||||
{claim.person_name}
|
||||
</a>
|
||||
<span className="text-xs" style={{ color: MUTED }}>
|
||||
{" "}
|
||||
· {day(claim.created_at)}
|
||||
</span>
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<button type="button" className={button} disabled={busy} onClick={() => decide("approve")}>
|
||||
Approve
|
||||
</button>
|
||||
<button type="button" className={danger} disabled={busy} onClick={() => decide("decline")}>
|
||||
Decline
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{claim.message && <p className="mt-2 text-sm text-body">“{preview(claim.message, 300)}”</p>}
|
||||
{error && <p className="mt-2 text-sm text-danger">{error}</p>}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function AccountRow({
|
||||
account,
|
||||
people,
|
||||
mail,
|
||||
onDone,
|
||||
}: {
|
||||
account: Account;
|
||||
people: { id: string; label: string }[];
|
||||
mail: boolean;
|
||||
onDone: () => void;
|
||||
}) {
|
||||
const personId = useId();
|
||||
const discordId = useId();
|
||||
const discordName = useId();
|
||||
const [person, setPerson] = useState(account.person_id ?? "");
|
||||
const [discord, setDiscord] = useState(account.discord_id ?? "");
|
||||
const [discordLabel, setDiscordLabel] = useState(account.discord_name ?? "");
|
||||
const [link, setLink] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function run(action: () => Promise<unknown>) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await action();
|
||||
onDone();
|
||||
} catch (err) {
|
||||
setError(message(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const status = !account.is_active
|
||||
? "Turned off"
|
||||
: account.signed_up
|
||||
? `Signed up · last in ${day(account.last_login_at)}`
|
||||
: account.invite_open
|
||||
? `Invited · link works until ${day(account.invite_expires_at)}`
|
||||
: "Invited · link expired";
|
||||
|
||||
return (
|
||||
<li className="bg-raised shadow-sm">
|
||||
<details>
|
||||
<summary className="flex cursor-pointer flex-wrap items-center gap-x-4 gap-y-1 p-4">
|
||||
<span className="font-semibold text-body">{account.name || account.email}</span>
|
||||
{account.name && <span className="text-sm" style={{ color: MUTED }}>{account.email}</span>}
|
||||
<span className="text-sm" style={{ color: MUTED }}>{status}</span>
|
||||
<span className="text-sm text-body">Profile: {account.person_name ?? "-"}</span>
|
||||
<span className="text-sm text-body">Discord: {account.discord_name ?? account.discord_id ?? "-"}</span>
|
||||
</summary>
|
||||
<div className="space-y-5 border-t border-brand/10 p-4">
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<div className="min-w-56 flex-1">
|
||||
<label htmlFor={personId} className="block text-sm font-medium text-body">
|
||||
Profile (People record)
|
||||
</label>
|
||||
<select id={personId} value={person} onChange={(e) => setPerson(e.target.value)} className={`mt-1 ${input}`}>
|
||||
<option value="">Default: none</option>
|
||||
{people.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy || person === (account.person_id ?? "")}
|
||||
onClick={() => run(() => patch(`/admin/profiles/${account.id}`, { person_id: person || null }))}
|
||||
>
|
||||
Save profile
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<div className="min-w-48 flex-1">
|
||||
<label htmlFor={discordId} className="block text-sm font-medium text-body">
|
||||
Discord user ID
|
||||
</label>
|
||||
<input id={discordId} inputMode="numeric" value={discord} onChange={(e) => setDiscord(e.target.value)} className={`mt-1 ${input}`} />
|
||||
</div>
|
||||
<div className="min-w-40 flex-1">
|
||||
<label htmlFor={discordName} className="block text-sm font-medium text-body">
|
||||
Discord name
|
||||
</label>
|
||||
<input id={discordName} value={discordLabel} onChange={(e) => setDiscordLabel(e.target.value)} className={`mt-1 ${input}`} />
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
run(() => patch(`/admin/profiles/${account.id}`, { discord_id: discord || null, discord_name: discordLabel }))
|
||||
}
|
||||
>
|
||||
Save Discord
|
||||
</button>
|
||||
</div>
|
||||
<p className="-mt-3 text-xs" style={{ color: MUTED }}>
|
||||
They link it themselves from their profile; this overrides it. The ID is the long number from Discord (Developer Mode, then Copy User ID), eg. 80351110224678912. Blank unlinks it.
|
||||
</p>
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
run(async () => {
|
||||
const result = await post(`/admin/profiles/${account.id}/invite`, {});
|
||||
setLink(result.link);
|
||||
})
|
||||
}
|
||||
>
|
||||
{account.signed_up ? "New sign-in link" : "New invite link"}
|
||||
</button>
|
||||
{mail && (
|
||||
<EmailInvite id={account.id} label={account.signed_up ? "Email a sign-in link" : "Email invite"} onDone={setLink} />
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => run(() => patch(`/admin/profiles/${account.id}`, { is_active: !account.is_active }))}
|
||||
>
|
||||
{account.is_active ? "Turn off" : "Turn on"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={danger}
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
if (window.confirm(`Remove ${account.email}'s account? Their People record stays.`)) {
|
||||
run(() => del(`/admin/profiles/${account.id}`));
|
||||
}
|
||||
}}
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
{link && (
|
||||
<LinkBox
|
||||
link={link}
|
||||
note={
|
||||
account.signed_up
|
||||
? "Opening it sets a new password. Any link before it stops working."
|
||||
: "Their invite link, for 14 days. Any link before it stops working."
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{error && <p className="text-sm text-danger">{error}</p>}
|
||||
</div>
|
||||
</details>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
|
@ -33,6 +33,15 @@
|
|||
None of this is protection. The server refuses the request; this
|
||||
only decides whether to draw a button that would be refused.
|
||||
|
||||
Drafts (server/src/drafts.js): an existing record can be saved as
|
||||
a draft instead, which isn't live. One per record: opening the
|
||||
record opens its draft, if it has one, for anyone who edits it.
|
||||
Preview saves it and opens the record's page (PREVIEW_PATHS) in a
|
||||
new tab showing it; Publish is the ordinary save, which drops the
|
||||
draft; Discard throws it away. A draft is applied over the live
|
||||
record as it is when published, so the editor says when the live
|
||||
one was saved after the draft was started.
|
||||
|
||||
The page is laid out as sections: the URL ID, each field group,
|
||||
then each child collection in a card of its own. SectionNav lists
|
||||
them (a sticky column on wide screens, a "Jump to" bar below lg),
|
||||
|
|
@ -50,11 +59,11 @@ import { ArrowLeft, Check, Copy } from "@phosphor-icons/react";
|
|||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useLocation, useNavigate, useParams } from "react-router-dom";
|
||||
|
||||
import { get, post, patch, del, ApiError } from "../../lib/api.ts";
|
||||
import { get, post, patch, put, del, ApiError } from "../../lib/api.ts";
|
||||
import { isUnauthorized, useAuth } from "../../lib/auth.tsx";
|
||||
import { useAdminDetail } from "../../lib/adminTitle.tsx";
|
||||
import { useWideAdminPage } from "../../lib/adminWidth.tsx";
|
||||
import { ADMIN_ENTITIES, optionsPath, slugify } from "../../lib/adminSchema.ts";
|
||||
import { ADMIN_ENTITIES, PREVIEW_PATHS, optionsPath, slugify } from "../../lib/adminSchema.ts";
|
||||
import { atLeast } from "../../lib/roles.ts";
|
||||
import { Field, FieldGrid, Repeater, getPath, setPath } from "../../components/admin/fields.tsx";
|
||||
import {
|
||||
|
|
@ -154,6 +163,8 @@ export default function EntityEdit() {
|
|||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [slugTouched, setSlugTouched] = useState(false);
|
||||
// This record's draft, when it has one: who saved it, when, stale.
|
||||
const [draft, setDraft] = useState<any>(null);
|
||||
|
||||
// The last state the server confirmed. Everything else compares
|
||||
// against this to decide whether there's anything to lose.
|
||||
|
|
@ -191,8 +202,17 @@ export default function EntityEdit() {
|
|||
setForm(start);
|
||||
} else {
|
||||
const data = await get(`/admin/${manifest.key}/${id}`, { ttl: 0 });
|
||||
setForm(data.row);
|
||||
baseline.current = JSON.stringify(data.row);
|
||||
const saved = (await get(`/admin/${manifest.key}/${id}/draft`, { ttl: 0 })).draft;
|
||||
// With a draft, the form is the draft, over the live record's
|
||||
// updated_at so publishing it passes the concurrency check.
|
||||
const start = saved
|
||||
? data.row.updated_at === undefined
|
||||
? saved.payload
|
||||
: { ...saved.payload, updated_at: data.row.updated_at }
|
||||
: data.row;
|
||||
setDraft(saved);
|
||||
setForm(start);
|
||||
baseline.current = JSON.stringify(start);
|
||||
}
|
||||
setMessage(null);
|
||||
} catch (err) {
|
||||
|
|
@ -292,7 +312,8 @@ export default function EntityEdit() {
|
|||
|
||||
setForm(data.row);
|
||||
baseline.current = JSON.stringify(data.row);
|
||||
setMessage({ tone: "ok", text: "Saved." });
|
||||
setMessage({ tone: "ok", text: draft ? "Published." : "Saved." });
|
||||
setDraft(null);
|
||||
|
||||
if (isNew) navigate(`/admin/${manifest.key}/${data.row.id}`, { replace: true });
|
||||
} catch (err) {
|
||||
|
|
@ -321,6 +342,64 @@ export default function EntityEdit() {
|
|||
}
|
||||
}
|
||||
|
||||
/* Saves the form as the draft. True when it took. */
|
||||
async function saveDraft(): Promise<boolean> {
|
||||
setSaving(true);
|
||||
setErrors({});
|
||||
setMessage(null);
|
||||
try {
|
||||
const data = await put(`/admin/${manifest.key}/${id}/draft`, form);
|
||||
setDraft(data.draft);
|
||||
baseline.current = JSON.stringify(form);
|
||||
setMessage({ tone: "ok", text: "Draft saved. It isn't live until you publish it." });
|
||||
return true;
|
||||
} catch (err) {
|
||||
if (isUnauthorized(err)) {
|
||||
navigate("/admin/login", { replace: true });
|
||||
return false;
|
||||
}
|
||||
if (err instanceof ApiError) {
|
||||
setErrors(err.fields ?? {});
|
||||
setMessage({
|
||||
tone: "error",
|
||||
text: err.fields ? "Some fields need attention." : friendly(err.message, manifest.singular),
|
||||
});
|
||||
} else {
|
||||
setMessage({ tone: "error", text: "Couldn't reach the server." });
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function preview() {
|
||||
const path = PREVIEW_PATHS[manifest.key]?.(form);
|
||||
if (!path) return;
|
||||
// Opened now, while this is still the click, so it isn't taken
|
||||
// for a popup; it's sent to the page once the draft is saved.
|
||||
const tab = window.open("about:blank", "_blank");
|
||||
if ((dirty || !draft) && !(await saveDraft())) {
|
||||
tab?.close();
|
||||
return;
|
||||
}
|
||||
const url = `${path}${path.includes("?") ? "&" : "?"}preview=${encodeURIComponent(`${manifest.key}/${id}`)}`;
|
||||
if (tab) tab.location.href = url;
|
||||
else window.location.href = url;
|
||||
}
|
||||
|
||||
async function discardDraft() {
|
||||
if (!window.confirm("Discard this draft? The live version stays as it is.")) return;
|
||||
try {
|
||||
await del(`/admin/${manifest.key}/${id}/draft`);
|
||||
setDraft(null);
|
||||
await load();
|
||||
setMessage({ tone: "ok", text: "Draft discarded." });
|
||||
} catch (err) {
|
||||
setMessage({ tone: "error", text: err instanceof ApiError ? err.message : "Couldn't reach the server." });
|
||||
}
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
if (!window.confirm(`Delete ${heading}? Its links, blocks and roles go with it.`)) return;
|
||||
|
||||
|
|
@ -383,6 +462,20 @@ export default function EntityEdit() {
|
|||
{isNew ? `New ${manifest.singular}` : heading}
|
||||
</h1>
|
||||
|
||||
{draft && (
|
||||
<div className="notice mt-4 p-4 text-sm">
|
||||
<p className="text-body">
|
||||
<strong>You're editing a draft</strong>, saved{draft.updated_by ? ` by ${draft.updated_by}` : ""} on{" "}
|
||||
{draft.updated_at}. It isn't live: Publish puts it on the site, Discard draft throws it away.
|
||||
</p>
|
||||
{draft.stale && (
|
||||
<p className="mt-1 text-danger">
|
||||
The live version was saved after this draft was started. Publishing replaces those changes with the draft.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ImportedNote />
|
||||
{fromRequest && (
|
||||
<RequestedChanges
|
||||
|
|
@ -508,11 +601,41 @@ export default function EntityEdit() {
|
|||
<button
|
||||
type="button"
|
||||
onClick={save}
|
||||
disabled={saving || !dirty}
|
||||
disabled={saving || (!dirty && !draft)}
|
||||
className="btn bg-action px-6 py-2 text-white transition-colors hover:bg-action-hover disabled:bg-muted/25"
|
||||
>
|
||||
{saving ? "Saving…" : isNew ? "Create" : "Save changes"}
|
||||
{saving ? "Saving…" : isNew ? "Create" : draft ? "Publish" : "Save changes"}
|
||||
</button>
|
||||
{!isNew && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={saveDraft}
|
||||
disabled={saving || !dirty}
|
||||
className="btn border border-brand px-4 py-2 text-sm text-link transition-colors hover:bg-tint disabled:opacity-50"
|
||||
>
|
||||
Save draft
|
||||
</button>
|
||||
)}
|
||||
{!isNew && PREVIEW_PATHS[manifest.key]?.(form) && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={preview}
|
||||
disabled={saving}
|
||||
className="btn border border-brand px-4 py-2 text-sm text-link transition-colors hover:bg-tint disabled:opacity-50"
|
||||
>
|
||||
Preview
|
||||
</button>
|
||||
)}
|
||||
{draft && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={discardDraft}
|
||||
disabled={saving}
|
||||
className="btn border border-danger/40 px-4 py-2 text-sm text-danger transition-colors hover:bg-danger-tint"
|
||||
>
|
||||
Discard draft
|
||||
</button>
|
||||
)}
|
||||
{!isNew && !singleton && canDelete && (
|
||||
<button
|
||||
type="button"
|
||||
|
|
|
|||
|
|
@ -29,6 +29,8 @@ export default function EntityList() {
|
|||
const [params, setParams] = useSearchParams();
|
||||
const [rows, setRows] = useState<any[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
// Ids with a draft waiting (server/src/drafts.js), marked in the list.
|
||||
const [drafts, setDrafts] = useState<Set<string>>(() => new Set());
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
const [options, setOptions] = useState<any>({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
|
@ -57,6 +59,7 @@ export default function EntityList() {
|
|||
]);
|
||||
setRows(list.rows);
|
||||
setTotal(list.total);
|
||||
setDrafts(new Set((list.drafts ?? []).map(String)));
|
||||
setOptions(opts.options);
|
||||
} catch (err) {
|
||||
if (isUnauthorized(err)) return navigate("/admin/login", { replace: true });
|
||||
|
|
@ -203,13 +206,18 @@ export default function EntityList() {
|
|||
}`}
|
||||
>
|
||||
{column.key === linkKey ? (
|
||||
<Link
|
||||
to={`/admin/${manifest.key}/${row.id}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="hover:underline"
|
||||
>
|
||||
{row[column.key] || row.id}
|
||||
</Link>
|
||||
<>
|
||||
<Link
|
||||
to={`/admin/${manifest.key}/${row.id}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="hover:underline"
|
||||
>
|
||||
{row[column.key] || row.id}
|
||||
</Link>
|
||||
{drafts.has(String(row.id)) && (
|
||||
<span className="ml-2 bg-tint px-2 py-0.5 text-xs font-medium text-link">Draft</span>
|
||||
)}
|
||||
</>
|
||||
) : column.widget === "bool" ? (
|
||||
row[column.key] ? (
|
||||
"Yes"
|
||||
|
|
|
|||
|
|
@ -95,6 +95,12 @@ export const DATA_NAV = {
|
|||
label: "Links/redirects",
|
||||
blurb: "Short /go/ links for the newsletter, with click counts, Plausible and UTM tracking.",
|
||||
},
|
||||
{
|
||||
to: "/admin/profiles",
|
||||
label: "Profile accounts",
|
||||
blurb: "Invite people to make a profile account, approve their claims to a People record, and link their Discord.",
|
||||
minRole: "admin",
|
||||
},
|
||||
{
|
||||
to: "/admin/blog_posts",
|
||||
label: "Blog posts",
|
||||
|
|
@ -114,6 +120,12 @@ export const PAGES_NAV = {
|
|||
label: "Pages",
|
||||
blurb: "What a page shows and in what order.",
|
||||
children: [
|
||||
// The header's and footer's links, page titles and hidden pages.
|
||||
{
|
||||
to: "/admin/navigation",
|
||||
label: "Navigation",
|
||||
blurb: "The header's pages and buttons, the footer's links, each page's title and intro, and which pages are hidden.",
|
||||
},
|
||||
// One record, not a list: the item opens it directly.
|
||||
{
|
||||
to: "/admin/front_page",
|
||||
|
|
@ -147,6 +159,11 @@ export const PAGES_NAV = {
|
|||
label: "History",
|
||||
blurb: "Its sections: the timeline (its entries are under Data), and anything else.",
|
||||
},
|
||||
{
|
||||
to: "/admin/shop_page",
|
||||
label: "Shop",
|
||||
blurb: "The shop's intro page: its sections and the links out to the store.",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
|
|
@ -227,7 +244,7 @@ export const PANEL_NAV = {
|
|||
{
|
||||
to: SITE_SETTINGS,
|
||||
label: "Site settings",
|
||||
blurb: "The site's name, description, preview image, icons, page titles and search indexing.",
|
||||
blurb: "The site's name, description, preview image, icons, colors, access groups and search indexing.",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
|
|
|||
|
|
@ -7,8 +7,9 @@
|
|||
the two sets are kept deliberately in step (MIN_MESSAGE, and the
|
||||
ids in FEEDBACK_TYPES).
|
||||
|
||||
The page and section options come from navConfig, so adding a
|
||||
page to the nav adds it to this form too.
|
||||
The page and section options come from the header's pages (Pages
|
||||
→ Navigation, useSiteNav.ts), so adding a page to the nav adds it
|
||||
to this form too.
|
||||
|
||||
With fixedType the type is set and neither picker shows. The
|
||||
Privacy page uses it for data requests (DATA_REQUEST), which also
|
||||
|
|
@ -18,7 +19,7 @@
|
|||
import { CaretDown } from '@phosphor-icons/react';
|
||||
import { useState } from "react";
|
||||
import { post, ApiError } from "../../lib/api.ts";
|
||||
import { PAGE_LINKS } from "../../navConfig.ts";
|
||||
import { useSiteNav } from "../../lib/useSiteNav.ts";
|
||||
import { useNavSections, type NavSection } from "../../lib/navSections.ts";
|
||||
import { DATA_REQUEST, FEEDBACK_TYPES } from "../../data/feedbackTypes.ts";
|
||||
import { accentText, BRAND } from '../../lib/color.ts'
|
||||
|
|
@ -185,6 +186,7 @@ export function TilePicker({
|
|||
|
||||
function LocationPicker({ page, section, onPageChange, onSectionChange }) {
|
||||
const sectionsOf = useNavSections();
|
||||
const { pages } = useSiteNav();
|
||||
const sections = page === SITE_WIDE ? [] : sectionsOf(page);
|
||||
|
||||
return (
|
||||
|
|
@ -210,7 +212,7 @@ function LocationPicker({ page, section, onPageChange, onSectionChange }) {
|
|||
}}
|
||||
>
|
||||
<option value={SITE_WIDE}>Not page-specific</option>
|
||||
{PAGE_LINKS.map((p) => (
|
||||
{pages.map((p) => (
|
||||
<option key={p.path} value={p.path}>
|
||||
{p.label}
|
||||
</option>
|
||||
|
|
@ -238,9 +240,9 @@ function LocationPicker({ page, section, onPageChange, onSectionChange }) {
|
|||
}
|
||||
|
||||
// Human-readable version of the picked location, for the thank-you panel.
|
||||
function describeLocation(page, section, sectionsOf: (path: string) => NavSection[]) {
|
||||
function describeLocation(page, section, sectionsOf: (path: string) => NavSection[], pages: { path: string; label: string }[]) {
|
||||
if (page === SITE_WIDE) return null;
|
||||
const pageLabel = PAGE_LINKS.find((p) => p.path === page)?.label ?? page;
|
||||
const pageLabel = pages.find((p) => p.path === page)?.label ?? page;
|
||||
const sectionLabel = sectionsOf(page).find(
|
||||
(s) => s.hash === section,
|
||||
)?.label;
|
||||
|
|
@ -251,6 +253,7 @@ function describeLocation(page, section, sectionsOf: (path: string) => NavSectio
|
|||
|
||||
export default function FeedbackForm({ fixedType }: { fixedType?: string } = {}) {
|
||||
const sectionsOf = useNavSections();
|
||||
const { pages } = useSiteNav();
|
||||
const request = fixedType === DATA_REQUEST.id;
|
||||
const [type, setType] = useState<any>(fixedType ?? null);
|
||||
const [page, setPage] = useState(SITE_WIDE);
|
||||
|
|
@ -320,7 +323,7 @@ export default function FeedbackForm({ fixedType }: { fixedType?: string } = {})
|
|||
}
|
||||
|
||||
if (status === "sent") {
|
||||
const where = describeLocation(page, section, sectionsOf);
|
||||
const where = describeLocation(page, section, sectionsOf, pages);
|
||||
return (
|
||||
<div
|
||||
aria-live="polite"
|
||||
|
|
|
|||
|
|
@ -19,8 +19,8 @@
|
|||
site like every other choice), a full http(s) address, or a bare
|
||||
domain, which gets https:// in front.
|
||||
|
||||
The main pages come from navConfig.ts, the same list the header
|
||||
draws; records come from GET /directory, which lists only what's
|
||||
The main pages come from Pages → Navigation (useSiteNav.ts), the
|
||||
same list the header draws; records come from GET /directory, which lists only what's
|
||||
published, and their URLs from hrefs.ts, the same builders the
|
||||
site links with. So a code can only point at a page that exists.
|
||||
|
||||
|
|
@ -34,7 +34,7 @@
|
|||
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
|
||||
import QrCode, { QR_DOVE, QR_INK, QR_PAPER, type QrCenter } from '../../components/QrCode.tsx'
|
||||
import { NAV_ACTIONS, PAGE_LINKS } from '../../navConfig.ts'
|
||||
import { useSiteNav } from '../../lib/useSiteNav.ts'
|
||||
import { useNavSections } from '../../lib/navSections.ts'
|
||||
import { awardHref, blogHref, eventHref, orgHref, personHref, teamHref } from '../../lib/hrefs.ts'
|
||||
import { siteUrl } from '../../lib/site.ts'
|
||||
|
|
@ -145,22 +145,21 @@ type Choice = { path: string; label: string }
|
|||
type Group = { label?: string; choices: Choice[] }
|
||||
|
||||
/* The header's pages, then any nav action that is a page of its own
|
||||
rather than an anchor on one of them (Give, not Contact Us). */
|
||||
function mainPages(): Choice[] {
|
||||
const pages = PAGE_LINKS.map((p) => ({ path: p.path, label: p.label }))
|
||||
on the site rather than an anchor on one of them (Give, not
|
||||
Contact Us). */
|
||||
function mainPages(nav: ReturnType<typeof useSiteNav>): Choice[] {
|
||||
const pages = nav.pages.map((p) => ({ path: p.path, label: p.label }))
|
||||
const known = new Set(pages.map((p) => p.path))
|
||||
for (const action of NAV_ACTIONS) {
|
||||
const path = action.to.split('#')[0]
|
||||
if (!action.to.includes('#') && !known.has(path)) {
|
||||
pages.push({ path, label: action.label })
|
||||
known.add(path)
|
||||
}
|
||||
for (const action of nav.actions) {
|
||||
if (!action.path.startsWith('/') || action.path.includes('#') || known.has(action.path)) continue
|
||||
pages.push({ path: action.path, label: action.label })
|
||||
known.add(action.path)
|
||||
}
|
||||
return pages
|
||||
}
|
||||
|
||||
function groupsFor(kind: Kind, directory: Directory | null): Group[] {
|
||||
if (kind === 'pages') return [{ choices: mainPages() }]
|
||||
function groupsFor(kind: Kind, directory: Directory | null, nav: ReturnType<typeof useSiteNav>): Group[] {
|
||||
if (kind === 'pages') return [{ choices: mainPages(nav) }]
|
||||
if (!directory) return []
|
||||
|
||||
switch (kind) {
|
||||
|
|
@ -268,7 +267,8 @@ export default function QrCodeMaker() {
|
|||
const [copied, setCopied] = useState(false)
|
||||
const svgRef = useRef<SVGSVGElement>(null)
|
||||
|
||||
const groups = useMemo(() => groupsFor(kind, directory), [kind, directory])
|
||||
const nav = useSiteNav()
|
||||
const groups = useMemo(() => groupsFor(kind, directory, nav), [kind, directory, nav])
|
||||
const choices = useMemo(() => groups.flatMap((group) => group.choices), [groups])
|
||||
// Past FILTER_FROM records, a box above the select narrows them;
|
||||
// the one chosen always stays.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue