Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

Add returnTo support for login, disable cloning without login (#794)

Ivan Starkov1ad428c79a73
diff --git a/apps/designer/app/routes/auth/dev.tsx b/apps/designer/app/routes/auth/dev.tsx
index ee5e6751cc..7285a8016f 100644
--- a/apps/designer/app/routes/auth/dev.tsx
+++ b/apps/designer/app/routes/auth/dev.tsx
@@ -1,16 +1,19 @@
import { type ActionArgs, redirect } from "@remix-run/node";
import { authenticator } from "~/services/auth.server";
-import { dashboardPath, loginPath } from "~/shared/router-utils";
+import { loginPath } from "~/shared/router-utils";
import { AUTH_PROVIDERS } from "~/shared/session";
+import { returnToPath } from "~/services/cookie.server";
export default function Dev() {
return null;
}
export const action = async ({ request }: ActionArgs) => {
+ const returnTo = await returnToPath(request);
+
try {
return await authenticator.authenticate("dev", request, {
- successRedirect: dashboardPath(),
+ successRedirect: returnTo,
throwOnError: true,
});
} catch (error: unknown) {
@@ -20,7 +23,11 @@ export const action = async ({ request }: ActionArgs) => {
}
if (error instanceof Error) {
return redirect(
- loginPath({ error: AUTH_PROVIDERS.LOGIN_DEV, message: error?.message })
+ loginPath({
+ error: AUTH_PROVIDERS.LOGIN_DEV,
+ message: error?.message,
+ returnTo,
+ })
);
}
}
diff --git a/apps/designer/app/routes/auth/github.tsx b/apps/designer/app/routes/auth/github.tsx
index 049c726d98..30a6050c5f 100644
--- a/apps/designer/app/routes/auth/github.tsx
+++ b/apps/designer/app/routes/auth/github.tsx
@@ -1,17 +1,20 @@
import { type ActionArgs, redirect } from "@remix-run/node";
import { authenticator } from "~/services/auth.server";
-import { dashboardPath, loginPath } from "~/shared/router-utils";
+import { loginPath } from "~/shared/router-utils";
import { sentryException } from "~/shared/sentry";
import { AUTH_PROVIDERS } from "~/shared/session";
+import { returnToPath } from "~/services/cookie.server";
export default function GH() {
return null;
}
export const action = async ({ request }: ActionArgs) => {
+ const returnTo = await returnToPath(request);
+
try {
return await authenticator.authenticate("github", request, {
- successRedirect: dashboardPath(),
+ successRedirect: returnTo,
throwOnError: true,
});
} catch (error: unknown) {
@@ -30,6 +33,7 @@ export const action = async ({ request }: ActionArgs) => {
loginPath({
error: AUTH_PROVIDERS.LOGIN_GITHUB,
message: error?.message,
+ returnTo,
})
);
}
diff --git a/apps/designer/app/routes/auth/github/callback.tsx b/apps/designer/app/routes/auth/github/callback.tsx
index 8443f068a2..cf36e23be3 100644
--- a/apps/designer/app/routes/auth/github/callback.tsx
+++ b/apps/designer/app/routes/auth/github/callback.tsx
@@ -1,9 +1,11 @@
import { type LoaderArgs, redirect } from "@remix-run/node";
import { authenticator } from "~/services/auth.server";
-import { dashboardPath, loginPath } from "~/shared/router-utils";
+import { loginPath } from "~/shared/router-utils";
import { AUTH_PROVIDERS } from "~/shared/session";
+import { returnToPath } from "~/services/cookie.server";
export const loader = async ({ request }: LoaderArgs) => {
+ const returnTo = await returnToPath(request);
const url = new URL(request.url);
const error = url.searchParams.get("error");
const errorDescription = url.searchParams.get("error_description");
@@ -12,11 +14,12 @@ export const loader = async ({ request }: LoaderArgs) => {
loginPath({
error: AUTH_PROVIDERS.LOGIN_GITHUB,
message: errorDescription || error,
+ returnTo,
})
);
}
return authenticator.authenticate("github", request, {
- successRedirect: dashboardPath(),
+ successRedirect: returnTo,
failureRedirect: loginPath({}),
});
};
diff --git a/apps/designer/app/routes/auth/google.tsx b/apps/designer/app/routes/auth/google.tsx
index cdf037d639..8c5b3a2aee 100644
--- a/apps/designer/app/routes/auth/google.tsx
+++ b/apps/designer/app/routes/auth/google.tsx
@@ -1,8 +1,9 @@
import { type ActionArgs, type LoaderArgs, redirect } from "@remix-run/node";
import { authenticator } from "~/services/auth.server";
-import { dashboardPath, loginPath } from "~/shared/router-utils";
+import { loginPath } from "~/shared/router-utils";
import { sentryException } from "~/shared/sentry";
import { AUTH_PROVIDERS } from "~/shared/session";
+import { returnToPath } from "~/services/cookie.server";
export default function Google() {
return null;
@@ -11,9 +12,11 @@ export default function Google() {
export const loader = (_args: LoaderArgs) => redirect("/login");
export const action = async ({ request }: ActionArgs) => {
+ const returnTo = await returnToPath(request);
+
try {
return await authenticator.authenticate("google", request, {
- successRedirect: dashboardPath(),
+ successRedirect: returnTo,
throwOnError: true,
});
} catch (error: unknown) {
@@ -32,6 +35,7 @@ export const action = async ({ request }: ActionArgs) => {
loginPath({
error: AUTH_PROVIDERS.LOGIN_GOOGLE,
message: error?.message,
+ returnTo,
})
);
}
diff --git a/apps/designer/app/routes/auth/google/callback.tsx b/apps/designer/app/routes/auth/google/callback.tsx
index c840bb3aa3..1069dc0a89 100644
--- a/apps/designer/app/routes/auth/google/callback.tsx
+++ b/apps/designer/app/routes/auth/google/callback.tsx
@@ -1,10 +1,13 @@
import type { LoaderArgs } from "@remix-run/node";
import { authenticator } from "~/services/auth.server";
-import { dashboardPath, loginPath } from "~/shared/router-utils";
+import { loginPath } from "~/shared/router-utils";
+import { returnToPath } from "~/services/cookie.server";
export const loader = async ({ request }: LoaderArgs) => {
+ const returnTo = await returnToPath(request);
+
return authenticator.authenticate("google", request, {
- successRedirect: dashboardPath(),
- failureRedirect: loginPath({}),
+ successRedirect: returnTo,
+ failureRedirect: loginPath({ returnTo }),
});
};
diff --git a/apps/designer/app/routes/dashboard/index.tsx b/apps/designer/app/routes/dashboard/index.tsx
index c96c906204..34f376625c 100644
--- a/apps/designer/app/routes/dashboard/index.tsx
+++ b/apps/designer/app/routes/dashboard/index.tsx
@@ -3,7 +3,6 @@ import type { ActionArgs, LoaderArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Dashboard, links } from "~/dashboard";
import { db } from "@webstudio-is/project/server";
-import { ensureUserCookie } from "~/shared/session";
import { findAuthenticatedUser } from "~/services/auth.server";
import { zfd } from "zod-form-data";
import { type Project, User as DbUser } from "@webstudio-is/prisma-client";
@@ -26,14 +25,17 @@ type Data = {
export const action = async ({ request }: ActionArgs) => {
const { project: title } = schema.parse(await request.formData());
- const { userId, headers } = await ensureUserCookie(request);
const authenticatedUser = await findAuthenticatedUser(request);
+ if (authenticatedUser === null) {
+ throw new Error("Not authenticated");
+ }
+
try {
const project = await db.project.create({
title,
- userId: authenticatedUser?.id || userId,
+ userId: authenticatedUser?.id,
});
- return redirect(designerPath({ projectId: project.id }), { headers });
+ return redirect(designerPath({ projectId: project.id }));
} catch (error) {
if (error instanceof Error) {
return { errors: error.message };
@@ -45,11 +47,16 @@ export const action = async ({ request }: ActionArgs) => {
export const loader = async ({ request }: LoaderArgs) => {
const user = await findAuthenticatedUser(request);
if (!user) {
- return redirect(loginPath({}));
+ const url = new URL(request.url);
+ return redirect(
+ loginPath({
+ returnTo: url.pathname,
+ })
+ );
}
- const { headers } = await ensureUserCookie(request);
+
const projects = await db.project.loadManyByUserId(user.id);
- return json({ projects, user }, headers);
+ return json({ projects, user });
};
const DashboardRoute = () => {
diff --git a/apps/designer/app/routes/login/index.tsx b/apps/designer/app/routes/login/index.tsx
index 573b941256..e3af48d559 100644
--- a/apps/designer/app/routes/login/index.tsx
+++ b/apps/designer/app/routes/login/index.tsx
@@ -1,4 +1,4 @@
-import { type LoaderArgs, redirect } from "@remix-run/node";
+import { type LoaderArgs, redirect, json } from "@remix-run/node";
import { findAuthenticatedUser } from "~/services/auth.server";
import env from "~/env.server";
@@ -6,24 +6,47 @@ import env from "~/env.server";
import { Login, links } from "~/auth";
import { useLoginErrorMessage } from "~/shared/session";
import { dashboardPath } from "~/shared/router-utils";
+import { returnToCookie } from "~/services/cookie.server";
export { links };
+const comparePathnames = (pathnameOrUrlA: string, pathnameOrUrlB: string) => {
+ const aPathname = new URL(pathnameOrUrlA, "http://localhost").pathname;
+ const bPathname = new URL(pathnameOrUrlB, "http://localhost").pathname;
+ return aPathname === bPathname;
+};
+
export const loader = async ({ request }: LoaderArgs) => {
const user = await findAuthenticatedUser(request);
+
+ const url = new URL(request.url);
+ let returnTo = url.searchParams.get("returnTo") ?? dashboardPath();
+
+ // Avoid loops
+ if (comparePathnames(returnTo, request.url)) {
+ returnTo = dashboardPath();
+ }
+
if (user) {
- return redirect(dashboardPath());
+ return redirect(returnTo);
}
- return {
- isDevLogin: process.env.DEV_LOGIN === "true",
- env,
- isGithubEnabled: Boolean(
- process.env.GH_CLIENT_ID && process.env.GH_CLIENT_SECRET
- ),
- isGoogleEnabled: Boolean(
- process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET
- ),
- };
+
+ const headers = new Headers();
+ headers.append("Set-Cookie", await returnToCookie.serialize(returnTo));
+
+ return json(
+ {
+ isDevLogin: process.env.DEV_LOGIN === "true",
+ env,
+ isGithubEnabled: Boolean(
+ process.env.GH_CLIENT_ID && process.env.GH_CLIENT_SECRET
+ ),
+ isGoogleEnabled: Boolean(
+ process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET
+ ),
+ },
+ { headers }
+ );
};
const LoginRoute = () => {
diff --git a/apps/designer/app/routes/rest/project/clone.$domain.ts b/apps/designer/app/routes/rest/project/clone.$domain.ts
index 38857daba3..500f0fc37f 100644
--- a/apps/designer/app/routes/rest/project/clone.$domain.ts
+++ b/apps/designer/app/routes/rest/project/clone.$domain.ts
@@ -2,10 +2,8 @@ import { redirect, type LoaderArgs } from "@remix-run/node";
import type { User } from "@webstudio-is/prisma-client";
import { db as projectDb } from "@webstudio-is/project/server";
import { type Project } from "@webstudio-is/project";
-import * as userDb from "~/shared/db";
-import { ensureUserCookie } from "~/shared/session";
import { findAuthenticatedUser } from "~/services/auth.server";
-import { designerPath } from "~/shared/router-utils";
+import { designerPath, loginPath } from "~/shared/router-utils";
const ensureProject = async ({
userId,
@@ -34,17 +32,25 @@ export const loader = async ({ request, params }: LoaderArgs) => {
if (params.domain === undefined) {
return { errors: "Domain required" };
}
+
const user = await findAuthenticatedUser(request);
- const { headers, userId: generatedUserId } = await ensureUserCookie(request);
+
+ if (user === null) {
+ const url = new URL(request.url);
+ return redirect(
+ loginPath({
+ returnTo: url.pathname,
+ })
+ );
+ }
+
try {
- const userId = await userDb.user.ensureUser({
- userId: user ? user.id : generatedUserId,
- });
const project = await ensureProject({
- userId,
+ userId: user.id,
domain: params.domain,
});
- return redirect(designerPath({ projectId: project.id }), { headers });
+
+ return redirect(designerPath({ projectId: project.id }));
} catch (error: unknown) {
if (error instanceof Error) {
return { errors: error.message };
diff --git a/apps/designer/app/services/cookie.server.ts b/apps/designer/app/services/cookie.server.ts
new file mode 100644
index 0000000000..4afae9b49f
--- /dev/null
+++ b/apps/designer/app/services/cookie.server.ts
@@ -0,0 +1,18 @@
+import { createCookie } from "@remix-run/node";
+import { dashboardPath } from "~/shared/router-utils";
+
+export const returnToCookie = createCookie("returnTo", {
+ path: "/",
+ httpOnly: true,
+ sameSite: "lax",
+ maxAge: 60, // 1 minute because it makes no sense to keep it for a long time
+ secure: process.env.NODE_ENV === "production",
+});
+
+export const returnToPath = async (request: Request) => {
+ const returnTo =
+ (await returnToCookie.parse(request.headers.get("Cookie"))) ??
+ dashboardPath();
+
+ return returnTo;
+};
diff --git a/apps/designer/app/shared/db/user.server.ts b/apps/designer/app/shared/db/user.server.ts
index ca944f2d17..d128d475c7 100644
--- a/apps/designer/app/shared/db/user.server.ts
+++ b/apps/designer/app/shared/db/user.server.ts
@@ -14,22 +14,6 @@ export const createDemoUser = async (userId: string) => {
});
};
-export const ensureUser = async ({ userId }: { userId: string }) => {
- // Always check if the account userId exists because account could have been deleted
- // or we could be in a demo mode with a generated user
- const isUserCreated = Boolean(
- await prisma.user.findUnique({
- where: { id: userId },
- })
- );
- if (isUserCreated) {
- return userId;
- }
- await createDemoUser(userId);
-
- return userId;
-};
-
const genericCreateAccount = async (userData: {
email: string;
username: string;
diff --git a/apps/designer/app/shared/router-utils/path-utils.ts b/apps/designer/app/shared/router-utils/path-utils.ts
index 9ee983ae14..247652de63 100644
--- a/apps/designer/app/shared/router-utils/path-utils.ts
+++ b/apps/designer/app/shared/router-utils/path-utils.ts
@@ -28,6 +28,7 @@ export const dashboardPath = () => "/dashboard";
export const loginPath = (params: {
error?: typeof AUTH_PROVIDERS[keyof typeof AUTH_PROVIDERS];
message?: string;
+ returnTo?: string;
}) => `/login${searchParams(params)}`;
export const logoutPath = () => "/logout";
diff --git a/apps/designer/app/shared/session/index.ts b/apps/designer/app/shared/session/index.ts
index d3127eaa39..6062ae5ae2 100644
--- a/apps/designer/app/shared/session/index.ts
+++ b/apps/designer/app/shared/session/index.ts
@@ -1,2 +1 @@
-export * from "./user.server";
export * from "./use-login-error-message";
diff --git a/apps/designer/app/shared/session/use-login-error-message.ts b/apps/designer/app/shared/session/use-login-error-message.ts
index 4d81d487d1..7e532e4142 100644
--- a/apps/designer/app/shared/session/use-login-error-message.ts
+++ b/apps/designer/app/shared/session/use-login-error-message.ts
@@ -31,7 +31,12 @@ export const useLoginErrorMessage = (): string => {
sentryMessage({ message });
setMessageToReturn(message);
- setSearchParams({});
+ setSearchParams((prevSearchParams) => {
+ const nextSearchParams = new URLSearchParams(prevSearchParams);
+ nextSearchParams.delete("error");
+ nextSearchParams.delete("message");
+ return nextSearchParams;
+ });
return;
}
@@ -49,8 +54,6 @@ export const useLoginErrorMessage = (): string => {
default:
break;
}
-
- setSearchParams({});
}, [searchParams, setSearchParams]);
return messageToReturn;
diff --git a/apps/designer/app/shared/session/user.server.ts b/apps/designer/app/shared/session/user.server.ts
deleted file mode 100644
index 28891cfcd1..0000000000
--- a/apps/designer/app/shared/session/user.server.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import ObjectId from "bson-objectid";
-import { createCookie } from "@remix-run/node";
-
-const userIdParser = createCookie("user-id", {
- maxAge: 604_800, // one week
-});
-
-export const ensureUserCookie = async (
- request: Request
-): Promise<{ userId: string; headers?: { [key: string]: string } }> => {
- const cookieString = request.headers.get("Cookie");
- const userId = await userIdParser.parse(cookieString);
- if (userId !== null) {
- return { userId };
- }
- // We use a generated id temporarily as a way to demonstrate the designer
- // to a new user without a signup.
- const generatedUserId = ObjectId().toString();
- return {
- headers: {
- "Set-Cookie": await userIdParser.serialize(generatedUserId),
- },
- userId: userId || generatedUserId,
- };
-};