feat(portal): replace magic-link with email/password + admin-initiated activation
The client portal no longer uses passwordless / magic-link sign-in. Each
client now has a `portal_users` row with a scrypt-hashed password,
created by an admin from the client detail page; the admin's invite
mails an activation link that the client uses to set their own password.
Forgot-password is wired through the same token mechanism.
Schema (migration `0009_outgoing_rumiko_fujikawa.sql`):
- `portal_users` — one per client account, separate from the CRM
`users` table (better-auth) so the auth realms stay isolated. Email
is globally unique, password is null until activation.
- `portal_auth_tokens` — single-use activation / reset tokens. Stores
only the SHA-256 hash so a DB compromise never leaks live tokens.
Services:
- `src/lib/portal/passwords.ts` — scrypt hash/verify (no new deps;
uses node:crypto), token mint+hash helpers.
- `src/lib/services/portal-auth.service.ts` — createPortalUser,
resendActivation, activateAccount, signIn (timing-safe),
requestPasswordReset, resetPassword. Auth failures throw the new
UnauthorizedError (401); enumeration-safe behaviour everywhere.
Routes:
- POST /api/portal/auth/sign-in — sets the existing portal JWT cookie.
- POST /api/portal/auth/forgot-password — always 200.
- POST /api/portal/auth/reset-password — token + new password.
- POST /api/portal/auth/activate — token + initial password.
- POST /api/v1/clients/:id/portal-user — admin invite (and `?action=resend`).
- Removed: /api/portal/auth/request, /api/portal/auth/verify (magic link).
UI:
- /portal/login — replaced email-only magic-link form with email +
password + "forgot password" link.
- /portal/forgot-password, /portal/reset-password, /portal/activate — new.
- New shared `PasswordSetForm` component used by activate + reset.
- New `PortalInviteButton` rendered on the client detail header.
Email send:
- `createTransporter` now wires SMTP auth when SMTP_USER+SMTP_PASS are
set (gmail app-password or marina-server creds, configured via env).
- `SMTP_FROM` env var lets the sender address be overridden without
pinning it to `noreply@${SMTP_HOST}`.
Tests:
- Smoke spec 17 (client-portal) updated to the new flow: 7/7 green.
- Smoke specs 02-crud-spine, 05-invoices, 20-critical-path updated to
match the post-refactor client + invoice forms (drop companyName,
use OwnerPicker + billingEmail).
- Vitest 652/652 still green; type-check clean.
Drops the dead `requestMagicLink` from portal.service.ts.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import { and, eq, count, inArray, isNull, desc } from 'drizzle-orm';
|
||||
|
||||
import { db } from '@/lib/db';
|
||||
import { clients, clientContacts } from '@/lib/db/schema/clients';
|
||||
import { clients } from '@/lib/db/schema/clients';
|
||||
import { interests } from '@/lib/db/schema/interests';
|
||||
import { documents, files } from '@/lib/db/schema/documents';
|
||||
import { invoices } from '@/lib/db/schema/financial';
|
||||
@@ -10,95 +10,7 @@ import { ports } from '@/lib/db/schema/ports';
|
||||
import { yachts } from '@/lib/db/schema/yachts';
|
||||
import { companies, companyMemberships } from '@/lib/db/schema/companies';
|
||||
import { berthReservations } from '@/lib/db/schema/reservations';
|
||||
import { createPortalToken } from '@/lib/portal/auth';
|
||||
import { sendEmail } from '@/lib/email';
|
||||
import { getPresignedUrl } from '@/lib/minio';
|
||||
import { env } from '@/lib/env';
|
||||
import { logger } from '@/lib/logger';
|
||||
|
||||
// ─── Magic Link ────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Requests a magic link for portal access.
|
||||
* Always returns success — never reveals whether an email exists in the system.
|
||||
*/
|
||||
export async function requestMagicLink(email: string): Promise<void> {
|
||||
const normalizedEmail = email.toLowerCase().trim();
|
||||
|
||||
// Find client contact with matching email
|
||||
const contact = await db.query.clientContacts.findFirst({
|
||||
where: and(eq(clientContacts.channel, 'email'), eq(clientContacts.value, normalizedEmail)),
|
||||
with: {
|
||||
client: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!contact || !contact.client) {
|
||||
// Don't reveal that the email doesn't exist — silently return
|
||||
logger.debug({ email: normalizedEmail }, 'Portal magic link: no matching client contact');
|
||||
return;
|
||||
}
|
||||
|
||||
const client = contact.client;
|
||||
|
||||
// Build the JWT
|
||||
const token = await createPortalToken({
|
||||
clientId: client.id,
|
||||
portId: client.portId,
|
||||
email: normalizedEmail,
|
||||
});
|
||||
|
||||
const magicLinkUrl = `${env.APP_URL}/verify?token=${encodeURIComponent(token)}`;
|
||||
|
||||
// Fetch port name for the email
|
||||
const port = await db.query.ports.findFirst({
|
||||
where: eq(ports.id, client.portId),
|
||||
});
|
||||
|
||||
const portName = port?.name ?? 'Port Nimara';
|
||||
const clientName = client.fullName;
|
||||
|
||||
const html = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
</head>
|
||||
<body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #f5f5f5; padding: 40px 0; margin: 0;">
|
||||
<div style="max-width: 480px; margin: 0 auto; background: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.08);">
|
||||
<div style="background: #1e2844; padding: 32px 40px; text-align: center;">
|
||||
<h1 style="color: #ffffff; margin: 0; font-size: 22px; font-weight: 600;">${portName}</h1>
|
||||
<p style="color: #9ca3af; margin: 6px 0 0; font-size: 14px;">Client Portal</p>
|
||||
</div>
|
||||
<div style="padding: 40px;">
|
||||
<p style="color: #374151; font-size: 16px; margin: 0 0 8px;">Hello, ${clientName}</p>
|
||||
<p style="color: #6b7280; font-size: 15px; margin: 0 0 32px; line-height: 1.6;">
|
||||
You requested access to your client portal. Click the button below to sign in. This link expires in 24 hours.
|
||||
</p>
|
||||
<div style="text-align: center; margin: 0 0 32px;">
|
||||
<a href="${magicLinkUrl}" style="display: inline-block; background: #1e2844; color: #ffffff; text-decoration: none; padding: 14px 32px; border-radius: 6px; font-size: 15px; font-weight: 500;">
|
||||
Access My Portal
|
||||
</a>
|
||||
</div>
|
||||
<p style="color: #9ca3af; font-size: 13px; margin: 0; line-height: 1.6;">
|
||||
If you didn't request this, you can safely ignore this email. If you're having trouble with the button above, copy and paste this URL into your browser:
|
||||
<br><br>
|
||||
<span style="color: #6b7280; word-break: break-all;">${magicLinkUrl}</span>
|
||||
</p>
|
||||
</div>
|
||||
<div style="background: #f9fafb; padding: 20px 40px; text-align: center; border-top: 1px solid #e5e7eb;">
|
||||
<p style="color: #9ca3af; font-size: 12px; margin: 0;">© ${new Date().getFullYear()} ${portName}. All rights reserved.</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
|
||||
await sendEmail(normalizedEmail, `Your ${portName} portal access link`, html);
|
||||
|
||||
logger.info({ clientId: client.id, portId: client.portId }, 'Portal magic link sent');
|
||||
}
|
||||
|
||||
// ─── Dashboard ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
Reference in New Issue
Block a user