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
Add CanCanCan-based permission checks to admin SPA
Damian Legawiec43e6ca7c6648
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex f59b44e7cb..c19c45d89f 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -17,6 +17,27 @@ export interface LoginCredentials {email: string;password: string;}++export interface PermissionRule {+ /** true for `can`, false for `cannot` */+ allow: boolean;+ /** Action names, e.g. ["read", "update"] or ["manage"] */+ actions: string[];+ /** Subject class names, e.g. ["Spree::Product"] or ["all"] */+ subjects: string[];+ /** Whether the server rule has per-record conditions. If true, the action may be denied at the record level and the SPA should expect possible 403. */+ has_conditions: boolean;+}++export interface MeResponse {+ user: {+ id: string;+ email: string;+ first_name: string | null;+ last_name: string | null;+ };+ permissions: PermissionRule[];+}import type { Store, Product, Order, Asset, Category, TaxCategory } from './types';import type {StoreUpdateParams,@@ -51,6 +72,16 @@ export class AdminClient {this.request<AuthTokens>('POST', '/auth/refresh', { ...options, body: params }),};+ // ============================================+ // Current admin user + permissions+ // ============================================++ readonly me = {+ /** Get the current admin user profile and their serialized permissions. */+ show: (options?: RequestOptions): Promise<MeResponse> =>+ this.request<MeResponse>('GET', '/me', options),+ };+// ============================================// Store Settings// ============================================diff --git a/packages/admin-sdk/src/index.ts b/packages/admin-sdk/src/index.tsindex 22fe6b70c3..8bb169fb61 100644--- a/packages/admin-sdk/src/index.ts+++ b/packages/admin-sdk/src/index.ts@@ -4,6 +4,7 @@ export type { AdminClientConfig, Client } from './client';// Admin client class (for advanced use / subclassing)export { AdminClient } from './admin-client';+export type { AuthTokens, LoginCredentials, PermissionRule, MeResponse } from './admin-client';// Request infrastructure (re-export from sdk-core)export { SpreeError } from '@spree/sdk-core';diff --git a/packages/admin/src/components/app-sidebar.tsx b/packages/admin/src/components/app-sidebar.tsxindex e4ada08a46..96064a5639 100644--- a/packages/admin/src/components/app-sidebar.tsx+++ b/packages/admin/src/components/app-sidebar.tsx@@ -14,12 +14,16 @@ import { NavMain } from '@/components/nav-main'import { NavUser } from '@/components/nav-user'import { StoreSwitcher } from '@/components/store-switcher'import { Sidebar, SidebarContent, SidebarFooter, SidebarHeader } from '@/components/ui/sidebar'+import { Subject, type SubjectName } from '@/lib/permissions'+import { type Permissions, usePermissions } from '@/providers/permission-provider'export type NavItem = {title: stringurl: stringicon: LucideIcon- items?: { title: string; url: string }[]+ /** CanCanCan subject required to see this item. If omitted, item is always visible. */+ subject?: SubjectName+ items?: { title: string; url: string; subject?: SubjectName }[]}function buildNavigation(storeId: string): NavItem[] {@@ -34,29 +38,33 @@ function buildNavigation(storeId: string): NavItem[] {title: 'Orders',url: `${p}/orders`,icon: InboxIcon,- items: [{ title: 'Draft Orders', url: `${p}/orders/drafts` }],+ subject: Subject.Order,+ items: [{ title: 'Draft Orders', url: `${p}/orders/drafts`, subject: Subject.Order }],},{title: 'Products',url: `${p}/products`,icon: PackageIcon,+ subject: Subject.Product,items: [- { title: 'Price Lists', url: `${p}/products/price-lists` },- { title: 'Stock', url: `${p}/products/stock` },- { title: 'Categories', url: `${p}/products/categories` },- { title: 'Options', url: `${p}/products/options` },+ { title: 'Price Lists', url: `${p}/products/price-lists`, subject: Subject.Product },+ { title: 'Stock', url: `${p}/products/stock`, subject: Subject.StockLocation },+ { title: 'Categories', url: `${p}/products/categories`, subject: Subject.Taxon },+ { title: 'Options', url: `${p}/products/options`, subject: Subject.OptionType },],},{title: 'Customers',url: `${p}/customers`,icon: UsersIcon,+ subject: Subject.Customer,},{title: 'Promotions',url: `${p}/promotions`,icon: TagIcon,- items: [{ title: 'Gift Cards', url: `${p}/promotions/gift-cards` }],+ subject: Subject.Promotion,+ items: [{ title: 'Gift Cards', url: `${p}/promotions/gift-cards`, subject: Subject.Promotion }],},{title: 'Reports',@@ -72,21 +80,36 @@ function buildBottomNavigation(storeId: string): NavItem[] {title: 'Settings',url: `/${storeId}/settings`,icon: SettingsIcon,+ subject: Subject.Store,},]}+/** Filter nav items by permission: hide items the user can't `read`. */+function filterByPermissions(items: NavItem[], permissions: Permissions): NavItem[] {+ return items+ .filter((item) => !item.subject || permissions.can('read', item.subject))+ .map((item) => ({+ ...item,+ items: item.items?.filter((sub) => !sub.subject || permissions.can('read', sub.subject)),+ }))+}+export function AppSidebar(props: ComponentProps<typeof Sidebar>) {const { storeId } = useParams({ strict: false }) as { storeId?: string }+ const { permissions } = usePermissions()const id = storeId || 'default'+ const navItems = filterByPermissions(buildNavigation(id), permissions)+ const bottomItems = filterByPermissions(buildBottomNavigation(id), permissions)+return (<Sidebar collapsible="icon" {...props}><SidebarHeader><StoreSwitcher /></SidebarHeader><SidebarContent>- <NavMain items={buildNavigation(id)} bottomItems={buildBottomNavigation(id)} />+ <NavMain items={navItems} bottomItems={bottomItems} /></SidebarContent><SidebarFooter><NavUser />diff --git a/packages/admin/src/components/can.tsx b/packages/admin/src/components/can.tsxnew file mode 100644index 0000000000..7e0b168758--- /dev/null+++ b/packages/admin/src/components/can.tsx@@ -0,0 +1,30 @@+import type { ReactNode } from 'react'+import { usePermissions } from '@/providers/permission-provider'+import type { ActionName, SubjectName } from '@/lib/permissions'++interface CanProps {+ /** Action name (e.g. "update", "destroy", "manage") */+ I: ActionName+ /** Subject class name (e.g. "Spree::Product") */+ a: SubjectName+ children: ReactNode+ fallback?: ReactNode+}++/**+ * Declarative permission check. Renders `children` if the current user+ * can perform `I` on `a`, otherwise renders `fallback` (or nothing).+ *+ * Example:+ * <Can I="destroy" a="Spree::Product">+ * <Button onClick={handleDelete}>Delete</Button>+ * </Can>+ *+ * Note: This is purely for UX. The backend still enforces CanCanCan+ * `authorize!` on every request — never rely on the frontend check+ * for security.+ */+export function Can({ I, a, children, fallback = null }: CanProps) {+ const { permissions } = usePermissions()+ return <>{permissions.can(I, a) ? children : fallback}</>+}diff --git a/packages/admin/src/lib/permissions.ts b/packages/admin/src/lib/permissions.tsnew file mode 100644index 0000000000..0e0ea52493--- /dev/null+++ b/packages/admin/src/lib/permissions.ts@@ -0,0 +1,38 @@+/**+ * CanCanCan subject class names — use these constants instead of raw strings+ * to avoid typos in permission checks.+ *+ * Matches the Ruby class names serialized by the /api/v3/admin/me endpoint.+ */+export const Subject = {+ All: 'all',+ Product: 'Spree::Product',+ Variant: 'Spree::Variant',+ Order: 'Spree::Order',+ Customer: 'Spree::User',+ AdminUser: 'Spree::AdminUser',+ Store: 'Spree::Store',+ Taxon: 'Spree::Taxon',+ Taxonomy: 'Spree::Taxonomy',+ OptionType: 'Spree::OptionType',+ OptionValue: 'Spree::OptionValue',+ TaxCategory: 'Spree::TaxCategory',+ PaymentMethod: 'Spree::PaymentMethod',+ ShippingMethod: 'Spree::ShippingMethod',+ StockLocation: 'Spree::StockLocation',+ Promotion: 'Spree::Promotion',+ Wishlist: 'Spree::Wishlist',+} as const++export type SubjectName = (typeof Subject)[keyof typeof Subject] | string++/** CanCanCan standard actions */+export const Action = {+ Manage: 'manage',+ Read: 'read',+ Create: 'create',+ Update: 'update',+ Destroy: 'destroy',+} as const++export type ActionName = (typeof Action)[keyof typeof Action] | stringdiff --git a/packages/admin/src/main.tsx b/packages/admin/src/main.tsxindex ef8861ef5f..7cd2574540 100644--- a/packages/admin/src/main.tsx+++ b/packages/admin/src/main.tsx@@ -6,21 +6,25 @@ import { TooltipProvider } from '@/components/ui/tooltip'import { useAuth } from '@/hooks/use-auth'import { queryClient } from '@/lib/query-client'import { AuthProvider } from '@/providers/auth-provider'+import { PermissionProvider, usePermissions } from '@/providers/permission-provider'import { router } from '@/router'import './index.css'function InnerApp() {const auth = useAuth()- return <RouterProvider router={router} context={{ auth }} />+ const { permissions } = usePermissions()+ return <RouterProvider router={router} context={{ auth, permissions }} />}createRoot(document.getElementById('root')!).render(<StrictMode><QueryClientProvider client={queryClient}><AuthProvider>- <TooltipProvider>- <InnerApp />- </TooltipProvider>+ <PermissionProvider>+ <TooltipProvider>+ <InnerApp />+ </TooltipProvider>+ </PermissionProvider></AuthProvider></QueryClientProvider></StrictMode>,diff --git a/packages/admin/src/providers/permission-provider.tsx b/packages/admin/src/providers/permission-provider.tsxnew file mode 100644index 0000000000..4443694d13--- /dev/null+++ b/packages/admin/src/providers/permission-provider.tsx@@ -0,0 +1,118 @@+import type { PermissionRule } from '@spree/admin-sdk'+import { createContext, type ReactNode, useContext, useEffect, useMemo, useState } from 'react'+import { adminClient } from '@/client'+import { useAuth } from '@/hooks/use-auth'+import type { ActionName, SubjectName } from '@/lib/permissions'++/**+ * Matcher that mirrors CanCanCan semantics:+ * - `manage` action matches any action+ * - `all` subject matches any subject+ * - Later rules override earlier rules (last-matching-wins)+ *+ * Per-record conditions are NOT evaluated — they stay on the server. The+ * `isConditional` flag indicates that a rule may still be rejected at the+ * per-record level, so the UI should expect possible 403 from the API.+ */+export interface Permissions {+ can: (action: ActionName, subject: SubjectName) => boolean+ cannot: (action: ActionName, subject: SubjectName) => boolean+ /** True if the matching rule has per-record conditions. Caller should expect possible 403. */+ isConditional: (action: ActionName, subject: SubjectName) => boolean+}++interface PermissionContextValue {+ permissions: Permissions+ rules: PermissionRule[]+ isLoading: boolean+}++const PermissionContext = createContext<PermissionContextValue | null>(null)++function ruleMatches(rule: PermissionRule, action: string, subject: string): boolean {+ const actionMatch = rule.actions.includes(action) || rule.actions.includes('manage')+ const subjectMatch = rule.subjects.includes(subject) || rule.subjects.includes('all')+ return actionMatch && subjectMatch+}++export function buildPermissions(rules: PermissionRule[]): Permissions {+ const can = (action: ActionName, subject: SubjectName): boolean => {+ // Walk rules in order — later matching rules override earlier ones+ let allowed = false+ for (const rule of rules) {+ if (ruleMatches(rule, action, subject)) {+ allowed = rule.allow+ }+ }+ return allowed+ }++ return {+ can,+ cannot: (action, subject) => !can(action, subject),+ isConditional: (action, subject) => {+ let conditional = false+ for (const rule of rules) {+ if (ruleMatches(rule, action, subject) && rule.allow && rule.has_conditions) {+ conditional = true+ }+ }+ return conditional+ },+ }+}++/** Empty permissions that deny everything — used before rules are loaded. */+const EMPTY_PERMISSIONS: Permissions = {+ can: () => false,+ cannot: () => true,+ isConditional: () => false,+}++export function PermissionProvider({ children }: { children: ReactNode }) {+ const { isAuthenticated } = useAuth()+ const [rules, setRules] = useState<PermissionRule[]>([])+ const [isLoading, setIsLoading] = useState(false)++ useEffect(() => {+ if (!isAuthenticated) {+ setRules([])+ return+ }++ let cancelled = false+ setIsLoading(true)+ adminClient.me+ .show()+ .then((res) => {+ if (!cancelled) setRules(res.permissions)+ })+ .catch(() => {+ if (!cancelled) setRules([])+ })+ .finally(() => {+ if (!cancelled) setIsLoading(false)+ })++ return () => {+ cancelled = true+ }+ }, [isAuthenticated])++ const permissions = useMemo(+ () => (rules.length > 0 ? buildPermissions(rules) : EMPTY_PERMISSIONS),+ [rules],+ )++ return (+ <PermissionContext.Provider value={{ permissions, rules, isLoading }}>+ {children}+ </PermissionContext.Provider>+ )+}++export function usePermissions(): PermissionContextValue {+ const ctx = useContext(PermissionContext)+ if (!ctx) throw new Error('usePermissions must be used within a PermissionProvider')+ return ctx+}diff --git a/packages/admin/src/router.tsx b/packages/admin/src/router.tsxindex 28ee8449af..e67922a487 100644--- a/packages/admin/src/router.tsx+++ b/packages/admin/src/router.tsx@@ -1,10 +1,12 @@import { createRouter } from '@tanstack/react-router'+import type { Permissions } from '@/providers/permission-provider'import { routeTree } from './routeTree.gen'export const router = createRouter({routeTree,context: {auth: undefined!,+ permissions: undefined! as Permissions,},})diff --git a/packages/admin/src/routes/__root.tsx b/packages/admin/src/routes/__root.tsxindex 25a58a0b9f..dfe16996d1 100644--- a/packages/admin/src/routes/__root.tsx+++ b/packages/admin/src/routes/__root.tsx@@ -1,11 +1,13 @@import { createRootRouteWithContext, Outlet } from '@tanstack/react-router'import { Toaster } from 'sonner'+import type { Permissions } from '@/providers/permission-provider'interface RouterContext {auth: {isAuthenticated: booleantoken: string | null}+ permissions: Permissions}export const Route = createRootRouteWithContext<RouterContext>()({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.rbnew file mode 100644index 0000000000..3826692744--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/me_controller.rb@@ -0,0 +1,67 @@+module Spree+ module Api+ module V3+ module Admin+ class MeController < Admin::BaseController+ # GET /api/v3/admin/me+ # Returns the current admin user along with a serialized representation+ # of their permissions (derived from CanCanCan rules). The SPA uses+ # the permissions list to decide which UI elements to show or hide.+ # The actual authorization check is still enforced server-side by+ # CanCanCan — the SPA list is purely for UX.+ def show+ render json: {+ user: admin_user_serializer.new(current_user, params: serializer_params).to_h,+ permissions: serialize_permissions(current_ability)+ }+ end++ private++ # Serializes CanCanCan's rules into a flat, JSON-safe list of permission rules.+ #+ # - Rule order is preserved so the frontend matcher can apply+ # CanCanCan's "last matching rule wins" semantics.+ # - Per-record conditions are NOT serialized (they often reference+ # scopes or blocks that don't translate to JSON). The frontend+ # receives `has_conditions: true` as a hint that the action might+ # be denied at the per-record level — in practice the SPA shows+ # the action optimistically and handles 403 from the API.+ def serialize_permissions(ability)+ ability.send(:rules).map do |rule|+ {+ allow: rule.base_behavior,+ actions: Array(rule.actions).map(&:to_s),+ subjects: Array(rule.subjects).map { |s| s.is_a?(Class) ? s.name : s.to_s },+ has_conditions: rule_has_conditions?(rule)+ }+ end+ end++ def rule_has_conditions?(rule)+ return true if rule.block.present?+ conditions = rule.conditions+ return false if conditions.nil?+ return !conditions.empty? if conditions.respond_to?(:empty?)++ true+ end++ def admin_user_serializer+ Spree.api.admin_admin_user_serializer+ end++ def serializer_params+ {+ store: current_store,+ locale: current_locale,+ currency: current_currency,+ user: current_user,+ includes: []+ }+ end+ end+ end+ end+ end+enddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex 79ed37f3dc..735d4bb581 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -95,6 +95,9 @@ Spree::Core::Engine.add_routes dopost 'auth/login', to: 'auth#create'post 'auth/refresh', to: 'auth#refresh'+ # Current admin user + permissions (for UI permission checks)+ get 'me', to: 'me#show'+# Store Settingsresource :store, only: [:show, :update], controller: 'store'diff --git a/spree/api/lib/spree/api/openapi/schema_helper.rb b/spree/api/lib/spree/api/openapi/schema_helper.rbindex 0ddf0627cb..648142c693 100644--- a/spree/api/lib/spree/api/openapi/schema_helper.rb+++ b/spree/api/lib/spree/api/openapi/schema_helper.rb@@ -86,6 +86,26 @@ module Spree},required: %w[token refresh_token user]},+ PermissionRule: {+ type: :object,+ description: 'A single permission rule (CanCanCan rule). Rules are applied in order, last-matching-wins.',+ properties: {+ allow: { type: :boolean, description: 'true for `can`, false for `cannot`' },+ actions: { type: :array, items: { type: :string }, description: 'Action names, e.g. ["read", "update"] or ["manage"]' },+ subjects: { type: :array, items: { type: :string }, description: 'Subject class names, e.g. ["Spree::Product"] or ["all"]' },+ has_conditions: { type: :boolean, description: 'True if the server-side rule has per-record conditions. The SPA shows the action optimistically and handles 403 from the API.' }+ },+ required: %w[allow actions subjects has_conditions]+ },+ MeResponse: {+ type: :object,+ description: 'Current admin user profile and serialized permissions',+ properties: {+ user: { '$ref' => '#/components/schemas/AdminUser' },+ permissions: { type: :array, items: { '$ref' => '#/components/schemas/PermissionRule' } }+ },+ required: %w[user permissions]+ },CheckoutRequirement: {type: :object,properties: {diff --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.rbnew file mode 100644index 0000000000..04fda0b457--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/me_controller_spec.rb@@ -0,0 +1,73 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::MeController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ before { request.headers.merge!(headers) }++ describe 'GET #show' do+ subject { get :show, as: :json }++ it 'returns ok' do+ subject+ expect(response).to have_http_status(:ok)+ end++ it 'does not raise accessing the internal CanCanCan rules' do+ # Regression: `Spree::Ability#rules` is protected in cancancan 3.x —+ # the controller must use `send(:rules)` to serialize them. If this+ # test fails with a 500, the fix has been undone.+ expect { subject }.not_to raise_error+ expect(response.status).to eq(200)+ expect(response.body).to include('"permissions"')+ end++ it 'returns the current admin user' do+ subject+ expect(json_response['user']).to be_present+ expect(json_response['user']['email']).to eq(admin_user.email)+ end++ it 'returns an array of permissions' do+ subject+ expect(json_response['permissions']).to be_an(Array)+ expect(json_response['permissions']).not_to be_empty+ end++ it 'serializes each rule with allow, actions, subjects and has_conditions' do+ subject+ rule = json_response['permissions'].first+ expect(rule.keys).to match_array(%w[allow actions subjects has_conditions])+ expect(rule['allow']).to be_in([true, false])+ expect(rule['actions']).to be_an(Array)+ expect(rule['subjects']).to be_an(Array)+ expect(rule['has_conditions']).to be_in([true, false])+ end++ it 'preserves rule order matching Spree::Ability' do+ subject+ ability = Spree::Ability.new(admin_user, store: store)+ returned = json_response['permissions']+ expect(returned.length).to eq(ability.send(:rules).length)+ end++ it 'includes a manage all rule for admin users' do+ subject+ manage_all_rule = json_response['permissions'].find do |rule|+ rule['allow'] && rule['actions'].include?('manage') && rule['subjects'].include?('all')+ end+ expect(manage_all_rule).to be_present+ end++ context 'without authentication' do+ let(:headers) { {} }++ it 'returns unauthorized' do+ subject+ expect(response).to have_http_status(:unauthorized)+ end+ end+ end+enddiff --git a/spree/api/spec/integration/spree/api/v3/admin/me_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/me_spec.rbnew file mode 100644index 0000000000..754e86c05d--- /dev/null+++ b/spree/api/spec/integration/spree/api/v3/admin/me_spec.rb@@ -0,0 +1,52 @@+# frozen_string_literal: true++require 'swagger_helper'++RSpec.describe 'Admin Me API', type: :request, swagger_doc: 'api-reference/admin.yaml' do+ include_context 'API v3 Admin'++ path '/api/v3/admin/me' do+ get 'Get current admin user and permissions' do+ tags 'Authentication'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description 'Returns the current admin user profile and a serialized list of permissions (CanCanCan rules). The SPA uses these to drive UI permission checks.'++ sdk_example <<~JS+ const me = await client.admin.me.show()+ if (me.permissions.some((r) => r.allow && r.actions.includes('manage') && r.subjects.includes('Spree::Product'))) {+ // show create product button+ }+ JS++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true,+ description: 'Bearer token for admin authentication'++ response '200', 'current admin user and permissions' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let(:Authorization) { "Bearer #{admin_jwt_token}" }++ schema '$ref' => '#/components/schemas/MeResponse'++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['user']).to be_present+ expect(data['user']['email']).to eq(admin_user.email)+ expect(data['permissions']).to be_an(Array)+ expect(data['permissions']).not_to be_empty+ expect(data['permissions'].first.keys).to match_array(%w[allow actions subjects has_conditions])+ end+ end++ response '401', 'unauthorized' do+ let(:'x-spree-api-key') { 'invalid' }+ let(:Authorization) { 'Bearer invalid' }++ schema '$ref' => '#/components/schemas/ErrorResponse'++ run_test!+ end+ end+ end+end