Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(web): respect DISABLE_WORKSPACE_CREATION on the onboarding screen (#1744)

Juan D Barretoff4f33699c86
diff --git a/apps/web/src/components/onboarding/onboarding-flow.test.tsx b/apps/web/src/components/onboarding/onboarding-flow.test.tsx
new file mode 100644
index 000000000..1207cf47d
--- /dev/null
+++ b/apps/web/src/components/onboarding/onboarding-flow.test.tsx
@@ -0,0 +1,272 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import {
+ act,
+ cleanup,
+ render as rtlRender,
+ screen,
+} from "@testing-library/react";
+import { createElement, type ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { OnboardingFlow } from "./onboarding-flow";
+
+const config = vi.fn();
+const authUser = vi.fn();
+const getSession = vi.fn();
+
+vi.mock("@tanstack/react-router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@tanstack/react-router")>()),
+ useNavigate: () => vi.fn(),
+}));
+
+// Renders a router Link, which needs a router context this test has no reason
+// to build.
+vi.mock("@/components/common/logo", () => ({
+ Logo: () => null,
+}));
+
+vi.mock("@/hooks/queries/config/use-get-config", () => ({
+ default: () => config(),
+}));
+
+vi.mock("@/lib/auth-client", () => ({
+ authClient: {
+ organization: { setActive: vi.fn() },
+ getSession: (options: unknown) => getSession(options),
+ },
+}));
+
+vi.mock("@/hooks/queries/workspace/use-create-workspace", () => ({
+ default: () => ({ mutateAsync: vi.fn(), isPending: false }),
+}));
+
+vi.mock("@/components/providers/auth-provider/hooks/use-auth", () => ({
+ default: () => ({ user: authUser(), refetchUser: vi.fn() }),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+ Trans: ({ i18nKey }: { i18nKey: string }) => i18nKey,
+ initReactI18next: { type: "3rdParty", init: vi.fn() },
+}));
+
+beforeEach(() => {
+ authUser.mockReturnValue({ id: "u1", name: "Sam", role: "user" });
+ // Better Auth resolves with `{ data, error }` and does not reject, which is
+ // the whole reason the hook reads `error` rather than catching.
+ getSession.mockResolvedValue({
+ data: { user: { id: "u1", role: "user" } },
+ error: null,
+ });
+ config.mockReturnValue({
+ data: { disableWorkspaceCreation: false },
+ isPending: false,
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+// A real client rather than a mocked one: the component reaches react-query
+// through hooks this test does not stub.
+function render(ui: ReactNode) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const wrap = (node: ReactNode) =>
+ createElement(QueryClientProvider, { client }, node) as never;
+ const result = rtlRender(wrap(ui));
+ // RTL's own rerender drops the wrapper, which the component needs.
+ return {
+ ...result,
+ rerender: (next: ReactNode) => result.rerender(wrap(next)),
+ };
+}
+
+const creationForm = () =>
+ screen.queryByText("auth:onboarding.createWorkspaceTitle");
+const restricted = () => screen.queryByText("auth:onboarding.restrictedTitle");
+
+// Nothing decides until the one-shot role refresh settles.
+const settled = () => act(async () => {});
+
+describe("OnboardingFlow", () => {
+ it("offers the creation form when anyone may create a workspace", async () => {
+ render(<OnboardingFlow />);
+ await settled();
+
+ expect(creationForm()).toBeInTheDocument();
+ expect(restricted()).not.toBeInTheDocument();
+ });
+
+ it("explains the restriction instead of offering a form that would fail", async () => {
+ config.mockReturnValue({
+ data: { disableWorkspaceCreation: true },
+ isPending: false,
+ });
+
+ render(<OnboardingFlow />);
+ await settled();
+
+ // The API refuses creation for non-admins, so offering the form here only
+ // produces an error at submit time.
+ expect(restricted()).toBeInTheDocument();
+ expect(creationForm()).not.toBeInTheDocument();
+ // Reaching this screen with an invitation waiting is possible, so it has
+ // to offer a route back to it.
+ expect(
+ screen.getByText("auth:onboarding.restrictedCheckInvitations"),
+ ).toBeInTheDocument();
+ });
+
+ it("still offers the form to an instance admin when creation is restricted", async () => {
+ config.mockReturnValue({
+ data: { disableWorkspaceCreation: true },
+ isPending: false,
+ });
+ getSession.mockResolvedValue({
+ data: { user: { id: "u1", role: "admin" } },
+ error: null,
+ });
+
+ render(<OnboardingFlow />);
+ await settled();
+
+ expect(creationForm()).toBeInTheDocument();
+ expect(restricted()).not.toBeInTheDocument();
+ });
+
+ it("does not make an instance admin wait for the config", async () => {
+ // The setting cannot restrict an admin, so its value cannot change what
+ // they are shown. Waiting would delay a form they always get.
+ config.mockReturnValue({ data: undefined, isPending: true });
+ getSession.mockResolvedValue({
+ data: { user: { id: "u1", role: "admin" } },
+ error: null,
+ });
+
+ render(<OnboardingFlow />);
+ await settled();
+
+ expect(creationForm()).toBeInTheDocument();
+ expect(restricted()).not.toBeInTheDocument();
+ });
+
+ it("still decides when the role refresh fails", async () => {
+ const unhandled = vi.fn();
+ process.on("unhandledRejection", unhandled);
+ getSession.mockResolvedValue({ data: null, error: { status: 500 } });
+
+ render(<OnboardingFlow />);
+ await settled();
+ await settled();
+
+ // The cached role stands, the screen resolves, and the failure does not
+ // escape as a global error.
+ expect(creationForm()).toBeInTheDocument();
+ expect(unhandled).not.toHaveBeenCalled();
+ process.off("unhandledRejection", unhandled);
+ });
+
+ it("offers the form when the role refresh fails under a restriction", async () => {
+ // The cached role cannot be trusted to take the form away: the one user
+ // whose role is most likely wrong here is the freshly promoted first
+ // administrator, who is entitled to it. The API still refuses the
+ // creation if the role really is `user`.
+ config.mockReturnValue({
+ data: { disableWorkspaceCreation: true },
+ isPending: false,
+ });
+ // The request failed; the session store would keep the stale role and
+ // report it alongside the error rather than rejecting.
+ getSession.mockResolvedValue({
+ data: null,
+ error: { status: 500, message: "network" },
+ });
+
+ render(<OnboardingFlow />);
+ await settled();
+ await settled();
+
+ expect(creationForm()).toBeInTheDocument();
+ expect(restricted()).not.toBeInTheDocument();
+ });
+
+ it("shows progress while the decision is pending", async () => {
+ config.mockReturnValue({ data: undefined, isPending: true });
+
+ render(<OnboardingFlow />);
+ await settled();
+
+ // Neither branch renders yet, and an empty page is not an answer.
+ expect(screen.getByRole("status")).toBeInTheDocument();
+ });
+
+ it("claims nothing while the config is still loading", async () => {
+ // `undefined` is the pending state. Showing the restriction here would
+ // flash a false statement before a working form resolves, and showing the
+ // form would invite a submit that fails.
+ config.mockReturnValue({ data: undefined, isPending: true });
+
+ render(<OnboardingFlow />);
+ await settled();
+
+ expect(creationForm()).not.toBeInTheDocument();
+ expect(restricted()).not.toBeInTheDocument();
+ });
+
+ it("falls back to the form when the config request fails", async () => {
+ // Settled with no data is an error, not a restriction. Claiming a
+ // restriction here would be untrue, and the API still has the final say.
+ config.mockReturnValue({ data: undefined, isPending: false });
+
+ render(<OnboardingFlow />);
+ await settled();
+
+ expect(creationForm()).toBeInTheDocument();
+ expect(restricted()).not.toBeInTheDocument();
+ });
+
+ it("re-reads the role past the cookie cache", async () => {
+ render(<OnboardingFlow />);
+ await settled();
+
+ // The first admin of an instance is promoted after the session is cached,
+ // so the cached copy is exactly the one that cannot be trusted here.
+ expect(getSession).toHaveBeenCalledWith({
+ query: { disableCookieCache: true },
+ });
+ });
+
+ it("prefers the re-read role over the cached one", async () => {
+ // The promotion the cached session has not caught up with yet.
+ config.mockReturnValue({
+ data: { disableWorkspaceCreation: true },
+ isPending: false,
+ });
+ getSession.mockResolvedValue({
+ data: { user: { id: "u1", role: "admin" } },
+ error: null,
+ });
+
+ render(<OnboardingFlow />);
+ await settled();
+
+ expect(creationForm()).toBeInTheDocument();
+ expect(restricted()).not.toBeInTheDocument();
+ });
+
+ it("re-reads the role only once, however often it rerenders", async () => {
+ const { rerender } = render(<OnboardingFlow />);
+ await settled();
+
+ getSession.mockClear();
+ rerender(<OnboardingFlow />);
+ await settled();
+ rerender(<OnboardingFlow />);
+ await settled();
+
+ expect(getSession).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/components/onboarding/onboarding-flow.tsx b/apps/web/src/components/onboarding/onboarding-flow.tsx
index fc835bd39..20859fb30 100644
--- a/apps/web/src/components/onboarding/onboarding-flow.tsx
+++ b/apps/web/src/components/onboarding/onboarding-flow.tsx
@@ -2,7 +2,7 @@ import { standardSchemaResolver } from "@hookform/resolvers/standard-schema";
import { useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router";
import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
-import { CheckCircle2 } from "lucide-react";
+import { CheckCircle2, MailQuestion } from "lucide-react";
import { useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { Trans, useTranslation } from "react-i18next";
@@ -20,7 +20,9 @@ import {
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
+import { Spinner } from "@/components/ui/spinner";
import useCreateWorkspace from "@/hooks/queries/workspace/use-create-workspace";
+import useWorkspaceCreationAccess from "@/hooks/use-workspace-creation-access";
import { authClient } from "@/lib/auth-client";
import { toast } from "@/lib/toast";
@@ -49,6 +51,7 @@ export function OnboardingFlow() {
const queryClient = useQueryClient();
const { mutateAsync: createWorkspace, isPending } = useCreateWorkspace();
const { user } = useAuth();
+ const { isCreationRestricted, isDecided } = useWorkspaceCreationAccess();
const workspaceSchema = useMemo(
() =>
@@ -221,12 +224,65 @@ export function OnboardingFlow() {
</motion.div>
);
+ const renderRestrictedStep = () => (
+ <motion.div
+ key="restricted"
+ variants={fadeTransition}
+ initial="initial"
+ animate="animate"
+ exit="exit"
+ transition={{ duration: 0.3, ease: [0.23, 1, 0.32, 1] }}
+ className="w-full max-w-sm mx-auto"
+ >
+ <Logo className="mx-auto mb-6 w-full flex items-end justify-center" />
+
+ <div className="rounded-xl border border-border bg-card p-6 shadow-sm text-center">
+ <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-muted">
+ <MailQuestion className="h-6 w-6 text-muted-foreground" />
+ </div>
+
+ <h1 className="text-xl font-semibold text-foreground mb-2">
+ {t("auth:onboarding.restrictedTitle")}
+ </h1>
+ <p className="text-muted-foreground text-sm">
+ {t("auth:onboarding.restrictedSubtitle")}
+ </p>
+
+ {/* The way back. Reaching this screen with an invitation waiting is
+ possible, and without this the only route to it is editing the
+ URL. The invitations screen hides its own skip control while
+ creation is restricted, so this does not bounce. */}
+ <Button
+ type="button"
+ variant="outline"
+ className="mt-6 w-full"
+ onClick={() => navigate({ to: "/invitations" })}
+ >
+ {t("auth:onboarding.restrictedCheckInvitations")}
+ </Button>
+ </div>
+ </motion.div>
+ );
+
return (
<>
<PageTitle title={t("auth:onboarding.workspacePageTitle")} />
<div className="min-h-screen w-full bg-background flex flex-col items-center justify-center p-4">
+ {/* The role refresh is a network round-trip that every visit makes,
+ so without this the screen is blank for the length of it. It sits
+ outside the AnimatePresence deliberately: as a child of it, its
+ exit animation would hold the form back until the fade finished. */}
+ {step === "workspace" && !isDecided && (
+ <Spinner className="h-6 w-6 text-muted-foreground" />
+ )}
<AnimatePresence mode="wait">
- {step === "workspace" && renderWorkspaceStep()}
+ {step === "workspace" &&
+ isDecided &&
+ !isCreationRestricted &&
+ renderWorkspaceStep()}
+ {step === "workspace" &&
+ isCreationRestricted &&
+ renderRestrictedStep()}
{step === "success" && renderSuccessStep()}
</AnimatePresence>
</div>
diff --git a/apps/web/src/hooks/use-workspace-creation-access.ts b/apps/web/src/hooks/use-workspace-creation-access.ts
new file mode 100644
index 000000000..683e48820
--- /dev/null
+++ b/apps/web/src/hooks/use-workspace-creation-access.ts
@@ -0,0 +1,99 @@
+import { useEffect, useRef, useState } from "react";
+import useAuth from "@/components/providers/auth-provider/hooks/use-auth";
+import useGetConfig from "@/hooks/queries/config/use-get-config";
+import { authClient } from "@/lib/auth-client";
+
+// "stale" is a refresh that failed: the cached role is all there is.
+type RoleStatus = "pending" | "fresh" | "stale";
+
+export type WorkspaceCreationAccess = {
+ /** A confirmed non-admin under a confirmed `DISABLE_WORKSPACE_CREATION`. */
+ isCreationRestricted: boolean;
+ /** Both answers have settled, one way or another. */
+ isDecided: boolean;
+ /** Decided, and not restricted. */
+ canCreateWorkspace: boolean;
+};
+
+/**
+ * Whether to offer this user a workspace to create. The API is the authority —
+ * it enforces `DISABLE_WORKSPACE_CREATION` through Better Auth's
+ * `allowUserToCreateOrganization` — so this only decides what is worth
+ * offering, and every screen that offers it has to agree.
+ */
+export default function useWorkspaceCreationAccess(): WorkspaceCreationAccess {
+ const { user } = useAuth();
+ const { data: config, isPending: configPending } = useGetConfig();
+
+ // The session role can be up to five minutes stale: `auth.ts` notes that the
+ // first-user bootstrap promotes to admin after the session is already
+ // cached. Elsewhere a stale role only hides a button; here it decides
+ // whether the first administrator of an instance is told to go and ask
+ // someone for an invitation. Re-read it once, bypassing that cache.
+ //
+ // `getSession` rather than the provider's `refetchUser`, because this needs
+ // to know whether the answer arrived. `useSession().refetch()` writes a
+ // failed request into the session store's `error` and keeps the stale
+ // `data` — deliberately, so a dropped connection does not sign anyone out —
+ // and resolves either way, so awaiting it cannot distinguish a confirmed
+ // role from an unconfirmed one.
+ //
+ // Guarded by a ref so React's development double-mount does not send it
+ // twice.
+ const refreshStarted = useRef(false);
+ const [roleStatus, setRoleStatus] = useState<RoleStatus>("pending");
+ const [refreshedRole, setRefreshedRole] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (refreshStarted.current) return;
+ refreshStarted.current = true;
+
+ void (async () => {
+ try {
+ const { data, error } = await authClient.getSession({
+ query: { disableCookieCache: true },
+ });
+ if (error || !data) {
+ setRoleStatus("stale");
+ return;
+ }
+ setRefreshedRole((data.user as { role?: string | null }).role ?? null);
+ setRoleStatus("fresh");
+ } catch {
+ // Swallowed rather than left to surface as an unhandled rejection.
+ setRoleStatus("stale");
+ }
+ })();
+ }, []);
+
+ // The re-read answer when there is one, the cached role when there is not.
+ const isInstanceAdmin =
+ roleStatus === "fresh"
+ ? refreshedRole === "admin"
+ : (user as { role?: string | null } | null | undefined)?.role === "admin";
+
+ // Only a confirmed non-admin under a confirmed restriction loses anything.
+ // Every other combination — a role that could not be re-read, a config
+ // request that failed — falls back to offering the form and leaves the API
+ // with the final say, which it has either way. Guessing the other way would
+ // strand a user on a screen with nothing on it.
+ const isCreationRestricted =
+ roleStatus === "fresh" &&
+ !isInstanceAdmin &&
+ !configPending &&
+ config?.disableWorkspaceCreation === true;
+
+ // An instance admin waits for the role refresh and nothing else: the setting
+ // cannot restrict them, so the config's value cannot change their outcome
+ // and waiting for it would only delay a form they are always entitled to.
+ // Everyone else waits for both, rather than being shown a screen or a
+ // control that the next render takes away.
+ const isDecided =
+ roleStatus !== "pending" && (isInstanceAdmin || !configPending);
+
+ return {
+ isCreationRestricted,
+ isDecided,
+ canCreateWorkspace: isDecided && !isCreationRestricted,
+ };
+}
diff --git a/apps/web/src/routes/_layout/_authenticated/invitations.test.tsx b/apps/web/src/routes/_layout/_authenticated/invitations.test.tsx
new file mode 100644
index 000000000..b722faf85
--- /dev/null
+++ b/apps/web/src/routes/_layout/_authenticated/invitations.test.tsx
@@ -0,0 +1,189 @@
+import { act, cleanup, render, screen } from "@testing-library/react";
+import type { ComponentType, ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Route } from "./invitations";
+
+const config = vi.fn();
+const authUser = vi.fn();
+const getSession = vi.fn();
+const pendingInvitations = vi.fn();
+
+vi.mock("@tanstack/react-router", () => ({
+ createFileRoute: () => (options: unknown) => options,
+ useNavigate: () => vi.fn(),
+}));
+
+vi.mock("@/hooks/queries/config/use-get-config", () => ({
+ default: () => config(),
+}));
+
+vi.mock("@/hooks/queries/invitation/use-pending-invitations", () => ({
+ usePendingInvitations: () => pendingInvitations(),
+}));
+
+vi.mock("@/components/providers/auth-provider/hooks/use-auth", () => ({
+ default: () => ({ user: authUser(), refetchUser: vi.fn() }),
+}));
+
+vi.mock("@/lib/auth-client", () => ({
+ authClient: {
+ organization: {
+ acceptInvitation: vi.fn(),
+ rejectInvitation: vi.fn(),
+ setActive: vi.fn(),
+ },
+ getSession: (options: unknown) => getSession(options),
+ },
+}));
+
+vi.mock("@tanstack/react-query", () => ({
+ useQueryClient: () => ({ invalidateQueries: vi.fn() }),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+ Trans: ({ i18nKey }: { i18nKey: string }) => <span>{i18nKey}</span>,
+ initReactI18next: { type: "3rdParty", init: vi.fn() },
+}));
+
+const InvitationsPage = (Route as unknown as { component: ComponentType })
+ .component;
+
+const invitation = {
+ id: "invitation-1",
+ workspaceId: "org-1",
+ workspaceName: "Kaneo",
+ inviterName: "Ada",
+ role: "member",
+ expiresAt: "2999-01-01T00:00:00.000Z",
+};
+
+beforeEach(() => {
+ authUser.mockReturnValue({ id: "u1", name: "Sam", role: "user" });
+ config.mockReturnValue({
+ data: { disableWorkspaceCreation: false },
+ isPending: false,
+ });
+ pendingInvitations.mockReturnValue({ data: [], isLoading: false });
+ // Better Auth resolves with `{ data, error }` and does not reject.
+ getSession.mockResolvedValue({
+ data: { user: { id: "u1", role: "user" } },
+ error: null,
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+const continueToSetup = () => screen.queryByText("invitations:continueToSetup");
+const skipForNow = () => screen.queryByText("invitations:skipForNow");
+
+// Neither control decides until the one-shot role refresh settles.
+const settled = () => act(async () => {});
+
+async function renderPage(node: ReactNode) {
+ render(node);
+ await settled();
+}
+
+describe("InvitationsPage", () => {
+ describe("with no invitation to accept", () => {
+ it("offers to continue to setup when creation is open", async () => {
+ await renderPage(<InvitationsPage />);
+
+ expect(continueToSetup()).toBeInTheDocument();
+ });
+
+ it("hides it from a restricted user, who has nowhere to continue to", async () => {
+ config.mockReturnValue({
+ data: { disableWorkspaceCreation: true },
+ isPending: false,
+ });
+
+ await renderPage(<InvitationsPage />);
+
+ // The onboarding screen it leads to would only send them back here.
+ expect(continueToSetup()).not.toBeInTheDocument();
+ });
+
+ it("keeps it for an instance admin when creation is restricted", async () => {
+ config.mockReturnValue({
+ data: { disableWorkspaceCreation: true },
+ isPending: false,
+ });
+ getSession.mockResolvedValue({
+ data: { user: { id: "u1", role: "admin" } },
+ error: null,
+ });
+
+ await renderPage(<InvitationsPage />);
+
+ expect(continueToSetup()).toBeInTheDocument();
+ });
+ });
+
+ describe("with an invitation waiting", () => {
+ beforeEach(() => {
+ pendingInvitations.mockReturnValue({
+ data: [invitation],
+ isLoading: false,
+ });
+ });
+
+ it("offers to skip when creation is open", async () => {
+ await renderPage(<InvitationsPage />);
+
+ expect(skipForNow()).toBeInTheDocument();
+ });
+
+ it("hides the skip from a restricted user", async () => {
+ config.mockReturnValue({
+ data: { disableWorkspaceCreation: true },
+ isPending: false,
+ });
+
+ await renderPage(<InvitationsPage />);
+
+ // Skipping exists to go and create a workspace instead. Restricted,
+ // it leads away from the invitation with no way back to it.
+ expect(skipForNow()).not.toBeInTheDocument();
+ // The invitation itself is still there to accept.
+ expect(screen.getByText("Kaneo")).toBeInTheDocument();
+ });
+
+ it("keeps the skip for an instance admin", async () => {
+ config.mockReturnValue({
+ data: { disableWorkspaceCreation: true },
+ isPending: false,
+ });
+ getSession.mockResolvedValue({
+ data: { user: { id: "u1", role: "admin" } },
+ error: null,
+ });
+
+ await renderPage(<InvitationsPage />);
+
+ expect(skipForNow()).toBeInTheDocument();
+ });
+
+ it("waits for the config rather than offering a skip it will withdraw", async () => {
+ config.mockReturnValue({ data: undefined, isPending: true });
+
+ await renderPage(<InvitationsPage />);
+
+ expect(skipForNow()).not.toBeInTheDocument();
+ });
+
+ it("offers the skip when the config request fails", async () => {
+ // Settled with no data is an error, not a restriction, and this page
+ // has no view to fall back to.
+ config.mockReturnValue({ data: undefined, isPending: false });
+
+ await renderPage(<InvitationsPage />);
+
+ expect(skipForNow()).toBeInTheDocument();
+ });
+ });
+});
diff --git a/apps/web/src/routes/_layout/_authenticated/invitations.tsx b/apps/web/src/routes/_layout/_authenticated/invitations.tsx
index e92452d1a..4a3dfec71 100644
--- a/apps/web/src/routes/_layout/_authenticated/invitations.tsx
+++ b/apps/web/src/routes/_layout/_authenticated/invitations.tsx
@@ -16,6 +16,7 @@ import {
TableRow,
} from "@/components/ui/table";
import { usePendingInvitations } from "@/hooks/queries/invitation/use-pending-invitations";
+import useWorkspaceCreationAccess from "@/hooks/use-workspace-creation-access";
import { authClient } from "@/lib/auth-client";
import { cn } from "@/lib/cn";
import { formatDateMedium } from "@/lib/format";
@@ -33,6 +34,12 @@ function InvitationsPage() {
const [acceptingId, setAcceptingId] = useState<string | null>(null);
const [rejectingId, setRejectingId] = useState<string | null>(null);
const { user } = useAuth();
+ // The same rule the onboarding screen applies, so this page cannot offer a
+ // route into a form that screen would refuse to show. It also covers the
+ // stale session role: the first administrator of an instance is promoted
+ // after their session is cached, and deciding on that would hide the only
+ // two controls on the page from the one user entitled to both.
+ const { canCreateWorkspace } = useWorkspaceCreationAccess();
const handleSkip = () => {
if (!user?.name) {
@@ -171,9 +178,14 @@ function InvitationsPage() {
<p className="text-sm text-muted-foreground max-w-md mb-6">
{t("invitations:noPendingDescription")}
</p>
- <Button onClick={handleSkip} variant="default">
- {t("invitations:continueToSetup")}
- </Button>
+ {canCreateWorkspace && (
+ // Without creation rights there is no setup to continue to,
+ // and this would bounce back to the onboarding screen that
+ // sent the user here.
+ <Button onClick={handleSkip} variant="default">
+ {t("invitations:continueToSetup")}
+ </Button>
+ )}
</div>
) : (
<div className="space-y-6">
@@ -274,15 +286,20 @@ function InvitationsPage() {
</TableBody>
</Table>
</div>
- <div className="flex justify-center pt-2">
- <Button
- variant="ghost"
- onClick={handleSkip}
- className="text-muted-foreground hover:text-foreground"
- >
- {t("invitations:skipForNow")}
- </Button>
- </div>
+ {canCreateWorkspace && (
+ // Skipping exists to go and create your own workspace. When
+ // only instance admins may create one, it leads to a screen
+ // with nothing to do and no way back to this invitation.
+ <div className="flex justify-center pt-2">
+ <Button
+ variant="ghost"
+ onClick={handleSkip}
+ className="text-muted-foreground hover:text-foreground"
+ >
+ {t("invitations:skipForNow")}
+ </Button>
+ </div>
+ )}
</div>
)}
</div>
diff --git a/i18n/az-AZ.json b/i18n/az-AZ.json
index d3c17f3a7..304a5fbf8 100644
--- a/i18n/az-AZ.json
+++ b/i18n/az-AZ.json
@@ -320,7 +320,10 @@
},
"validation": {
"workspaceNameRequired": "İş sahəsinin adı tələb olunur"
- }
+ },
+ "restrictedSubtitle": "Burada yalnız instans administratoru iş sahəsi yarada bilər. Sizi dəvət etməsini xahiş edin, sonra bu səhifəni yeniləyin.",
+ "restrictedCheckInvitations": "Dəvətlərə bax",
+ "restrictedTitle": "Dəvət lazımdır"
},
"profileSetup": {
"pageTitle": "Profili tamamla",
diff --git a/i18n/de-DE.json b/i18n/de-DE.json
index ef0d32edc..2196ee4af 100644
--- a/i18n/de-DE.json
+++ b/i18n/de-DE.json
@@ -320,7 +320,10 @@
},
"validation": {
"workspaceNameRequired": "Workspace-Name ist erforderlich"
- }
+ },
+ "restrictedSubtitle": "Nur eine Instanzadministration kann hier Workspaces anlegen. Bitte um eine Einladung und lade diese Seite neu.",
+ "restrictedCheckInvitations": "Einladungen prüfen",
+ "restrictedTitle": "Du brauchst eine Einladung"
},
"profileSetup": {
"pageTitle": "Profil vervollständigen",
diff --git a/i18n/el-GR.json b/i18n/el-GR.json
index 20b1a0cb2..01f47dbbb 100644
--- a/i18n/el-GR.json
+++ b/i18n/el-GR.json
@@ -320,7 +320,10 @@
},
"validation": {
"workspaceNameRequired": "Το όνομα χώρου εργασίας είναι υποχρεωτικό"
- }
+ },
+ "restrictedSubtitle": "Μόνο ένας διαχειριστής της εγκατάστασης μπορεί να δημιουργεί χώρους εργασίας εδώ. Ζητήστε πρόσκληση και ανανεώστε τη σελίδα.",
+ "restrictedCheckInvitations": "Έλεγχος προσκλήσεων",
+ "restrictedTitle": "Χρειάζεστε πρόσκληση"
},
"profileSetup": {
"pageTitle": "Ολοκλήρωση προφίλ",
diff --git a/i18n/en-US.json b/i18n/en-US.json
index 34589dbc3..2f0bb000c 100644
--- a/i18n/en-US.json
+++ b/i18n/en-US.json
@@ -312,6 +312,9 @@
"descriptionPlaceholder": "What does your team work on?",
"creating": "Creating...",
"createWorkspace": "Create workspace",
+ "restrictedTitle": "You need an invitation",
+ "restrictedSubtitle": "Only an instance administrator can create workspaces here. Ask one to invite you, then reload this page.",
+ "restrictedCheckInvitations": "Check invitations",
"workspaceCreatedTitle": "Workspace created",
"redirectingToWorkspace": "Taking you to <name>{{name}}</name>...",
"toast": {
diff --git a/i18n/es-ES.json b/i18n/es-ES.json
index 672d9309a..3f99d6dd2 100644
--- a/i18n/es-ES.json
+++ b/i18n/es-ES.json
@@ -320,7 +320,10 @@
},
"validation": {
"workspaceNameRequired": "El nombre del espacio de trabajo es obligatorio"
- }
+ },
+ "restrictedSubtitle": "Aquí solo un administrador de la instancia puede crear espacios de trabajo. Pide que te inviten y recarga esta página.",
+ "restrictedCheckInvitations": "Ver invitaciones",
+ "restrictedTitle": "Necesitas una invitación"
},
"profileSetup": {
"pageTitle": "Completar Perfil",
diff --git a/i18n/fr-FR.json b/i18n/fr-FR.json
index d9ab613df..309172cb8 100644
--- a/i18n/fr-FR.json
+++ b/i18n/fr-FR.json
@@ -320,7 +320,10 @@
},
"validation": {
"workspaceNameRequired": "Le nom de l'espace de travail est requis"
- }
+ },
+ "restrictedSubtitle": "Seul un administrateur de l'instance peut créer des espaces de travail ici. Demandez une invitation, puis rechargez cette page.",
+ "restrictedCheckInvitations": "Voir les invitations",
+ "restrictedTitle": "Vous avez besoin d'une invitation"
},
"profileSetup": {
"pageTitle": "Compléter le profil",
diff --git a/i18n/hi-IN.json b/i18n/hi-IN.json
index 8340f681d..dce88612a 100644
--- a/i18n/hi-IN.json
+++ b/i18n/hi-IN.json
@@ -320,7 +320,10 @@
},
"validation": {
"workspaceNameRequired": "वर्कस्पेस का नाम आवश्यक है"
- }
+ },
+ "restrictedSubtitle": "यहाँ केवल इंस्टेंस व्यवस्थापक ही कार्यक्षेत्र बना सकता है। आमंत्रण के लिए कहें, फिर यह पृष्ठ पुनः लोड करें।",
+ "restrictedCheckInvitations": "आमंत्रण देखें",
+ "restrictedTitle": "आपको आमंत्रण चाहिए"
},
"profileSetup": {
"pageTitle": "प्रोफ़ाइल पूरा करें",
diff --git a/i18n/id-ID.json b/i18n/id-ID.json
index e2b1adb07..e1d90a198 100644
--- a/i18n/id-ID.json
+++ b/i18n/id-ID.json
@@ -320,7 +320,10 @@
},
"validation": {
"workspaceNameRequired": "Nama ruang kerja wajib diisi"
- }
+ },
+ "restrictedSubtitle": "Hanya administrator instance yang dapat membuat ruang kerja di sini. Minta undangan, lalu muat ulang halaman ini.",
+ "restrictedCheckInvitations": "Lihat undangan",
+ "restrictedTitle": "Anda perlu undangan"
},
"profileSetup": {
"pageTitle": "Lengkapi Profil",
diff --git a/i18n/it-IT.json b/i18n/it-IT.json
index 01e366ec7..f9906886a 100644
--- a/i18n/it-IT.json
+++ b/i18n/it-IT.json
@@ -320,7 +320,10 @@
},
"validation": {
"workspaceNameRequired": "Il nome del workspace è obbligatorio"
- }
+ },
+ "restrictedSubtitle": "Qui solo un amministratore dell'istanza può creare spazi di lavoro. Chiedi un invito e ricarica questa pagina.",
+ "restrictedCheckInvitations": "Controlla gli inviti",
+ "restrictedTitle": "Ti serve un invito"
},
"profileSetup": {
"pageTitle": "Completa Profilo",
diff --git a/i18n/ja-JP.json b/i18n/ja-JP.json
index 03a1378c7..e9bd3ff53 100644
--- a/i18n/ja-JP.json
+++ b/i18n/ja-JP.json
@@ -320,7 +320,10 @@
},
"validation": {
"workspaceNameRequired": "ワークスペース名を入力してください"
- }
+ },
+ "restrictedSubtitle": "このインスタンスでワークスペースを作成できるのは管理者だけです。招待を依頼してから、このページを再読み込みしてください。",
+ "restrictedCheckInvitations": "招待を確認",
+ "restrictedTitle": "招待が必要です"
},
"profileSetup": {
"pageTitle": "プロフィール設定",
diff --git a/i18n/ko-KR.json b/i18n/ko-KR.json
index bffa69301..50b0bf77a 100644
--- a/i18n/ko-KR.json
+++ b/i18n/ko-KR.json
@@ -320,7 +320,10 @@
},
"validation": {
"workspaceNameRequired": "워크스페이스 이름은 필수입니다"
- }
+ },
+ "restrictedSubtitle": "이 인스턴스에서는 관리자만 워크스페이스를 만들 수 있습니다. 초대를 요청한 뒤 이 페이지를 새로고침하세요.",
+ "restrictedCheckInvitations": "초대 확인",
+ "restrictedTitle": "초대가 필요합니다"
},
"profileSetup": {
"pageTitle": "프로필 완성",
diff --git a/i18n/mk-MK.json b/i18n/mk-MK.json
index 9947e596d..dff71e2d0 100644
--- a/i18n/mk-MK.json
+++ b/i18n/mk-MK.json
@@ -320,7 +320,10 @@
},
"validation": {
"workspaceNameRequired": "Името на работниот простор е задолжително"
- }
+ },
+ "restrictedSubtitle": "Овде само администратор на инстанцата може да создава работни простори. Побарајте покана и освежете ја страницата.",
+ "restrictedCheckInvitations": "Провери покани",
+ "restrictedTitle": "Ви треба покана"
},
"profileSetup": {
"pageTitle": "Заврши го профилот",
diff --git a/i18n/nl-NL.json b/i18n/nl-NL.json
index c57e618e8..bb42f6de2 100644
--- a/i18n/nl-NL.json
+++ b/i18n/nl-NL.json
@@ -320,7 +320,10 @@
},
"validation": {
"workspaceNameRequired": "Werkruimtenaam is verplicht"
- }
+ },
+ "restrictedSubtitle": "Alleen een instantiebeheerder kan hier workspaces aanmaken. Vraag om een uitnodiging en laad deze pagina opnieuw.",
+ "restrictedCheckInvitations": "Uitnodigingen bekijken",
+ "restrictedTitle": "Je hebt een uitnodiging nodig"
},
"profileSetup": {
"pageTitle": "Profiel Voltooien",
diff --git a/i18n/pl-PL.json b/i18n/pl-PL.json
index af9a1fc1e..27befcc80 100644
--- a/i18n/pl-PL.json
+++ b/i18n/pl-PL.json
@@ -320,7 +320,10 @@
},
"validation": {
"workspaceNameRequired": "Nazwa obszaru roboczego jest wymagana"
- }
+ },
+ "restrictedSubtitle": "Tutaj tylko administrator instancji może tworzyć przestrzenie robocze. Poproś o zaproszenie i odśwież tę stronę.",
+ "restrictedCheckInvitations": "Sprawdź zaproszenia",
+ "restrictedTitle": "Potrzebujesz zaproszenia"
},
"profileSetup": {
"pageTitle": "Uzupełnij profil",
diff --git a/i18n/pt-BR.json b/i18n/pt-BR.json
index dd394407d..5aa05c1e3 100644
--- a/i18n/pt-BR.json
+++ b/i18n/pt-BR.json
@@ -320,7 +320,10 @@
},
"validation": {
"workspaceNameRequired": "O nome do espaço de trabalho é obrigatório"
- }
+ },
+ "restrictedSubtitle": "Aqui apenas um administrador da instância pode criar espaços de trabalho. Peça um convite e recarregue esta página.",
+ "restrictedCheckInvitations": "Ver convites",
+ "restrictedTitle": "Você precisa de um convite"
},
"profileSetup": {
"pageTitle": "Completar perfil",
diff --git a/i18n/ru-RU.json b/i18n/ru-RU.json
index 97a07c882..a8f2024d0 100644
--- a/i18n/ru-RU.json
+++ b/i18n/ru-RU.json
@@ -320,7 +320,10 @@
},
"validation": {
"workspaceNameRequired": "Название рабочей области обязательно"
- }
+ },
+ "restrictedSubtitle": "Здесь создавать рабочие пространства может только администратор экземпляра. Попросите приглашение и обновите страницу.",
+ "restrictedCheckInvitations": "Проверить приглашения",
+ "restrictedTitle": "Нужно приглашение"
},
"profileSetup": {
"pageTitle": "Заполнение профиля",
diff --git a/i18n/schema.json b/i18n/schema.json
index 093fab032..bbf8f52d8 100644
--- a/i18n/schema.json
+++ b/i18n/schema.json
@@ -1225,6 +1225,15 @@
"createWorkspace": {
"type": "string"
},
+ "restrictedTitle": {
+ "type": "string"
+ },
+ "restrictedSubtitle": {
+ "type": "string"
+ },
+ "restrictedCheckInvitations": {
+ "type": "string"
+ },
"workspaceCreatedTitle": {
"type": "string"
},
@@ -1266,6 +1275,9 @@
"descriptionPlaceholder",
"creating",
"createWorkspace",
+ "restrictedTitle",
+ "restrictedSubtitle",
+ "restrictedCheckInvitations",
"workspaceCreatedTitle",
"redirectingToWorkspace",
"toast",
diff --git a/i18n/tr-TR.json b/i18n/tr-TR.json
index 6228075f8..287ef9b6e 100644
--- a/i18n/tr-TR.json
+++ b/i18n/tr-TR.json
@@ -320,7 +320,10 @@
},
"validation": {
"workspaceNameRequired": "Çalışma alanı adı gereklidir"
- }
+ },
+ "restrictedSubtitle": "Burada yalnızca örnek yöneticisi çalışma alanı oluşturabilir. Davet isteyin, ardından bu sayfayı yenileyin.",
+ "restrictedCheckInvitations": "Davetleri görüntüle",
+ "restrictedTitle": "Davet gerekiyor"
},
"profileSetup": {
"pageTitle": "Profili Tamamla",
diff --git a/i18n/uk-UA.json b/i18n/uk-UA.json
index f36112a82..02ba52f69 100644
--- a/i18n/uk-UA.json
+++ b/i18n/uk-UA.json
@@ -320,7 +320,10 @@
},
"validation": {
"workspaceNameRequired": "Назва робочого простору є обов'язковою"
- }
+ },
+ "restrictedSubtitle": "Тут створювати робочі простори може лише адміністратор інстансу. Попросіть запрошення й оновіть цю сторінку.",
+ "restrictedCheckInvitations": "Переглянути запрошення",
+ "restrictedTitle": "Потрібне запрошення"
},
"profileSetup": {
"pageTitle": "Заповнення профілю",
diff --git a/i18n/vi-VN.json b/i18n/vi-VN.json
index 94cf62eb7..a8969e1da 100644
--- a/i18n/vi-VN.json
+++ b/i18n/vi-VN.json
@@ -320,7 +320,10 @@
},
"validation": {
"workspaceNameRequired": "Cần có tên không gian làm việc"
- }
+ },
+ "restrictedSubtitle": "Tại đây chỉ quản trị viên hệ thống mới có thể tạo không gian làm việc. Hãy xin lời mời rồi tải lại trang này.",
+ "restrictedCheckInvitations": "Xem lời mời",
+ "restrictedTitle": "Bạn cần một lời mời"
},
"profileSetup": {
"pageTitle": "Hoàn tất hồ sơ",
diff --git a/i18n/zh-CN.json b/i18n/zh-CN.json
index 5c2595a7e..d34c9e652 100644
--- a/i18n/zh-CN.json
+++ b/i18n/zh-CN.json
@@ -320,7 +320,10 @@
},
"validation": {
"workspaceNameRequired": "工作区名称不能为空"
- }
+ },
+ "restrictedSubtitle": "在此实例中只有管理员可以创建工作区。请联系管理员邀请你,然后刷新此页面。",
+ "restrictedCheckInvitations": "查看邀请",
+ "restrictedTitle": "你需要一份邀请"
},
"profileSetup": {
"pageTitle": "完善资料",