Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

fix(mcp): unblock the OAuth consent flow for new and returning users (#15520)

moaaz9891daf5f25d
diff --git a/brain/knowledge/ai-intelligence/mcp-server.md b/brain/knowledge/ai-intelligence/mcp-server.md
index e130b21e783..d2cd7b043ee 100644
--- a/brain/knowledge/ai-intelligence/mcp-server.md
+++ b/brain/knowledge/ai-intelligence/mcp-server.md
@@ -38,6 +38,9 @@ Exposes an Activepieces project as an MCP server so AI clients (Claude Desktop,
### Gotchas
+- **The consent page (`/mcp-authorize`) must treat an `ONBOARDING` token as signed out.** `isLoggedIn()` is only a JWT-expiry check; `GET /v1/projects` answers 403 for that principal, so gating on it alone rendered an empty project select with Authorize disabled forever. It now also checks `isOnboarding()` and sends the visitor to `/sign-in?from=…`, where the drawer resumes at the name step and returns to consent.
+- **`/verify-email` cannot see the OAuth `from=`** (the link is server-generated), so both `SignUpForm` and `SignInForm` store it via `pendingRedirect` in `navigation-utils` when they show the check-your-email note, and `/verify-email` hands it back as `/sign-in?from=…`. Only matters when passwordless is off — the code flow never leaves the page.
+- **Deny goes through `POST /v1/mcp-oauth/deny`**, which verifies the `authRequestId` JWT and returns the client's redirect with `error=access_denied` (it used to be `history.back()`, a no-op in the tab the client opened, so the client never heard back). The consent page only *decodes* the JWT for display: `clientName`, the platform/project scope, and `exp` so an expired request says "go back to {client}" instead of inviting a retry. The browser clock only drives that notice, never the buttons (a clock 10 minutes fast would otherwise lock the user out of a request the server still accepts); Authorize and Deny are disabled only after the server itself answers 400 `invalid_request`. Switch account is a full page load, not a `navigate`, because the query cache would otherwise hand the previous account's projects to the next one. It also preselects a single project and names the signed-in account with a Switch account link, because a browser already signed into another workspace would otherwise authorize it silently.
- **`mcp_server.token` is dead — nothing reads it.** It is written by the `getOrCreate` defaults and by both `/rotate` routes (`mcpServerService.rotateToken` / `rotatePlatformToken`), and consulted by **no authenticator**, so "rotating" it rotates a secret that grants nothing. It is still on the public `McpServer` zod schema, so the API keeps shipping a secret-shaped 72-char string that authenticates nothing — do not reach for it as a credential, and do not tell a self-hoster to. The settings panel is consistent with reality already (`mcp-credentials.tsx` renders the URL and *"Authentication is handled via OAuth"*, never a token). Deleting the column, the two routes, and the schema field is a breaking API-response change and has not been done.
- **`mcp_oauth_token.clientKey` is decided once, at sign-in.** `exchangeCode` derives it from the registration's
redirect URIs via `mcpOAuthClientIdentity`, so the grants list can filter and group in SQL instead of loading
diff --git a/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-approve.controller.ts b/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-approve.controller.ts
index 8e9d553c940..37344130583 100644
--- a/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-approve.controller.ts
+++ b/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-approve.controller.ts
@@ -1,4 +1,4 @@
-import { isNil } from '@activepieces/core-utils'
+import { isNil, tryCatch } from '@activepieces/core-utils'
import { PlatformRole, PrincipalType } from '@activepieces/shared'
import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
import { z } from 'zod'
@@ -33,23 +33,11 @@ export const mcpOAuthApproveController: FastifyPluginAsyncZod = async (app) => {
}
}
- const key = await jwtUtils.getJwtSecret()
- let authRequest: AuthRequestPayload
- try {
- authRequest = await jwtUtils.decodeAndVerify<AuthRequestPayload>({
- jwt: authRequestId,
- key,
- audience: JwtAudience.MCP_OAUTH_AUTH_REQUEST,
- })
- }
- catch {
+ const { data: authRequest, error } = await tryCatch(() => verifyAuthRequest(authRequestId))
+ if (error) {
return reply.status(400).send({ error: 'invalid_request', error_description: 'Invalid or expired authorization request' })
}
- if (authRequest.type !== 'mcp_auth_request') {
- return reply.status(400).send({ error: 'invalid_request', error_description: 'Invalid authorization request type' })
- }
-
const code = await mcpOAuthCodeService.create({
clientId: authRequest.clientId,
userId,
@@ -71,6 +59,34 @@ export const mcpOAuthApproveController: FastifyPluginAsyncZod = async (app) => {
return reply.send({ redirectUrl: redirectUrl.toString() })
})
+
+ app.post('/v1/mcp-oauth/deny', DenyRequest, async (req, reply) => {
+ const { data: authRequest, error } = await tryCatch(() => verifyAuthRequest(req.body.authRequestId))
+ if (error) {
+ return reply.status(400).send({ error: 'invalid_request', error_description: 'Invalid or expired authorization request' })
+ }
+
+ const redirectUrl = new URL(authRequest.redirectUri)
+ redirectUrl.searchParams.set('error', 'access_denied')
+ if (authRequest.state) {
+ redirectUrl.searchParams.set('state', authRequest.state)
+ }
+
+ return reply.send({ redirectUrl: redirectUrl.toString() })
+ })
+}
+
+async function verifyAuthRequest(authRequestId: string): Promise<AuthRequestPayload> {
+ const key = await jwtUtils.getJwtSecret()
+ const authRequest = await jwtUtils.decodeAndVerify<AuthRequestPayload>({
+ jwt: authRequestId,
+ key,
+ audience: JwtAudience.MCP_OAUTH_AUTH_REQUEST,
+ })
+ if (authRequest.type !== 'mcp_auth_request') {
+ throw new Error('Invalid authorization request type')
+ }
+ return authRequest
}
const ApproveRequest = {
@@ -86,6 +102,18 @@ const ApproveRequest = {
},
}
+const DenyRequest = {
+ config: {
+ security: securityAccess.publicPlatform([PrincipalType.USER]),
+ },
+ schema: {
+ tags: ['mcp-oauth'],
+ body: z.object({
+ authRequestId: z.string(),
+ }),
+ },
+}
+
type AuthRequestPayload = {
clientId: string
redirectUri: string
diff --git a/packages/server/api/test/integration/ce/mcp/mcp-oauth-deny.test.ts b/packages/server/api/test/integration/ce/mcp/mcp-oauth-deny.test.ts
new file mode 100644
index 00000000000..1ed6972674e
--- /dev/null
+++ b/packages/server/api/test/integration/ce/mcp/mcp-oauth-deny.test.ts
@@ -0,0 +1,113 @@
+import { FastifyInstance } from 'fastify'
+import { beforeAll, describe, expect, it } from 'vitest'
+import { JwtAudience, jwtUtils } from '../../../../src/app/helper/jwt-utils'
+import { MCP_OAUTH_REDIRECT_URI, mcpOAuthTestHelpers } from '../../../helpers/mcp-oauth'
+import { createTestContext, TestContext } from '../../../helpers/test-context'
+import { setupTestEnvironment } from '../../../helpers/test-setup'
+
+let app: FastifyInstance
+let ctx: TestContext
+
+const STATE = 'client-state-123'
+
+async function startAuthorization({ state }: { state: string | null } = { state: STATE }): Promise<string> {
+ const client = await mcpOAuthTestHelpers.registerClient({ app, tokenEndpointAuthMethod: 'none' })
+ const { challenge } = mcpOAuthTestHelpers.generatePkce()
+
+ const consent = await app.inject({
+ method: 'GET',
+ url: '/authorize?' + new URLSearchParams({
+ client_id: client.client_id,
+ redirect_uri: MCP_OAUTH_REDIRECT_URI,
+ response_type: 'code',
+ code_challenge: challenge,
+ code_challenge_method: 'S256',
+ scope: 'mcp',
+ ...(state ? { state } : {}),
+ }).toString(),
+ })
+ expect(consent.statusCode).toBe(302)
+
+ return new URL(String(consent.headers.location), MCP_OAUTH_REDIRECT_URI).searchParams.get('authRequestId') ?? ''
+}
+
+async function signAuthRequest({ expiresInSeconds, type }: { expiresInSeconds: number, type: string }): Promise<string> {
+ return jwtUtils.sign({
+ payload: {
+ clientId: 'irrelevant',
+ clientName: 'Irrelevant',
+ redirectUri: MCP_OAUTH_REDIRECT_URI,
+ codeChallenge: 'x'.repeat(43),
+ codeChallengeMethod: 'S256',
+ state: STATE,
+ scopes: ['mcp'],
+ resource: null,
+ type,
+ },
+ key: await jwtUtils.getJwtSecret(),
+ expiresInSeconds,
+ audience: JwtAudience.MCP_OAUTH_AUTH_REQUEST,
+ })
+}
+
+describe('MCP OAuth deny', () => {
+ beforeAll(async () => {
+ app = await setupTestEnvironment()
+ ctx = await createTestContext(app)
+ })
+
+ it('sends the client back with access_denied and its state, and no code', async () => {
+ const authRequestId = await startAuthorization()
+
+ const denied = await ctx.post('/v1/mcp-oauth/deny', { authRequestId })
+
+ expect(denied.statusCode).toBe(200)
+ const redirect = new URL(denied.json().redirectUrl)
+ expect(redirect.origin + redirect.pathname).toBe(MCP_OAUTH_REDIRECT_URI)
+ expect(redirect.searchParams.get('error')).toBe('access_denied')
+ expect(redirect.searchParams.get('state')).toBe(STATE)
+ expect(redirect.searchParams.get('code')).toBeNull()
+ })
+
+ it('omits state when the client sent none', async () => {
+ const authRequestId = await startAuthorization({ state: null })
+
+ const denied = await ctx.post('/v1/mcp-oauth/deny', { authRequestId })
+
+ expect(denied.statusCode).toBe(200)
+ const redirect = new URL(denied.json().redirectUrl)
+ expect(redirect.searchParams.get('error')).toBe('access_denied')
+ expect(redirect.searchParams.has('state')).toBe(false)
+ })
+
+ it('refuses a tampered request', async () => {
+ const authRequestId = await startAuthorization()
+ const [header, payload, signature] = authRequestId.split('.')
+ const forged = JSON.parse(Buffer.from(payload, 'base64url').toString())
+ forged.redirectUri = 'https://attacker.example/callback'
+ const tampered = [header, Buffer.from(JSON.stringify(forged)).toString('base64url'), signature].join('.')
+
+ const denied = await ctx.post('/v1/mcp-oauth/deny', { authRequestId: tampered })
+
+ expect(denied.statusCode).toBe(400)
+ expect(denied.json().error).toBe('invalid_request')
+ })
+
+ it('refuses an expired request', async () => {
+ const authRequestId = await signAuthRequest({ expiresInSeconds: -1, type: 'mcp_auth_request' })
+
+ const denied = await ctx.post('/v1/mcp-oauth/deny', { authRequestId })
+
+ expect(denied.statusCode).toBe(400)
+ expect(denied.json().error).toBe('invalid_request')
+ })
+
+ it('refuses a signed token that is not an authorization request', async () => {
+ const authRequestId = await signAuthRequest({ expiresInSeconds: 600, type: 'something_else' })
+
+ const denied = await ctx.post('/v1/mcp-oauth/deny', { authRequestId })
+
+ expect(denied.statusCode).toBe(400)
+ expect(denied.json().error).toBe('invalid_request')
+ })
+})
diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.json
index 71bafc1268d..0a5a8d089e2 100644
--- a/packages/web/public/locales/en/translation.json
+++ b/packages/web/public/locales/en/translation.json
@@ -949,6 +949,9 @@
"Build, test, and manage automations": "Build, test, and manage automations",
"Use connections and execute flows": "Use connections and execute flows",
"Authorization failed. Please try again.": "Authorization failed. Please try again.",
+ "This request has expired. Go back to {client} and start the connection again.": "This request has expired. Go back to {client} and start the connection again.",
+ "Signed in as {email}": "Signed in as {email}",
+ "Switch account": "Switch account",
"Deny": "Deny",
"Authorize": "Authorize",
"Unknown app": "Unknown app",
diff --git a/packages/web/src/app/routes/mcp-authorize/index.tsx b/packages/web/src/app/routes/mcp-authorize/index.tsx
index 8f05217170f..b10c12f7d0c 100644
--- a/packages/web/src/app/routes/mcp-authorize/index.tsx
+++ b/packages/web/src/app/routes/mcp-authorize/index.tsx
@@ -4,7 +4,7 @@ import { useMutation, useQuery } from '@tanstack/react-query';
import { t } from 'i18next';
import { jwtDecode } from 'jwt-decode';
import { CheckCircle, FolderKanban, Lock, Plug, Workflow } from 'lucide-react';
-import { useMemo, useState } from 'react';
+import { useEffect, useMemo, useState } from 'react';
import { Navigate, useSearchParams } from 'react-router-dom';
import { useDebouncedCallback } from 'use-debounce';
@@ -21,23 +21,45 @@ import {
} from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { MultiSelectFilter } from '@/features/automations/components/multi-select-filter';
+import { userHooks } from '@/hooks/user-hooks';
import { api } from '@/lib/api';
import { authenticationSession } from '@/lib/authentication-session';
+import { FROM_QUERY_PARAM } from '@/lib/navigation-utils';
import { PermissionItem } from './permission-item';
function McpAuthorizePage() {
const [searchParams] = useSearchParams();
const authRequestId = searchParams.get('authRequestId');
- const { clientName, isPlatformScoped } = decodeJwtPayload(authRequestId);
+ const { clientName, isPlatformScoped, expiresAt } =
+ decodeJwtPayload(authRequestId);
const [selectedProjectId, setSelectedProjectId] = useState<
string | undefined
>(undefined);
const [searchValue, setSearchValue] = useState('');
const [selectedTypes, setSelectedTypes] = useState<string[]>([]);
const [authorized, setAuthorized] = useState(false);
+ const [requestExpired, setRequestExpired] = useState(
+ expiresAt !== null && expiresAt * 1000 <= Date.now(),
+ );
+ const [requestRejected, setRequestRejected] = useState(false);
const debouncedSetSearchValue = useDebouncedCallback(setSearchValue, 300);
- const isLoggedIn = authenticationSession.isLoggedIn();
+ const markRejectedOnInvalidRequest = (error: unknown) => {
+ if (
+ api.isError(error) &&
+ error.response?.status === 400 &&
+ (error.response.data as { error?: string } | undefined)?.error ===
+ 'invalid_request'
+ ) {
+ setRequestRejected(true);
+ }
+ };
+ const isLoggedIn =
+ authenticationSession.isLoggedIn() && !authenticationSession.isOnboarding();
+ const currentUserId = authenticationSession.getCurrentUserId();
+ const signInPath = `/sign-in?${new URLSearchParams({
+ [FROM_QUERY_PARAM]: `/mcp-authorize?${searchParams.toString()}`,
+ }).toString()}`;
const projectTypeOptions = [
{ value: ProjectType.TEAM, label: t('Team') },
{ value: ProjectType.PERSONAL, label: t('Personal') },
@@ -54,6 +76,28 @@ function McpAuthorizePage() {
enabled: isLoggedIn && !!authRequestId && !isPlatformScoped,
});
+ const { data: currentUser } = userHooks.useUserById(
+ isLoggedIn ? currentUserId : null,
+ );
+
+ useEffect(() => {
+ if (expiresAt === null || requestExpired) {
+ return;
+ }
+ const timer = setTimeout(
+ () => setRequestExpired(true),
+ Math.max(expiresAt * 1000 - Date.now(), 0),
+ );
+ return () => clearTimeout(timer);
+ }, [expiresAt, requestExpired]);
+
+ useEffect(() => {
+ const projects = projectsPage?.data ?? [];
+ if (!selectedProjectId && projects.length === 1 && !searchValue) {
+ setSelectedProjectId(projects[0].id);
+ }
+ }, [projectsPage?.data, selectedProjectId, searchValue]);
+
const approveMutation = useMutation({
mutationFn: (body: { authRequestId: string; projectId?: string }) =>
api.post<{ redirectUrl: string }>('/v1/mcp-oauth/approve', body),
@@ -61,6 +105,16 @@ function McpAuthorizePage() {
window.location.href = data.redirectUrl;
setAuthorized(true);
},
+ onError: markRejectedOnInvalidRequest,
+ });
+
+ const denyMutation = useMutation({
+ mutationFn: (body: { authRequestId: string }) =>
+ api.post<{ redirectUrl: string }>('/v1/mcp-oauth/deny', body),
+ onSuccess: (data) => {
+ window.location.href = data.redirectUrl;
+ },
+ onError: markRejectedOnInvalidRequest,
});
const { projectsMap, options } = useMemo(() => {
@@ -76,11 +130,14 @@ function McpAuthorizePage() {
}
if (!isLoggedIn) {
- const returnUrl = `/mcp-authorize?${searchParams.toString()}`;
- const loginParams = new URLSearchParams({ from: returnUrl });
- return <Navigate to={`/sign-in?${loginParams.toString()}`} replace />;
+ return <Navigate to={signInPath} replace />;
}
+ const switchAccount = () => {
+ authenticationSession.clearSession();
+ window.location.href = signInPath;
+ };
+
const handleAuthorize = () => {
if (!isPlatformScoped && !selectedProjectId) return;
approveMutation.mutate({
@@ -134,6 +191,19 @@ function McpAuthorizePage() {
<span className="font-semibold text-foreground">{clientName}</span>{' '}
{t('wants to connect to your Activepieces account')}
</CardDescription>
+ {currentUser && (
+ <p className="text-sm text-muted-foreground">
+ {t('Signed in as {email}', { email: currentUser.email })}
+ <span className="px-1.5">·</span>
+ <button
+ type="button"
+ className="underline underline-offset-2 hover:text-foreground"
+ onClick={switchAccount}
+ >
+ {t('Switch account')}
+ </button>
+ </p>
+ )}
</CardHeader>
<CardContent className="flex flex-col gap-5">
@@ -190,9 +260,20 @@ function McpAuthorizePage() {
</div>
)}
- {approveMutation.isError && (
+ {(requestExpired ||
+ requestRejected ||
+ approveMutation.isError ||
+ denyMutation.isError) && (
<div className="rounded-md border border-destructive/50 bg-destructive-100 p-3 text-sm text-destructive">
- {t('Authorization failed. Please try again.')}
+ {requestRejected ||
+ (requestExpired &&
+ !approveMutation.isError &&
+ !denyMutation.isError)
+ ? t(
+ 'This request has expired. Go back to {client} and start the connection again.',
+ { client: clientName },
+ )
+ : t('Authorization failed. Please try again.')}
</div>
)}
@@ -201,7 +282,9 @@ function McpAuthorizePage() {
type="button"
variant="outline"
className="flex-1"
- onClick={() => window.history.back()}
+ loading={denyMutation.isPending}
+ disabled={requestRejected}
+ onClick={() => denyMutation.mutate({ authRequestId })}
>
{t('Deny')}
</Button>
@@ -209,7 +292,9 @@ function McpAuthorizePage() {
type="button"
className="flex-1"
loading={approveMutation.isPending}
- disabled={!isPlatformScoped && !selectedProjectId}
+ disabled={
+ requestRejected || (!isPlatformScoped && !selectedProjectId)
+ }
onClick={handleAuthorize}
>
{t('Authorize')}
@@ -221,23 +306,35 @@ function McpAuthorizePage() {
);
}
-function decodeJwtPayload(token: string | null): {
- clientName: string;
- isPlatformScoped: boolean;
-} {
+function decodeJwtPayload(token: string | null): AuthRequestSummary {
+ const fallback: AuthRequestSummary = {
+ clientName: t('Unknown app'),
+ isPlatformScoped: false,
+ expiresAt: null,
+ };
try {
- if (!token)
- return { clientName: t('Unknown app'), isPlatformScoped: false };
- const payload = jwtDecode<{ clientName?: string; resource?: string }>(
- token,
- );
- const clientName = payload.clientName ?? t('Unknown app');
- const isPlatformScoped =
- payload.resource?.endsWith('/mcp/platform') ?? false;
- return { clientName, isPlatformScoped };
+ if (!token) {
+ return fallback;
+ }
+ const payload = jwtDecode<{
+ clientName?: string;
+ resource?: string;
+ exp?: number;
+ }>(token);
+ return {
+ clientName: payload.clientName ?? t('Unknown app'),
+ isPlatformScoped: payload.resource?.endsWith('/mcp/platform') ?? false,
+ expiresAt: payload.exp ?? null,
+ };
} catch {
- return { clientName: t('Unknown app'), isPlatformScoped: false };
+ return fallback;
}
}
+type AuthRequestSummary = {
+ clientName: string;
+ isPlatformScoped: boolean;
+ expiresAt: number | null;
+};
+
export { McpAuthorizePage };
diff --git a/packages/web/src/features/authentication/components/sign-in-form.tsx b/packages/web/src/features/authentication/components/sign-in-form.tsx
index 5d0fa5aecec..2d22e89433e 100644
--- a/packages/web/src/features/authentication/components/sign-in-form.tsx
+++ b/packages/web/src/features/authentication/components/sign-in-form.tsx
@@ -13,7 +13,7 @@ import { t } from 'i18next';
import { Eye, EyeOff } from 'lucide-react';
import { useState } from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
-import { Link, useNavigate } from 'react-router-dom';
+import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import { z } from 'zod';
import { authenticationApi } from '@/api/authentication-api';
@@ -27,7 +27,11 @@ import { acquisitionUtils } from '@/lib/acquisition-utils';
import { HttpError, api } from '@/lib/api';
import { authenticationSession } from '@/lib/authentication-session';
import { formatUtils } from '@/lib/format-utils';
-import { useRedirectAfterLogin } from '@/lib/navigation-utils';
+import {
+ FROM_QUERY_PARAM,
+ pendingRedirect,
+ useRedirectAfterLogin,
+} from '@/lib/navigation-utils';
import { CheckEmailNote } from './check-email-note';
@@ -53,6 +57,7 @@ const SignInForm = ({ onForgotPassword }: SignInFormProps) => {
const { data: edition } = flagsHooks.useFlag(ApFlagId.EDITION);
const redirectAfterLogin = useRedirectAfterLogin();
+ const [searchParams] = useSearchParams();
const navigate = useNavigate();
const { capture } = useTelemetry();
@@ -100,6 +105,7 @@ const SignInForm = ({ onForgotPassword }: SignInFormProps) => {
break;
}
case ErrorCode.EMAIL_IS_NOT_VERIFIED: {
+ pendingRedirect.remember(searchParams.get(FROM_QUERY_PARAM));
setShowCheckYourEmailNote(true);
break;
}
diff --git a/packages/web/src/features/authentication/components/sign-up-form.tsx b/packages/web/src/features/authentication/components/sign-up-form.tsx
index 4a3150e390c..177edf4078d 100644
--- a/packages/web/src/features/authentication/components/sign-up-form.tsx
+++ b/packages/web/src/features/authentication/components/sign-up-form.tsx
@@ -40,7 +40,11 @@ import { acquisitionUtils } from '@/lib/acquisition-utils';
import { api } from '@/lib/api';
import { authenticationSession } from '@/lib/authentication-session';
import { formatUtils } from '@/lib/format-utils';
-import { useRedirectAfterLogin } from '@/lib/navigation-utils';
+import {
+ FROM_QUERY_PARAM,
+ pendingRedirect,
+ useRedirectAfterLogin,
+} from '@/lib/navigation-utils';
import { authMutations } from '../hooks/auth-hooks';
import { captchaUtils } from '../utils/captcha-utils';
@@ -98,6 +102,10 @@ const SignUpForm = ({
const redirectAfterLogin = useRedirectAfterLogin();
const navigate = useNavigate();
const { capture } = useTelemetry();
+ const askToCheckEmail = () => {
+ pendingRedirect.remember(searchParams.get(FROM_QUERY_PARAM));
+ setShowCheckYourEmailNote(true);
+ };
const { mutate, isPending } = authMutations.useSignUp({
onSuccess: (data) => {
@@ -110,7 +118,7 @@ const SignUpForm = ({
}
redirectAfterLogin();
} else {
- setShowCheckYourEmailNote(true);
+ askToCheckEmail();
}
},
onError: (error) => {
@@ -139,7 +147,7 @@ const SignUpForm = ({
}
switch (errorCode) {
case ErrorCode.EMAIL_IS_NOT_VERIFIED: {
- setShowCheckYourEmailNote(true);
+ askToCheckEmail();
break;
}
case ErrorCode.INVITATION_ONLY_SIGN_UP: {
diff --git a/packages/web/src/features/authentication/components/verify-email.tsx b/packages/web/src/features/authentication/components/verify-email.tsx
index 36fd77ca88c..5e67d3dd181 100644
--- a/packages/web/src/features/authentication/components/verify-email.tsx
+++ b/packages/web/src/features/authentication/components/verify-email.tsx
@@ -12,6 +12,7 @@ import { Card } from '@/components/ui/card';
import { internalErrorToast } from '@/components/ui/sonner';
import { usePartnerStack } from '@/hooks/use-partner-stack';
import { api } from '@/lib/api';
+import { pendingRedirect } from '@/lib/navigation-utils';
import { authMutations } from '../hooks/auth-hooks';
@@ -32,7 +33,7 @@ const VerifyEmail = () => {
payload: {},
});
reportSignup(email, firstName);
- setTimeout(() => navigate('/sign-in'), 5000);
+ setTimeout(() => navigate(pendingRedirect.takeSignInPath()), 5000);
},
onError: (error) => {
if (
@@ -40,11 +41,11 @@ const VerifyEmail = () => {
error.response?.status === HttpStatusCode.Gone
) {
setIsExpired(true);
- setTimeout(() => navigate('/sign-in'), 5000);
+ setTimeout(() => navigate(pendingRedirect.takeSignInPath()), 5000);
} else {
console.error(error);
internalErrorToast();
- setTimeout(() => navigate('/sign-in'), 5000);
+ setTimeout(() => navigate(pendingRedirect.takeSignInPath()), 5000);
}
},
});
diff --git a/packages/web/src/lib/navigation-utils.tsx b/packages/web/src/lib/navigation-utils.tsx
index c6113b666b6..0c2482060bc 100644
--- a/packages/web/src/lib/navigation-utils.tsx
+++ b/packages/web/src/lib/navigation-utils.tsx
@@ -2,6 +2,8 @@ import { useNavigate, useSearchParams } from 'react-router-dom';
import { useEmbedding } from '@/components/providers/embed-provider';
+import { ApStorage } from './ap-browser-storage';
+
export const useNewWindow = () => {
const { embedState } = useEmbedding();
const navigate = useNavigate();
@@ -31,6 +33,23 @@ export const useDefaultRedirectPath = () => {
return '/';
};
+export const pendingRedirect = {
+ remember(from: string | null) {
+ if (from) {
+ ApStorage.getInstance().setItem(PENDING_REDIRECT_KEY, from);
+ } else {
+ ApStorage.getInstance().removeItem(PENDING_REDIRECT_KEY);
+ }
+ },
+ takeSignInPath(): string {
+ const from = ApStorage.getInstance().getItem(PENDING_REDIRECT_KEY);
+ ApStorage.getInstance().removeItem(PENDING_REDIRECT_KEY);
+ return from
+ ? `/sign-in?${FROM_QUERY_PARAM}=${encodeURIComponent(from)}`
+ : '/sign-in';
+ },
+};
+
export const useRedirectAfterLogin = () => {
const navigate = useNavigate();
const [searchParams] = useSearchParams();
@@ -38,3 +57,5 @@ export const useRedirectAfterLogin = () => {
const from = searchParams.get(FROM_QUERY_PARAM) ?? defaultRedirectPath;
return () => navigate(from);
};
+
+const PENDING_REDIRECT_KEY = 'redirectAfterEmailVerification';