diff --git a/e2e/member-onboarding.spec.js b/e2e/member-onboarding.spec.js
new file mode 100644
index 0000000..498d4d5
--- /dev/null
+++ b/e2e/member-onboarding.spec.js
@@ -0,0 +1,137 @@
+// e2e/member-onboarding.spec.js - E2E tests for new member onboarding flow and responsive layouts.
+import { test, expect } from '@playwright/test';
+import { expectNoHorizontalOverflow } from './helpers.js';
+import { makeUserUnonboarded, reseed } from './reseed.js';
+
+test.describe('New Member Onboarding Journey', () => {
+ test.beforeEach(async () => {
+ await makeUserUnonboarded('Test Guest Bala');
+ });
+
+ test.afterAll(async () => {
+ await reseed();
+ });
+
+ test('Complete onboarding flow: Welcome -> Age -> Profile -> Interests -> Optional -> Complete', async ({ page }) => {
+ await page.setViewportSize({ width: 393, height: 852 }); // Mobile viewport (iPhone 14/15)
+
+ // 1. Visit /onboarding while unauthenticated -> redirected to /signin
+ await page.goto('/onboarding');
+ await expect(page).toHaveURL(/\/signin/);
+
+ // 2. Sign in as Bala (un-onboarded test user)
+ await page.getByRole('button', { name: /Test Guest Bala/ }).click();
+ await page.waitForURL(/\/onboarding/);
+
+ const container = page.locator('[data-onboarding-container]');
+ await expect(container).toBeVisible();
+
+ // Verify progress header exists
+ const progressFill = page.locator('[data-progress-fill]');
+ await expect(progressFill).toBeVisible();
+
+ // Verify Step 1: Welcome is visible
+ const step1 = page.locator('[data-step-panel="1"]');
+ await expect(step1).toBeVisible();
+ await expect(step1.locator('.onboarding-title')).toContainText('Welcome to NIGHTLIFEZ');
+
+ // Click "Get Started →"
+ const startBtn = page.locator('[data-onboard-action="next-step"][data-target-step="2"]');
+ await startBtn.click();
+
+ // Step 2: 21+ Age confirmation
+ const step2 = page.locator('[data-step-panel="2"]');
+ await expect(step2).toBeVisible();
+ const ageCheck = page.locator('#onboard-age-check');
+ await ageCheck.check();
+ expect(await ageCheck.isChecked()).toBe(true);
+
+ const step2Submit = page.locator('[data-onboard-submit="2"]');
+ await step2Submit.click();
+
+ // Step 3: Basic Profile
+ const step3 = page.locator('[data-step-panel="3"]');
+ await expect(step3).toBeVisible();
+
+ await page.locator('#onboard-display-name').fill('Priya Sharma');
+ await page.locator('#onboard-gender').selectOption('female');
+ await page.locator('#onboard-city').selectOption('Bengaluru');
+
+ const step3Submit = page.locator('[data-onboard-submit="3"]');
+ await step3Submit.click();
+
+ // Step 4: Interests Selection
+ const step4 = page.locator('[data-step-panel="4"]');
+ await expect(step4).toBeVisible();
+
+ // Select 2 interest chips
+ await page.locator('label:has(input[value="parties_nightlife"])').click();
+ await page.locator('label:has(input[value="dining_food"])').click();
+
+ // Verify active count indicator
+ await expect(page.locator('[data-interests-counter]')).toContainText('2 interests selected');
+
+ const step4Submit = page.locator('[data-onboard-submit="4"]');
+ await step4Submit.click();
+
+ // Step 5: Optional profile
+ const step5 = page.locator('[data-step-panel="5"]');
+ await expect(step5).toBeVisible();
+
+ // Fill bio
+ await page.locator('#onboard-bio').fill('Love exploring new restaurants and live music events.');
+ const langEnglish = page.locator('label:has(input[value="English"])');
+ if (await langEnglish.count() > 0) await langEnglish.click();
+
+ const step5Submit = page.locator('[data-onboard-submit="5"]');
+ await step5Submit.click();
+
+ // Step 6: Personalised Completion Screen
+ const step6 = page.locator('[data-step-panel="6"]');
+ await expect(step6).toBeVisible();
+ await expect(page.locator('[data-welcome-subheading]')).toContainText('Priya Sharma');
+
+ // Complete onboarding
+ const finishBtn = page.locator('[data-onboard-action="finish-onboarding"]');
+ await finishBtn.click();
+ await page.waitForLoadState('domcontentloaded');
+
+ // Verify redirection to /me
+ await expect(page).toHaveURL(/\/me/);
+ await expect(page.locator('[data-attendee-hub]')).toBeVisible();
+
+ // Verify subsequent visit to /onboarding redirects immediately to /me
+ await page.goto('/onboarding');
+ await expect(page).toHaveURL(/\/me/);
+ });
+
+ test('Responsive viewports on /onboarding have no horizontal overflow', async ({ page }) => {
+ // Sign in as Bala to view /onboarding
+ await page.goto('/signin');
+ await page.getByRole('button', { name: /Test Guest Bala/ }).click();
+ await page.waitForURL(/\/onboarding/);
+
+ const widths = [320, 360, 375, 393, 430, 768, 1024, 1280];
+ for (const width of widths) {
+ await page.setViewportSize({ width, height: 800 });
+ await expectNoHorizontalOverflow(page);
+ }
+ });
+
+ test('Sign-out button in focused onboarding header revokes session cleanly', async ({ page }) => {
+ await page.setViewportSize({ width: 393, height: 852 });
+ await page.goto('/signin');
+ await page.getByRole('button', { name: /Test Guest Bala/ }).click();
+ await page.waitForURL(/\/onboarding/);
+
+ const signoutBtn = page.locator('header [data-signout]');
+ await expect(signoutBtn).toBeVisible();
+ await signoutBtn.click();
+ await page.waitForLoadState('domcontentloaded');
+ await expect(page).toHaveURL(/\/signin/);
+
+ // Ensure session is gone: visiting /me redirects to /signin
+ await page.goto('/me');
+ await expect(page).toHaveURL(/\/signin/);
+ });
+});
diff --git a/e2e/reseed.js b/e2e/reseed.js
index 0910d71..27dd94d 100644
--- a/e2e/reseed.js
+++ b/e2e/reseed.js
@@ -21,6 +21,18 @@ export async function reseed() {
await db.query('DELETE FROM rate_limits');
}
+export async function makeUserUnonboarded(alias = 'Test Guest Bala') {
+ const { db } = await load();
+ await db.query(
+ `UPDATE users SET onboarding_completed = FALSE, onboarding_step = 0, age_confirmed_21 = FALSE, gender = NULL WHERE alias = $1`,
+ [alias]
+ );
+ await db.query(
+ `DELETE FROM member_interests WHERE user_id = (SELECT id FROM users WHERE alias = $1)`,
+ [alias]
+ );
+}
+
export async function closeDb() {
if (handle) { await handle.db.close(); handle = null; }
}
diff --git a/e2e/telegram-explicit-login.spec.js b/e2e/telegram-explicit-login.spec.js
index 11fd175..6d20d05 100644
--- a/e2e/telegram-explicit-login.spec.js
+++ b/e2e/telegram-explicit-login.spec.js
@@ -119,15 +119,15 @@ test.describe('Telegram Explicit Initiation & Session Logout', () => {
await page.locator('#otp-input').fill(devOtp);
await page.locator('[data-wa-verify-btn]').click();
- await page.waitForURL(/\/me$/);
+ await page.waitForURL(/\/onboarding|\/me$/);
// Verify session exists
let cookies = await page.context().cookies();
let sessionCookie = cookies.find((c) => c.name === 'sm_session');
expect(sessionCookie).toBeTruthy();
- // Click sign out in attendee hub
- const signoutBtn = page.locator('[data-attendee-hub] [data-signout]');
+ // Click sign out (works in focused onboarding header or attendee hub)
+ const signoutBtn = page.locator('[data-signout]').first();
await expect(signoutBtn).toBeVisible();
await signoutBtn.click();
@@ -171,17 +171,23 @@ test.describe('Telegram Explicit Initiation & Session Logout', () => {
await page.locator('#otp-input').fill(devOtp);
await page.locator('[data-wa-verify-btn]').click();
- await page.waitForURL(/\/me$/);
-
- // Open mobile hamburger menu
- const navToggle = page.locator('.nav-toggle');
- await expect(navToggle).toBeVisible();
- await navToggle.click();
-
- // Mobile signout button should be visible in drawer
- const mobileSignoutBtn = page.locator('.mobile-signout-btn');
- await expect(mobileSignoutBtn).toBeVisible();
- await mobileSignoutBtn.click();
+ await page.waitForURL(/\/onboarding|\/me$/);
+
+ if (page.url().includes('/onboarding')) {
+ const headerSignout = page.locator('header [data-signout]');
+ await expect(headerSignout).toBeVisible();
+ await headerSignout.click();
+ } else {
+ // Open mobile hamburger menu
+ const navToggle = page.locator('.nav-toggle');
+ await expect(navToggle).toBeVisible();
+ await navToggle.click();
+
+ // Mobile signout button should be visible in drawer
+ const mobileSignoutBtn = page.locator('.mobile-signout-btn');
+ await expect(mobileSignoutBtn).toBeVisible();
+ await mobileSignoutBtn.click();
+ }
// Verify redirected to /signin
await page.waitForURL(/\/signin/);
diff --git a/e2e/whatsapp-auth.spec.js b/e2e/whatsapp-auth.spec.js
index 41c5acc..278e31d 100644
--- a/e2e/whatsapp-auth.spec.js
+++ b/e2e/whatsapp-auth.spec.js
@@ -56,8 +56,28 @@ test.describe('WhatsApp OTP Authentication E2E', () => {
await page.locator('#otp-input').fill(code);
await page.locator('[data-wa-verify-btn]').click();
- // 5. User lands on /me authenticated
- await page.waitForURL(/\/me$/);
+ // 5. User lands on /onboarding (new member) or /me (existing member)
+ await page.waitForURL(/\/onboarding|\/me$/);
+ if (page.url().includes('/onboarding')) {
+ // Step 1: Welcome
+ await page.locator('[data-onboard-action="next-step"][data-target-step="2"]').click();
+ // Step 2: 21+ Age confirmation
+ await page.locator('#onboard-age-check').check();
+ await page.locator('[data-onboard-submit="2"]').click();
+ // Step 3: Profile
+ await page.locator('#onboard-display-name').fill('WhatsApp User');
+ await page.locator('#onboard-gender').selectOption('prefer_not_to_say');
+ await page.locator('#onboard-city').selectOption('Bengaluru');
+ await page.locator('[data-onboard-submit="3"]').click();
+ // Step 4: Interests
+ await page.locator('label:has(input[value="parties_nightlife"])').click();
+ await page.locator('[data-onboard-submit="4"]').click();
+ // Step 5: Optional details
+ await page.locator('[data-onboard-submit="5"]').click();
+ // Step 6: Finish
+ await page.locator('[data-onboard-action="finish-onboarding"]').click();
+ await page.waitForURL(/\/me$/);
+ }
await expect(page.getByRole('heading', { level: 1 })).toContainText('My bookings');
// 6. Navigate to Account & Logins tab
diff --git a/lib/handlers/auth.js b/lib/handlers/auth.js
index d1f614b..c35bdf7 100644
--- a/lib/handlers/auth.js
+++ b/lib/handlers/auth.js
@@ -53,8 +53,33 @@ const DevAuthBody = z.object({
ageConfirmed: z.boolean().optional()
}).strict();
-function publicUser(u) {
- return { alias: u.alias, ageConfirmed: u.age_confirmed_21 };
+export function publicUser(u) {
+ return {
+ alias: u.alias,
+ displayName: u.display_name || u.alias,
+ city: u.city || null,
+ gender: u.gender || null,
+ ageConfirmed: u.age_confirmed_21,
+ onboardingCompleted: Boolean(u.onboarding_completed),
+ onboardingStep: u.onboarding_step || 0
+ };
+}
+
+export function authDestination(user, next = '/me') {
+ const target = safeNext(next);
+ const isBootstrapOrAdmin = user && (
+ user.role === 'admin' ||
+ user.role === 'super_admin' ||
+ Boolean(user.is_staff) ||
+ (process.env.ADMIN_BOOTSTRAP_TELEGRAM_ID && String(user.telegram_user_id) === String(process.env.ADMIN_BOOTSTRAP_TELEGRAM_ID))
+ );
+ if (isBootstrapOrAdmin) {
+ return target;
+ }
+ if (!user.onboarding_completed) {
+ return target && target !== '/me' ? `/onboarding?next=${encodeURIComponent(target)}` : '/onboarding';
+ }
+ return target;
}
/** POST /api/auth/telegram — Mini App initData or legacy Login Widget payload. */
@@ -81,7 +106,8 @@ export async function telegramAuth({ req, res, ip }) {
telegramUserId: user.telegram_user_id,
botStarted: false
}).catch((err) => logger.warn('telegram onboarding registration failed', { error: err.message }));
- sendJson(res, 200, { ok: true, csrf, user: publicUser(user), startParam: v.startParam || null });
+ const destination = authDestination(user, null);
+ sendJson(res, 200, { ok: true, csrf, user: publicUser(user), redirect: destination, isNewUser: !user.onboarding_completed, startParam: v.startParam || null });
}
// ---------- Telegram Login (OpenID Connect, Authorization Code + PKCE) ----------
@@ -160,7 +186,8 @@ export async function oidcCallback({ req, res, query }) {
botStarted: true
}).catch((err) => logger.warn('telegram onboarding registration on oidc failed', { error: err.message }));
await startSession(req, res, user);
- redirect(res, sealed.next);
+ const destination = authDestination(user, sealed.next);
+ redirect(res, destination);
} catch (err) {
if (err instanceof HttpError) throw err;
logger.warn('oidc login failed', { reason: err.message });
@@ -187,6 +214,7 @@ export async function widgetCallback({ req, res, query, ip }) {
const stateQuery = query.get('state');
const secure = Boolean(process.env.VERCEL) || req.headers['x-forwarded-proto'] === 'https';
appendHeader(res, 'Set-Cookie', serializeCookie(TG_STATE_COOKIE, '', { maxAge: 0, secure, path: '/auth/telegram' }));
+ appendHeader(res, 'Set-Cookie', serializeCookie(TG_STATE_COOKIE, '', { maxAge: 0, secure, path: '/' }));
if (!stateCookie || !stateQuery || !safeEqual(stateCookie, stateQuery)) {
logger.warn('telegram widget callback rejected: state mismatch or expired');
@@ -246,7 +274,8 @@ export async function widgetCallback({ req, res, query, ip }) {
botStarted: false
}).catch((err) => logger.warn('telegram onboarding registration on widget failed', { error: err.message }));
await startSession(req, res, user);
- return redirect(res, nextPath);
+ const destination = authDestination(user, nextPath);
+ return redirect(res, destination);
} catch (err) {
if (err instanceof HttpError) throw err;
logger.warn('telegram widget callback login failed', { reason: err.message });
@@ -286,9 +315,9 @@ export async function previewReviewerAuth({ req, res, query, ip }) {
let user = await db.one('SELECT * FROM users WHERE telegram_user_id = $1', [REVIEWER_TG_ID]);
if (!user) {
user = (await db.query(
- `INSERT INTO users (telegram_user_id, alias, age_confirmed_21, age_confirmed_at, status, bot_started)
- VALUES ($1, $2, true, now(), 'active', true)
- ON CONFLICT (telegram_user_id) DO UPDATE SET age_confirmed_21 = true, status = 'active'
+ `INSERT INTO users (telegram_user_id, alias, display_name, age_confirmed_21, age_confirmed_at, status, bot_started, onboarding_completed, onboarding_step)
+ VALUES ($1, $2, $2, true, now(), 'active', true, true, 6)
+ ON CONFLICT (telegram_user_id) DO UPDATE SET age_confirmed_21 = true, status = 'active', onboarding_completed = true
RETURNING *`,
[REVIEWER_TG_ID, REVIEWER_ALIAS]
)).rows[0];
@@ -304,7 +333,9 @@ export async function previewReviewerAuth({ req, res, query, ip }) {
}
}
-/** Sign out this browser: revoke its server-side session (CSRF-checked when signed in) and clear the cookie. */
+/** Sign out this browser: revoke its server-side session (CSRF-checked when signed in) and clear the cookie.
+ * If the user is present but CSRF is missing/invalid, we still revoke and clear — CSRF is defence-in-depth,
+ * not a gate for the logout-only action which is inherently benign (the user requested sign-out). */
export async function logout({ req, res }) {
let user = null;
try {
@@ -319,7 +350,11 @@ export async function logout({ req, res }) {
clearSessionCookie(req, res);
const secure = Boolean(process.env.VERCEL) || req.headers['x-forwarded-proto'] === 'https';
appendHeader(res, 'Set-Cookie', serializeCookie('sm_wa_step', '', { maxAge: 0, secure, path: '/' }));
+ appendHeader(res, 'Set-Cookie', serializeCookie('sm_wa_last_phone', '', { maxAge: 0, secure, path: '/' }));
appendHeader(res, 'Set-Cookie', serializeCookie(TG_STATE_COOKIE, '', { maxAge: 0, secure, path: '/auth/telegram' }));
+ appendHeader(res, 'Set-Cookie', serializeCookie(OIDC_COOKIE, '', { maxAge: 0, secure, path: '/auth/telegram' }));
+ // Also set a Cache-Control to prevent caching the authenticated page
+ res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
sendJson(res, 200, { ok: true });
}
@@ -343,10 +378,10 @@ export async function me({ req, res }) {
sendJson(res, 200, { ok: true, user: publicUser(user), csrf: csrfTokenFor(user.sessionToken) });
}
-export async function confirmAge({ req, res }) {
+export async function confirmAge({ req, res, ip }) {
const user = await requireUser(req);
requireCsrf(req, user);
- await confirmAgeSvc(user.id);
+ await confirmAgeSvc(user.id, { ip, userAgent: req.headers['user-agent'] });
sendJson(res, 200, { ok: true });
}
@@ -590,11 +625,13 @@ export async function verifyWhatsAppOtpHandler({ req, res, ip }) {
phone: auth.user.phone
}).catch((err) => logger.warn('whatsapp onboarding registration failed', { error: err.message }));
+ const destination = authDestination(auth.user, nextUrl);
+
if (isHtmlAccept) {
const secure = Boolean(process.env.VERCEL) || req.headers['x-forwarded-proto'] === 'https';
appendHeader(res, 'Set-Cookie', serializeCookie('sm_wa_step', '', { maxAge: 0, secure, path: '/' }));
appendHeader(res, 'Set-Cookie', serializeCookie('sm_wa_last_phone', '', { maxAge: 0, secure, path: '/' }));
- return redirect(res, nextUrl);
+ return redirect(res, destination);
}
sendJson(res, 200, {
@@ -602,6 +639,7 @@ export async function verifyWhatsAppOtpHandler({ req, res, ip }) {
csrf,
user: publicUser(auth.user),
isNewUser: auth.isNewUser,
+ redirect: destination,
onboarding: {
channel: 'whatsapp',
channelUrl: whatsappChannelUrl(),
diff --git a/lib/handlers/onboarding.js b/lib/handlers/onboarding.js
new file mode 100644
index 0000000..a387003
--- /dev/null
+++ b/lib/handlers/onboarding.js
@@ -0,0 +1,117 @@
+// lib/handlers/onboarding.js - Member onboarding API handlers.
+// Guides new members through mandatory profile completion with server-side validation.
+import { readJson, sendJson } from '../http.js';
+import { requireUser, requireCsrf } from '../session.js';
+import { rateLimit } from '../ratelimit.js';
+import { hashIp } from '../http.js';
+import { parse, z } from '../validate.js';
+import {
+ getOnboardingStatus,
+ confirmAgeEligibility,
+ rejectAgeEligibility,
+ saveBasicProfile,
+ saveInterests,
+ saveOptionalProfile,
+ completeOnboarding,
+ INTEREST_OPTIONS,
+ GENDER_OPTIONS,
+ INTEREST_KEYS
+} from '../services/member-onboarding.js';
+
+/** GET /api/onboarding/status — Get current onboarding state. */
+export async function getStatus({ req, res }) {
+ const user = await requireUser(req);
+ const status = await getOnboardingStatus(user.id);
+ sendJson(res, 200, {
+ ok: true,
+ ...status,
+ options: {
+ interests: INTEREST_OPTIONS,
+ genders: GENDER_OPTIONS
+ }
+ });
+}
+
+const AgeBody = z.object({
+ confirmed: z.boolean(),
+ policyVersion: z.string().max(20).optional().default('1.0')
+}).strict();
+
+/** POST /api/onboarding/age — Confirm or reject age eligibility. */
+export async function confirmAge({ req, res, ip }) {
+ const user = await requireUser(req);
+ requireCsrf(req, user);
+ await rateLimit(`onboard:${user.id}`, 30, 300);
+
+ const body = parse(AgeBody, await readJson(req));
+ if (!body.confirmed) {
+ const result = await rejectAgeEligibility(user.id);
+ return sendJson(res, 200, { ok: true, eligible: false, ...result });
+ }
+
+ const userAgent = req.headers['user-agent'] || null;
+ const result = await confirmAgeEligibility(user.id, {
+ ip: hashIp(ip),
+ userAgent,
+ policyVersion: body.policyVersion
+ });
+ sendJson(res, 200, { ok: true, eligible: true, ...result });
+}
+
+const ProfileBody = z.object({
+ displayName: z.string().min(1).max(50),
+ gender: z.enum(['female', 'male', 'non_binary', 'other', 'prefer_not_to_say']),
+ city: z.string().min(1).max(100)
+}).strict();
+
+/** POST /api/onboarding/profile — Save basic profile (display name, gender, city). */
+export async function saveProfile({ req, res }) {
+ const user = await requireUser(req);
+ requireCsrf(req, user);
+ await rateLimit(`onboard:${user.id}`, 30, 300);
+
+ const body = parse(ProfileBody, await readJson(req));
+ const result = await saveBasicProfile(user.id, body);
+ sendJson(res, 200, { ok: true, ...result });
+}
+
+const InterestsBody = z.object({
+ interests: z.array(z.string()).min(1).max(10)
+}).strict();
+
+/** POST /api/onboarding/interests — Save selected interests. */
+export async function saveInterestsHandler({ req, res }) {
+ const user = await requireUser(req);
+ requireCsrf(req, user);
+ await rateLimit(`onboard:${user.id}`, 30, 300);
+
+ const body = parse(InterestsBody, await readJson(req));
+ const result = await saveInterests(user.id, body.interests);
+ sendJson(res, 200, { ok: true, ...result });
+}
+
+const OptionalBody = z.object({
+ bio: z.string().max(500).optional(),
+ languages: z.array(z.string().max(50)).max(10).optional()
+}).strict();
+
+/** POST /api/onboarding/optional — Save optional profile enhancements. */
+export async function saveOptional({ req, res }) {
+ const user = await requireUser(req);
+ requireCsrf(req, user);
+ await rateLimit(`onboard:${user.id}`, 30, 300);
+
+ const body = parse(OptionalBody, await readJson(req));
+ const result = await saveOptionalProfile(user.id, body);
+ sendJson(res, 200, { ok: true, ...result });
+}
+
+/** POST /api/onboarding/complete — Finalize onboarding (validates all mandatory fields). */
+export async function complete({ req, res }) {
+ const user = await requireUser(req);
+ requireCsrf(req, user);
+ await rateLimit(`onboard:${user.id}`, 10, 300);
+
+ const result = await completeOnboarding(user.id);
+ sendJson(res, 200, { ok: true, ...result });
+}
diff --git a/lib/handlers/pages.js b/lib/handlers/pages.js
index 8a26711..4ce3e4d 100644
--- a/lib/handlers/pages.js
+++ b/lib/handlers/pages.js
@@ -119,6 +119,25 @@ export async function staticPage({ res, pathname }) {
sendHtml(res, 200, STATIC[pathname.replace(/\/$/, '')](), { cache: PUBLIC_CACHE });
}
+export async function onboardingPage({ req, res, query }) {
+ const user = await getSessionUser(req).catch(() => null);
+ const nextVal = query.get('next') || '/me';
+ const safeNextVal = nextVal && /^\/(?![\/\\])[\w\-./?=%]*$/.test(nextVal) ? nextVal : '/me';
+
+ if (!user) {
+ res.setHeader('Cache-Control', 'no-store');
+ return redirect(res, `/signin?next=${encodeURIComponent(`/onboarding${safeNextVal !== '/me' ? `?next=${encodeURIComponent(safeNextVal)}` : ''}`)}`);
+ }
+
+ // If user has already completed onboarding, redirect them to intended next destination or /me
+ if (user.onboarding_completed) {
+ res.setHeader('Cache-Control', 'no-store');
+ return redirect(res, safeNextVal);
+ }
+
+ sendHtml(res, 200, P.renderOnboarding({ user, next: safeNextVal }), { cache: 'no-store' });
+}
+
export async function memberPage({ req, res, pathname, query }) {
if (pathname.startsWith('/me')) {
const user = await getSessionUser(req).catch(() => null);
@@ -126,7 +145,12 @@ export async function memberPage({ req, res, pathname, query }) {
res.setHeader('Cache-Control', 'no-store');
return redirect(res, `/signin?next=${encodeURIComponent('/me')}`);
}
- const html = P.renderMe();
+ // New or incomplete members must complete onboarding before member hub
+ if (!user.onboarding_completed) {
+ res.setHeader('Cache-Control', 'no-store');
+ return redirect(res, `/onboarding?next=${encodeURIComponent('/me')}`);
+ }
+ const html = P.renderMe({ user });
return sendHtml(res, 200, html, { cache: 'no-store' });
}
diff --git a/lib/http.js b/lib/http.js
index 8b3ea4e..d3c34b4 100644
--- a/lib/http.js
+++ b/lib/http.js
@@ -88,7 +88,10 @@ export function parseCookies(header = '') {
export function serializeCookie(name, value, { maxAge, httpOnly = true, secure = true, sameSite = 'Lax', path = '/' } = {}) {
let c = `${name}=${encodeURIComponent(value)}; Path=${path}; SameSite=${sameSite}`;
- if (maxAge !== undefined) c += `; Max-Age=${maxAge}`;
+ if (maxAge !== undefined) {
+ c += `; Max-Age=${maxAge}`;
+ if (maxAge === 0) c += '; Expires=Thu, 01 Jan 1970 00:00:00 GMT';
+ }
if (httpOnly) c += '; HttpOnly';
if (secure) c += '; Secure';
return c;
diff --git a/lib/router.js b/lib/router.js
index c486904..3bbcfe9 100644
--- a/lib/router.js
+++ b/lib/router.js
@@ -32,6 +32,7 @@ const ROUTES = [
['GET', '/refunds', h('pages', 'staticPage')],
['GET', '/contact', h('pages', 'staticPage')],
['GET', '/signin', h('pages', 'memberPage')],
+ ['GET', '/onboarding', h('pages', 'onboardingPage')],
['GET', '/me', h('pages', 'memberPage')],
['GET', '/bookings/:id', h('pages', 'bookingPage')],
['GET', '/checkout/:slug', h('checkout', 'checkoutRedirect')],
@@ -79,6 +80,12 @@ const ROUTES = [
['PATCH', '/api/me/communication-preferences', h('auth', 'updateMyCommunicationPreferences')],
['GET', '/api/me/onboarding', h('auth', 'getMyOnboardingHandler')],
['POST', '/api/onboarding/track', h('auth', 'trackOnboardingHandler')],
+ ['GET', '/api/onboarding/status', h('onboarding', 'getStatus')],
+ ['POST', '/api/onboarding/age', h('onboarding', 'confirmAge')],
+ ['POST', '/api/onboarding/profile', h('onboarding', 'saveProfile')],
+ ['POST', '/api/onboarding/interests', h('onboarding', 'saveInterestsHandler')],
+ ['POST', '/api/onboarding/optional', h('onboarding', 'saveOptional')],
+ ['POST', '/api/onboarding/complete', h('onboarding', 'complete')],
['POST', '/api/auth/dev', h('auth', 'devAuth')],
['POST', '/api/auth/preview-reviewer', h('auth', 'previewReviewerAuth')],
['POST', '/api/auth/logout', h('auth', 'logout')],
diff --git a/lib/services/member-onboarding.js b/lib/services/member-onboarding.js
new file mode 100644
index 0000000..d41b6e9
--- /dev/null
+++ b/lib/services/member-onboarding.js
@@ -0,0 +1,280 @@
+// lib/services/member-onboarding.js - Member onboarding profile completion service.
+// Handles mandatory profile fields, step tracking, interest storage, and consent recording.
+import { db } from '../db.js';
+import { HttpError } from '../http.js';
+import { logger } from '../logger.js';
+
+// Onboarding steps: 1=Welcome, 2=Age, 3=Profile, 4=Interests, 5=OptionalProfile, 6=Complete
+export const ONBOARDING_STEPS = {
+ WELCOME: 1,
+ AGE_ELIGIBILITY: 2,
+ BASIC_PROFILE: 3,
+ INTERESTS: 4,
+ OPTIONAL_PROFILE: 5,
+ COMPLETE: 6
+};
+
+export const INTEREST_OPTIONS = [
+ { key: 'parties_nightlife', label: 'Parties & Nightlife', icon: '🎉' },
+ { key: 'music_concerts', label: 'Music & Concerts', icon: '🎵' },
+ { key: 'social_meetups', label: 'Social Meetups', icon: '👋' },
+ { key: 'dining_food', label: 'Dining & Food', icon: '🍽️' },
+ { key: 'travel_trips', label: 'Travel & Trips', icon: '✈️' },
+ { key: 'adventure_outdoors', label: 'Adventure & Outdoors', icon: '🏔️' },
+ { key: 'fitness_sports', label: 'Fitness & Sports', icon: '💪' },
+ { key: 'arts_culture', label: 'Arts & Culture', icon: '🎭' },
+ { key: 'networking_professional', label: 'Networking', icon: '🤝' },
+ { key: 'experiences_activities', label: 'Experiences', icon: '⭐' }
+];
+
+export const GENDER_OPTIONS = [
+ { key: 'female', label: 'Woman' },
+ { key: 'male', label: 'Man' },
+ { key: 'non_binary', label: 'Non-binary' },
+ { key: 'other', label: 'Other' },
+ { key: 'prefer_not_to_say', label: 'Prefer not to say' }
+];
+
+export const INTEREST_KEYS = INTEREST_OPTIONS.map(o => o.key);
+
+/** Get the current onboarding state for a user. */
+export async function getOnboardingStatus(userId) {
+ const user = await db.one(
+ `SELECT id, onboarding_completed, onboarding_step, display_name, gender, city,
+ age_confirmed_21, age_confirmed_at, age_consent_policy_version,
+ bio, languages, profile_photo_url
+ FROM users WHERE id = $1`, [userId]
+ );
+ if (!user) throw new HttpError(404, 'not_found', 'User not found');
+
+ const interests = await db.query(
+ 'SELECT interest_key FROM member_interests WHERE user_id = $1 ORDER BY created_at', [userId]
+ );
+
+ return {
+ completed: user.onboarding_completed,
+ currentStep: user.onboarding_step,
+ totalSteps: 6,
+ profile: {
+ displayName: user.display_name,
+ gender: user.gender,
+ city: user.city,
+ ageConfirmed: user.age_confirmed_21,
+ bio: user.bio,
+ languages: user.languages || [],
+ profilePhotoUrl: user.profile_photo_url,
+ interests: interests.rows.map(r => r.interest_key)
+ }
+ };
+}
+
+/** Confirm age eligibility (21+). Step 2. */
+export async function confirmAgeEligibility(userId, { ip, userAgent, policyVersion = '1.0' } = {}) {
+ return await db.tx(async (client) => {
+ await client.query(
+ `UPDATE users SET
+ age_confirmed_21 = true,
+ age_confirmed_at = COALESCE(age_confirmed_at, now()),
+ age_consent_policy_version = $2,
+ onboarding_step = GREATEST(onboarding_step, $3)
+ WHERE id = $1`,
+ [userId, policyVersion, ONBOARDING_STEPS.AGE_ELIGIBILITY]
+ );
+
+ await client.query(
+ `INSERT INTO onboarding_consents (user_id, consent_type, confirmed, policy_version, ip, user_agent, consented_at)
+ VALUES ($1, 'age_21_plus', true, $2, $3, $4, now())
+ ON CONFLICT (user_id, consent_type) DO UPDATE SET
+ confirmed = true, policy_version = $2, ip = $3, user_agent = $4, consented_at = now()`,
+ [userId, policyVersion, ip || null, userAgent || null]
+ );
+
+ logger.info('age eligibility confirmed', { userId });
+ return { confirmed: true };
+ });
+}
+
+/** Reject age eligibility. The user cannot proceed. */
+export async function rejectAgeEligibility(userId) {
+ // Record that user declared ineligibility — they cannot create a profile or continue
+ return await db.tx(async (client) => {
+ await client.query(
+ `INSERT INTO onboarding_consents (user_id, consent_type, confirmed, policy_version, consented_at)
+ VALUES ($1, 'age_21_plus', false, '1.0', now())
+ ON CONFLICT (user_id, consent_type) DO UPDATE SET confirmed = false, consented_at = now()`,
+ [userId]
+ );
+ await client.query(
+ `UPDATE users SET age_confirmed_21 = false WHERE id = $1`,
+ [userId]
+ );
+ logger.warn('age eligibility rejected', { userId });
+ return { rejected: true };
+ });
+}
+
+/** Save basic profile. Step 3. */
+export async function saveBasicProfile(userId, { displayName, gender, city }) {
+ if (!displayName || typeof displayName !== 'string' || displayName.trim().length < 1) {
+ throw new HttpError(400, 'validation', 'Display name is required');
+ }
+ if (displayName.trim().length > 50) {
+ throw new HttpError(400, 'validation', 'Display name must be 50 characters or less');
+ }
+ const validGenders = GENDER_OPTIONS.map(g => g.key);
+ if (!gender || !validGenders.includes(gender)) {
+ throw new HttpError(400, 'validation', 'Please select a gender');
+ }
+ if (!city || typeof city !== 'string' || city.trim().length < 1) {
+ throw new HttpError(400, 'validation', 'City is required');
+ }
+ if (city.trim().length > 100) {
+ throw new HttpError(400, 'validation', 'City name must be 100 characters or less');
+ }
+
+ await db.query(
+ `UPDATE users SET
+ display_name = $2,
+ gender = $3::user_gender,
+ city = $4,
+ onboarding_step = GREATEST(onboarding_step, $5)
+ WHERE id = $1`,
+ [userId, displayName.trim(), gender, city.trim(), ONBOARDING_STEPS.BASIC_PROFILE]
+ );
+
+ logger.info('basic profile saved', { userId });
+ return { saved: true };
+}
+
+/** Save interests. Step 4. Requires at least 1 interest. */
+export async function saveInterests(userId, interestKeys) {
+ if (!Array.isArray(interestKeys) || interestKeys.length < 1) {
+ throw new HttpError(400, 'validation', 'Please select at least one interest');
+ }
+
+ const valid = [...new Set(interestKeys.filter(k => INTEREST_KEYS.includes(k)))];
+ if (valid.length < 1) {
+ throw new HttpError(400, 'validation', 'Please select at least one valid interest');
+ }
+ if (valid.length > INTEREST_KEYS.length) {
+ throw new HttpError(400, 'validation', 'Too many interests selected');
+ }
+
+ // Transactional: delete existing + insert new
+ return await db.tx(async (client) => {
+ await client.query('DELETE FROM member_interests WHERE user_id = $1', [userId]);
+ for (const key of valid) {
+ await client.query(
+ 'INSERT INTO member_interests (user_id, interest_key) VALUES ($1, $2) ON CONFLICT (user_id, interest_key) DO NOTHING',
+ [userId, key]
+ );
+ }
+ // Also update the legacy interests array on users table for backward compat
+ await client.query(
+ `UPDATE users SET
+ interests = $2::text[],
+ onboarding_step = GREATEST(onboarding_step, $3)
+ WHERE id = $1`,
+ [userId, valid, ONBOARDING_STEPS.INTERESTS]
+ );
+ logger.info('interests saved', { userId, count: valid.length });
+ return { saved: true, count: valid.length };
+ });
+}
+
+/** Save optional profile enhancements. Step 5. */
+export async function saveOptionalProfile(userId, { bio, languages }) {
+ const updates = {};
+ if (bio !== undefined) {
+ updates.bio = typeof bio === 'string' ? bio.trim().slice(0, 500) : null;
+ }
+ if (languages !== undefined) {
+ updates.languages = Array.isArray(languages)
+ ? languages.filter(l => typeof l === 'string' && l.trim()).map(l => l.trim()).slice(0, 10)
+ : null;
+ }
+
+ await db.query(
+ `UPDATE users SET
+ bio = COALESCE($2, bio),
+ languages = COALESCE($3, languages),
+ onboarding_step = GREATEST(onboarding_step, $4)
+ WHERE id = $1`,
+ [userId, updates.bio ?? null, updates.languages ?? null, ONBOARDING_STEPS.OPTIONAL_PROFILE]
+ );
+
+ logger.info('optional profile saved', { userId });
+ return { saved: true };
+}
+
+/** Mark onboarding as complete. Step 6. Validates all mandatory fields and authoritative age consent are present. */
+export async function completeOnboarding(userId) {
+ return await db.tx(async (client) => {
+ // Validate all mandatory fields are actually filled
+ const user = (await client.query(
+ `SELECT age_confirmed_21, display_name, gender, city FROM users WHERE id = $1`, [userId]
+ )).rows[0];
+ if (!user) throw new HttpError(404, 'not_found', 'User not found');
+
+ if (!user.age_confirmed_21) {
+ throw new HttpError(400, 'validation', 'Age confirmation is required');
+ }
+
+ // Authoritative verification: MUST have confirmed=true in onboarding_consents
+ const consent = (await client.query(
+ `SELECT confirmed, policy_version FROM onboarding_consents WHERE user_id = $1 AND consent_type = 'age_21_plus'`,
+ [userId]
+ )).rows[0];
+ if (!consent || !consent.confirmed) {
+ throw new HttpError(403, 'age_ineligible', 'Age confirmation (21+) is required to complete membership');
+ }
+
+ if (!user.display_name || user.display_name.trim().length < 1) {
+ throw new HttpError(400, 'validation', 'Display name is required');
+ }
+ if (!user.gender) {
+ throw new HttpError(400, 'validation', 'Gender selection is required');
+ }
+ if (!user.city || user.city.trim().length < 1) {
+ throw new HttpError(400, 'validation', 'City is required');
+ }
+
+ // Check at least one interest
+ const interests = (await client.query(
+ 'SELECT COUNT(*) AS cnt FROM member_interests WHERE user_id = $1', [userId]
+ )).rows[0];
+ if (!interests || Number(interests.cnt) < 1) {
+ throw new HttpError(400, 'validation', 'At least one interest is required');
+ }
+
+ await client.query(
+ `UPDATE users SET
+ onboarding_completed = true,
+ onboarding_completed_at = now(),
+ onboarding_step = $2
+ WHERE id = $1`,
+ [userId, ONBOARDING_STEPS.COMPLETE]
+ );
+
+ logger.info('onboarding completed', { userId });
+ return { completed: true };
+ });
+}
+
+/** Check if user needs onboarding and return redirect path if so. */
+export async function checkOnboardingRequired(userId) {
+ const user = await db.one(
+ 'SELECT onboarding_completed, onboarding_step FROM users WHERE id = $1', [userId]
+ );
+ if (!user) return { required: false };
+
+ if (user.onboarding_completed) {
+ return { required: false };
+ }
+
+ return {
+ required: true,
+ currentStep: user.onboarding_step || 0,
+ redirectTo: '/onboarding'
+ };
+}
diff --git a/lib/services/users.js b/lib/services/users.js
index 2e55081..98af536 100644
--- a/lib/services/users.js
+++ b/lib/services/users.js
@@ -15,14 +15,17 @@ function aliasFrom(tgUser) {
*/
export async function upsertTelegramUser(tgUser, { ageConfirmed = false, botStarted = false } = {}, client = db) {
const { rows } = await client.query(
- `INSERT INTO users (telegram_user_id, alias, age_confirmed_21, age_confirmed_at, bot_started)
- VALUES ($1, $2, $3, CASE WHEN $3 THEN now() END, $4)
+ `INSERT INTO users (telegram_user_id, alias, display_name, age_confirmed_21, age_confirmed_at, bot_started)
+ VALUES ($1, $2, $2, $3, CASE WHEN $3 THEN now() END, $4)
ON CONFLICT (telegram_user_id) DO UPDATE SET
alias = COALESCE(EXCLUDED.alias, users.alias),
+ display_name = COALESCE(users.display_name, EXCLUDED.display_name),
age_confirmed_21 = users.age_confirmed_21 OR EXCLUDED.age_confirmed_21,
age_confirmed_at = COALESCE(users.age_confirmed_at, EXCLUDED.age_confirmed_at),
bot_started = users.bot_started OR EXCLUDED.bot_started
- RETURNING id, telegram_user_id, alias, age_confirmed_21, status, bot_started`,
+ RETURNING id, telegram_user_id, alias, display_name, gender, city, age_confirmed_21, status, bot_started,
+ COALESCE(onboarding_completed, false) AS onboarding_completed,
+ COALESCE(onboarding_step, 0) AS onboarding_step`,
[tgUser.id, aliasFrom(tgUser), Boolean(ageConfirmed), Boolean(botStarted)]
);
const user = rows[0];
@@ -33,9 +36,24 @@ export async function upsertTelegramUser(tgUser, { ageConfirmed = false, botStar
return user;
}
-export async function confirmAge(userId) {
- await db.query(
- `UPDATE users SET age_confirmed_21 = true, age_confirmed_at = COALESCE(age_confirmed_at, now()) WHERE id = $1`, [userId]);
+export async function confirmAge(userId, { ip, userAgent, policyVersion = '1.0' } = {}) {
+ await db.tx(async (client) => {
+ await client.query(
+ `UPDATE users SET
+ age_confirmed_21 = true,
+ age_confirmed_at = COALESCE(age_confirmed_at, now()),
+ age_consent_policy_version = COALESCE(age_consent_policy_version, $2)
+ WHERE id = $1`,
+ [userId, policyVersion]
+ );
+ await client.query(
+ `INSERT INTO onboarding_consents (user_id, consent_type, confirmed, policy_version, ip, user_agent, consented_at)
+ VALUES ($1, 'age_21_plus', true, $2, $3, $4, now())
+ ON CONFLICT (user_id, consent_type) DO UPDATE SET
+ confirmed = true, policy_version = $2, ip = $3, user_agent = $4, consented_at = now()`,
+ [userId, policyVersion, ip || null, userAgent || null]
+ );
+ });
}
export async function userByTelegramId(telegramUserId, client = db) {
diff --git a/lib/session.js b/lib/session.js
index 13d3a5f..8e94e59 100644
--- a/lib/session.js
+++ b/lib/session.js
@@ -92,7 +92,7 @@ export function setSessionCookie(req, res, token) {
}
export function clearSessionCookie(req, res) {
- appendHeader(res, 'Set-Cookie', serializeCookie(SESSION_COOKIE, '', { maxAge: 0, secure: isSecureRequest(req) }));
+ appendHeader(res, 'Set-Cookie', serializeCookie(SESSION_COOKIE, '', { maxAge: 0, secure: isSecureRequest(req), path: '/' }));
}
/** Resolve the current user from the cookie. Returns null when signed out or user not active. */
@@ -103,7 +103,10 @@ export async function getSessionUser(req) {
let user = null;
if (data) {
user = await db.one(
- `SELECT u.id, u.telegram_user_id, u.alias, u.city, u.age_confirmed_21, u.status, u.bot_started, u.organiser_enabled
+ `SELECT u.id, u.telegram_user_id, u.phone, u.alias, u.display_name, u.city, u.gender,
+ u.age_confirmed_21, u.status, u.bot_started, u.organiser_enabled,
+ COALESCE(u.onboarding_completed, false) AS onboarding_completed,
+ COALESCE(u.onboarding_step, 0) AS onboarding_step
FROM users u JOIN user_sessions s ON s.user_id = u.id
WHERE u.id = $1 AND s.id = $2 AND s.revoked_at IS NULL AND s.expires_at > now()`, [data.u, data.s]);
if (user && user.status !== 'active') user = null;
@@ -122,6 +125,18 @@ export async function requireUser(req) {
return user;
}
+/** Require an active user who has completed mandatory onboarding. */
+export async function requireOnboardedUser(req) {
+ const user = await requireUser(req);
+ if (!user.onboarding_completed) {
+ throw new HttpError(403, 'onboarding_required', 'Please complete member onboarding first', {
+ onboardingStep: user.onboarding_step || 0,
+ redirectTo: '/onboarding'
+ });
+ }
+ return user;
+}
+
/** Double-check CSRF on state-changing session-authenticated requests. */
export function requireCsrf(req, user) {
const header = req.headers['x-csrf-token'];
diff --git a/lib/views/layout.js b/lib/views/layout.js
index 9f779e2..f9446c4 100644
--- a/lib/views/layout.js
+++ b/lib/views/layout.js
@@ -154,7 +154,21 @@ function searchBar() {
`;
}
-function nav(current) {
+function nav(current, path = '') {
+ if (path === '/onboarding') {
+ return html``;
+ }
+
return html`