Staff exclusions + contact-password auth sync

- contacts.password now auto-syncs to auth.users.encrypted_password via
  trg_contact_password_sync, so setting a password on the contact row in the
  Supabase UI makes it work with signInWithPassword immediately (fixes staff
  like Bruno not being able to log in with a UI-set password). One-time
  reconciliation in the migration.
- Staff excluded from the leaderboard: _sync_leaderboard skips/removes staff
  rows, get_leaderboard() filters type='staff', seed no longer inserts staff.
  Affects the attendee Leaderboard and the admin Dashboard 'Top points'.
- Home/Agenda/Profile identical for all roles: Home quick-action always
  'Scan & connect' (no 'Check-in' relabel), footer role badge removed, tab
  label always 'Scan' (staff keep check-in via the Scan screen mode toggle).
- Profile: removed the duplicate Staff pill (type pill already shows Staff).
- Agenda session sheet: 'Download material' moved to the bottom of the button
  stack with spacing.
- Docs updated (schema, rpcs, seed, screens, architecture, next-steps).

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
This commit is contained in:
committed 2026-08-23 18:27:01 +02:00
1 parent 0221b1a8c0
commit 5886de9d19
12 files changed
+203 -45

No files matched your search

+3 -1
View File
@@ -80,7 +80,9 @@ function Shell() {
); );
} }
const scanLabel = contact.is_admin ? 'Check-in' : 'Scan'; // The home page (incl. the tab bar) is identical for every role. Staff keep
// their check-in capability inside the Scan screen (Attendee/Staff toggle).
const scanLabel = 'Scan';
return ( return (
<div className="app"> <div className="app">
+6 -7
View File
@@ -199,13 +199,6 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
</div> </div>
)} )}
{/* Material download (all attendees). */}
{selected.material_path && (
<a className="btn primary" href={sessionMaterialUrl(selected.material_path)} target="_blank" rel="noreferrer">
📎 Download material
</a>
)}
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{selStatus === 'done' && selCheckedIn && ( {selStatus === 'done' && selCheckedIn && (
<button className="btn primary" onClick={() => openFeedback(selected.id)}> <button className="btn primary" onClick={() => openFeedback(selected.id)}>
@@ -223,6 +216,12 @@ export function Agenda({ openFeedback }: { openFeedback: (sessionId: string) =>
> >
{pickFor(selected.slot_id) === selected.id ? 'Remove my pick' : 'Pick this session'} {pickFor(selected.slot_id) === selected.id ? 'Remove my pick' : 'Pick this session'}
</button> </button>
{/* Material download (all attendees) — pinned to the bottom. */}
{selected.material_path && (
<a className="btn primary" href={sessionMaterialUrl(selected.material_path)} target="_blank" rel="noreferrer">
📎 Download material
</a>
)}
</div> </div>
</> </>
)} )}
+3 -9
View File
@@ -2,9 +2,9 @@ import { useEffect, useState } from 'react';
import { useAuth } from '../context/AuthContext'; import { useAuth } from '../context/AuthContext';
import { useEvent } from '../lib/useEvent'; import { useEvent } from '../lib/useEvent';
import { getMyCheckins, getMyPreferences } from '../lib/api'; import { getMyCheckins, getMyPreferences } from '../lib/api';
import { capWords, fmtRange, greeting, slotStatus } from '../lib/time'; import { fmtRange, greeting, slotStatus } from '../lib/time';
import type { Preference } from '../lib/types'; import type { Preference } from '../lib/types';
import { Avatar, Empty, Spinner } from '../components/ui'; import { Empty, Spinner } from '../components/ui';
export function Home({ go }: { go: (tab: string) => void }) { export function Home({ go }: { go: (tab: string) => void }) {
const { contact, registration } = useAuth(); const { contact, registration } = useAuth();
@@ -53,7 +53,6 @@ export function Home({ go }: { go: (tab: string) => void }) {
} }
const points = registration?.points ?? 0; const points = registration?.points ?? 0;
const isStaff = contact.is_admin;
const pickFor = (slotId: number) => prefs.find((p) => p.slot_id === slotId)?.session_id; const pickFor = (slotId: number) => prefs.find((p) => p.slot_id === slotId)?.session_id;
const current = slots.find(({ slot }) => slotStatus(slot, now) === 'now'); const current = slots.find(({ slot }) => slotStatus(slot, now) === 'now');
const next = slots.find(({ slot }) => slotStatus(slot, now) === 'next'); const next = slots.find(({ slot }) => slotStatus(slot, now) === 'next');
@@ -130,7 +129,7 @@ export function Home({ go }: { go: (tab: string) => void }) {
<div className="qa-grid"> <div className="qa-grid">
<div className="qa" onClick={() => go('scan')}> <div className="qa" onClick={() => go('scan')}>
<span className="ico">📷</span> <span className="ico">📷</span>
<span className="lbl">{isStaff ? 'Check-in' : 'Scan & connect'}</span> <span className="lbl">Scan & connect</span>
</div> </div>
<div className="qa" onClick={() => go('agenda')}> <div className="qa" onClick={() => go('agenda')}>
<span className="ico">📅</span> <span className="ico">📅</span>
@@ -146,11 +145,6 @@ export function Home({ go }: { go: (tab: string) => void }) {
</div> </div>
</div> </div>
<div style={{ height: 8 }} /> <div style={{ height: 8 }} />
{registration && registration.type !== 'attendee' && (
<div className="muted small" style={{ textAlign: 'center', opacity: 0.5 }}>
<Avatar name={contact.full_name} id={contact.email} size={22} fs={9} /> {capWords(registration.type)}
</div>
)}
</section> </section>
); );
} }
+1 -1
View File
@@ -76,7 +76,7 @@ export function Profile() {
<div className="muted small">{contact.email}</div> <div className="muted small">{contact.email}</div>
<div className="row" style={{ justifyContent: 'center', marginTop: 10, gap: 8 }}> <div className="row" style={{ justifyContent: 'center', marginTop: 10, gap: 8 }}>
{registration && <span className={`pill reg-${registration.type}`}>{capWords(registration.type)}</span>} {registration && <span className={`pill reg-${registration.type}`}>{capWords(registration.type)}</span>}
{contact.is_admin && <span className="pill admin">staff</span>} {contact.is_admin && registration?.type !== 'staff' && <span className="pill admin">staff</span>}
<span className="pill amber">⚡ {points} pts</span> <span className="pill amber">⚡ {points} pts</span>
</div> </div>
</div> </div>
+7 -5
View File
@@ -130,11 +130,13 @@ the work atomically, and the `leaderboard` table change fans out over Realtime.
- **Attendees & staff:** the **QR token is the Supabase Auth password**; the - **Attendees & staff:** the **QR token is the Supabase Auth password**; the
**email is the identifier**. Login is a standard **email is the identifier**. Login is a standard
`signInWithPassword({ email, password: qrToken })`. `signInWithPassword({ email, password: qrToken })`.
- **APPE Admin:** logs in with **email + a real password** (event-independent, so - **APPE Admin / staff:** can log in with **email + a real password**
it works for any event). The password is recorded in `contacts.password` and (event-independent, so it works for any event). The password is recorded in
must match the bcrypt hash in `auth.users.encrypted_password`. It is set `contacts.password`; a trigger (`trg_contact_password_sync`) **auto-syncs** it
directly in Supabase (no self-service UI). Staff can also open the admin app as the bcrypt hash in `auth.users.encrypted_password`, so setting it in the
with their email + QR token, since that is their Auth password. Supabase Table Editor makes it work with `signInWithPassword` immediately.
Staff can also still log in with their email + QR token (their seeded Auth
password).
- `enable_confirmations = false`, so **no email is sent** — the email is only a - `enable_confirmations = false`, so **no email is sent** — the email is only a
"confirm it's you" check against the ticket purchase. "confirm it's you" check against the ticket purchase.
- After login, the app holds a **session JWT** (in `localStorage`) that lasts - After login, the app holds a **session JWT** (in `localStorage`) that lasts
+5 -2
View File
@@ -43,7 +43,10 @@ The single place points change. In one transaction it:
### `_sync_leaderboard(p_event_id, p_contact_email)` ### `_sync_leaderboard(p_event_id, p_contact_email)`
Upserts the `leaderboard` row for that (event, contact) from `registrations` + Upserts the `leaderboard` row for that (event, contact) from `registrations` +
`contacts` (`on conflict (event_id, contact_email) do update ...`). This is what `contacts` (`on conflict (event_id, contact_email) do update ...`). This is what
makes the leaderboard a consistent, Realtime-friendly mirror. makes the leaderboard a consistent, Realtime-friendly mirror. **Staff are
excluded:** if the contact's registration `type` is `staff` (or there is no
registration), the function **deletes** any existing leaderboard row instead of
inserting — so staff never appear on the board even if they hold points.
### `_recalc_event_aggregates(p_event_id)` ### `_recalc_event_aggregates(p_event_id)`
Recomputes the `events` aggregate columns (`num_sessions`, `num_speakers`, Recomputes the `events` aggregate columns (`num_sessions`, `num_speakers`,
@@ -54,7 +57,7 @@ triggers and the feedback RPC.
| Function | Returns | Used for | | Function | Returns | Used for |
|---|---|---| |---|---|---|
| `get_leaderboard()` | `event_id, contact_email, full_name, points` (active event, ordered by points) | Leaderboard initial load + realtime re-fetch | | `get_leaderboard()` | `event_id, contact_email, full_name, points` (active event, **staff excluded**, ordered by points) | Leaderboard initial load + realtime re-fetch |
| `lanyard_lookup(p_qr_token)` | `email, full_name, linkedin_url` (null unless `show_linkedin`), `show_email`, `registration_type` | Resolve a scanned QR (pre-login + connect) | | `lanyard_lookup(p_qr_token)` | `email, full_name, linkedin_url` (null unless `show_linkedin`), `show_email`, `registration_type` | Resolve a scanned QR (pre-login + connect) |
| `get_public_contacts()` | `email, full_name, linkedin_url`, `show_email`, `registration_type` (active-event registrants) | Connections name/type lookups | | `get_public_contacts()` | `email, full_name, linkedin_url`, `show_email`, `registration_type` (active-event registrants) | Connections name/type lookups |
| `get_agenda()` | flat rows: slot fields + session fields + `speakers` (string_agg) | Agenda + Home | | `get_agenda()` | flat rows: slot fields + session fields + `speakers` (string_agg) | Agenda + Home |
+5 -1
View File
@@ -56,7 +56,7 @@ password).
| `show_email` | `boolean` | default `false` — visibility toggle | | `show_email` | `boolean` | default `false` — visibility toggle |
| `show_linkedin` | `boolean` | default `false` — visibility toggle | | `show_linkedin` | `boolean` | default `false` — visibility toggle |
| `is_admin` | `boolean` | default `false` — **staff = admin (merged)**; grants check-in + APPE Admin access | | `is_admin` | `boolean` | default `false` — **staff = admin (merged)**; grants check-in + APPE Admin access |
| `password` | `text` | nullable — **admin-only**: the APPE Admin login password (event-independent). To work it must match the bcrypt hash in `auth.users.encrypted_password`. Set directly in Supabase (no self-service UI) | | `password` | `text` | nullable — the **login password** (event-independent) for admin/staff. Setting it (e.g. in the Supabase Table Editor) **auto-syncs** the bcrypt hash into `auth.users.encrypted_password` via the `trg_contact_password_sync` trigger, so it works with `signInWithPassword` immediately |
| `external_id` | `text` | nullable — the Pretix order code (set by the sync) | | `external_id` | `text` | nullable — the Pretix order code (set by the sync) |
| `created_at` | `timestamptz` | | | `created_at` | `timestamptz` | |
@@ -247,6 +247,10 @@ truth — it is kept in sync transactionally by the RPCs (see
this table to update the leaderboard live. See this table to update the leaderboard live. See
[../frontend/screens.md#leaderboard](../frontend/screens.md#leaderboard). [../frontend/screens.md#leaderboard](../frontend/screens.md#leaderboard).
> **Staff are excluded.** `_sync_leaderboard` skips (and removes) staff rows, so
> staff never appear on the board even if they hold points. `get_leaderboard()`
> also filters `type = 'staff'` as defense in depth.
## `points_log` — audit trail ## `points_log` — audit trail
Powers the per-category points breakdown on the Profile screen (per event). Powers the per-category points breakdown on the Profile screen (per event).
+7 -5
View File
@@ -15,7 +15,7 @@ Source of truth: [`supabase/seed.sql`](../../supabase/seed.sql). The seed runs o
| `slots` | 6 | 23 Oct, 09:00–15:45 (see table below) | | `slots` | 6 | 23 Oct, 09:00–15:45 (see table below) |
| `sessions` | 18 | 3 per slot (Main Stage / Room A / Room B) | | `sessions` | 18 | 3 per slot (Main Stage / Room A / Room B) |
| `session_speakers` | 22 | M:N session → contact | | `session_speakers` | 22 | M:N session → contact |
| `leaderboard` | 13 | mirrored from `registrations` | | `leaderboard` | 10 | mirrored from `registrations`, **staff excluded** (13 registrants − 3 staff) |
| `points_log` | 16 | Ana's coherent breakdown + one `admin` entry per other user | | `points_log` | 16 | Ana's coherent breakdown + one `admin` entry per other user |
| Ana's demo state | — | 6 preferences, 2 check-ins, 4 connections, 1 feedback | | Ana's demo state | — | 6 preferences, 2 check-ins, 4 connections, 1 feedback |
@@ -43,10 +43,12 @@ Source of truth: [`supabase/seed.sql`](../../supabase/seed.sql). The seed runs o
## Demo accounts ## Demo accounts
**Attendees & staff** log in with **QR code** (typed or scanned) + **email** — **Attendees & staff** log in with **QR code** (typed or scanned) + **email** —
the QR token is the Auth password. The **APPE Admin** is different: it logs in the QR token is the Auth password. The **APPE Admin** (and any staff member you
with **email + password** (event-independent, so it works for any event). The give one) can also log in with **email + password** (event-independent, so it
admin's password is stored in `contacts.password` **and** as the bcrypt hash in works for any event). The password lives in `contacts.password`; a trigger
`auth.users.encrypted_password` (they must match). Set it directly in Supabase. (`trg_contact_password_sync`) **auto-syncs** it as the bcrypt hash in
`auth.users.encrypted_password`, so just set `contacts.password` in Supabase and
it works with `signInWithPassword` immediately.
| Person | Type | Login | Email | Start pts | | Person | Type | Login | Email | Start pts |
|---|---|---|---|---| |---|---|---|---|---|
+18 -11
View File
@@ -11,7 +11,7 @@ from `useAuth()` (`contact` + `registration`).
| Login | `Login.tsx` | shown when not authenticated | | Login | `Login.tsx` | shown when not authenticated |
| Home | `Home.tsx` | tab (default) | | Home | `Home.tsx` | tab (default) |
| Agenda | `Agenda.tsx` | tab | | Agenda | `Agenda.tsx` | tab |
| Scan / Check-in | `Scan.tsx` | tab (role-aware label) | | Scan | `Scan.tsx` | tab (staff get an Attendee/Staff mode toggle inside) |
| Connections | `Connections.tsx` | tab | | Connections | `Connections.tsx` | tab |
| Profile | `Profile.tsx` | tab | | Profile | `Profile.tsx` | tab |
| Leaderboard | `Leaderboard.tsx` | from Home (points pill / quick action) | | Leaderboard | `Leaderboard.tsx` | from Home (points pill / quick action) |
@@ -45,12 +45,14 @@ The landing screen. Shows:
- **Next card** — the pick for the next slot. - **Next card** — the pick for the next slot.
- **My picks today** — shows only **2 rows** (the current slot's pick + the next - **My picks today** — shows only **2 rows** (the current slot's pick + the next
slot's pick). "tap to change" is a **hyperlink** to the Agenda. slot's pick). "tap to change" is a **hyperlink** to the Agenda.
- **Footer type badge** — the registration-type pill is shown **only for non- - **Quick actions** — Scan & connect, Agenda, Connections, Leaderboard.
attendee** types (Attendee is the default and is not shown at the bottom).
- **Quick actions** — Scan & connect / Check-in, Agenda, Connections, Leaderboard.
- **No active event** — a graceful empty state ("No active event right now. - **No active event** — a graceful empty state ("No active event right now.
Check back soon!"). Check back soon!").
> **Identical for every role.** The Home screen (and the tab bar) is the same for
> attendees and staff — no role badge, no "Check-in" relabel. Staff keep their
> check-in capability inside the **Scan** screen (Attendee/Staff mode toggle).
Data: `useEvent()` (event + agenda + clock) + `getMyPreferences()` + Data: `useEvent()` (event + agenda + clock) + `getMyPreferences()` +
`getMyCheckins(email)`. Slot status comes from `slotStatus(slot, now)` `getMyCheckins(email)`. Slot status comes from `slotStatus(slot, now)`
([app-structure.md#the-event-clock](./app-structure.md#the-event-clock)). ([app-structure.md#the-event-clock](./app-structure.md#the-event-clock)).
@@ -71,8 +73,9 @@ user speaks shows a **"🎤 you"** tag; a session with material shows a **📎**
is uploaded yet, a **non-dismissible** "📎 Upload your session material" notice is uploaded yet, a **non-dismissible** "📎 Upload your session material" notice
with a file input. Uploading stores the file in the `materials` bucket and with a file input. Uploading stores the file in the `materials` bucket and
calls `set_session_material` (via `uploadSessionMaterial`). Once uploaded, the calls `set_session_material` (via `uploadSessionMaterial`). Once uploaded, the
notice is gone and a **📎 Download material** link appears (visible to **all** notice is gone and a **📎 Download material** button appears (visible to **all**
attendees). attendees), pinned to the **bottom** of the sheet's button stack (below
"Pick this session").
- Picking is "one per slot" — picking a new session in a slot replaces the old - Picking is "one per slot" — picking a new session in a slot replaces the old
pick (enforced by the `set_preference` RPC). pick (enforced by the `set_preference` RPC).
@@ -81,9 +84,10 @@ Data: `useEvent()` + `getMyPreferences()` + `getMyCheckins(email)` +
## Scan / Check-in ## Scan / Check-in
One screen, two modes (segmented control: **Attendee / Staff**). The default mode One screen, two modes (segmented control: **Attendee / Staff**). The tab label is
and the tab label are role-aware: staff (`contact.is_admin`) default to **Staff** always **"Scan"** (the home page is identical for every role); the **default mode**
mode and the tab reads **Check-in**. is role-aware — staff (`contact.is_admin`) default to **Staff** mode, attendees to
**Attendee** mode.
- **Attendee mode (connect):** scan a peer's lanyard → `lanyardLookup` → a - **Attendee mode (connect):** scan a peer's lanyard → `lanyardLookup` → a
"Connect with {name}?" sheet (with the peer's registration-type badge + LinkedIn "Connect with {name}?" sheet (with the peer's registration-type badge + LinkedIn
@@ -136,6 +140,8 @@ Data: `useEvent()` (session/slot) + `submitFeedback`.
The live leaderboard. The live leaderboard.
- **Podium** for the top 3 (1st/2nd/3rd bars), then the rest as ranked rows. - **Podium** for the top 3 (1st/2nd/3rd bars), then the rest as ranked rows.
- **Staff are excluded** — only attendees appear (enforced in
`get_leaderboard()` / `_sync_leaderboard`).
- **Your row is highlighted** (`me`). - **Your row is highlighted** (`me`).
- **Live:** subscribes to Realtime `postgres_changes` on the `leaderboard` table - **Live:** subscribes to Realtime `postgres_changes` on the `leaderboard` table
and re-fetches on any change — so it updates the moment points change anywhere. and re-fetches on any change — so it updates the moment points change anywhere.
@@ -154,8 +160,9 @@ event). The `leaderboard` table is kept in sync transactionally by the RPCs —
## Profile ## Profile
- **Header** — avatar, name, email, registration-type pill, a **staff** pill when - **Header** — avatar, name, email, registration-type pill, a **staff** pill
`contact.is_admin`, and a points pill. (only when `contact.is_admin` **and** the type isn't already `staff`, so it
never shows twice), and a points pill.
- **My QR code** — renders `registration.qr_token` (the token lives on the - **My QR code** — renders `registration.qr_token` (the token lives on the
registration, per event) as a scannable QR (`QrImage`). "Show this to staff for registration, per event) as a scannable QR (`QrImage`). "Show this to staff for
check-in and to peers to connect." check-in and to peers to connect."
+38 -3
View File
@@ -4,12 +4,15 @@ What's done, what's next, and the open decisions. The full roadmap lives in the
root [`roadmap.md`](../roadmap.md); this file is the working detail for the root [`roadmap.md`](../roadmap.md); this file is the working detail for the
current phase. current phase.
> **Current state:** Phases 0–8 are complete and verified, plus two polish > **Current state:** Phases 0–8 are complete and verified, plus three polish
> rounds: **Fixes & Refinements** (QR token moved to the registration, role-pill > rounds: **Fixes & Refinements** (QR token moved to the registration, role-pill
> capitalization, connection detail sheet + red-dot recalc, admin schedule > capitalization, connection detail sheet + red-dot recalc, admin schedule
> speaker multi-select + upload/speaker bug fixes, sponsor contact search) and > speaker multi-select + upload/speaker bug fixes, sponsor contact search),
> **Admin password + profile self-service** (admin logs in with email + password; > **Admin password + profile self-service** (admin logs in with email + password;
> attendees set LinkedIn + visibility on their Profile). > attendees set LinkedIn + visibility on their Profile), and **Staff exclusions
> + password sync** (setting `contacts.password` auto-syncs the Auth password;
> staff excluded from the leaderboard; Home/Agenda/Profile identical for all
> roles).
> Remaining work is cross-cutting (real event clock, deployment, testing) and > Remaining work is cross-cutting (real event clock, deployment, testing) and
> the open questions in [backend/interfaces.md](./backend/interfaces.md). > the open questions in [backend/interfaces.md](./backend/interfaces.md).
@@ -269,6 +272,38 @@ browser-verified.
`show_linkedin` is off and omits the email when `show_email` is off, so the `show_linkedin` is off and omits the email when `show_email` is off, so the
toggles actually control what other attendees see. toggles actually control what other attendees see.
## Staff exclusions + password sync — ✅ complete
Migration `20260828000000_staff_exclusions_password_sync.sql` + app changes, all
browser-verified.
**Setting `contacts.password` now works for login.**
- A trigger (`trg_contact_password_sync`) re-hashes `contacts.password` into
`auth.users.encrypted_password` whenever it's set/changed, so entering a
password on the contact row in the Supabase Table Editor makes it work with
`signInWithPassword` immediately (previously the two had to be kept in sync
by hand). A one-time reconciliation in the migration synced any already-set
passwords.
- This is how a staff member (e.g. Bruno) can be given a password and log in.
**Staff are excluded from the leaderboard.**
- `_sync_leaderboard` skips (and removes) staff rows, so staff never appear on
the board even if they hold points. `get_leaderboard()` also filters
`type = 'staff'` (defense in depth), and the seed no longer inserts staff.
- Affects the attendee Leaderboard **and** the admin Dashboard "Top points".
**Home / Agenda / Profile are identical for every role.**
- Home: the quick-action tile is always **"Scan & connect"** (was
"Check-in" for staff) and the footer role badge is removed. The tab bar label
is always **"Scan"** (was "Check-in" for staff).
- Staff keep their check-in capability **inside the Scan screen** (the
Attendee/Staff mode toggle), so the home page stays role-agnostic.
- Profile: the duplicate **Staff** pill is gone (the registration-type pill
already shows "Staff" for staff; the extra `is_admin` pill only shows for
admins whose type isn't staff).
- Agenda session sheet: **"Download material"** moved to the **bottom** of the
button stack (below "Pick this session") with proper spacing.
## Cross-cutting / later ## Cross-cutting / later
- **Real event clock** — replace the simulated `DEFAULT_NOW` - **Real event clock** — replace the simulated `DEFAULT_NOW`
@@ -0,0 +1,108 @@
-- =============================================================================
-- Convivo — Staff exclusions + contact-password → auth sync
--
-- 1. `contacts.password` now drives the Auth password. Setting it (e.g. from the
-- Supabase Table Editor) re-hashes it into `auth.users.encrypted_password`,
-- so an admin/staff member can log in with that password. This is what makes
-- "set the password on the contact row in Supabase" actually work for login.
--
-- 2. Staff are excluded from the leaderboard (the "top points" board). They can
-- still hold points on their registration, but they never appear on the
-- public leaderboard or the admin Dashboard's "Top points".
-- =============================================================================
-- -----------------------------------------------------------------------------
-- 1. CONTACT PASSWORD → AUTH PASSWORD SYNC
-- -----------------------------------------------------------------------------
-- When `contacts.password` is set/changed, re-hash it as the Auth password so
-- the value works with `signInWithPassword`. Security-definer (owner postgres)
-- so it can write `auth.users`. pgcrypto lives in the `extensions` schema.
create or replace function public._sync_contact_password()
returns trigger
language plpgsql security definer set search_path = public as $$
begin
if new.password is not null then
update auth.users
set encrypted_password = extensions.crypt(new.password, extensions.gen_salt('bf'))
where email = new.email;
end if;
return new;
end;
$$;
drop trigger if exists trg_contact_password_sync on public.contacts;
create trigger trg_contact_password_sync
after update of password on public.contacts
for each row
when (new.password is distinct from old.password and new.password is not null)
execute function public._sync_contact_password();
comment on column public.contacts.password is
'Admin/staff login password (event-independent). Setting this value re-hashes '
'it into auth.users.encrypted_password (see trg_contact_password_sync), so it '
'works with signInWithPassword. Set it directly in Supabase.';
-- One-time reconciliation: any contact that already has a password set (e.g.
-- entered in the Supabase Table Editor before this migration) gets it synced
-- into auth.users now, so it works immediately.
update auth.users u
set encrypted_password = extensions.crypt(c.password, extensions.gen_salt('bf'))
from public.contacts c
where u.email = c.email
and c.password is not null;
-- -----------------------------------------------------------------------------
-- 2. LEADERBOARD — EXCLUDE STAFF
-- -----------------------------------------------------------------------------
-- `_sync_leaderboard` is the single writer of the leaderboard mirror. Make it
-- skip staff (and remove any existing staff row), so staff never appear on the
-- board even if they earn points.
create or replace function public._sync_leaderboard(p_event_id uuid, p_contact_email text) returns void
language plpgsql security definer set search_path = public as $$
declare
v_type text;
begin
select r.type into v_type
from public.registrations r
where r.contact_email = p_contact_email and r.event_id = p_event_id;
-- Staff (or no registration) are excluded from the leaderboard.
if v_type is null or v_type = 'staff' then
delete from public.leaderboard
where event_id = p_event_id and contact_email = p_contact_email;
return;
end if;
insert into public.leaderboard (event_id, contact_email, full_name, points)
select p_event_id, c.email, c.full_name, r.points
from public.contacts c
join public.registrations r on r.contact_email = c.email and r.event_id = p_event_id
where c.email = p_contact_email
on conflict (event_id, contact_email) do update
set full_name = excluded.full_name,
points = excluded.points,
updated_at = now();
end;
$$;
-- Defense in depth: the read function also filters staff, so the board is
-- correct even if a stray staff row exists in the table.
create or replace function public.get_leaderboard()
returns table (event_id uuid, contact_email text, full_name text, points integer)
language sql stable security definer set search_path = public as $$
select l.event_id, l.contact_email, l.full_name, l.points
from public.leaderboard l
join public.events e on e.id = l.event_id
left join public.registrations r
on r.contact_email = l.contact_email and r.event_id = l.event_id
where e.is_active
and coalesce(r.type, 'attendee') <> 'staff'
order by l.points desc, l.full_name asc;
$$;
-- One-time cleanup: remove any staff rows already in the leaderboard.
delete from public.leaderboard l
using public.registrations r
where r.event_id = l.event_id
and r.contact_email = l.contact_email
and r.type = 'staff';
+2
View File
@@ -213,10 +213,12 @@ on conflict (event_id, contact_email, session_id) do nothing;
-- ----------------------------------------------------------------------------- -- -----------------------------------------------------------------------------
-- LEADERBOARD (mirror of registration points, per event) -- LEADERBOARD (mirror of registration points, per event)
-- ----------------------------------------------------------------------------- -- -----------------------------------------------------------------------------
-- Staff are excluded from the leaderboard (they don't compete for top points).
insert into public.leaderboard (event_id, contact_email, full_name, points) insert into public.leaderboard (event_id, contact_email, full_name, points)
select r.event_id, r.contact_email, c.full_name, r.points select r.event_id, r.contact_email, c.full_name, r.points
from public.registrations r from public.registrations r
join public.contacts c on c.email = r.contact_email join public.contacts c on c.email = r.contact_email
where r.type <> 'staff'
on conflict (event_id, contact_email) do update on conflict (event_id, contact_email) do update
set full_name = excluded.full_name, points = excluded.points, updated_at = now(); set full_name = excluded.full_name, points = excluded.points, updated_at = now();