Profile accounts: invites, any-Google sign-in, claiming People, visibility, Discord
Migration 076 adds a member role below viewer (the site and its own profile, never the admin: /api/admin now needs viewer), invites, person claims, a Discord link on accounts and people.hide_* switches. Public reads of people go through v_people_public, which nulls hidden fields, and the views that read people are rebuilt over it. Admins invite an email from Data -> Profile accounts (link shown once, emailed on request). The invitee sets a password or signs in with any Google account under that email, asks to claim their People record, and once approved edits it and chooses what shows at /account. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
0cc2a3f721
commit
e4c7e165d1
34 changed files with 2483 additions and 74 deletions
20
src/App.tsx
20
src/App.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 />}>
|
||||
|
|
@ -114,6 +121,9 @@ export default function App() {
|
|||
<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. */}
|
||||
|
|
@ -127,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 />} />
|
||||
|
|
@ -152,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 />} />
|
||||
|
|
@ -159,6 +168,7 @@ export default function App() {
|
|||
</Route>
|
||||
</Route>
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { Link } from "react-router-dom";
|
||||
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";
|
||||
|
|
@ -10,7 +11,8 @@ import { SOCIAL_LINKS } from "../data/socialLinks.ts";
|
|||
/* 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. */
|
||||
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";
|
||||
|
|
@ -27,6 +29,7 @@ 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">
|
||||
|
|
@ -144,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">
|
||||
<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}
|
||||
</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>
|
||||
)
|
||||
}
|
||||
|
|
@ -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: [
|
||||
|
|
|
|||
|
|
@ -123,7 +123,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);
|
||||
|
|
|
|||
|
|
@ -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 />;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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')
|
||||
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>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
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>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
@ -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",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue