mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 17:46:06 +00:00
feat(invitations): guide invited users without an account through sign-up
Clicking an invitation link while signed out dropped the visitor on a bare login form, even though most invitees have no account yet and nothing on screen told them to create one. Signed-out visitors now get the invitation itself: who invited them, which workspace/project, which role, and which address it was sent to. The primary call to action follows whether an account already exists for that address — "Create your account" when it does not, "Sign in to accept" when it does. The sign-up path carries the invitation forward, so a new account lands back on the invitation and from there on the shared workspace/project instead of the onboarding wizard: - the register link passes invitationToken, the invited email and a callbackUrl - the register form locks the email to the invited address and shows what is being joined - the verification email round-trips the destination through a sanitized `next` parameter - login and verify-email keep the pending destination in their sign-in links Signing in with a different address than the one invited now explains the mismatch instead of silently redirecting to the dashboard. Callback sanitization moves to lib/safe-redirect.ts so login, register, verify-email and the verification route share one open-redirect guard.
This commit is contained in:
@@ -9,17 +9,21 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com
|
|||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Label } from '@/components/ui/label';
|
import { Label } from '@/components/ui/label';
|
||||||
import { signIn } from 'next-auth/react';
|
import { signIn } from 'next-auth/react';
|
||||||
|
import { getSafeCallbackUrl, isInvitationCallbackUrl } from '@/lib/safe-redirect';
|
||||||
|
|
||||||
function getSafeCallbackUrl(value: string | null): string {
|
/**
|
||||||
if (!value) return '/dashboard';
|
* Sign-up link that carries the pending destination — and, when that destination is an
|
||||||
try {
|
* invitation, the invitation token itself so the new account is bound to the invite.
|
||||||
const baseOrigin = typeof window === 'undefined' ? 'http://localhost' : window.location.origin;
|
*/
|
||||||
const parsed = new URL(value, baseOrigin);
|
function buildRegisterHref(callbackUrl: string): string {
|
||||||
if (parsed.origin !== baseOrigin) return '/dashboard';
|
if (callbackUrl === '/dashboard') return '/register';
|
||||||
return `${parsed.pathname}${parsed.search}${parsed.hash}`;
|
|
||||||
} catch {
|
const params = new URLSearchParams({ callbackUrl });
|
||||||
return '/dashboard';
|
if (isInvitationCallbackUrl(callbackUrl)) {
|
||||||
|
const token = new URLSearchParams(callbackUrl.split('?')[1] ?? '').get('token');
|
||||||
|
if (token) params.set('invitationToken', token);
|
||||||
}
|
}
|
||||||
|
return `/register?${params.toString()}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ERROR_MESSAGES: Record<string, string> = {
|
const ERROR_MESSAGES: Record<string, string> = {
|
||||||
@@ -50,6 +54,8 @@ function LoginFormInner({ googleEnabled, githubEnabled }: LoginFormInnerProps) {
|
|||||||
const [showSuccess, setShowSuccess] = useState(false);
|
const [showSuccess, setShowSuccess] = useState(false);
|
||||||
const [showVerifiedSuccess, setShowVerifiedSuccess] = useState(false);
|
const [showVerifiedSuccess, setShowVerifiedSuccess] = useState(false);
|
||||||
const callbackUrl = getSafeCallbackUrl(searchParams.get('callbackUrl'));
|
const callbackUrl = getSafeCallbackUrl(searchParams.get('callbackUrl'));
|
||||||
|
const isInvitationFlow = isInvitationCallbackUrl(callbackUrl);
|
||||||
|
const registerHref = buildRegisterHref(callbackUrl);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (searchParams.get('registered') === 'true') {
|
if (searchParams.get('registered') === 'true') {
|
||||||
@@ -105,7 +111,11 @@ function LoginFormInner({ googleEnabled, githubEnabled }: LoginFormInnerProps) {
|
|||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="text-center">
|
<CardHeader className="text-center">
|
||||||
<CardTitle>Welcome back</CardTitle>
|
<CardTitle>Welcome back</CardTitle>
|
||||||
<CardDescription>Sign in to your account to continue</CardDescription>
|
<CardDescription>
|
||||||
|
{isInvitationFlow
|
||||||
|
? 'Sign in to accept your invitation'
|
||||||
|
: 'Sign in to your account to continue'}
|
||||||
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
{showSuccess && (
|
{showSuccess && (
|
||||||
@@ -242,7 +252,7 @@ function LoginFormInner({ googleEnabled, githubEnabled }: LoginFormInnerProps) {
|
|||||||
|
|
||||||
<p className="text-center text-sm text-muted-foreground mt-6">
|
<p className="text-center text-sm text-muted-foreground mt-6">
|
||||||
Don't have an account?{' '}
|
Don't have an account?{' '}
|
||||||
<Link href="/register" className="text-primary hover:underline">
|
<Link href={registerHref} className="text-primary hover:underline">
|
||||||
Sign up
|
Sign up
|
||||||
</Link>
|
</Link>
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -1,15 +1,34 @@
|
|||||||
import { isInviteCodeRequired } from '@/lib/feature-flags';
|
import { isInviteCodeRequired } from '@/lib/feature-flags';
|
||||||
|
import { getInvitationPreviewByToken } from '@/lib/invitations';
|
||||||
import RegisterPageClient from './register-page-client';
|
import RegisterPageClient from './register-page-client';
|
||||||
|
|
||||||
export default function RegisterPage() {
|
interface RegisterPageProps {
|
||||||
|
searchParams: Promise<{ invitationToken?: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function RegisterPage({ searchParams }: RegisterPageProps) {
|
||||||
const googleEnabled = Boolean(process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET);
|
const googleEnabled = Boolean(process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET);
|
||||||
const githubEnabled = Boolean(process.env.GITHUB_CLIENT_ID && process.env.GITHUB_CLIENT_SECRET);
|
const githubEnabled = Boolean(process.env.GITHUB_CLIENT_ID && process.env.GITHUB_CLIENT_SECRET);
|
||||||
|
|
||||||
|
const token = (await searchParams)?.invitationToken?.trim();
|
||||||
|
const preview = token ? await getInvitationPreviewByToken(token) : null;
|
||||||
|
const invitation =
|
||||||
|
preview && preview.status === 'PENDING' && !preview.isExpired
|
||||||
|
? {
|
||||||
|
email: preview.email,
|
||||||
|
inviterName: preview.inviterName,
|
||||||
|
roleLabel: preview.roleLabel,
|
||||||
|
scopeLabel: preview.scopeLabel,
|
||||||
|
targetName: preview.targetName,
|
||||||
|
}
|
||||||
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<RegisterPageClient
|
<RegisterPageClient
|
||||||
requireInviteCode={isInviteCodeRequired()}
|
requireInviteCode={isInviteCodeRequired()}
|
||||||
googleEnabled={googleEnabled}
|
googleEnabled={googleEnabled}
|
||||||
githubEnabled={githubEnabled}
|
githubEnabled={githubEnabled}
|
||||||
|
invitation={invitation}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,24 +9,49 @@ import { Button } from '@/components/ui/button';
|
|||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Label } from '@/components/ui/label';
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { getSafeCallbackUrl } from '@/lib/safe-redirect';
|
||||||
|
|
||||||
|
export interface RegisterInvitation {
|
||||||
|
email: string;
|
||||||
|
inviterName: string;
|
||||||
|
roleLabel: string;
|
||||||
|
scopeLabel: string;
|
||||||
|
targetName: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
interface RegisterPageClientProps {
|
interface RegisterPageClientProps {
|
||||||
requireInviteCode: boolean;
|
requireInviteCode: boolean;
|
||||||
googleEnabled: boolean;
|
googleEnabled: boolean;
|
||||||
githubEnabled: boolean;
|
githubEnabled: boolean;
|
||||||
|
invitation?: RegisterInvitation | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function RegisterPageClient({
|
export default function RegisterPageClient({
|
||||||
requireInviteCode,
|
requireInviteCode,
|
||||||
googleEnabled,
|
googleEnabled,
|
||||||
githubEnabled,
|
githubEnabled,
|
||||||
|
invitation = null,
|
||||||
}: RegisterPageClientProps) {
|
}: RegisterPageClientProps) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const invitationToken = useMemo(() => searchParams.get('invitationToken') || '', [searchParams]);
|
const invitationToken = useMemo(() => searchParams.get('invitationToken') || '', [searchParams]);
|
||||||
const invitedEmail = useMemo(() => searchParams.get('email') || '', [searchParams]);
|
const invitedEmail = useMemo(
|
||||||
|
() => invitation?.email || searchParams.get('email') || '',
|
||||||
|
[invitation, searchParams]
|
||||||
|
);
|
||||||
|
// Where to send the user once they are signed in — for invitations this points back
|
||||||
|
// at /invitations/accept so they land on the workspace/project they were invited to
|
||||||
|
// instead of the onboarding wizard.
|
||||||
|
const callbackUrl = useMemo(
|
||||||
|
() => getSafeCallbackUrl(searchParams.get('callbackUrl')),
|
||||||
|
[searchParams]
|
||||||
|
);
|
||||||
const isInvitationFlow = invitationToken.length > 0;
|
const isInvitationFlow = invitationToken.length > 0;
|
||||||
const shouldShowInviteCode = requireInviteCode && !isInvitationFlow;
|
const shouldShowInviteCode = requireInviteCode && !isInvitationFlow;
|
||||||
|
const loginHref =
|
||||||
|
callbackUrl === '/dashboard'
|
||||||
|
? '/login'
|
||||||
|
: `/login?callbackUrl=${encodeURIComponent(callbackUrl)}`;
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [oauthLoading, setOauthLoading] = useState<string | null>(null);
|
const [oauthLoading, setOauthLoading] = useState<string | null>(null);
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
@@ -91,10 +116,11 @@ export default function RegisterPageClient({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const callbackParam = `&callbackUrl=${encodeURIComponent(callbackUrl)}`;
|
||||||
if (data.data?.emailVerificationRequired) {
|
if (data.data?.emailVerificationRequired) {
|
||||||
router.push(`/verify-email?email=${encodeURIComponent(formData.email)}`);
|
router.push(`/verify-email?email=${encodeURIComponent(formData.email)}${callbackParam}`);
|
||||||
} else {
|
} else {
|
||||||
router.push('/login?registered=true');
|
router.push(`/login?registered=true${callbackParam}`);
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
setError('Something went wrong. Please try again.');
|
setError('Something went wrong. Please try again.');
|
||||||
@@ -106,7 +132,7 @@ export default function RegisterPageClient({
|
|||||||
const handleOAuthSignUp = async (provider: string) => {
|
const handleOAuthSignUp = async (provider: string) => {
|
||||||
setOauthLoading(provider);
|
setOauthLoading(provider);
|
||||||
setError('');
|
setError('');
|
||||||
await signIn(provider, { callbackUrl: '/dashboard' });
|
await signIn(provider, { callbackUrl });
|
||||||
};
|
};
|
||||||
|
|
||||||
const hasOAuth = googleEnabled || githubEnabled;
|
const hasOAuth = googleEnabled || githubEnabled;
|
||||||
@@ -204,9 +230,24 @@ export default function RegisterPageClient({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
<form onSubmit={handleRegister} className="space-y-4">
|
<form onSubmit={handleRegister} className="space-y-4">
|
||||||
{isInvitationFlow ? (
|
{isInvitationFlow && invitation ? (
|
||||||
<div className="p-3 rounded-md bg-primary/10 text-sm">
|
<div className="p-3 rounded-md bg-primary/10 text-sm space-y-1">
|
||||||
You are registering via an invitation link.
|
<p>
|
||||||
|
{invitation.inviterName} invited you to{' '}
|
||||||
|
<strong>
|
||||||
|
{invitation.targetName
|
||||||
|
? `${invitation.targetName} (${invitation.scopeLabel})`
|
||||||
|
: `a ${invitation.scopeLabel}`}
|
||||||
|
</strong>{' '}
|
||||||
|
as {invitation.roleLabel}.
|
||||||
|
</p>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
Create your account below — you'll be taken straight to it.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : isInvitationFlow ? (
|
||||||
|
<div className="p-3 rounded-md bg-amber-500/10 text-sm">
|
||||||
|
This invitation link is no longer valid. Ask whoever invited you for a new one.
|
||||||
</div>
|
</div>
|
||||||
) : shouldShowInviteCode ? (
|
) : shouldShowInviteCode ? (
|
||||||
<>
|
<>
|
||||||
@@ -261,7 +302,14 @@ export default function RegisterPageClient({
|
|||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
required
|
required
|
||||||
disabled={isLoading}
|
disabled={isLoading}
|
||||||
|
readOnly={Boolean(invitation)}
|
||||||
|
className={invitation ? 'bg-muted text-muted-foreground' : undefined}
|
||||||
/>
|
/>
|
||||||
|
{invitation && (
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
The invitation is tied to this address.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
@@ -307,7 +355,7 @@ export default function RegisterPageClient({
|
|||||||
|
|
||||||
<p className="text-center text-sm text-muted-foreground mt-6">
|
<p className="text-center text-sm text-muted-foreground mt-6">
|
||||||
Already have an account?{' '}
|
Already have an account?{' '}
|
||||||
<Link href="/login" className="text-primary hover:underline">
|
<Link href={loginHref} className="text-primary hover:underline">
|
||||||
Sign in
|
Sign in
|
||||||
</Link>
|
</Link>
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -8,10 +8,16 @@ import { Video, Mail, Loader2 } from 'lucide-react';
|
|||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { getSafeCallbackUrl } from '@/lib/safe-redirect';
|
||||||
|
|
||||||
function VerifyEmailContent() {
|
function VerifyEmailContent() {
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const emailParam = searchParams.get('email') || '';
|
const emailParam = searchParams.get('email') || '';
|
||||||
|
const callbackUrl = getSafeCallbackUrl(searchParams.get('callbackUrl'));
|
||||||
|
const loginHref =
|
||||||
|
callbackUrl === '/dashboard'
|
||||||
|
? '/login'
|
||||||
|
: `/login?callbackUrl=${encodeURIComponent(callbackUrl)}`;
|
||||||
const [resendEmail, setResendEmail] = useState(emailParam);
|
const [resendEmail, setResendEmail] = useState(emailParam);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [sent, setSent] = useState(false);
|
const [sent, setSent] = useState(false);
|
||||||
@@ -107,7 +113,7 @@ function VerifyEmailContent() {
|
|||||||
|
|
||||||
<p className="text-center text-sm text-muted-foreground">
|
<p className="text-center text-sm text-muted-foreground">
|
||||||
Already verified?{' '}
|
Already verified?{' '}
|
||||||
<Link href="/login" className="text-primary hover:underline">
|
<Link href={loginHref} className="text-primary hover:underline">
|
||||||
Sign in
|
Sign in
|
||||||
</Link>
|
</Link>
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -135,7 +135,13 @@ export async function POST(request: NextRequest) {
|
|||||||
// Send verification email if SMTP is configured
|
// Send verification email if SMTP is configured
|
||||||
if (emailVerificationRequired) {
|
if (emailVerificationRequired) {
|
||||||
const verificationToken = await createVerificationToken(normalizedEmail);
|
const verificationToken = await createVerificationToken(normalizedEmail);
|
||||||
await sendVerificationEmail(normalizedEmail, verificationToken);
|
// Invited users are sent back to the invitation after verifying, which forwards them
|
||||||
|
// to the workspace/project they joined instead of the generic dashboard.
|
||||||
|
await sendVerificationEmail(normalizedEmail, verificationToken, {
|
||||||
|
next: validatedInvitationToken
|
||||||
|
? `/invitations/accept?token=${encodeURIComponent(validatedInvitationToken)}`
|
||||||
|
: undefined,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const message = emailVerificationRequired
|
const message = emailVerificationRequired
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { consumeVerificationToken } from '@/lib/email-verification';
|
|||||||
import { rateLimit } from '@/lib/rate-limit';
|
import { rateLimit } from '@/lib/rate-limit';
|
||||||
import { logError } from '@/lib/logger';
|
import { logError } from '@/lib/logger';
|
||||||
import { getPublicOrigin } from '@/lib/request-origin';
|
import { getPublicOrigin } from '@/lib/request-origin';
|
||||||
|
import { getSafeCallbackUrl } from '@/lib/safe-redirect';
|
||||||
|
|
||||||
// A raw 32-byte hex token is exactly 64 characters.
|
// A raw 32-byte hex token is exactly 64 characters.
|
||||||
const TOKEN_REGEX = /^[0-9a-f]{64}$/;
|
const TOKEN_REGEX = /^[0-9a-f]{64}$/;
|
||||||
@@ -31,7 +32,15 @@ export async function GET(request: NextRequest) {
|
|||||||
return redirectTo('/login?error=InvalidVerificationToken');
|
return redirectTo('/login?error=InvalidVerificationToken');
|
||||||
}
|
}
|
||||||
|
|
||||||
return redirectTo('/login?verified=true');
|
// Keep the post-verification destination (e.g. an invitation) if one was carried along.
|
||||||
|
const next = getSafeCallbackUrl(request.nextUrl.searchParams.get('next'), {
|
||||||
|
origin,
|
||||||
|
fallback: '',
|
||||||
|
});
|
||||||
|
|
||||||
|
return redirectTo(
|
||||||
|
next ? `/login?verified=true&callbackUrl=${encodeURIComponent(next)}` : '/login?verified=true'
|
||||||
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logError('Email verification error:', err);
|
logError('Email verification error:', err);
|
||||||
return redirectTo('/login?error=VerificationFailed');
|
return redirectTo('/login?error=VerificationFailed');
|
||||||
|
|||||||
@@ -0,0 +1,190 @@
|
|||||||
|
import Link from 'next/link';
|
||||||
|
import { Video, UserPlus, LogIn, MailWarning } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
|
import type { InvitationPreview } from '@/lib/invitations';
|
||||||
|
|
||||||
|
interface InvitationLandingProps {
|
||||||
|
token: string;
|
||||||
|
preview: InvitationPreview | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Shell({ children }: { children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center p-4 bg-background">
|
||||||
|
<div className="w-full max-w-md">
|
||||||
|
<Link href="/" className="flex items-center justify-center gap-2 mb-8">
|
||||||
|
<Video className="h-8 w-8 text-primary" />
|
||||||
|
<span className="font-bold text-2xl">OpenFrame</span>
|
||||||
|
</Link>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function UnusableInvitation({ title, message }: { title: string; message: string }) {
|
||||||
|
return (
|
||||||
|
<Shell>
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="text-center">
|
||||||
|
<CardTitle className="flex items-center justify-center gap-2">
|
||||||
|
<MailWarning className="h-5 w-5 text-amber-500" />
|
||||||
|
{title}
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription>{message}</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-3">
|
||||||
|
<Button asChild className="w-full">
|
||||||
|
<Link href="/login">Sign in</Link>
|
||||||
|
</Button>
|
||||||
|
<p className="text-center text-sm text-muted-foreground">
|
||||||
|
Ask whoever invited you to send a new invitation link.
|
||||||
|
</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</Shell>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Signed in, but with an account whose address the invitation was not issued to. */
|
||||||
|
export function InvitationAccountMismatch({
|
||||||
|
invitedEmail,
|
||||||
|
signedInEmail,
|
||||||
|
}: {
|
||||||
|
invitedEmail: string;
|
||||||
|
signedInEmail: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<Shell>
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="text-center">
|
||||||
|
<CardTitle className="flex items-center justify-center gap-2">
|
||||||
|
<MailWarning className="h-5 w-5 text-amber-500" />
|
||||||
|
Wrong account
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
This invitation was sent to <strong>{invitedEmail}</strong>, but you are signed in as{' '}
|
||||||
|
<strong>{signedInEmail}</strong>.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-3">
|
||||||
|
<Button asChild className="w-full">
|
||||||
|
<Link href="/signout">Sign out and switch account</Link>
|
||||||
|
</Button>
|
||||||
|
<Button asChild variant="outline" className="w-full">
|
||||||
|
<Link href="/dashboard">Back to dashboard</Link>
|
||||||
|
</Button>
|
||||||
|
<p className="text-center text-sm text-muted-foreground">
|
||||||
|
After signing out, open the invitation link from your email again.
|
||||||
|
</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</Shell>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function InvitationLanding({ token, preview }: InvitationLandingProps) {
|
||||||
|
const acceptPath = `/invitations/accept?token=${encodeURIComponent(token)}`;
|
||||||
|
const loginHref = `/login?callbackUrl=${encodeURIComponent(acceptPath)}`;
|
||||||
|
|
||||||
|
if (!preview) {
|
||||||
|
return (
|
||||||
|
<UnusableInvitation
|
||||||
|
title="Invitation not found"
|
||||||
|
message="This invitation link is invalid. It may have been revoked or replaced by a newer one."
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (preview.status === 'CANCELED') {
|
||||||
|
return (
|
||||||
|
<UnusableInvitation
|
||||||
|
title="Invitation revoked"
|
||||||
|
message="This invitation is no longer valid."
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (preview.status === 'EXPIRED' || preview.isExpired) {
|
||||||
|
return (
|
||||||
|
<UnusableInvitation
|
||||||
|
title="Invitation expired"
|
||||||
|
message={`The invitation sent to ${preview.email} has expired.`}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const registerHref =
|
||||||
|
`/register?invitationToken=${encodeURIComponent(token)}` +
|
||||||
|
`&email=${encodeURIComponent(preview.email)}` +
|
||||||
|
`&callbackUrl=${encodeURIComponent(acceptPath)}`;
|
||||||
|
|
||||||
|
const alreadyAccepted = preview.status === 'ACCEPTED';
|
||||||
|
const targetLabel = preview.targetName
|
||||||
|
? `${preview.targetName} (${preview.scopeLabel})`
|
||||||
|
: `a ${preview.scopeLabel}`;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Shell>
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="text-center">
|
||||||
|
<CardTitle>You've been invited</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
{preview.inviterName} invited you to join <strong>{targetLabel}</strong> on OpenFrame as{' '}
|
||||||
|
{preview.roleLabel}.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<div className="rounded-md border bg-muted/40 p-3 text-sm">
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
This invitation was sent to{' '}
|
||||||
|
<strong className="text-foreground">{preview.email}</strong>.{' '}
|
||||||
|
{preview.hasAccount || alreadyAccepted ? 'Sign in with' : 'Use'} that address to
|
||||||
|
accept it.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{preview.hasAccount || alreadyAccepted ? (
|
||||||
|
<>
|
||||||
|
<Button asChild className="w-full">
|
||||||
|
<Link href={loginHref}>
|
||||||
|
<LogIn className="h-4 w-4 mr-2" />
|
||||||
|
Sign in to accept
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
{!alreadyAccepted && (
|
||||||
|
<p className="text-center text-sm text-muted-foreground">
|
||||||
|
Wrong address?{' '}
|
||||||
|
<Link href={registerHref} className="text-primary hover:underline">
|
||||||
|
Create an account instead
|
||||||
|
</Link>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
You don't have an OpenFrame account yet. Create one to open this{' '}
|
||||||
|
{preview.scopeLabel} — we'll bring you right back here once you're signed
|
||||||
|
in.
|
||||||
|
</p>
|
||||||
|
<Button asChild className="w-full">
|
||||||
|
<Link href={registerHref}>
|
||||||
|
<UserPlus className="h-4 w-4 mr-2" />
|
||||||
|
Create your account
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
<p className="text-center text-sm text-muted-foreground">
|
||||||
|
Already have an account?{' '}
|
||||||
|
<Link href={loginHref} className="text-primary hover:underline">
|
||||||
|
Sign in
|
||||||
|
</Link>
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</Shell>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
import { redirect } from 'next/navigation';
|
import { redirect } from 'next/navigation';
|
||||||
import { auth } from '@/lib/auth';
|
import { auth } from '@/lib/auth';
|
||||||
import { db } from '@/lib/db';
|
import { db } from '@/lib/db';
|
||||||
import { acceptInvitationTokenForUser } from '@/lib/invitations';
|
import { acceptInvitationTokenForUser, getInvitationPreviewByToken } from '@/lib/invitations';
|
||||||
|
import { InvitationAccountMismatch, InvitationLanding } from './invitation-landing';
|
||||||
|
|
||||||
interface InvitationAcceptPageProps {
|
interface InvitationAcceptPageProps {
|
||||||
searchParams: Promise<{
|
searchParams: Promise<{
|
||||||
@@ -19,14 +20,17 @@ export default async function InvitationAcceptPage({ searchParams }: InvitationA
|
|||||||
|
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
if (!session?.user?.id) {
|
if (!session?.user?.id) {
|
||||||
const callbackUrl = `/invitations/accept?token=${encodeURIComponent(token)}`;
|
// Signed-out visitors get the invitation itself instead of a bare login form:
|
||||||
redirect(`/login?callbackUrl=${encodeURIComponent(callbackUrl)}`);
|
// most of them have no account yet and need to be told to create one.
|
||||||
|
const preview = await getInvitationPreviewByToken(token);
|
||||||
|
return <InvitationLanding token={token} preview={preview} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
const invitation = await db.invitation.findUnique({
|
const invitation = await db.invitation.findUnique({
|
||||||
where: { token },
|
where: { token },
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
|
email: true,
|
||||||
status: true,
|
status: true,
|
||||||
scope: true,
|
scope: true,
|
||||||
workspaceId: true,
|
workspaceId: true,
|
||||||
@@ -63,7 +67,14 @@ export default async function InvitationAcceptPage({ searchParams }: InvitationA
|
|||||||
redirect('/dashboard?invite=expired');
|
redirect('/dashboard?invite=expired');
|
||||||
}
|
}
|
||||||
if (result === 'forbidden') {
|
if (result === 'forbidden') {
|
||||||
redirect('/dashboard?invite=wrong_account');
|
// Signed in with a different address than the one invited — say so instead of
|
||||||
|
// dropping the user on the dashboard with no explanation.
|
||||||
|
return (
|
||||||
|
<InvitationAccountMismatch
|
||||||
|
invitedEmail={invitation?.email ?? 'another address'}
|
||||||
|
signedInEmail={userEmail}
|
||||||
|
/>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (result === 'not_found' && invitation?.status === 'ACCEPTED') {
|
if (result === 'not_found' && invitation?.status === 'ACCEPTED') {
|
||||||
|
|||||||
@@ -94,7 +94,11 @@ function createTransport() {
|
|||||||
return nodemailer.createTransport({ host, port, secure: port === 465, auth: { user, pass } });
|
return nodemailer.createTransport({ host, port, secure: port === 465, auth: { user, pass } });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function sendVerificationEmail(email: string, token: string): Promise<void> {
|
export async function sendVerificationEmail(
|
||||||
|
email: string,
|
||||||
|
token: string,
|
||||||
|
options?: { next?: string }
|
||||||
|
): Promise<void> {
|
||||||
const transporter = createTransport();
|
const transporter = createTransport();
|
||||||
if (!transporter) return;
|
if (!transporter) return;
|
||||||
|
|
||||||
@@ -109,7 +113,10 @@ export async function sendVerificationEmail(email: string, token: string): Promi
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const verifyUrl = `${baseUrl}/api/auth/verify-email?token=${encodeURIComponent(token)}`;
|
// `next` survives the round-trip so an invited user lands back on the invitation
|
||||||
|
// (and from there on the shared project) instead of a generic login page.
|
||||||
|
const nextParam = options?.next ? `&next=${encodeURIComponent(options.next)}` : '';
|
||||||
|
const verifyUrl = `${baseUrl}/api/auth/verify-email?token=${encodeURIComponent(token)}${nextParam}`;
|
||||||
const from = process.env.SMTP_FROM || process.env.EMAIL_FROM || 'OpenFrame <[email protected]>';
|
const from = process.env.SMTP_FROM || process.env.EMAIL_FROM || 'OpenFrame <[email protected]>';
|
||||||
|
|
||||||
const html = brandedEmailTemplate(
|
const html = brandedEmailTemplate(
|
||||||
|
|||||||
@@ -221,6 +221,64 @@ export async function createOrRefreshInvitation(params: {
|
|||||||
throw new Error('Failed to create invitation after retrying');
|
throw new Error('Failed to create invitation after retrying');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface InvitationPreview {
|
||||||
|
email: string;
|
||||||
|
role: InvitationRole;
|
||||||
|
roleLabel: string;
|
||||||
|
scope: InvitationScope;
|
||||||
|
scopeLabel: string;
|
||||||
|
status: InvitationStatus;
|
||||||
|
/** PENDING but past its expiry — the DB row is only flipped to EXPIRED on acceptance. */
|
||||||
|
isExpired: boolean;
|
||||||
|
inviterName: string;
|
||||||
|
targetName: string | null;
|
||||||
|
/** Whether an account already exists for the invited address. */
|
||||||
|
hasAccount: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Public-facing summary of an invitation, safe to render to a signed-out visitor:
|
||||||
|
* the token itself is the secret, and everything here was already in the email we sent
|
||||||
|
* to that address.
|
||||||
|
*/
|
||||||
|
export async function getInvitationPreviewByToken(
|
||||||
|
token: string
|
||||||
|
): Promise<InvitationPreview | null> {
|
||||||
|
const invitation = await db.invitation.findUnique({
|
||||||
|
where: { token },
|
||||||
|
select: {
|
||||||
|
email: true,
|
||||||
|
role: true,
|
||||||
|
scope: true,
|
||||||
|
status: true,
|
||||||
|
expiresAt: true,
|
||||||
|
invitedBy: { select: { name: true } },
|
||||||
|
workspace: { select: { name: true } },
|
||||||
|
project: { select: { name: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!invitation) return null;
|
||||||
|
|
||||||
|
const existingUser = await db.user.findUnique({
|
||||||
|
where: { email: invitation.email },
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
email: invitation.email,
|
||||||
|
role: invitation.role,
|
||||||
|
roleLabel: roleLabel(invitation.role),
|
||||||
|
scope: invitation.scope,
|
||||||
|
scopeLabel: scopeLabel(invitation.scope),
|
||||||
|
status: invitation.status,
|
||||||
|
isExpired: invitation.expiresAt <= new Date(),
|
||||||
|
inviterName: invitation.invitedBy?.name?.trim() || 'A team member',
|
||||||
|
targetName: invitation.workspace?.name ?? invitation.project?.name ?? null,
|
||||||
|
hasAccount: Boolean(existingUser),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export async function getValidInvitationByToken(token: string) {
|
export async function getValidInvitationByToken(token: string) {
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
return db.invitation.findFirst({
|
return db.invitation.findFirst({
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
/**
|
||||||
|
* Reduce an untrusted `callbackUrl`/`next` value to a same-origin relative path.
|
||||||
|
* Anything absolute, cross-origin or unparsable falls back to `fallback`.
|
||||||
|
*
|
||||||
|
* Works on both sides: in the browser the origin defaults to `window.location.origin`
|
||||||
|
* (so next-auth's absolute `result.url` still passes), on the server pass the public origin.
|
||||||
|
*/
|
||||||
|
export function getSafeCallbackUrl(
|
||||||
|
value: string | null | undefined,
|
||||||
|
options?: { origin?: string; fallback?: string }
|
||||||
|
): string {
|
||||||
|
const fallback = options?.fallback ?? '/dashboard';
|
||||||
|
if (!value) return fallback;
|
||||||
|
|
||||||
|
const baseOrigin =
|
||||||
|
options?.origin ??
|
||||||
|
(typeof window === 'undefined' ? 'http://localhost' : window.location.origin);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const parsed = new URL(value, baseOrigin);
|
||||||
|
if (parsed.origin !== baseOrigin) return fallback;
|
||||||
|
return `${parsed.pathname}${parsed.search}${parsed.hash}`;
|
||||||
|
} catch {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True when a sanitized path points at the invitation acceptance route. */
|
||||||
|
export function isInvitationCallbackUrl(path: string): boolean {
|
||||||
|
return path.startsWith('/invitations/accept');
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user