mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 17:41:51 +00:00
Add "guest" trip participants — people without a Trek account who can still be assigned to costs, packing, to-dos and day-plan activities. A guest is a credential-less users row (is_guest=1) joined into trip_members, so it is assignable everywhere a real member is, with the cost-splitting, settlement, packing and assignment paths working unchanged. Guests are firewalled from everything account-related: they can never sign in (password, OIDC and reset lookups skip them), never appear in the global user directory, the member-add picker or admin user management, are never resolved as notification recipients, can't be invited to another trip, and can't be made owner. The trip owner manages guests from the share dialog in a dedicated, clearly-labelled section (add / rename / remove), and guests carry a "Guest" badge wherever members are picked. All 22 locales stay in parity.
This commit is contained in:
@@ -3147,6 +3147,17 @@ function runMigrations(db: Database.Database): void {
|
||||
}
|
||||
}
|
||||
},
|
||||
// Guest members (#1362): people added to a trip without an account. A guest is a
|
||||
// users row flagged is_guest=1 (no usable credentials) joined into trip_members,
|
||||
// so it's assignable everywhere a member is — but must never authenticate or show
|
||||
// up in the global user directory. The flag is the discriminator for those guards.
|
||||
() => {
|
||||
try {
|
||||
db.exec('ALTER TABLE users ADD COLUMN is_guest INTEGER NOT NULL DEFAULT 0');
|
||||
} catch (err: any) {
|
||||
if (!err.message?.includes('duplicate column name')) throw err;
|
||||
}
|
||||
},
|
||||
];
|
||||
|
||||
if (currentVersion < migrations.length) {
|
||||
|
||||
@@ -27,6 +27,7 @@ function createTables(db: Database.Database): void {
|
||||
must_change_password INTEGER DEFAULT 0,
|
||||
password_version INTEGER NOT NULL DEFAULT 0,
|
||||
feed_token TEXT,
|
||||
is_guest INTEGER NOT NULL DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
@@ -314,6 +314,60 @@ export class TripsController {
|
||||
}
|
||||
}
|
||||
|
||||
/** Loads the trip or throws 404, then asserts the caller is its owner (guest CRUD, #1362). */
|
||||
private requireOwner(id: string, user: User): void {
|
||||
const access = this.trips.canAccessTrip(id, user.id);
|
||||
if (!access) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
if (access.user_id !== user.id) {
|
||||
throw new HttpException({ error: 'Only the owner can manage guests' }, 403);
|
||||
}
|
||||
}
|
||||
|
||||
@Post(':id/guests')
|
||||
@HttpCode(201)
|
||||
createGuest(@CurrentUser() user: User, @Param('id') id: string, @Body('name') name: unknown) {
|
||||
this.requireOwner(id, user);
|
||||
if (typeof name !== 'string' || !name.trim()) {
|
||||
throw new HttpException({ error: 'Guest name is required' }, 400);
|
||||
}
|
||||
try {
|
||||
// No notifyInvite: a guest has no inbox.
|
||||
return this.trips.createGuest(id, name, user.id);
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof ValidationError) throw new HttpException({ error: e.message }, 400);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@Put(':id/guests/:userId')
|
||||
renameGuest(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string, @Body('name') name: unknown) {
|
||||
this.requireOwner(id, user);
|
||||
if (typeof name !== 'string' || !name.trim()) {
|
||||
throw new HttpException({ error: 'Guest name is required' }, 400);
|
||||
}
|
||||
try {
|
||||
if (!this.trips.renameGuest(id, parseInt(userId), name)) {
|
||||
throw new HttpException({ error: 'Guest not found' }, 404);
|
||||
}
|
||||
return { success: true };
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof HttpException) throw e;
|
||||
if (e instanceof ValidationError) throw new HttpException({ error: e.message }, 400);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@Delete(':id/guests/:userId')
|
||||
deleteGuest(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string) {
|
||||
this.requireOwner(id, user);
|
||||
if (!this.trips.deleteGuest(id, parseInt(userId))) {
|
||||
throw new HttpException({ error: 'Guest not found' }, 404);
|
||||
}
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@Get(':id/bundle')
|
||||
bundle(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const trip = this.trips.get(id, user.id) as { user_id: number } | undefined;
|
||||
|
||||
@@ -99,6 +99,18 @@ export class TripsService {
|
||||
return tripSvc.transferOwnership(tripId, newOwnerId, currentOwnerId);
|
||||
}
|
||||
|
||||
createGuest(tripId: string, name: string, invitedBy: number) {
|
||||
return tripSvc.createGuest(tripId, name, invitedBy);
|
||||
}
|
||||
|
||||
renameGuest(tripId: string, guestUserId: number, name: string): boolean {
|
||||
return tripSvc.renameGuest(tripId, guestUserId, name);
|
||||
}
|
||||
|
||||
deleteGuest(tripId: string, guestUserId: number): boolean {
|
||||
return tripSvc.deleteGuest(tripId, guestUserId);
|
||||
}
|
||||
|
||||
exportICS(tripId: string) {
|
||||
return tripSvc.exportICS(tripId);
|
||||
}
|
||||
|
||||
@@ -59,8 +59,10 @@ export const isDocker = (() => {
|
||||
// ── User CRUD ──────────────────────────────────────────────────────────────
|
||||
|
||||
export function listUsers() {
|
||||
// Guests (#1362) are accountless trip participants, not real users — keep them out
|
||||
// of admin user management entirely.
|
||||
const users = db.prepare(
|
||||
'SELECT id, username, email, role, avatar, created_at, updated_at, last_login FROM users ORDER BY created_at DESC'
|
||||
'SELECT id, username, email, role, avatar, created_at, updated_at, last_login FROM users WHERE COALESCE(is_guest, 0) = 0 ORDER BY created_at DESC'
|
||||
).all() as (Pick<User, 'id' | 'username' | 'email' | 'role' | 'created_at' | 'updated_at' | 'last_login'> & { avatar?: string | null })[];
|
||||
let onlineUserIds = new Set<number>();
|
||||
try {
|
||||
@@ -93,10 +95,11 @@ export function createUser(data: { username: string; email: string; password: st
|
||||
return { error: 'Invalid role', status: 400 };
|
||||
}
|
||||
|
||||
const existingUsername = db.prepare('SELECT id FROM users WHERE username = ?').get(username);
|
||||
// Guests (#1362) live in a reserved synthetic namespace; never let one block a real account.
|
||||
const existingUsername = db.prepare('SELECT id FROM users WHERE username = ? AND COALESCE(is_guest, 0) = 0').get(username);
|
||||
if (existingUsername) return { error: 'Username already taken', status: 409 };
|
||||
|
||||
const existingEmail = db.prepare('SELECT id FROM users WHERE email = ?').get(email);
|
||||
const existingEmail = db.prepare('SELECT id FROM users WHERE email = ? AND COALESCE(is_guest, 0) = 0').get(email);
|
||||
if (existingEmail) return { error: 'Email already taken', status: 409 };
|
||||
|
||||
const passwordHash = bcrypt.hashSync(password, BCRYPT_COST);
|
||||
@@ -129,11 +132,11 @@ export function updateUser(id: string, data: { username?: string; email?: string
|
||||
}
|
||||
|
||||
if (username && username !== user.username) {
|
||||
const conflict = db.prepare('SELECT id FROM users WHERE username = ? AND id != ?').get(username, id);
|
||||
const conflict = db.prepare('SELECT id FROM users WHERE username = ? AND id != ? AND COALESCE(is_guest, 0) = 0').get(username, id);
|
||||
if (conflict) return { error: 'Username already taken', status: 409 };
|
||||
}
|
||||
if (email && email !== user.email) {
|
||||
const conflict = db.prepare('SELECT id FROM users WHERE email = ? AND id != ?').get(email, id);
|
||||
const conflict = db.prepare('SELECT id FROM users WHERE email = ? AND id != ? AND COALESCE(is_guest, 0) = 0').get(email, id);
|
||||
if (conflict) return { error: 'Email already taken', status: 409 };
|
||||
}
|
||||
|
||||
@@ -195,7 +198,7 @@ export function deleteUser(id: string, currentUserId: number) {
|
||||
// ── Stats ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export function getStats() {
|
||||
const totalUsers = (db.prepare('SELECT COUNT(*) as count FROM users').get() as { count: number }).count;
|
||||
const totalUsers = (db.prepare('SELECT COUNT(*) as count FROM users WHERE COALESCE(is_guest, 0) = 0').get() as { count: number }).count;
|
||||
const totalTrips = (db.prepare('SELECT COUNT(*) as count FROM trips').get() as { count: number }).count;
|
||||
const totalPlaces = (db.prepare('SELECT COUNT(*) as count FROM places').get() as { count: number }).count;
|
||||
const totalFiles = (db.prepare('SELECT COUNT(*) as count FROM trip_files').get() as { count: number }).count;
|
||||
|
||||
@@ -277,7 +277,7 @@ export function getPendingMfaSecret(userId: number): string | null {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function getAppConfig(authenticatedUser: { id: number } | null) {
|
||||
const userCount = (db.prepare('SELECT COUNT(*) as count FROM users').get() as { count: number }).count;
|
||||
const userCount = (db.prepare('SELECT COUNT(*) as count FROM users WHERE COALESCE(is_guest, 0) = 0').get() as { count: number }).count;
|
||||
const isDemo = process.env.DEMO_MODE?.toLowerCase() === 'true';
|
||||
const toggles = resolveAuthToggles();
|
||||
const version: string = process.env.APP_VERSION ?? require('../../package.json').version;
|
||||
@@ -378,7 +378,7 @@ export function registerUser(body: {
|
||||
const email = typeof body.email === 'string' ? body.email.trim() : '';
|
||||
const { password, invite_token } = body;
|
||||
|
||||
const userCount = (db.prepare('SELECT COUNT(*) as count FROM users').get() as { count: number }).count;
|
||||
const userCount = (db.prepare('SELECT COUNT(*) as count FROM users WHERE COALESCE(is_guest, 0) = 0').get() as { count: number }).count;
|
||||
|
||||
let validInvite: any = null;
|
||||
if (invite_token) {
|
||||
@@ -406,7 +406,8 @@ export function registerUser(body: {
|
||||
return { error: 'Invalid email format', status: 400 };
|
||||
}
|
||||
|
||||
const existingUser = db.prepare('SELECT id FROM users WHERE LOWER(email) = LOWER(?) OR LOWER(username) = LOWER(?)').get(email, username);
|
||||
// Ignore guests (#1362): their synthetic username/email must never block a real signup.
|
||||
const existingUser = db.prepare('SELECT id FROM users WHERE (LOWER(email) = LOWER(?) OR LOWER(username) = LOWER(?)) AND COALESCE(is_guest, 0) = 0').get(email, username);
|
||||
if (existingUser) {
|
||||
return { error: 'Registration failed. Please try different credentials.', status: 409 };
|
||||
}
|
||||
@@ -469,7 +470,9 @@ export function loginUser(body: {
|
||||
return { error: 'Email and password are required', status: 400 };
|
||||
}
|
||||
|
||||
const user = db.prepare('SELECT * FROM users WHERE LOWER(email) = LOWER(?)').get(email) as User | undefined;
|
||||
// Guests (#1362) carry a synthetic email but must never authenticate — treat a
|
||||
// matched guest row exactly like an unknown email (dummy-hash timing preserved).
|
||||
const user = db.prepare('SELECT * FROM users WHERE LOWER(email) = LOWER(?) AND COALESCE(is_guest, 0) = 0').get(email) as User | undefined;
|
||||
|
||||
// Always run bcrypt — even for unknown/OIDC-only users — so response time
|
||||
// does not reveal whether the email exists in the database (CWE-203/208).
|
||||
@@ -649,7 +652,7 @@ export function updateSettings(
|
||||
if (!/^[a-zA-Z0-9_.-]+$/.test(trimmed)) {
|
||||
return { error: 'Username can only contain letters, numbers, underscores, dots and hyphens', status: 400 };
|
||||
}
|
||||
const conflict = db.prepare('SELECT id FROM users WHERE LOWER(username) = LOWER(?) AND id != ?').get(trimmed, userId);
|
||||
const conflict = db.prepare('SELECT id FROM users WHERE LOWER(username) = LOWER(?) AND id != ? AND COALESCE(is_guest, 0) = 0').get(trimmed, userId);
|
||||
if (conflict) return { error: 'Username already taken', status: 409 };
|
||||
}
|
||||
|
||||
@@ -658,7 +661,7 @@ export function updateSettings(
|
||||
if (!trimmed || !EMAIL_REGEX.test(trimmed)) {
|
||||
return { error: 'Invalid email format', status: 400 };
|
||||
}
|
||||
const conflict = db.prepare('SELECT id FROM users WHERE LOWER(email) = LOWER(?) AND id != ?').get(trimmed, userId);
|
||||
const conflict = db.prepare('SELECT id FROM users WHERE LOWER(email) = LOWER(?) AND id != ? AND COALESCE(is_guest, 0) = 0').get(trimmed, userId);
|
||||
if (conflict) return { error: 'Email already taken', status: 409 };
|
||||
}
|
||||
|
||||
@@ -735,8 +738,10 @@ export async function deleteAvatar(userId: number) {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function listUsers(excludeUserId: number) {
|
||||
// The global user directory feeds the trip member-add / contributor pickers —
|
||||
// guests (#1362) are trip-scoped and must never be selectable here.
|
||||
const users = db.prepare(
|
||||
'SELECT id, username, avatar FROM users WHERE id != ? ORDER BY username ASC'
|
||||
'SELECT id, username, avatar FROM users WHERE id != ? AND COALESCE(is_guest, 0) = 0 ORDER BY username ASC'
|
||||
).all(excludeUserId) as Pick<User, 'id' | 'username' | 'avatar'>[];
|
||||
return users.map(u => ({ ...u, avatar_url: avatarUrl(u) }));
|
||||
}
|
||||
@@ -1201,7 +1206,8 @@ export function requestPasswordReset(rawEmail: string, createdIp: string | null)
|
||||
return { tokenForDelivery: null, userId: null, userEmail: null, reason: 'no_user' };
|
||||
}
|
||||
|
||||
const user = db.prepare('SELECT id, email, password_hash, oidc_sub FROM users WHERE email = ?').get(email) as
|
||||
// A guest (#1362) must never receive a reset link — treat its synthetic email as unknown.
|
||||
const user = db.prepare('SELECT id, email, password_hash, oidc_sub FROM users WHERE email = ? AND COALESCE(is_guest, 0) = 0').get(email) as
|
||||
| { id: number; email: string; password_hash: string | null; oidc_sub: string | null }
|
||||
| undefined;
|
||||
|
||||
|
||||
@@ -73,17 +73,22 @@ interface NotificationRow {
|
||||
export function resolveRecipients(scope: NotificationScope, target: number, excludeUserId?: number | null): number[] {
|
||||
let userIds: number[] = [];
|
||||
|
||||
// Guests (#1362) are trip members for assignment purposes but have no inbox/email,
|
||||
// so they must never be resolved as notification recipients on any scope. This is the
|
||||
// single chokepoint for in-app/email/webhook/ntfy, so filtering here covers all channels.
|
||||
if (scope === 'trip') {
|
||||
const owner = db.prepare('SELECT user_id FROM trips WHERE id = ?').get(target) as { user_id: number } | undefined;
|
||||
const members = db.prepare('SELECT user_id FROM trip_members WHERE trip_id = ?').all(target) as { user_id: number }[];
|
||||
const members = db.prepare('SELECT m.user_id FROM trip_members m JOIN users u ON u.id = m.user_id WHERE m.trip_id = ? AND COALESCE(u.is_guest, 0) = 0').all(target) as { user_id: number }[];
|
||||
const ids = new Set<number>();
|
||||
if (owner) ids.add(owner.user_id);
|
||||
for (const m of members) ids.add(m.user_id);
|
||||
userIds = Array.from(ids);
|
||||
} else if (scope === 'user') {
|
||||
userIds = [target];
|
||||
// A guest can be a todo assignee (scope='user'); never notify them.
|
||||
const u = db.prepare('SELECT is_guest FROM users WHERE id = ?').get(target) as { is_guest?: number } | undefined;
|
||||
userIds = u && u.is_guest ? [] : [target];
|
||||
} else if (scope === 'admin') {
|
||||
const admins = db.prepare('SELECT id FROM users WHERE role = ?').all('admin') as { id: number }[];
|
||||
const admins = db.prepare("SELECT id FROM users WHERE role = ? AND COALESCE(is_guest, 0) = 0").all('admin') as { id: number }[];
|
||||
userIds = admins.map(a => a.id);
|
||||
}
|
||||
|
||||
|
||||
@@ -93,7 +93,8 @@ export function getMcpSafeUrl(): string {
|
||||
}
|
||||
|
||||
export function getUserEmail(userId: number): string | null {
|
||||
return (db.prepare('SELECT email FROM users WHERE id = ?').get(userId) as { email: string } | undefined)?.email || null;
|
||||
// Defense-in-depth (#1362): a guest's synthetic email must never be emailed.
|
||||
return (db.prepare('SELECT email FROM users WHERE id = ? AND COALESCE(is_guest, 0) = 0').get(userId) as { email: string } | undefined)?.email || null;
|
||||
}
|
||||
|
||||
export function getUserLanguage(userId: number): string {
|
||||
|
||||
@@ -367,7 +367,8 @@ export function findOrCreateUser(
|
||||
// Try to find existing user by sub, then by email
|
||||
let user = db.prepare('SELECT * FROM users WHERE oidc_sub = ? AND oidc_issuer = ?').get(sub, config.issuer) as User | undefined;
|
||||
if (!user) {
|
||||
user = db.prepare('SELECT * FROM users WHERE LOWER(email) = ?').get(email) as User | undefined;
|
||||
// Never link/log-in to a guest (#1362) via its synthetic email.
|
||||
user = db.prepare('SELECT * FROM users WHERE LOWER(email) = ? AND COALESCE(is_guest, 0) = 0').get(email) as User | undefined;
|
||||
}
|
||||
|
||||
if (user) {
|
||||
@@ -405,7 +406,7 @@ export function findOrCreateUser(
|
||||
}
|
||||
|
||||
// --- New user registration ---
|
||||
const userCount = (db.prepare('SELECT COUNT(*) as count FROM users').get() as { count: number }).count;
|
||||
const userCount = (db.prepare('SELECT COUNT(*) as count FROM users WHERE COALESCE(is_guest, 0) = 0').get() as { count: number }).count;
|
||||
const isFirstUser = userCount === 0;
|
||||
|
||||
let validInvite: any = null;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { db, isOwner } from '../db/database';
|
||||
import { Trip, User } from '../types';
|
||||
import { listDays, listAccommodations } from './dayService';
|
||||
@@ -347,8 +348,10 @@ export function getTripOwner(tripId: string | number): { user_id: number } | und
|
||||
// ── Members ───────────────────────────────────────────────────────────────
|
||||
|
||||
export function listMembers(tripId: string | number, tripOwnerId: number) {
|
||||
// u.is_guest rides along (#1362) so guests stay assignable everywhere a member is,
|
||||
// while the UI can badge them and suppress owner-only actions. The owner is never a guest.
|
||||
const members = db.prepare(`
|
||||
SELECT u.id, u.username, u.email, u.avatar,
|
||||
SELECT u.id, u.username, u.email, u.avatar, u.is_guest,
|
||||
CASE WHEN u.id = ? THEN 'owner' ELSE 'member' END as role,
|
||||
m.added_at,
|
||||
ib.username as invited_by_username
|
||||
@@ -357,13 +360,13 @@ export function listMembers(tripId: string | number, tripOwnerId: number) {
|
||||
LEFT JOIN users ib ON ib.id = m.invited_by
|
||||
WHERE m.trip_id = ?
|
||||
ORDER BY m.added_at ASC
|
||||
`).all(tripOwnerId, tripId) as { id: number; username: string; email: string; avatar: string | null; role: string; added_at: string; invited_by_username: string | null }[];
|
||||
`).all(tripOwnerId, tripId) as { id: number; username: string; email: string; avatar: string | null; is_guest: number; role: string; added_at: string; invited_by_username: string | null }[];
|
||||
|
||||
const owner = db.prepare('SELECT id, username, email, avatar FROM users WHERE id = ?').get(tripOwnerId) as Pick<User, 'id' | 'username' | 'email' | 'avatar'>;
|
||||
|
||||
return {
|
||||
owner: { ...owner, role: 'owner', avatar_url: owner.avatar ? `/uploads/avatars/${owner.avatar}` : null },
|
||||
members: members.map(m => ({ ...m, avatar_url: m.avatar ? `/uploads/avatars/${m.avatar}` : null })),
|
||||
owner: { ...owner, role: 'owner', is_guest: false, avatar_url: owner.avatar ? `/uploads/avatars/${owner.avatar}` : null },
|
||||
members: members.map(m => ({ ...m, is_guest: !!m.is_guest, avatar_url: m.avatar ? `/uploads/avatars/${m.avatar}` : null })),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -376,8 +379,10 @@ export interface AddMemberResult {
|
||||
export function addMember(tripId: string | number, identifier: string, tripOwnerId: number, invitedByUserId: number): AddMemberResult {
|
||||
if (!identifier) throw new ValidationError('Email or username required');
|
||||
|
||||
// Guests (#1362) are not invitable accounts — exclude them so a trip-scoped guest
|
||||
// can never be resolved (and re-attached to another trip) through the invite box.
|
||||
const target = db.prepare(
|
||||
'SELECT id, username, email, avatar FROM users WHERE email = ? OR username = ?'
|
||||
'SELECT id, username, email, avatar FROM users WHERE (email = ? OR username = ?) AND COALESCE(is_guest, 0) = 0'
|
||||
).get(identifier.trim(), identifier.trim()) as Pick<User, 'id' | 'username' | 'email' | 'avatar'> | undefined;
|
||||
|
||||
if (!target) throw new NotFoundError('User not found');
|
||||
@@ -425,8 +430,10 @@ export function transferOwnership(
|
||||
if (trip.user_id !== currentOwnerId) throw new ValidationError('Only the owner can transfer ownership');
|
||||
if (newOwnerId === currentOwnerId) throw new ValidationError('You already own this trip');
|
||||
|
||||
const newOwner = db.prepare('SELECT id, email FROM users WHERE id = ?').get(newOwnerId) as { id: number; email: string } | undefined;
|
||||
const newOwner = db.prepare('SELECT id, email, is_guest FROM users WHERE id = ?').get(newOwnerId) as { id: number; email: string; is_guest?: number } | undefined;
|
||||
if (!newOwner) throw new NotFoundError('User not found');
|
||||
// A guest (#1362) can never log in, so it must never become the owner of a trip.
|
||||
if (newOwner.is_guest) throw new ValidationError('Cannot transfer ownership to a guest');
|
||||
|
||||
const isMember = db.prepare('SELECT id FROM trip_members WHERE trip_id = ? AND user_id = ?').get(tripId, newOwnerId);
|
||||
if (!isMember) throw new ValidationError('New owner must be a trip member');
|
||||
@@ -445,6 +452,85 @@ export function transferOwnership(
|
||||
return { tripTitle: trip.title, fromEmail, toEmail: newOwner.email };
|
||||
}
|
||||
|
||||
// ── Guest members (#1362) ───────────────────────────────────────────────────
|
||||
//
|
||||
// A guest is a credential-less users row (is_guest=1) joined into trip_members, so
|
||||
// it is assignable everywhere a real member is (budget splits, packing, to-dos, day
|
||||
// participants) yet can never authenticate (the auth/global-list guards exclude
|
||||
// is_guest=1). The display name lives in users.username so every existing JOIN that
|
||||
// renders a member name shows the guest correctly; a synthetic, non-deliverable
|
||||
// email keeps the UNIQUE/NOT NULL constraints satisfied.
|
||||
|
||||
export interface GuestMember {
|
||||
id: number;
|
||||
username: string;
|
||||
email: string;
|
||||
role: 'member';
|
||||
is_guest: true;
|
||||
avatar_url: null;
|
||||
}
|
||||
|
||||
/** username is UNIQUE across all users — keep the typed name but disambiguate guests
|
||||
* that happen to share it (e.g. two "Anna"s) with a numeric suffix. */
|
||||
function uniqueGuestUsername(name: string, excludeId?: number): string {
|
||||
let candidate = name;
|
||||
let n = 2;
|
||||
const probe = excludeId != null
|
||||
? db.prepare('SELECT id FROM users WHERE LOWER(username) = LOWER(?) AND id != ?')
|
||||
: db.prepare('SELECT id FROM users WHERE LOWER(username) = LOWER(?)');
|
||||
while (excludeId != null ? probe.get(candidate, excludeId) : probe.get(candidate)) {
|
||||
candidate = `${name} ${n++}`;
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
export function createGuest(tripId: string | number, name: string, invitedByUserId: number): { member: GuestMember } {
|
||||
const display = (name || '').trim();
|
||||
if (!display) throw new ValidationError('Guest name is required');
|
||||
if (display.length > 50) throw new ValidationError('Guest name must be 50 characters or fewer');
|
||||
|
||||
const email = `guest-${randomUUID()}@guests.invalid`;
|
||||
const username = uniqueGuestUsername(display);
|
||||
|
||||
const create = db.transaction(() => {
|
||||
const res = db.prepare(
|
||||
"INSERT INTO users (username, email, password_hash, role, is_guest) VALUES (?, ?, '', 'user', 1)"
|
||||
).run(username, email);
|
||||
const guestId = Number(res.lastInsertRowid);
|
||||
db.prepare('INSERT INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)').run(tripId, guestId, invitedByUserId);
|
||||
return guestId;
|
||||
});
|
||||
const guestId = create();
|
||||
|
||||
return { member: { id: guestId, username, email, role: 'member', is_guest: true, avatar_url: null } };
|
||||
}
|
||||
|
||||
/** Confirms a user id is a guest of THIS trip, so guest mutations stay trip-scoped. */
|
||||
function guestOfTrip(tripId: string | number, guestUserId: number): boolean {
|
||||
return !!db.prepare(
|
||||
'SELECT u.id FROM users u JOIN trip_members m ON m.user_id = u.id WHERE u.id = ? AND m.trip_id = ? AND u.is_guest = 1'
|
||||
).get(guestUserId, tripId);
|
||||
}
|
||||
|
||||
export function renameGuest(tripId: string | number, guestUserId: number, name: string): boolean {
|
||||
const display = (name || '').trim();
|
||||
if (!display) throw new ValidationError('Guest name is required');
|
||||
if (display.length > 50) throw new ValidationError('Guest name must be 50 characters or fewer');
|
||||
if (!guestOfTrip(tripId, guestUserId)) return false;
|
||||
|
||||
const username = uniqueGuestUsername(display, guestUserId);
|
||||
db.prepare('UPDATE users SET username = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND is_guest = 1').run(username, guestUserId);
|
||||
return true;
|
||||
}
|
||||
|
||||
export function deleteGuest(tripId: string | number, guestUserId: number): boolean {
|
||||
if (!guestOfTrip(tripId, guestUserId)) return false;
|
||||
// Deleting the guest's users row cascades its membership and every assignment join
|
||||
// (trip_members, budget/packing/assignment links) via the ON DELETE foreign keys.
|
||||
db.prepare('DELETE FROM users WHERE id = ? AND is_guest = 1').run(guestUserId);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── ICS export ────────────────────────────────────────────────────────────
|
||||
|
||||
// RFC 5545 §3.1: content lines longer than 75 octets must be folded with a CRLF
|
||||
|
||||
@@ -19,6 +19,9 @@ export interface User {
|
||||
must_change_password?: number | boolean;
|
||||
first_seen_version?: string;
|
||||
login_count?: number;
|
||||
// Guest members (#1362): accountless trip participants. Flagged guests must never
|
||||
// authenticate or appear in the global user directory.
|
||||
is_guest?: number | boolean;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user