Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Added a no store access screen to the dashboard (#14691)
Damian Legawiec86d4b93193e9
diff --git a/.changeset/dashboard-no-store-access.md b/.changeset/dashboard-no-store-access.mdnew file mode 100644index 0000000000..8834de242a--- /dev/null+++ b/.changeset/dashboard-no-store-access.md@@ -0,0 +1,6 @@+---+"@spree/dashboard": patch+"@spree/dashboard-core": patch+---++Added a "no store access" screen for admins who sign in without a role on any store, replacing the sign-in redirect loop they hit before. Hosts can replace the screen by registering on the new `no_store_access` slot (`NO_STORE_ACCESS_SLOT` and `NoStoreAccessSlotContext` from `@spree/dashboard-core`).diff --git a/docs/plans/6.0-admin-spa.md b/docs/plans/6.0-admin-spa.mdindex a6322d505c..9434c23036 100644--- a/docs/plans/6.0-admin-spa.md+++ b/docs/plans/6.0-admin-spa.md@@ -405,6 +405,9 @@ Slot naming convention: drop the `_partials` suffix from the Rails struct member**Page chrome (replaces `content_for` seams):**- `page.title`, `page.subtitle`, `page.actions`, `page.actions_dropdown`, `page.alerts`, `page.tabs` — consumed by `<PageHeader>` / `<PageTabs>`. Context: `{ resource, route }`.+**Sign-in:**+- `no_store_access` — replaces the screen shown to a signed-in admin who holds a role on no store. Context: `{ user, signOut }`. Name and context type exported from `@spree/dashboard-core` (`NO_STORE_ACCESS_SLOT`, `NoStoreAccessSlotContext`).+**Dashboard:**- `dashboard.sidebar`, `dashboard.analytics`diff --git a/packages/dashboard-core/src/lib/slot-registry.ts b/packages/dashboard-core/src/lib/slot-registry.tsindex 6ea8577a34..000dcac1b5 100644--- a/packages/dashboard-core/src/lib/slot-registry.ts+++ b/packages/dashboard-core/src/lib/slot-registry.ts@@ -1,3 +1,4 @@+import type { AdminUser } from '@spree/admin-sdk'import type { ComponentType } from 'react'import { useSyncExternalStore } from 'react'@@ -26,6 +27,23 @@ export interface SlotEntry<TContext = unknown> {if?: (ctx: TContext & SlotAmbientContext) => boolean}+// ============================================================================+// Built-in slot names shared with plugins+// ============================================================================++/**+ * The screen a signed-in admin sees when they hold a role on no store — not+ * yet invited to one, or removed from all of them. Registering an entry+ * replaces the built-in message, for example to render a different call to+ * action or send the user elsewhere from an effect.+ */+export const NO_STORE_ACCESS_SLOT = 'no_store_access'++export interface NoStoreAccessSlotContext {+ user: AdminUser+ signOut: () => Promise<void>+}+// ============================================================================// Registry — module-singleton keyed by slot name// ============================================================================diff --git a/packages/dashboard-core/src/locales/ar.json b/packages/dashboard-core/src/locales/ar.jsonindex 4c74e96d05..af02e5cea5 100644--- a/packages/dashboard-core/src/locales/ar.json+++ b/packages/dashboard-core/src/locales/ar.json@@ -125,6 +125,11 @@"title": "مرحبًا بعودتك"},"logout": "تسجيل الخروج",+ "no_store_access": {+ "description": "لقد سجّلت الدخول، لكن حسابك ليس عضوًا في أي متجر بعد. اطلب من مسؤول المتجر دعوتك، أو سجّل الدخول بحساب آخر.",+ "signed_in_as": "تم تسجيل الدخول باسم {{email}}",+ "title": "ليس لديك صلاحية الوصول إلى أي متجر"+ },"reset_password": {"confirm_password_label": "تأكيد كلمة المرور الجديدة","error": "حدث خطأ ما. يرجى المحاولة مرة أخرى.",diff --git a/packages/dashboard-core/src/locales/de.json b/packages/dashboard-core/src/locales/de.jsonindex 8de6d569b7..3302747e59 100644--- a/packages/dashboard-core/src/locales/de.json+++ b/packages/dashboard-core/src/locales/de.json@@ -125,6 +125,11 @@"title": "Willkommen zurück"},"logout": "Abmelden",+ "no_store_access": {+ "description": "Sie sind angemeldet, aber Ihr Konto gehört noch keinem Store an. Bitten Sie einen Store-Administrator um eine Einladung oder melden Sie sich mit einem anderen Konto an.",+ "signed_in_as": "Angemeldet als {{email}}",+ "title": "Sie haben keinen Zugriff auf einen Store"+ },"reset_password": {"confirm_password_label": "Neues Passwort bestätigen","error": "Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut.",diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.jsonindex 1f050dda9a..950e1f9f21 100644--- a/packages/dashboard-core/src/locales/en.json+++ b/packages/dashboard-core/src/locales/en.json@@ -125,6 +125,11 @@"title": "Welcome back"},"logout": "Sign out",+ "no_store_access": {+ "description": "You're signed in, but your account isn't a member of any store yet. Ask a store administrator to invite you, or sign in with a different account.",+ "signed_in_as": "Signed in as {{email}}",+ "title": "You don't have access to any store"+ },"reset_password": {"confirm_password_label": "Confirm new password","error": "Something went wrong. Please try again.",diff --git a/packages/dashboard-core/src/locales/es.json b/packages/dashboard-core/src/locales/es.jsonindex 9db2085bdd..251386f18a 100644--- a/packages/dashboard-core/src/locales/es.json+++ b/packages/dashboard-core/src/locales/es.json@@ -1696,6 +1696,11 @@"title": "Bienvenido de nuevo"},"logout": "Cerrar sesión",+ "no_store_access": {+ "description": "Iniciaste sesión, pero tu cuenta todavía no pertenece a ninguna tienda. Pedile a un administrador de la tienda que te invite o iniciá sesión con otra cuenta.",+ "signed_in_as": "Sesión iniciada como {{email}}",+ "title": "No tenés acceso a ninguna tienda"+ },"reset_password": {"confirm_password_label": "Confirmar nueva contraseña","error": "Algo salió mal. Volvé a intentar.",diff --git a/packages/dashboard-core/src/locales/fr.json b/packages/dashboard-core/src/locales/fr.jsonindex e31aaaf28f..15ad649a04 100644--- a/packages/dashboard-core/src/locales/fr.json+++ b/packages/dashboard-core/src/locales/fr.json@@ -125,6 +125,11 @@"title": "Bon retour"},"logout": "Se déconnecter",+ "no_store_access": {+ "description": "Vous êtes connecté, mais votre compte n'est encore membre d'aucune boutique. Demandez à un administrateur de boutique de vous inviter, ou connectez-vous avec un autre compte.",+ "signed_in_as": "Connecté en tant que {{email}}",+ "title": "Vous n'avez accès à aucune boutique"+ },"reset_password": {"confirm_password_label": "Confirmer le nouveau mot de passe","error": "Une erreur s'est produite. Veuillez réessayer.",diff --git a/packages/dashboard-core/src/locales/pl.json b/packages/dashboard-core/src/locales/pl.jsonindex fb96fbf205..1a5bea1d7c 100644--- a/packages/dashboard-core/src/locales/pl.json+++ b/packages/dashboard-core/src/locales/pl.json@@ -125,6 +125,11 @@"title": "Witaj ponownie"},"logout": "Wyloguj się",+ "no_store_access": {+ "description": "Jesteś zalogowany, ale Twoje konto nie należy jeszcze do żadnego sklepu. Poproś administratora sklepu o zaproszenie lub zaloguj się na inne konto.",+ "signed_in_as": "Zalogowano jako {{email}}",+ "title": "Nie masz dostępu do żadnego sklepu"+ },"reset_password": {"confirm_password_label": "Potwierdź nowe hasło","error": "Coś poszło nie tak. Spróbuj ponownie.",diff --git a/packages/dashboard-core/src/locales/zh-CN.json b/packages/dashboard-core/src/locales/zh-CN.jsonindex 46e73f07b5..598f4fdbbd 100644--- a/packages/dashboard-core/src/locales/zh-CN.json+++ b/packages/dashboard-core/src/locales/zh-CN.json@@ -125,6 +125,11 @@"title": "欢迎回来"},"logout": "退出登录",+ "no_store_access": {+ "description": "您已登录,但您的账户尚未加入任何店铺。请联系店铺管理员邀请您,或使用其他账户登录。",+ "signed_in_as": "当前登录账户:{{email}}",+ "title": "您无权访问任何店铺"+ },"reset_password": {"confirm_password_label": "确认新密码","error": "出了点问题,请重试。",diff --git a/packages/dashboard/src/components/spree/no-store-access.test.tsx b/packages/dashboard/src/components/spree/no-store-access.test.tsxnew file mode 100644index 0000000000..a6bbdbb25f--- /dev/null+++ b/packages/dashboard/src/components/spree/no-store-access.test.tsx@@ -0,0 +1,63 @@+import type { AdminUser } from '@spree/admin-sdk'+import {+ AuthContext,+ NO_STORE_ACCESS_SLOT,+ type NoStoreAccessSlotContext,+ registerSlot,+ removeSlot,+} from '@spree/dashboard-core'+import { ThemeProvider } from '@spree/dashboard-ui'+import type { ContextType } from 'react'+import { renderToStaticMarkup } from 'react-dom/server'+import { afterEach, describe, expect, it } from 'vitest'+import { Route as IndexRoute } from '../../routes/_authenticated/index'+import { NoStoreAccess } from './no-store-access'++const storelessUser = {+ id: 'admin_1',+ email: '[email protected]',+ stores: [],+ roles: [],+} as unknown as AdminUser++const signOut = async () => {}++function renderIndexRoute(user: AdminUser) {+ const IndexRedirect = IndexRoute.options.component!+ const auth = { user, logout: signOut } as unknown as NonNullable<ContextType<typeof AuthContext>>++ return renderToStaticMarkup(+ <ThemeProvider>+ <AuthContext.Provider value={auth}>+ <IndexRedirect />+ </AuthContext.Provider>+ </ThemeProvider>,+ )+}++describe('the no store access screen', () => {+ afterEach(() => removeSlot(NO_STORE_ACCESS_SLOT, 'create-store'))++ it('is what the index route renders for a user who holds no store', () => {+ const html = renderIndexRoute(storelessUser)++ expect(html).toContain('You don't have access to any store')+ expect(html).toContain('Signed in as [email protected]')+ expect(html).toContain('Sign out')+ })++ it('is replaced by a plugin registered on its slot', () => {+ function CreateStore({ user }: NoStoreAccessSlotContext) {+ return <a href="https://platform.example.com/new-store">Create a store for {user.email}</a>+ }+ registerSlot<NoStoreAccessSlotContext>(NO_STORE_ACCESS_SLOT, {+ id: 'create-store',+ component: CreateStore,+ })++ const html = renderToStaticMarkup(<NoStoreAccess user={storelessUser} signOut={signOut} />)++ expect(html).toContain('Create a store for [email protected]')+ expect(html).not.toContain('Sign out')+ })+})diff --git a/packages/dashboard/src/components/spree/no-store-access.tsx b/packages/dashboard/src/components/spree/no-store-access.tsxnew file mode 100644index 0000000000..2addbbc9a0--- /dev/null+++ b/packages/dashboard/src/components/spree/no-store-access.tsx@@ -0,0 +1,38 @@+import { NO_STORE_ACCESS_SLOT, type NoStoreAccessSlotContext, Slot } from '@spree/dashboard-core'+import { Button } from '@spree/dashboard-ui'+import { useTranslation } from 'react-i18next'++/**+ * Shown to a signed-in admin who holds a role on no store. Plugins replace the+ * built-in message by registering on the `no_store_access` slot.+ */+export function NoStoreAccess(context: NoStoreAccessSlotContext) {+ return (+ <Slot<NoStoreAccessSlotContext>+ name={NO_STORE_ACCESS_SLOT}+ context={context}+ fallback={<NoStoreAccessMessage {...context} />}+ />+ )+}++function NoStoreAccessMessage({ user, signOut }: NoStoreAccessSlotContext) {+ const { t } = useTranslation()++ return (+ <>+ <div className="flex flex-col gap-2">+ <h1 className="text-2xl font-bold">{t('admin.auth.no_store_access.title')}</h1>+ <p className="text-sm text-muted-foreground">+ {t('admin.auth.no_store_access.description')}+ </p>+ <p className="text-sm text-muted-foreground">+ {t('admin.auth.no_store_access.signed_in_as', { email: user.email })}+ </p>+ </div>+ <Button variant="outline" className="w-full" onClick={() => signOut()}>+ {t('admin.auth.logout')}+ </Button>+ </>+ )+}diff --git a/packages/dashboard/src/routes/_authenticated/index.tsx b/packages/dashboard/src/routes/_authenticated/index.tsxindex 1e109b89ee..ad69a45004 100644--- a/packages/dashboard/src/routes/_authenticated/index.tsx+++ b/packages/dashboard/src/routes/_authenticated/index.tsx@@ -1,42 +1,24 @@-import { adminClient, useAuth } from '@spree/dashboard-core'-import { createFileRoute, useNavigate } from '@tanstack/react-router'-import { useEffect } from 'react'+import { useAuth } from '@spree/dashboard-core'+import { createFileRoute, Navigate } from '@tanstack/react-router'+import { AuthShell } from '../../components/spree/auth-shell'+import { NoStoreAccess } from '../../components/spree/no-store-access'export const Route = createFileRoute('/_authenticated/')({component: IndexRedirect,})function IndexRedirect() {- const navigate = useNavigate()- const { user } = useAuth()+ const { user, logout } = useAuth()+ if (!user) return null- // The authenticated user's stores list is the source of the initial store —- // no request needed. The header-less `store.get()` fallback covers sessions- // whose cached user predates the stores field; it resolves the default- // store server-side.- useEffect(() => {- const firstStoreId = user?.stores?.[0]?.id- if (firstStoreId) {- navigate({ to: '/$storeId', params: { storeId: firstStoreId }, replace: true })- return- }+ const firstStoreId = user.stores[0]?.id+ if (firstStoreId) {+ return <Navigate to="/$storeId" params={{ storeId: firstStoreId }} replace />+ }- let cancelled = false- adminClient.store- .get()- .then((store) => {- if (!cancelled) navigate({ to: '/$storeId', params: { storeId: store.id }, replace: true })- })- .catch(() => {- // Nothing resolved a store — send them to login rather than leaving- // them on a blank page with no way out. A live session that merely hit- // a network blip lands back here after the redirect.- if (!cancelled) navigate({ to: '/login', replace: true })- })- return () => {- cancelled = true- }- }, [navigate, user])-- return null+ return (+ <AuthShell>+ <NoStoreAccess user={user} signOut={logout} />+ </AuthShell>+ )}diff --git a/spree/api/app/controllers/spree/api/v3/admin/me_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/me_controller.rbindex 31ef85ab6f..8f5fa9290a 100644--- a/spree/api/app/controllers/spree/api/v3/admin/me_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/me_controller.rb@@ -58,6 +58,17 @@ module Spree)end+ # /me describes the signed-in user rather than a store, and the+ # dashboard reads it before any store is selected. A user who holds+ # no role on any store (not yet given one, or removed from all of+ # them) must still reach it, or they cannot finish signing in. A+ # request that names a store keeps the membership check.+ def require_store_membership!+ return true if store_id_header.nil?++ super+ end+def permitted_paramsparams.permit(:selected_locale, :first_name, :last_name, :avatar)enddiff --git a/spree/api/spec/controllers/concerns/spree/api/v3/admin/store_context_spec.rb b/spree/api/spec/controllers/concerns/spree/api/v3/admin/store_context_spec.rbindex 0760f8965f..f96d6459aa 100644--- a/spree/api/spec/controllers/concerns/spree/api/v3/admin/store_context_spec.rb+++ b/spree/api/spec/controllers/concerns/spree/api/v3/admin/store_context_spec.rb@@ -55,6 +55,17 @@ RSpec.describe Spree::Api::V3::Admin::TaxCategoriesController, type: :controllerendend+ context 'without the header, as an admin who holds no role on any store' do+ let(:admin_user) { create(:admin_user, :without_admin_role) }++ it 'returns 403 access_denied rather than resolving the default store' do+ get :index, as: :json++ expect(response).to have_http_status(:forbidden)+ expect(json_response['error']['code']).to eq('access_denied')+ end+ end+context 'without the header' do# No Spree::Deprecation here by design: /me and the auth endpoints# structurally cannot send the header, and deprecations-as-errors woulddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/me_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/me_controller_spec.rbindex 093011ca7a..374cdc33eb 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/me_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/me_controller_spec.rb@@ -123,6 +123,32 @@ RSpec.describe Spree::Api::V3::Admin::MeController, type: :controller doexpect(json_response['user']).to have_key('selected_locale')end+ context 'as an admin who holds no role on any store' do+ let(:storeless_user) { create(:admin_user, :without_admin_role) }+ let(:headers) do+ { 'Authorization' => "Bearer #{Spree::Api::V3::TestingSupport.generate_jwt(storeless_user, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN)}" }+ end++ it 'returns the user with no stores, roles or permission keys' do+ subject+ expect(response).to have_http_status(:ok)+ expect(json_response['user']['email']).to eq(storeless_user.email)+ expect(json_response['user']['stores']).to eq([])+ expect(json_response['user']['roles']).to eq([])+ expect(json_response['permission_keys']).to eq([])+ end++ context 'when the request names a store' do+ before { request.headers['X-Spree-Store-Id'] = store.prefixed_id }++ it 'returns forbidden' do+ subject+ expect(response).to have_http_status(:forbidden)+ expect(json_response['error']['code']).to eq('access_denied')+ end+ end+ end+context 'without authentication' dolet(:headers) { {} }