mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-06 02:34:21 +00:00
Return the registration invites to the domain that consumes them
invite_tokens gates signup. Its consumer is the registration path in AuthService, not anything in admin/, which held the four management methods only because the routes sit under /api/admin. Worth spelling out because the names invite it: invite_tokens and trip_invite_tokens are different tables for different jobs, and this one has nothing to do with adding a member to a trip. An earlier reading of the plan had these going to trip-invite/, which would have been the wrong home. The routes keep their paths and their admin guard; AdminController injects the service instead of carrying another domain's SQL. Also recorded, in the file, why the app-settings pair did NOT move to settings/ with the other app_settings readers: updateAppSettings runs the lockout guard that stops an admin disabling every login method, and that guard is auth's own resolveAuthToggles. Moving it would put an AuthModule import inside a leaf module half the container pulls in.
This commit is contained in:
@@ -3,6 +3,7 @@ import type { Request } from 'express';
|
||||
import { readEnv } from '../../app-config';
|
||||
import { AdminService } from './admin.service';
|
||||
import { TokenService } from '../tokens/token.service';
|
||||
import { RegistrationInvitesService } from '../auth/registration-invites.service';
|
||||
import {
|
||||
AdminUserCreateDto,
|
||||
AdminUserUpdateDto,
|
||||
@@ -63,6 +64,7 @@ export class AdminController {
|
||||
private readonly audit: AuditService,
|
||||
private readonly notifications: NotificationsService,
|
||||
private readonly tokens: TokenService,
|
||||
private readonly invites: RegistrationInvitesService,
|
||||
) {}
|
||||
|
||||
// ── Users ──
|
||||
@@ -139,23 +141,23 @@ export class AdminController {
|
||||
|
||||
// ── Invites ──
|
||||
@Get('invites')
|
||||
listInvites() { return { invites: this.admin.listInvites() }; }
|
||||
listInvites() { return { invites: this.invites.listInvites() }; }
|
||||
|
||||
// Trips an admin can optionally bind a registration invite to (#1402).
|
||||
@Get('invites/trips')
|
||||
listInviteTrips() { return { trips: this.admin.listTripsForInvite() }; }
|
||||
listInviteTrips() { return { trips: this.invites.listTripsForInvite() }; }
|
||||
|
||||
@Post('invites')
|
||||
@HttpCode(201)
|
||||
createInvite(@CurrentUser() user: User, @Body() body: AdminInviteCreateDto, @Req() req: Request) {
|
||||
const result = this.admin.createInvite(user.id, body);
|
||||
const result = this.invites.createInvite(user.id, body);
|
||||
this.audit.writeAudit({ userId: user.id, action: 'admin.invite_create', resource: String(result.inviteId), ip: getClientIp(req), details: { max_uses: result.uses, expires_in_days: result.expiresInDays, trip_id: result.tripId } });
|
||||
return { invite: result.invite };
|
||||
}
|
||||
|
||||
@Delete('invites/:id')
|
||||
deleteInvite(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) {
|
||||
ok(this.admin.deleteInvite(id));
|
||||
ok(this.invites.deleteInvite(id));
|
||||
this.audit.writeAudit({ userId: user.id, action: 'admin.invite_delete', resource: String(id), ip: getClientIp(req) });
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@@ -456,71 +456,6 @@ export class AdminService {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Invite Tokens ──────────────────────────────────────────────────────────
|
||||
|
||||
listInvites() {
|
||||
return this.db.all(`
|
||||
SELECT i.*, u.username as created_by_name, t.title as trip_title
|
||||
FROM invite_tokens i
|
||||
JOIN users u ON i.created_by = u.id
|
||||
LEFT JOIN trips t ON i.trip_id = t.id
|
||||
ORDER BY i.created_at DESC
|
||||
`);
|
||||
}
|
||||
|
||||
/** Trips an admin can bind an invite to — id + title only, for the picker (#1402). */
|
||||
listTripsForInvite() {
|
||||
return this.db.all('SELECT id, title FROM trips ORDER BY title COLLATE NOCASE ASC');
|
||||
}
|
||||
|
||||
createInvite(
|
||||
createdBy: number,
|
||||
data: { max_uses?: string | number; expires_in_days?: string | number; trip_id?: string | number | null },
|
||||
) {
|
||||
const rawUses = parseInt(String(data.max_uses));
|
||||
const uses = rawUses === 0 ? 0 : Math.min(Math.max(rawUses || 1, 1), 5);
|
||||
const token = crypto.randomBytes(16).toString('hex');
|
||||
const expiresAt = data.expires_in_days
|
||||
? new Date(Date.now() + parseInt(String(data.expires_in_days)) * 86400000).toISOString()
|
||||
: null;
|
||||
|
||||
// Optional trip binding: only persist a trip that actually exists, so a stale
|
||||
// or forged id can never bind (and never auto-adds anyone on registration).
|
||||
let tripId: number | null = null;
|
||||
if (data.trip_id != null && String(data.trip_id).trim() !== '') {
|
||||
const parsed = parseInt(String(data.trip_id));
|
||||
if (!Number.isInteger(parsed) || !this.db.get('SELECT id FROM trips WHERE id = ?', parsed)) {
|
||||
// Used to bind null silently, handing back a plain registration invite
|
||||
// the admin never asked for.
|
||||
return { error: 'Trip not found', status: 404 };
|
||||
}
|
||||
tripId = parsed;
|
||||
}
|
||||
|
||||
const ins = this.db.run(
|
||||
'INSERT INTO invite_tokens (token, max_uses, expires_at, created_by, trip_id) VALUES (?, ?, ?, ?, ?)',
|
||||
token, uses, expiresAt, createdBy, tripId,
|
||||
);
|
||||
|
||||
const inviteId = Number(ins.lastInsertRowid);
|
||||
const invite = this.db.get(`
|
||||
SELECT i.*, u.username as created_by_name, t.title as trip_title
|
||||
FROM invite_tokens i
|
||||
JOIN users u ON i.created_by = u.id
|
||||
LEFT JOIN trips t ON i.trip_id = t.id
|
||||
WHERE i.id = ?
|
||||
`, inviteId);
|
||||
|
||||
return { invite, inviteId, uses, expiresInDays: data.expires_in_days ?? null, tripId };
|
||||
}
|
||||
|
||||
deleteInvite(id: string) {
|
||||
const invite = this.db.get('SELECT id FROM invite_tokens WHERE id = ?', id);
|
||||
if (!invite) return { error: 'Invite not found', status: 404 };
|
||||
this.db.run('DELETE FROM invite_tokens WHERE id = ?', id);
|
||||
return {};
|
||||
}
|
||||
|
||||
// ── Addons ─────────────────────────────────────────────────────────────────
|
||||
|
||||
listAddons() {
|
||||
|
||||
@@ -6,6 +6,7 @@ import { AuthController } from './auth.controller';
|
||||
import { PasskeyController } from './passkey.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { UserProfileService } from './user-profile.service';
|
||||
import { RegistrationInvitesService } from './registration-invites.service';
|
||||
import { PasskeyService } from './passkey.service';
|
||||
import { AuthMcp } from './auth.mcp';
|
||||
import { UserCleanupService } from './user-cleanup.service';
|
||||
@@ -39,7 +40,7 @@ import { TripMembershipModule } from '../trip-membership/trip-membership.module'
|
||||
@Module({
|
||||
imports: [RateLimitModule, AuditModule, PermissionsModule, TripMembershipModule, MailerModule, AppConfigModule, TokensModule],
|
||||
controllers: [AuthPublicController, AuthController, PasskeyController],
|
||||
providers: [AuthService, UserProfileService, PasskeyService, UserCleanupService, WebauthnConfigService, AuthMcp],
|
||||
exports: [AuthService, PasskeyService, UserCleanupService],
|
||||
providers: [AuthService, UserProfileService, RegistrationInvitesService, PasskeyService, UserCleanupService, WebauthnConfigService, AuthMcp],
|
||||
exports: [AuthService, RegistrationInvitesService, PasskeyService, UserCleanupService],
|
||||
})
|
||||
export class AuthModule {}
|
||||
|
||||
@@ -574,6 +574,16 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Admin settings
|
||||
//
|
||||
// These stay here, against the first instinct to file them under settings/
|
||||
// with the other app_settings readers. updateAppSettings runs the lockout
|
||||
// guard that stops an admin disabling every login method at once, and that
|
||||
// guard is resolveAuthToggles — auth's own view of which methods exist.
|
||||
// Moving the pair would put an AuthModule import inside SettingsModule, a
|
||||
// leaf that half the container pulls in, to buy nothing but a tidier
|
||||
// directory. The role check below is likewise left as written: swapping it
|
||||
// for AdminGuard changes the response body, so it belongs with the guard
|
||||
// work, not with a move.
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
getAppSettings(userId: number): { error?: string; status?: number; data?: Record<string, string> } {
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import crypto from 'crypto';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
|
||||
/**
|
||||
* Registration invites: the tokens an admin hands out so someone can create an
|
||||
* account on a closed instance, optionally dropping them straight into a trip.
|
||||
*
|
||||
* This lives in auth/ and not in trip-invite/, which is the trap the name sets.
|
||||
* invite_tokens and trip_invite_tokens are different tables for different
|
||||
* things — the first gates signup, the second adds an existing user to a trip.
|
||||
* The consumer of this one is the registration path in AuthService, so the
|
||||
* table belongs to the auth domain.
|
||||
*
|
||||
* The four methods moved verbatim out of AdminService, which held them only
|
||||
* because the management routes are under /api/admin. Those routes keep their
|
||||
* paths and their guards; AdminController now injects this instead of carrying
|
||||
* another domain's SQL.
|
||||
*/
|
||||
@Injectable()
|
||||
export class RegistrationInvitesService {
|
||||
constructor(private readonly db: DatabaseService) {}
|
||||
|
||||
listInvites() {
|
||||
return this.db.all(`
|
||||
SELECT i.*, u.username as created_by_name, t.title as trip_title
|
||||
FROM invite_tokens i
|
||||
JOIN users u ON i.created_by = u.id
|
||||
LEFT JOIN trips t ON i.trip_id = t.id
|
||||
ORDER BY i.created_at DESC
|
||||
`);
|
||||
}
|
||||
|
||||
/** Trips an admin can bind an invite to — id + title only, for the picker (#1402). */
|
||||
listTripsForInvite() {
|
||||
return this.db.all('SELECT id, title FROM trips ORDER BY title COLLATE NOCASE ASC');
|
||||
}
|
||||
|
||||
createInvite(
|
||||
createdBy: number,
|
||||
data: { max_uses?: string | number; expires_in_days?: string | number; trip_id?: string | number | null },
|
||||
) {
|
||||
const rawUses = parseInt(String(data.max_uses));
|
||||
const uses = rawUses === 0 ? 0 : Math.min(Math.max(rawUses || 1, 1), 5);
|
||||
const token = crypto.randomBytes(16).toString('hex');
|
||||
const expiresAt = data.expires_in_days
|
||||
? new Date(Date.now() + parseInt(String(data.expires_in_days)) * 86400000).toISOString()
|
||||
: null;
|
||||
|
||||
// Optional trip binding: only persist a trip that actually exists, so a stale
|
||||
// or forged id can never bind (and never auto-adds anyone on registration).
|
||||
let tripId: number | null = null;
|
||||
if (data.trip_id != null && String(data.trip_id).trim() !== '') {
|
||||
const parsed = parseInt(String(data.trip_id));
|
||||
if (!Number.isInteger(parsed) || !this.db.get('SELECT id FROM trips WHERE id = ?', parsed)) {
|
||||
// Used to bind null silently, handing back a plain registration invite
|
||||
// the admin never asked for.
|
||||
return { error: 'Trip not found', status: 404 };
|
||||
}
|
||||
tripId = parsed;
|
||||
}
|
||||
|
||||
const ins = this.db.run(
|
||||
'INSERT INTO invite_tokens (token, max_uses, expires_at, created_by, trip_id) VALUES (?, ?, ?, ?, ?)',
|
||||
token, uses, expiresAt, createdBy, tripId,
|
||||
);
|
||||
|
||||
const inviteId = Number(ins.lastInsertRowid);
|
||||
const invite = this.db.get(`
|
||||
SELECT i.*, u.username as created_by_name, t.title as trip_title
|
||||
FROM invite_tokens i
|
||||
JOIN users u ON i.created_by = u.id
|
||||
LEFT JOIN trips t ON i.trip_id = t.id
|
||||
WHERE i.id = ?
|
||||
`, inviteId);
|
||||
|
||||
return { invite, inviteId, uses, expiresInDays: data.expires_in_days ?? null, tripId };
|
||||
}
|
||||
|
||||
deleteInvite(id: string) {
|
||||
const invite = this.db.get('SELECT id FROM invite_tokens WHERE id = ?', id);
|
||||
if (!invite) return { error: 'Invite not found', status: 404 };
|
||||
this.db.run('DELETE FROM invite_tokens WHERE id = ?', id);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user