Events 3.3.0, Accounts 1.3.0, contracts 1.11.0: Accounts looks like Events, backups; sign-out and upload fixes
- Accounts: account and admin pages in Cross Events' layout (top bar, sidebar, a page per section, dark footer); quick links to the church's sites (GET /me/apps); nightly pg_dump backups with Admin -> Backups (run, keep, download, audited; heartbeat lastBackupAt); a fuller built-in privacy notice with headings and bullets; a fixed favicon. /backups/ ignored (anchored, so src/backups is kept). - Contracts 1.11.0: people.removeDemo (only @example.com, never an admin). - Events: uploads served from the folder they're saved in (a backend started outside backend/ answered 404 for a logo it had just saved); Branding checks the file loads before saving; logout waits for the sign-out call so Accounts signs out too; set-demo removes the last demo's people from Accounts. Tests: Accounts 62 + e2e 8, Events 782, contracts 225; npm run check passes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,6 +5,28 @@ All notable changes to this project are documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project follows [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [3.3.0] - 2026-11-20
|
||||
|
||||
Works with Accounts 1.3.0 (needed for the demo-data part; with an older Accounts the old demo people
|
||||
just stay there).
|
||||
|
||||
### Fixed
|
||||
|
||||
- **An uploaded logo or favicon could point at a file that "didn't exist".** Uploads were saved in
|
||||
`backend/public/uploads` but served from `public/uploads` under whatever folder the backend
|
||||
was started from, so a backend started elsewhere answered 404 for a logo it had just saved. Both
|
||||
now use one folder (`src/utils/uploads.js`); logos saved before the fix show again. Settings →
|
||||
Branding also checks the new file loads before saving it, and says why an upload failed.
|
||||
- **Signing out didn't sign out of Accounts.** The navbar and bottom bar loaded the home page
|
||||
straight after starting the sign-out call, which cancelled it. `logout()` now waits for it, then
|
||||
goes to Accounts' sign-out (and back) itself.
|
||||
|
||||
### Changed
|
||||
|
||||
- **New demo data replaces the old demo people in Accounts too** (`set-demo`, `crosscode demo`,
|
||||
the Hub's Load demo data): the last demo's people are removed there first (contracts 1.11.0
|
||||
`people.removeDemo`, `src/accounts/move.ts removeDemoPeople`), then the new ones moved in.
|
||||
|
||||
## [3.2.0] - 2026-11-19
|
||||
|
||||
### Added
|
||||
|
||||
@@ -12,6 +12,13 @@ Write for church admins, not developers: no environment variables, endpoints or
|
||||
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
|
||||
-->
|
||||
|
||||
## 3.3.0
|
||||
|
||||
- **Fix:** a new logo or favicon sometimes didn't show after saving. It's saved and shown properly
|
||||
now, and logos that went missing this way come back.
|
||||
- **Fix:** signing out of this site now also signs you out of your church account.
|
||||
- Loading new demo data replaces the old demo people in the church's Accounts too.
|
||||
|
||||
## 3.2.0
|
||||
|
||||
- Cross Code now sees when an event is on at your church before an urgent update, so it isn't taken
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "3.2.0",
|
||||
"version": "3.3.0",
|
||||
"description": "Event Management System Backend",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -1888,6 +1888,9 @@ async function main() {
|
||||
if (profile.campuses) assignCampuses();
|
||||
buildAnalytics();
|
||||
|
||||
// 3.3.0: the church accounts of the people about to be cleared, so the old demo people leave
|
||||
// Accounts too (only demo addresses; Accounts checks).
|
||||
const oldSubs = (await prisma.user.findMany({ where: { id: { not: admin.id }, accountId: { not: null } }, select: { accountId: true } })).map(u => u.accountId);
|
||||
const cleared = await prisma.$transaction(async (tx) => {
|
||||
const result = await clearData(tx);
|
||||
for (const model of INSERT_ORDER) {
|
||||
@@ -1904,7 +1907,7 @@ async function main() {
|
||||
}, { maxWait: 10 * 1000, timeout: 5 * 60 * 1000 });
|
||||
clearScheduledEmails();
|
||||
const pastFinancials = await closePastEvents();
|
||||
const accounts = await demoAccounts();
|
||||
const accounts = await demoAccounts(oldSubs);
|
||||
|
||||
const count = (model, where = () => true) => (rows[model] || []).filter(where).length;
|
||||
console.log(`\nCleared ${cleared.tables} tables and ${cleared.users} users.`);
|
||||
@@ -1954,18 +1957,21 @@ async function main() {
|
||||
for (const s of staffTeam) console.log(` ${s.role.padEnd(10)} ${s.email}`);
|
||||
console.log(`Every other demo person also uses ${DEMO_PASSWORD}.`);
|
||||
if (accounts) {
|
||||
if (accounts.removed) console.log(`The ${accounts.removed} demo people of the last demo were removed from the church's Accounts.`);
|
||||
console.log(`Sign-in goes through the church's Accounts: ${accounts.moved} demo people have church accounts with that password${accounts.refused.length ? ` (${accounts.refused.length} couldn't: ${accounts.refused.map(r => `${r.email} ${r.reason}`).join('; ')})` : ''}.`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 3.0.0: with sign-in through the church's Accounts, the demo people are moved there too (with the
|
||||
* demo password), so they can sign in (src/accounts/move.ts moveNewPeople). A demo person whose
|
||||
* demo password), so they can sign in (src/accounts/move.ts moveNewPeople). 3.3.0: first, the last
|
||||
* demo's people (`oldSubs`) are removed from Accounts (removeDemoPeople), so Accounts has the
|
||||
* same people as the site. A demo person whose
|
||||
* email already has an account from an earlier demo is linked to it. The compiled code (dist/) on a
|
||||
* server; the TypeScript through tsx in development.
|
||||
*/
|
||||
let accountsDb = null;
|
||||
async function demoAccounts() {
|
||||
async function demoAccounts(oldSubs = []) {
|
||||
const dist = path.join(__dirname, '..', 'dist', 'accounts', 'move.js');
|
||||
let move;
|
||||
if (fs.existsSync(dist)) {
|
||||
@@ -1978,7 +1984,12 @@ async function demoAccounts() {
|
||||
const mode = await prisma.appSetting.findUnique({ where: { key: 'auth_mode' } });
|
||||
if (mode?.value !== 'accounts') return null;
|
||||
try {
|
||||
return await move.moveNewPeople(admin.accountId || null);
|
||||
// Accounts before 1.3.0 doesn't know the request: the new demo still moves, the old stays.
|
||||
const gone = await move.removeDemoPeople(oldSubs, admin.accountId || null).catch((e) => {
|
||||
console.warn(`[warn] The last demo's people couldn't be removed from Accounts (${e.message}); they stay there until Accounts is updated to 1.3.0 and the demo is loaded again.`);
|
||||
return { removed: 0 };
|
||||
});
|
||||
return { ...(await move.moveNewPeople(admin.accountId || null)), removed: gone.removed };
|
||||
} catch (e) {
|
||||
console.warn(`[warn] The demo people couldn't be moved to Accounts (${e.message}). Run the demo again once Accounts can be reached.`);
|
||||
process.exitCode = 1;
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
* deleted people stay Events-only. Recovery codes don't move (decision 2): Accounts shows new ones.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import { IMPORT_BATCH_MAX, phoneSchema, type ImportPerson, type ImportResult } from '@crosscode/contracts';
|
||||
import { IMPORT_BATCH_MAX, phoneSchema, REMOVE_DEMO_MAX, type ImportPerson, type ImportResult } from '@crosscode/contracts';
|
||||
import { siteUrl } from '../feed/context';
|
||||
import { accounts, accountsLink, AccountsUnavailable } from './client';
|
||||
import { accountsMessaging } from './messaging';
|
||||
@@ -263,6 +263,26 @@ export async function moveNewPeople(actor: string | null = null): Promise<{ move
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 3.3.0: new demo data replaced the old (set-demo), so the old demo people's church accounts go
|
||||
* too (contracts 1.11.0 `people.removeDemo`). Accounts removes only demo addresses
|
||||
* (`@example.com`) it knows through this site, never an Accounts admin. Only while sign-in goes
|
||||
* through Accounts; returns how many went and how many it kept.
|
||||
*/
|
||||
export async function removeDemoPeople(subs: string[], actor: string | null = null): Promise<{ removed: number; kept: number }> {
|
||||
const unique = [...new Set(subs.filter(Boolean))];
|
||||
if ((await authMode()) !== 'accounts' || !unique.length) return { removed: 0, kept: 0 };
|
||||
const auth = await accounts();
|
||||
let removed = 0;
|
||||
let kept = 0;
|
||||
for (const batch of chunk(unique, REMOVE_DEMO_MAX)) {
|
||||
const r = await auth.request<{ removed: number; kept: unknown[] }>({ type: 'people.removeDemo', actor, subs: batch }, { timeoutMs: 120000 });
|
||||
removed += r.removed;
|
||||
kept += r.kept.length;
|
||||
}
|
||||
return { removed, kept };
|
||||
}
|
||||
|
||||
/** The move. Throws MoveError when it doesn't finish; nothing changes for anyone then. */
|
||||
export async function move(opts: { actor: { id: string; role: string; name?: string }; adminIds: string[]; keepAccountsNotices?: boolean; ip?: string | null }): Promise<MoveReport> {
|
||||
const auth = await connected();
|
||||
|
||||
@@ -196,18 +196,11 @@ app.get('/docs', (req, res) => res.redirect(301, '/api/docs/v2'));
|
||||
// Pre-warm the settings cache so synchronous helpers have DB values from startup
|
||||
const { getSettingSync, warmCache } = require('./utils/settingsCache');
|
||||
warmCache().catch(() => {});
|
||||
// Uploaded branding assets can include SVGs, which may embed <script>/event
|
||||
// handlers. Serving them inline lets a compromised/malicious upload run script
|
||||
// in the site's origin if opened directly, so pin the safe response headers
|
||||
// (no inline execution, no MIME-sniffing to HTML/script) on every asset here.
|
||||
// Uploaded files, with safe headers (utils/uploads.js): served from the folder they're saved in
|
||||
// (3.3.0; before, from one relative to where the process started, so a new logo could be "missing").
|
||||
// Stored paths stay "/uploads/…"; they're given out as /api/uploads/… (v2/schemas.ts absoluteUrl).
|
||||
// /uploads still answers for links made before 2.2.0.
|
||||
const uploads = express.static('public/uploads', {
|
||||
setHeaders: (res) => {
|
||||
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
},
|
||||
});
|
||||
const uploads = require('./utils/uploads').serveUploads();
|
||||
app.use('/api/uploads', uploads, notFound); // a missing file is 404, not "API v1 removed"
|
||||
app.use('/uploads', uploads);
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ const path = require('path');
|
||||
const fs = require('fs');
|
||||
const crypto = require('crypto');
|
||||
const multer = require('multer');
|
||||
const { UPLOADS_DIR } = require('../utils/uploads');
|
||||
|
||||
// Builds a filename multer can never be tricked into escaping the upload
|
||||
// directory with — extension only, no attacker-controlled path segments.
|
||||
@@ -13,7 +14,7 @@ function safeFilename(prefix, ext) {
|
||||
// Setup multer storage
|
||||
const storage = multer.diskStorage({
|
||||
destination: function (req, file, cb) {
|
||||
const uploadPath = path.join(__dirname, '..', '..','public', 'uploads', 'events');
|
||||
const uploadPath = path.join(UPLOADS_DIR, 'events');
|
||||
|
||||
// Check if the upload location exists
|
||||
try {
|
||||
@@ -52,7 +53,7 @@ const upload = multer({
|
||||
// Logo storage (separate subfolder)
|
||||
const logoStorage = multer.diskStorage({
|
||||
destination: function (req, file, cb) {
|
||||
const uploadPath = path.join(__dirname, '..', '..', 'public', 'uploads', 'branding');
|
||||
const uploadPath = path.join(UPLOADS_DIR, 'branding');
|
||||
try {
|
||||
if (!fs.existsSync(uploadPath)) fs.mkdirSync(uploadPath, { recursive: true });
|
||||
cb(null, uploadPath);
|
||||
@@ -80,7 +81,7 @@ const uploadLogo = multer({
|
||||
// Favicon storage (same subfolder as the logo — both are "branding" assets)
|
||||
const faviconStorage = multer.diskStorage({
|
||||
destination: function (req, file, cb) {
|
||||
const uploadPath = path.join(__dirname, '..', '..', 'public', 'uploads', 'branding');
|
||||
const uploadPath = path.join(UPLOADS_DIR, 'branding');
|
||||
try {
|
||||
if (!fs.existsSync(uploadPath)) fs.mkdirSync(uploadPath, { recursive: true });
|
||||
cb(null, uploadPath);
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
// Where uploaded files live, and how they're served (3.3.0). One folder for saving and serving:
|
||||
// backend/public/uploads, the same from src/ and dist/. Before 3.3.0 the files were served from
|
||||
// "public/uploads" relative to wherever the process was started, so a backend started from
|
||||
// another folder saved a logo in one place and answered 404 for it from another.
|
||||
const path = require('path');
|
||||
const express = require('express');
|
||||
|
||||
const UPLOADS_DIR = path.join(__dirname, '..', '..', 'public', 'uploads');
|
||||
|
||||
/** The folder for one kind of upload (e.g. "branding"), made if it isn't there yet. */
|
||||
function uploadsDir(sub) {
|
||||
const dir = path.join(UPLOADS_DIR, sub);
|
||||
require('fs').mkdirSync(dir, { recursive: true });
|
||||
return dir;
|
||||
}
|
||||
|
||||
// Uploaded branding assets can include SVGs, which may embed <script>/event handlers. Serving
|
||||
// them inline lets a malicious upload run script in the site's origin if opened directly, so pin
|
||||
// the safe response headers (no inline execution, no MIME-sniffing to HTML/script) on every file.
|
||||
function serveUploads() {
|
||||
return express.static(UPLOADS_DIR, {
|
||||
setHeaders: (res) => {
|
||||
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { UPLOADS_DIR, uploadsDir, serveUploads };
|
||||
@@ -0,0 +1,39 @@
|
||||
// 3.3.0: new demo data (set-demo) removes the last demo's people from the church's Accounts
|
||||
// (contracts 1.11.0 people.removeDemo), only while sign-in goes through Accounts.
|
||||
const mockRequests: Record<string, unknown>[] = [];
|
||||
let mockMode = 'accounts';
|
||||
|
||||
jest.mock('../src/config/db', () => ({}));
|
||||
jest.mock('../src/accounts/client', () => ({
|
||||
accounts: async () => ({
|
||||
request: async (body: { subs: string[] }) => { mockRequests.push(body); return { removed: body.subs.length - 1, kept: [{ sub: body.subs[0], reason: 'not_demo' }] }; },
|
||||
}),
|
||||
accountsLink: async () => null,
|
||||
AccountsUnavailable: class extends Error {},
|
||||
}));
|
||||
jest.mock('../src/accounts/mode', () => ({
|
||||
...jest.requireActual('../src/accounts/mode'),
|
||||
authMode: async () => mockMode,
|
||||
}));
|
||||
|
||||
import { removeDemoPeople } from '../src/accounts/move';
|
||||
|
||||
const sub = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;
|
||||
|
||||
beforeEach(() => { mockRequests.length = 0; mockMode = 'accounts'; });
|
||||
|
||||
test('asks Accounts to remove each old demo person once, a thousand at a time', async () => {
|
||||
const subs = Array.from({ length: 1500 }, (_, i) => sub(i));
|
||||
const r = await removeDemoPeople([...subs, subs[0]!, ''], 'admin-sub');
|
||||
expect(mockRequests.map((q) => (q.subs as string[]).length)).toEqual([1000, 500]);
|
||||
expect(mockRequests[0]).toMatchObject({ type: 'people.removeDemo', actor: 'admin-sub' });
|
||||
expect(r).toEqual({ removed: 1498, kept: 2 });
|
||||
});
|
||||
|
||||
test('nothing to ask while sign-in is Events\' own, or with nobody to remove', async () => {
|
||||
mockMode = 'events';
|
||||
expect(await removeDemoPeople([sub(1)])).toEqual({ removed: 0, kept: 0 });
|
||||
mockMode = 'accounts';
|
||||
expect(await removeDemoPeople([])).toEqual({ removed: 0, kept: 0 });
|
||||
expect(mockRequests).toHaveLength(0);
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
// Branding uploads end to end (3.3.0): the real v2 upload routes (multer saving to disk) and the
|
||||
// real file serving, as app.js mounts them. The logo and favicon saved are the files the returned
|
||||
// address serves, wherever the backend was started from (before 3.3.0 a backend started outside
|
||||
// backend/ answered 404 for a logo it had just saved). Only the database is a stand-in (no admin
|
||||
// yet, so the upload is allowed as during setup).
|
||||
import express from 'express';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import request from 'supertest';
|
||||
import { v2Router } from '../src/v2';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const { serveUploads } = require('../src/utils/uploads');
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
function site() {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api/v2', v2Router());
|
||||
app.use('/api/uploads', serveUploads());
|
||||
return app;
|
||||
}
|
||||
|
||||
// Any model, any call: nothing found, no users (as before setup).
|
||||
jest.mock('../src/config/db', () => {
|
||||
const anything: unknown = new Proxy(function () { /* callable */ }, {
|
||||
get: (_t, key) => (key === 'then' ? undefined : key === 'count' ? async () => 0 : anything),
|
||||
apply: async () => null,
|
||||
});
|
||||
return anything;
|
||||
});
|
||||
|
||||
// The real upload folder of this checkout (as multer writes it), cleaned up after.
|
||||
const BRANDING = path.join(__dirname, '..', 'public', 'uploads', 'branding');
|
||||
const made: string[] = [];
|
||||
afterAll(() => { for (const f of made) fs.rmSync(path.join(BRANDING, f), { force: true }); });
|
||||
|
||||
const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');
|
||||
|
||||
describe('branding uploads', () => {
|
||||
const startedIn = process.cwd();
|
||||
// PM2 or a script may start the backend from anywhere: the served files mustn't depend on it.
|
||||
beforeAll(() => process.chdir(fs.mkdtempSync(path.join(os.tmpdir(), 'events-cwd-'))));
|
||||
afterAll(() => process.chdir(startedIn));
|
||||
|
||||
test.each([['logo', 'logo.png'], ['favicon', 'icon.png']])('a %s upload is served at the address it answers with', async (kind, name) => {
|
||||
const app = site();
|
||||
const up = await request(app).post(`/api/v2/uploads/${kind}`).attach('image', PNG, { filename: name, contentType: 'image/png' });
|
||||
expect(up.status).toBe(200);
|
||||
const saved = String(up.body.data.path);
|
||||
expect(saved).toMatch(new RegExp(`^/uploads/branding/${kind}-[\\w-]+\\.png$`));
|
||||
made.push(path.basename(saved));
|
||||
expect(fs.existsSync(path.join(BRANDING, path.basename(saved)))).toBe(true);
|
||||
|
||||
const got = await request(app).get(new URL(up.body.data.url).pathname);
|
||||
expect(got.status).toBe(200);
|
||||
expect(Buffer.compare(got.body as Buffer, PNG)).toBe(0);
|
||||
});
|
||||
|
||||
test('app.js serves uploads from that same folder, never one relative to where it started', () => {
|
||||
const source = fs.readFileSync(path.join(__dirname, '..', 'src', 'app.js'), 'utf8');
|
||||
expect(source).toContain("require('./utils/uploads').serveUploads()");
|
||||
expect(source).not.toMatch(/express\.static\(\s*['"`]/);
|
||||
});
|
||||
|
||||
test('a file that isn\'t an image is refused, and nothing is saved', async () => {
|
||||
const app = site();
|
||||
const before = fs.existsSync(BRANDING) ? fs.readdirSync(BRANDING).length : 0;
|
||||
const up = await request(app).post('/api/v2/uploads/logo').attach('image', Buffer.from('<html>'), { filename: 'page.html', contentType: 'text/html' });
|
||||
expect(up.status).toBe(400);
|
||||
expect((fs.existsSync(BRANDING) ? fs.readdirSync(BRANDING).length : 0)).toBe(before);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-frontend",
|
||||
"version": "3.2.0",
|
||||
"version": "3.3.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
|
||||
@@ -240,24 +240,34 @@ function SiteSettingsPageInner() {
|
||||
google_site_verification: googleVerificationCode(googleVerification),
|
||||
});
|
||||
|
||||
// 3.3.0: an upload counts only once the site can show the file, so a setting never points at a
|
||||
// file that isn't there (as it did when the backend served uploads from the wrong folder).
|
||||
const uploadBrandingAsset = async (file: File, kind: "logo" | "favicon"): Promise<string> => {
|
||||
const what = kind === "logo" ? "logo" : "favicon";
|
||||
let path: string;
|
||||
try {
|
||||
return await uploadImage(token, kind, file);
|
||||
} catch {
|
||||
throw new Error(`${kind === "logo" ? "Logo" : "Favicon"} upload failed`);
|
||||
path = await uploadImage(token, kind, file);
|
||||
} catch (e) {
|
||||
throw new Error(`The ${what} couldn't be uploaded: ${errorMessage(e) || "please try again"}.`);
|
||||
}
|
||||
const shown = await fetch(resolveToApiOrigin(path) || path, { cache: "no-store" }).then((r) => r.ok).catch(() => false);
|
||||
if (!shown) throw new Error(`The ${what} was uploaded, but the site can't show it yet, so nothing was changed. Please try again; if it keeps happening, the server's uploads folder needs checking.`);
|
||||
return path;
|
||||
};
|
||||
|
||||
const saveBranding = async () => {
|
||||
if (!token) return;
|
||||
if (!token) {
|
||||
setResult({ ok: false, message: "You've been signed out. Sign in again, then save." });
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
setResult(null);
|
||||
try {
|
||||
let finalLogoUrl = logoUrl;
|
||||
if (logoFile) finalLogoUrl = await uploadBrandingAsset(logoFile, "logo") || logoUrl;
|
||||
if (logoFile) finalLogoUrl = await uploadBrandingAsset(logoFile, "logo");
|
||||
|
||||
let finalFaviconUrl = faviconUrl;
|
||||
if (faviconFile) finalFaviconUrl = await uploadBrandingAsset(faviconFile, "favicon") || faviconUrl;
|
||||
if (faviconFile) finalFaviconUrl = await uploadBrandingAsset(faviconFile, "favicon");
|
||||
|
||||
await apiV2Data("put", "/settings", {
|
||||
authToken: token,
|
||||
|
||||
@@ -182,7 +182,7 @@ export default function PrivacyCentrePage() {
|
||||
body: { type: "deletion", password: deletePassword, details: deleteReason || undefined },
|
||||
}) as Promise<{ message?: string }>);
|
||||
setDeleteMsg({ type: "ok", text: res?.message || "Your account is closed." });
|
||||
setTimeout(() => logout(), 3000);
|
||||
setTimeout(() => { void logout(); }, 3000);
|
||||
} catch (e) {
|
||||
setDeleteMsg({ type: "err", text: errorMessage(e) || "Could not send the request." });
|
||||
} finally {
|
||||
|
||||
@@ -348,7 +348,7 @@ export default function UserProfilePage() {
|
||||
}) as Promise<{ message?: string }>);
|
||||
setCloseMsg({ type: "ok", text: res?.message || "Account closed." });
|
||||
// Slight delay so the user can read the message, then log out
|
||||
setTimeout(() => logout(), 2500);
|
||||
setTimeout(() => { void logout(); }, 2500);
|
||||
} catch (e) {
|
||||
setCloseMsg({ type: "err", text: errorMessage(e) || "Failed to close account." });
|
||||
} finally {
|
||||
|
||||
@@ -5,7 +5,6 @@ import { usePathname } from "next/navigation";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { Home, Calendar, Phone, LogIn, UserPlus, LayoutDashboard, LogOut } from "lucide-react";
|
||||
import { useBrandColorVar } from "@/lib/theme";
|
||||
import { hardNavigate } from "@/lib/navigation";
|
||||
|
||||
export const BottomNav = () => {
|
||||
const { user, loading: authLoading, logout } = useAuth();
|
||||
@@ -15,8 +14,7 @@ export const BottomNav = () => {
|
||||
const accentColor = useBrandColorVar("--brand-600");
|
||||
|
||||
const handleLogout = () => {
|
||||
logout();
|
||||
hardNavigate("/"); // a full load, so nothing of the old session stays in memory
|
||||
void logout(); // signs out of Accounts too, then a full load of the next page
|
||||
};
|
||||
|
||||
const isActive = (href: string) => {
|
||||
|
||||
@@ -9,7 +9,6 @@ import { BottomNav } from "./BottomNav";
|
||||
import defaultLogo from "@/app/default_logo.png";
|
||||
import { appName } from "@/lib/siteConfig";
|
||||
import { resolveToApiOrigin } from "@/lib/api";
|
||||
import { hardNavigate } from "@/lib/navigation";
|
||||
|
||||
type NavLink = {
|
||||
href: string;
|
||||
@@ -31,8 +30,7 @@ export const Navbar = () => {
|
||||
};
|
||||
|
||||
const handleLogout = () => {
|
||||
logout();
|
||||
hardNavigate("/"); // a full load, so nothing of the old session stays in memory
|
||||
void logout(); // signs out of Accounts too, then a full load of the next page
|
||||
};
|
||||
|
||||
const navLinks: NavLink[] = [
|
||||
|
||||
@@ -23,7 +23,8 @@ export type AuthContextValue = {
|
||||
verifyTwoFactor: (challengeId: string, code: string, rememberDevice: boolean) => Promise<AuthUser>;
|
||||
resendTwoFactor: (challengeId: string) => Promise<TwoFactorChallenge>;
|
||||
register: (data: { name: string; email: string; password: string; phoneNumber?: string; notificationPreference?: "email" | "whatsapp" | "both"; newsOptIn?: boolean }) => Promise<void>;
|
||||
logout: () => void;
|
||||
/** Signs out here (and of Accounts, when sign-in goes through it), then leaves the page. */
|
||||
logout: () => Promise<void>;
|
||||
updateToken: (token: string) => void;
|
||||
};
|
||||
|
||||
@@ -143,22 +144,28 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
setUser(registeredUser);
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
const logout = useCallback(async () => {
|
||||
const t = getToken();
|
||||
clearToken();
|
||||
cacheUser(null);
|
||||
setToken(null);
|
||||
setUser(null);
|
||||
// 3.0.0: signed in through the church's Accounts, signing out here signs out there too (and of
|
||||
// the church's other products), then comes back to this site's home page.
|
||||
// the church's other products), then comes back to this site's home page. 3.3.0: this waits
|
||||
// for that answer before leaving the page; before, callers loaded "/" straight away, which
|
||||
// cancelled the call, so people stayed signed in to Accounts.
|
||||
let next = "/";
|
||||
if (t) {
|
||||
fetchAuthMode()
|
||||
.then((m) => (m === "accounts"
|
||||
? fetch(`${API_BASE}/api/auth/signout`, { method: "POST", headers: { Authorization: `Bearer ${t}`, "Content-Type": "application/json" }, body: "{}" }).then((r) => r.json())
|
||||
: null))
|
||||
.then((j: { data?: { url?: string | null } } | null) => { if (j?.data?.url) window.location.assign(j.data.url); })
|
||||
.catch(() => { /* signed out here either way */ });
|
||||
try {
|
||||
if ((await fetchAuthMode()) === "accounts") {
|
||||
const r = await fetch(`${API_BASE}/api/auth/signout`, { method: "POST", keepalive: true, headers: { Authorization: `Bearer ${t}`, "Content-Type": "application/json" }, body: "{}" });
|
||||
const j = (await r.json().catch(() => null)) as { data?: { url?: string | null } } | null;
|
||||
if (j?.data?.url) next = j.data.url;
|
||||
}
|
||||
} catch { /* signed out here either way */ }
|
||||
}
|
||||
// A full load, so nothing of the old session stays in memory.
|
||||
window.location.assign(new URL(next, window.location.origin).href);
|
||||
}, []);
|
||||
|
||||
// Some endpoints (profile update, password change, session revocation) issue a
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events",
|
||||
"version": "3.2.0",
|
||||
"version": "3.3.0",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"dev:backend": "cd backend && npm run dev",
|
||||
|
||||
Reference in New Issue
Block a user