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 deactivation of staff accounts (#14967)
Damian Legawiec6a1b118cd862
diff --git a/.changeset/staff-account-deactivated.md b/.changeset/staff-account-deactivated.mdnew file mode 100644index 0000000000..e676efca8b--- /dev/null+++ b/.changeset/staff-account-deactivated.md@@ -0,0 +1,6 @@+---+"@spree/dashboard": patch+"@spree/dashboard-core": patch+---++The login page explains a refused sign-in when a staff account has been deactivated, instead of reporting a generic sign-in failure.diff --git a/docs/developer/core-concepts/staff-roles.mdx b/docs/developer/core-concepts/staff-roles.mdxindex 963cbd468a..b3eb33da26 100644--- a/docs/developer/core-concepts/staff-roles.mdx+++ b/docs/developer/core-concepts/staff-roles.mdx@@ -124,6 +124,32 @@ spree user create --email [email protected] --password secret123The created user gets the `admin` role on the default store.+## Deactivating Admin Users++When someone should lose access, deactivate their account rather than deleting it. Records keep naming the person who approved, refunded or created them, so the history stays intact, and the account can be reactivated later.++```ruby+admin_user = Spree.admin_user_class.find_by!(email: '[email protected]')++admin_user.deactivate! # switches the account off and ends its sessions+admin_user.deactivated? # => true+admin_user.reactivate! # lets the account sign in again+```++Deactivating ends every session the account holds. Its refresh tokens are deleted, OAuth tokens and grants issued to apps on its behalf are revoked, and access tokens already issued are refused from the next request. While deactivated, the account cannot:++- sign in to the dashboard or the seller panel, with a password or any identity provider;+- accept an invitation;+- request or complete a password reset. A reset request answers as it would for an unknown address and sends nothing.++A sign-in is refused with `403` and the error code `account_deactivated`, but only after the password or identity provider has proven who the person is. A wrong password gets the usual `authentication_failed`, so the response never tells a stranger which accounts are switched off.++Reactivating does not restore the sessions that deactivation ended; the person signs in again. Secret API keys belong to the store rather than the person who created them, so deactivation leaves them working. Revoke any the person should no longer control from the store's API keys settings.++<Note>+A custom admin user class opts in by including `Spree::AccountDeactivation` and adding a `deactivated_at` datetime column. The checks are duck-typed, so a class without them is never refused.+</Note>+## Authentication & identity providersStaff authenticate against the Admin API, which issues a short-lived JWT used for subsequent requests. How a staff member proves who they are is **pluggable** — Spree ships email/password out of the box, and you can plug in any external identity provider (Okta, Microsoft Entra ID, Google Workspace, a custom JWT issuer, SAML, etc.) without changing the rest of the API.diff --git a/packages/dashboard-core/src/locales/ar.json b/packages/dashboard-core/src/locales/ar.jsonindex d11777a807..1267b5641b 100644--- a/packages/dashboard-core/src/locales/ar.json+++ b/packages/dashboard-core/src/locales/ar.json@@ -117,6 +117,7 @@"title": "إعادة تعيين كلمة المرور"},"login": {+ "account_deactivated": "تم إلغاء تفعيل هذا الحساب. تواصل مع المسؤول لاستعادة الوصول.","account_not_provisioned": "هذا الحساب غير مصرح له بالوصول إلى هذا المتجر. اطلب دعوة من المسؤول.","divider": "أو","invalid_oauth_state": "انتهت صلاحية جلسة تسجيل الدخول أو أنها غير صالحة. يرجى بدء تسجيل الدخول من جديد.",diff --git a/packages/dashboard-core/src/locales/de.json b/packages/dashboard-core/src/locales/de.jsonindex a3cbd4c3a5..44692828b7 100644--- a/packages/dashboard-core/src/locales/de.json+++ b/packages/dashboard-core/src/locales/de.json@@ -117,6 +117,7 @@"title": "Passwort zurücksetzen"},"login": {+ "account_deactivated": "Dieses Konto wurde deaktiviert. Wenden Sie sich an einen Administrator, um den Zugang wiederherzustellen.","account_not_provisioned": "Dieses Konto ist für diesen Shop nicht freigegeben. Bitten Sie einen Administrator um eine Einladung.","divider": "oder","invalid_oauth_state": "Die Anmeldesitzung ist abgelaufen oder ungültig. Bitte melden Sie sich erneut an.",diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.jsonindex 48ed4dc1f5..6333a0eebe 100644--- a/packages/dashboard-core/src/locales/en.json+++ b/packages/dashboard-core/src/locales/en.json@@ -117,6 +117,7 @@"title": "Reset your password"},"login": {+ "account_deactivated": "This account has been deactivated. Contact an administrator to restore access.","account_not_provisioned": "This account is not authorized for this store. Ask an administrator for an invitation.","divider": "or","invalid_oauth_state": "That sign-in session expired or was invalid. Please start signing in again.",diff --git a/packages/dashboard-core/src/locales/es.json b/packages/dashboard-core/src/locales/es.jsonindex 1d20a1272e..47d664504f 100644--- a/packages/dashboard-core/src/locales/es.json+++ b/packages/dashboard-core/src/locales/es.json@@ -1729,6 +1729,7 @@"title": "Restablecer tu contraseña"},"login": {+ "account_deactivated": "Esta cuenta fue desactivada. Contactá a un administrador para recuperar el acceso.","account_not_provisioned": "Esta cuenta no está autorizada para esta tienda. Pedile una invitación a un administrador.","divider": "o","invalid_oauth_state": "Esa sesión de inicio caducó o fue inválida. Empezá a iniciar sesión de nuevo.",diff --git a/packages/dashboard-core/src/locales/fr.json b/packages/dashboard-core/src/locales/fr.jsonindex 40a63ea6fa..a5a4499be4 100644--- a/packages/dashboard-core/src/locales/fr.json+++ b/packages/dashboard-core/src/locales/fr.json@@ -117,6 +117,7 @@"title": "Réinitialiser votre mot de passe"},"login": {+ "account_deactivated": "Ce compte a été désactivé. Contactez un administrateur pour rétablir l'accès.","account_not_provisioned": "Ce compte n'est pas autorisé pour cette boutique. Demandez une invitation à un administrateur.","divider": "ou","invalid_oauth_state": "Cette session de connexion a expiré ou n'était pas valide. Veuillez recommencer.",diff --git a/packages/dashboard-core/src/locales/pl.json b/packages/dashboard-core/src/locales/pl.jsonindex 54c7fcf47d..fb1c170598 100644--- a/packages/dashboard-core/src/locales/pl.json+++ b/packages/dashboard-core/src/locales/pl.json@@ -117,6 +117,7 @@"title": "Zresetuj hasło"},"login": {+ "account_deactivated": "To konto zostało dezaktywowane. Skontaktuj się z administratorem, aby przywrócić dostęp.","account_not_provisioned": "To konto nie ma dostępu do tego sklepu. Poproś administratora o zaproszenie.","divider": "lub","invalid_oauth_state": "Ta sesja logowania wygasła lub była nieprawidłowa. Zaloguj się ponownie.",diff --git a/packages/dashboard-core/src/locales/zh-CN.json b/packages/dashboard-core/src/locales/zh-CN.jsonindex 3ebdb520cc..0701dac0bd 100644--- a/packages/dashboard-core/src/locales/zh-CN.json+++ b/packages/dashboard-core/src/locales/zh-CN.json@@ -117,6 +117,7 @@"title": "重置密码"},"login": {+ "account_deactivated": "此账户已被停用。请联系管理员恢复访问权限。","account_not_provisioned": "此账户无权访问该店铺。请向管理员申请邀请。","divider": "或","invalid_oauth_state": "登录会话已过期或无效。请重新登录。",diff --git a/packages/dashboard/src/hooks/use-auth-providers.test.ts b/packages/dashboard/src/hooks/use-auth-providers.test.tsindex 8439571cf6..e1c89dfdd7 100644--- a/packages/dashboard/src/hooks/use-auth-providers.test.ts+++ b/packages/dashboard/src/hooks/use-auth-providers.test.ts@@ -6,6 +6,7 @@ describe('authCallbackErrorKey', () => {expect(authCallbackErrorKey('account_not_provisioned')).toBe('admin.auth.login.account_not_provisioned',)+ expect(authCallbackErrorKey('account_deactivated')).toBe('admin.auth.login.account_deactivated')})it('falls back to the generic message for unknown and inherited names', () => {diff --git a/packages/dashboard/src/hooks/use-auth-providers.ts b/packages/dashboard/src/hooks/use-auth-providers.tsindex 95a0710cd0..db6c2448f5 100644--- a/packages/dashboard/src/hooks/use-auth-providers.ts+++ b/packages/dashboard/src/hooks/use-auth-providers.ts@@ -38,6 +38,7 @@ export function useAuthProviders() {* to the identity provider — so each code says what actually needs to happen.*/const CALLBACK_ERROR_KEYS: Record<string, string> = {+ account_deactivated: 'admin.auth.login.account_deactivated',account_not_provisioned: 'admin.auth.login.account_not_provisioned',invalid_oauth_state: 'admin.auth.login.invalid_oauth_state',invalid_provider: 'admin.auth.login.sso_failed',diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin_authentication.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin_authentication.rbindex c5a527486e..fb7f12cbec 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/admin_authentication.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin_authentication.rb@@ -77,6 +77,7 @@ module Spreeowner = token.resource_ownerreturn false unless owner.is_a?(Spree.admin_user_class)+ return false if account_deactivated?(owner)@current_api_key = nil@current_user = ownerdiff --git a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rbindex 2bd408bd08..f902f9871b 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb@@ -16,6 +16,9 @@ module Spree# Distinct from authentication_failed: the person proved who they are to# the identity provider, but no account here is authorized for them.account_not_provisioned: 'account_not_provisioned',+ # The person proved who they are, but the account has been switched+ # off (Spree::AccountDeactivation).+ account_deactivated: 'account_deactivated',invalid_oauth_state: 'invalid_oauth_state',current_password_invalid: 'current_password_invalid',password_reset_token_invalid: 'password_reset_token_invalid',diff --git a/spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb b/spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rbindex 05b126e187..590522c6d6 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb@@ -111,7 +111,7 @@ module Spreecase user_typewhen USER_TYPE_ADMIN- Spree.admin_user_class.find(user_id)+ admin_user_from(user_id)elsecustomer_from(user_id)end@@ -128,6 +128,32 @@ module Spreecustomer.respond_to?(:anonymized?) && customer.anonymized? ? nil : customerend+ # A deactivated staff account stops answering to its old tokens on the+ # next request, rather than when they expire.+ def admin_user_from(user_id)+ admin_user = Spree.admin_user_class.find(user_id)++ account_deactivated?(admin_user) ? nil : admin_user+ end++ # Duck-typed, like the anonymized check above: a custom admin user+ # class without Spree::AccountDeactivation is never refused.+ def account_deactivated?(user)+ user.respond_to?(:deactivated?) && user.deactivated?+ end++ # For a person who proved who they are: a password that matched, a+ # provider that vouched for them, a reset or invitation link they hold.+ # Anyone else gets the same answer as for any failed attempt, so this+ # never tells a stranger which accounts are switched off.+ def render_account_deactivated+ render_error(+ code: ErrorHandler::ERROR_CODES[:account_deactivated],+ message: I18n.t('spree.api.account_deactivated'),+ status: :forbidden+ )+ end+def determine_user_type(user)if user.is_a?(Spree.admin_user_class)USER_TYPE_ADMINdiff --git a/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rbindex 52b3fd56f2..8ae56a13d0 100644--- a/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb@@ -36,6 +36,8 @@ module Spreeif result.success?user = result.value+ return render_account_deactivated if account_deactivated?(user)+refresh_token = Spree::RefreshToken.create_for(user, audience: JWT_AUDIENCE_ADMIN, request_env: request_env_for_token)set_refresh_cookie(refresh_token)render json: auth_response(user)@@ -99,6 +101,8 @@ module Spreereturn redirect_to_dashboard(error: callback_error_code(strategy))end+ return redirect_to_dashboard(error: ERROR_CODES[:account_deactivated]) if account_deactivated?(result.value)+set_refresh_cookie(Spree::RefreshToken.create_for(result.value, audience: JWT_AUDIENCE_ADMIN, request_env: request_env_for_token))@@ -131,6 +135,14 @@ module Spreeenduser = refresh_token.user+ # Deactivating deletes the account's refresh tokens; this catches a+ # refresh already under way when that happened.+ if account_deactivated?(user)+ refresh_token.destroy+ clear_refresh_cookie+ return render_account_deactivated+ end+new_refresh_token = refresh_token.rotate!(request_env: request_env_for_token)set_refresh_cookie(new_refresh_token)diff --git a/spree/api/app/controllers/spree/api/v3/admin/invitation_acceptances_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/invitation_acceptances_controller.rbindex be52a6b85d..120c82d1ae 100644--- a/spree/api/app/controllers/spree/api/v3/admin/invitation_acceptances_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/invitation_acceptances_controller.rb@@ -37,6 +37,8 @@ module Spreeuser = resolve_or_create_invitee(@invitation)return if performed?+ # Checked before accepting: a deactivated account gains no role.+ return render_account_deactivated if account_deactivated?(user)@invitation.invitee = userresult = Spree.invitation_accept_workflow.call(invitation: @invitation)diff --git a/spree/api/app/controllers/spree/api/v3/admin/password_resets_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/password_resets_controller.rbindex b5f3f7d35e..368e0f6c38 100644--- a/spree/api/app/controllers/spree/api/v3/admin/password_resets_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/password_resets_controller.rb@@ -36,7 +36,9 @@ module Spreedef createuser = Spree.admin_user_class.find_by(email: params[:email])- if user+ # A deactivated account is treated as no account: no email is sent,+ # and the response is the same 202.+ if user && !account_deactivated?(user)event_name = 'admin_user.password_reset_requested'payload = user.event_payload_for(event_name,@@ -62,6 +64,10 @@ module Spree)end+ # A link sent before the account was switched off must not change+ # its password or sign it in.+ return render_account_deactivated if account_deactivated?(user)+if user.update(password: params[:password], password_confirmation: params[:password_confirmation])user.publish_event('admin_user.password_reset')# A password reset must kill every existing session — a stolendiff --git a/spree/api/app/controllers/spree/api/v3/seller/auth_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/auth_controller.rbindex 6e0f013395..012bff8fc7 100644--- a/spree/api/app/controllers/spree/api/v3/seller/auth_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/auth_controller.rb@@ -52,6 +52,8 @@ module Spreereturn render_authentication_failed(result.error) unless result.success?user = result.value+ return render_account_deactivated if account_deactivated?(user)+# A store's own staff share this user class, so authenticating is# not enough: without a role on some seller there is no panel to# sign in to, and minting a token would hand out an audience the@@ -101,6 +103,14 @@ module Spreeenduser = refresh_token.user+ # Deactivating deletes the account's refresh tokens; this catches a+ # refresh already under way when that happened.+ if account_deactivated?(user)+ refresh_token.destroy+ clear_refresh_cookie+ return render_account_deactivated+ end+# Membership can be revoked while a session is live; the refresh is# where that takes effect.unless user.seller_member?diff --git a/spree/api/app/controllers/spree/api/v3/seller/invitation_acceptances_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/invitation_acceptances_controller.rbindex e598e82f6e..3af5d8b2c1 100644--- a/spree/api/app/controllers/spree/api/v3/seller/invitation_acceptances_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/invitation_acceptances_controller.rb@@ -46,6 +46,8 @@ module Spreeuser = resolve_or_create_invitee(@invitation)return if performed?+ # Checked before accepting: a deactivated account gains no role.+ return render_account_deactivated if account_deactivated?(user)@invitation.invitee = userresult = Spree.invitation_accept_workflow.call(invitation: @invitation)diff --git a/spree/api/app/controllers/spree/api/v3/seller/password_resets_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/password_resets_controller.rbindex 29f605bac3..ef58f30ed3 100644--- a/spree/api/app/controllers/spree/api/v3/seller/password_resets_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/password_resets_controller.rb@@ -43,7 +43,8 @@ module Spree# admin who runs no seller has no panel to be sent to, and mailing# them a seller reset link would be an invitation to a session they# cannot hold.- if user&.seller_member?+ # A deactivated account is treated as no account: no email is sent.+ if user&.seller_member? && !account_deactivated?(user)user.publish_event(RESET_REQUESTED_EVENT, event_payload(user))end@@ -60,6 +61,9 @@ module Spree# it can be revoked between the email being sent and the link being# opened, and signing in is what the success path does.return render_token_invalid unless user&.seller_member?+ # A link sent before the account was switched off must not change+ # its password or sign it in.+ return render_account_deactivated if account_deactivated?(user)unless user.update(password: params[:password], password_confirmation: params[:password_confirmation])return render_errors(user.errors)diff --git a/spree/api/config/locales/en.yml b/spree/api/config/locales/en.ymlindex 6c58a98724..bc127ba35e 100644--- a/spree/api/config/locales/en.yml+++ b/spree/api/config/locales/en.yml@@ -2,6 +2,7 @@en:spree:api:+ account_deactivated: This account has been deactivated. Contact an administrator to restore access.cannot_delete: "%{model} cannot be deleted"cannot_modify_seller_import: This import belongs to a seller. It can be viewed here, but only the seller can retry or delete it.current_password_invalid: Current password is invalid or missingdiff --git a/spree/api/spec/controllers/spree/api/v3/admin/auth_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/auth_controller_spec.rbindex 44e3ed5bdb..c0f0ad1264 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/auth_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/auth_controller_spec.rb@@ -480,6 +480,21 @@ RSpec.describe Spree::Api::V3::Admin::AuthController, type: :controller doendend+ context 'when the matching account is deactivated' do+ before do+ admin.deactivate!+ stub_claims('sub' => 'idp-subject-1', 'email' => admin.email, 'email_verified' => 'true')+ end++ it 'sends the browser back with account_deactivated and no session' do+ get :callback, params: { provider: 'entra', code: 'auth-code', state: valid_state }++ expect(response).to have_http_status(:redirect)+ expect(response.location).to include('error=account_deactivated')+ expect(set_cookie_for('spree_admin_refresh_token')).to be_nil+ end+ end+context 'when the IdP does not assert a verified email' dobefore dostub_claims('sub' => 'idp-subject-1', 'email' => admin.email, 'email_verified' => 'false')diff --git a/spree/api/spec/requests/spree/api/v3/admin/deactivated_account_spec.rb b/spree/api/spec/requests/spree/api/v3/admin/deactivated_account_spec.rbnew file mode 100644index 0000000000..be61eebd2b--- /dev/null+++ b/spree/api/spec/requests/spree/api/v3/admin/deactivated_account_spec.rb@@ -0,0 +1,170 @@+require 'spec_helper'++# A deactivated staff account (Spree::AccountDeactivation) must lose every way+# back in, not only the login form. The SSO callback is covered in the auth+# controller spec.+RSpec.describe 'Deactivated staff accounts on the Admin API', type: :request do+ include_context 'API v3 Admin'++ let(:password) { 'password123' }+ let(:admin_user) { create(:admin_user, password: password, password_confirmation: password) }++ def json+ JSON.parse(response.body)+ end++ def log_in(with: password)+ post '/api/v3/admin/auth/login', params: { email: admin_user.email, password: with }+ end++ describe 'signing in' do+ it 'is refused once the password is proven, with no session' do+ admin_user.deactivate!++ log_in++ expect(response).to have_http_status(:forbidden)+ expect(json['error']['code']).to eq('account_deactivated')+ expect(response.headers['Set-Cookie'].to_s).not_to include('spree_admin_refresh_token=')+ end++ # Telling a stranger the account is switched off would confirm it exists.+ it 'answers a wrong password exactly as for any account' do+ admin_user.deactivate!++ log_in(with: 'wrong-password')++ expect(response).to have_http_status(:unauthorized)+ expect(json['error']['code']).to eq('authentication_failed')+ end+ end++ describe 'an access token issued before deactivation' do+ let(:headers) { { 'Authorization' => "Bearer #{admin_jwt_token}" } }++ it 'stops working on the next request' do+ get '/api/v3/admin/me', headers: headers+ expect(response).to have_http_status(:ok)++ admin_user.deactivate!++ get '/api/v3/admin/me', headers: headers+ expect(response).to have_http_status(:unauthorized)+ end++ it 'works again once the account is reactivated' do+ admin_user.deactivate!+ admin_user.reactivate!++ get '/api/v3/admin/me', headers: headers+ expect(response).to have_http_status(:ok)+ end+ end++ describe 'refreshing a session' do+ before { log_in }++ it 'fails once deactivation has ended the session' do+ admin_user.deactivate!++ post '/api/v3/admin/auth/refresh'++ expect(response).to have_http_status(:unauthorized)+ expect(json['error']['code']).to eq('invalid_refresh_token')+ end++ # A refresh token that outlived the deactivation, as a refresh already+ # under way when it happened would leave it.+ it 'refuses a surviving refresh token and deletes it' do+ admin_user.update_column(:deactivated_at, Time.current)++ post '/api/v3/admin/auth/refresh'++ expect(response).to have_http_status(:forbidden)+ expect(json['error']['code']).to eq('account_deactivated')+ expect(Spree::RefreshToken.where(user: admin_user)).to be_empty+ end+ end++ describe 'an OAuth app token' do+ let(:application) do+ store.oauth_applications.create!(name: 'Assistant', redirect_uri: 'https://example.test/cb', confidential: false)+ end+ let!(:oauth_token) do+ Spree::OauthAccessToken.create!(+ application: application, resource_owner: admin_user, scopes: 'read_products',+ expires_in: 2.hours.to_i, resource: Spree::Api::Oauth.resource_identifier(:admin)+ )+ end+ let(:headers) { { 'Authorization' => "Bearer #{oauth_token.plaintext_token}" } }++ it 'is revoked by deactivation' do+ get '/api/v3/admin/products', headers: headers+ expect(response).to have_http_status(:ok)++ admin_user.deactivate!++ expect(oauth_token.reload).to be_revoked+ get '/api/v3/admin/products', headers: headers+ expect(response).to have_http_status(:unauthorized)+ end++ it 'is refused for a deactivated account even when not revoked' do+ admin_user.update_column(:deactivated_at, Time.current)++ get '/api/v3/admin/products', headers: headers++ expect(response).to have_http_status(:unauthorized)+ end+ end++ describe 'accepting an invitation' do+ # Staff of another store, invited to this one.+ let(:invitee) { create(:admin_user, :without_admin_role, password: password, password_confirmation: password) }+ let!(:invitation) { create(:invitation, resource: store, email: invitee.email) }++ it 'is refused once the password is proven, and grants no role' do+ invitee.deactivate!++ expect do+ post "/api/v3/admin/auth/invitations/#{invitation.prefixed_id}/accept",+ params: { token: invitation.token, password: password }+ end.not_to change(Spree::RoleUser, :count)++ expect(response).to have_http_status(:forbidden)+ expect(json['error']['code']).to eq('account_deactivated')+ expect(Spree::Invitation.pending.exists?(invitation.id)).to be(true)+ end+ end++ describe 'resetting the password' do+ it 'sends nothing for a deactivated account and answers as for any address' do+ admin_user.deactivate!+ expect_any_instance_of(Spree.admin_user_class).not_to receive(:publish_event)++ post '/api/v3/admin/auth/password_resets', params: { email: admin_user.email }, headers: api_key_headers++ expect(response).to have_http_status(:accepted)+ end++ it 'still sends the reset email to an active account' do+ expect_any_instance_of(Spree.admin_user_class).to receive(:publish_event).+ with('admin_user.password_reset_requested', anything)++ post '/api/v3/admin/auth/password_resets', params: { email: admin_user.email }, headers: api_key_headers+ end++ it 'refuses a link sent before deactivation, leaving the password unchanged' do+ token = admin_user.generate_token_for(:password_reset)+ admin_user.deactivate!++ patch "/api/v3/admin/auth/password_resets/#{token}",+ params: { password: 'new-password-123', password_confirmation: 'new-password-123' },+ headers: api_key_headers++ expect(response).to have_http_status(:forbidden)+ expect(json['error']['code']).to eq('account_deactivated')+ expect(admin_user.reload.valid_password?(password)).to be(true)+ end+ end+enddiff --git a/spree/api/spec/requests/spree/api/v3/seller/deactivated_account_spec.rb b/spree/api/spec/requests/spree/api/v3/seller/deactivated_account_spec.rbnew file mode 100644index 0000000000..9cc7675be6--- /dev/null+++ b/spree/api/spec/requests/spree/api/v3/seller/deactivated_account_spec.rb@@ -0,0 +1,108 @@+require 'spec_helper'++# Sellers sign in with staff accounts, so a deactivated account+# (Spree::AccountDeactivation) must lose the seller panel too.+RSpec.describe 'Deactivated staff accounts on the Seller API', type: :request do+ include_context 'API v3 Seller'++ let(:password) { 'password123' }+ let(:seller_user) do+ create(:admin_user, :without_admin_role, password: password, password_confirmation: password).+ tap { |user| seller.add_user(user, seller_role) }+ end++ def json+ JSON.parse(response.body)+ end++ def log_in(with: password)+ post '/api/v3/seller/auth/login', params: { email: seller_user.email, password: with }+ end++ it 'refuses to sign in once the password is proven' do+ seller_user.deactivate!++ log_in++ expect(response).to have_http_status(:forbidden)+ expect(json['error']['code']).to eq('account_deactivated')+ end++ it 'answers a wrong password exactly as for any account' do+ seller_user.deactivate!++ log_in(with: 'wrong-password')++ expect(response).to have_http_status(:unauthorized)+ expect(json['error']['code']).to eq('authentication_failed')+ end++ it 'stops an access token issued before deactivation on the next request' do+ get '/api/v3/seller/me', headers: seller_headers+ expect(response).to have_http_status(:ok)++ seller_user.deactivate!++ get '/api/v3/seller/me', headers: seller_headers+ expect(response).to have_http_status(:unauthorized)+ end++ describe 'refreshing a session' do+ before { log_in }++ it 'fails once deactivation has ended the session' do+ seller_user.deactivate!++ post '/api/v3/seller/auth/refresh'++ expect(response).to have_http_status(:unauthorized)+ end++ it 'refuses a surviving refresh token and deletes it' do+ seller_user.update_column(:deactivated_at, Time.current)++ post '/api/v3/seller/auth/refresh'++ expect(response).to have_http_status(:forbidden)+ expect(json['error']['code']).to eq('account_deactivated')+ expect(Spree::RefreshToken.where(user: seller_user)).to be_empty+ end+ end++ it 'refuses an invitation to another seller once the password is proven' do+ other_seller = create(:seller, :approved, store: store)+ invitation = create(:invitation, resource: other_seller, inviter: create(:admin_user),+ email: seller_user.email, role: other_seller.default_user_role)+ seller_user.deactivate!++ post "/api/v3/seller/auth/invitations/#{invitation.prefixed_id}/accept",+ params: { token: invitation.token, password: password }++ expect(response).to have_http_status(:forbidden)+ expect(json['error']['code']).to eq('account_deactivated')+ expect(other_seller.reload.users).not_to include(seller_user)+ end++ describe 'resetting the password' do+ it 'sends nothing for a deactivated account and answers as for any address' do+ seller_user.deactivate!+ expect_any_instance_of(Spree.admin_user_class).not_to receive(:publish_event)++ post '/api/v3/seller/auth/password_resets', params: { email: seller_user.email }++ expect(response).to have_http_status(:accepted)+ end++ it 'refuses a link sent before deactivation, leaving the password unchanged' do+ token = seller_user.generate_token_for(:password_reset)+ seller_user.deactivate!++ patch "/api/v3/seller/auth/password_resets/#{token}",+ params: { password: 'new-password-123', password_confirmation: 'new-password-123' }++ expect(response).to have_http_status(:forbidden)+ expect(json['error']['code']).to eq('account_deactivated')+ expect(seller_user.reload.valid_password?(password)).to be(true)+ end+ end+enddiff --git a/spree/core/app/models/concerns/spree/account_deactivation.rb b/spree/core/app/models/concerns/spree/account_deactivation.rbnew file mode 100644index 0000000000..a7979727a0--- /dev/null+++ b/spree/core/app/models/concerns/spree/account_deactivation.rb@@ -0,0 +1,54 @@+module Spree+ # Switches a staff account off without deleting it. Deleting a staff member+ # clears them from every record that names them as its actor, so the history+ # of who approved, refunded or created what is lost; deactivating keeps the+ # account and refuses every way back in.+ #+ # Enforcement lives in the API: a deactivated account cannot sign in by any+ # strategy, accept an invitation, finish a password reset or refresh a+ # session, and its access tokens stop working on the next request. Including+ # this concern opts a model in; the checks are duck-typed, so a custom admin+ # user class without it is never refused.+ #+ # Secret API keys are left alone: they belong to the store, not to the person+ # who created them, and revoking them would break the store's integrations.+ module AccountDeactivation+ # @return [Boolean]+ def deactivated?+ deactivated_at.present?+ end++ # Deactivates the account and ends every session it holds: refresh tokens+ # are deleted, and OAuth tokens and grants issued to apps on its behalf are+ # revoked. Access tokens already issued are refused from the next request.+ #+ # Safe to call again. The first deactivation time is kept, but sessions+ # are ended every time, so an account whose column was set some other way+ # still loses the credentials it holds.+ #+ # Skips validations: switching an account off must not fail because some+ # unrelated attribute no longer passes today's rules.+ #+ # @return [void]+ def deactivate!+ now = Time.current+ transaction do+ update_columns(deactivated_at: now, updated_at: now) unless deactivated?+ Spree::RefreshToken.revoke_all_for(self)+ oauth_owner = { resource_owner_type: self.class.polymorphic_name, resource_owner_id: id, revoked_at: nil }+ Spree::OauthAccessToken.where(oauth_owner).update_all(revoked_at: now)+ Spree::OauthAccessGrant.where(oauth_owner).update_all(revoked_at: now)+ end+ end++ # Lets the account sign in again. Sessions ended by deactivation stay+ # ended; the person signs in afresh.+ #+ # @return [void]+ def reactivate!+ return unless deactivated?++ update_columns(deactivated_at: nil, updated_at: Time.current)+ end+ end+enddiff --git a/spree/core/app/models/spree/admin_user.rb b/spree/core/app/models/spree/admin_user.rbindex 03f25c15f9..2a1336f482 100644--- a/spree/core/app/models/spree/admin_user.rb+++ b/spree/core/app/models/spree/admin_user.rb@@ -8,6 +8,7 @@ module Spreeinclude Spree::AdminUserMethodsinclude Spree::AccountLockout+ include Spree::AccountDeactivationinclude Spree::PasswordPolicyvalidates :email, presence: true, uniqueness: { case_sensitive: false }diff --git a/spree/core/db/migrate/20261023100001_add_deactivated_at_to_spree_admin_users.rb b/spree/core/db/migrate/20261023100001_add_deactivated_at_to_spree_admin_users.rbnew file mode 100644index 0000000000..735d7344a0--- /dev/null+++ b/spree/core/db/migrate/20261023100001_add_deactivated_at_to_spree_admin_users.rb@@ -0,0 +1,7 @@+# Lets a staff account be switched off without deleting it, so records that+# name it as their actor keep their history. See Spree::AccountDeactivation.+class AddDeactivatedAtToSpreeAdminUsers < ActiveRecord::Migration[8.1]+ def change+ add_column :spree_admin_users, :deactivated_at, :datetime+ end+enddiff --git a/spree/core/spec/models/spree/admin_user_spec.rb b/spree/core/spec/models/spree/admin_user_spec.rbindex a2d64ad26a..267a01a1c3 100644--- a/spree/core/spec/models/spree/admin_user_spec.rb+++ b/spree/core/spec/models/spree/admin_user_spec.rb@@ -20,6 +20,65 @@ describe Spree.admin_user_class, type: :model doendend+ describe 'deactivation' do+ it 'starts active' do+ expect(admin_user).not_to be_deactivated+ end++ it 'records when the account was switched off' do+ admin_user.deactivate!++ expect(admin_user.reload).to be_deactivated+ expect(admin_user.deactivated_at).to be_within(2.seconds).of(Time.current)+ end++ it 'ends every session the account holds, on every surface' do+ create(:refresh_token, :for_admin, user: admin_user)+ create(:refresh_token, user: admin_user, audience: 'seller_api')+ someone_else = create(:refresh_token, :for_admin)++ admin_user.deactivate!++ expect(Spree::RefreshToken.where(user: admin_user)).to be_empty+ expect(Spree::RefreshToken.exists?(someone_else.id)).to be(true)+ end++ it 'keeps the first deactivation time when called again' do+ admin_user.deactivate!+ first = admin_user.reload.deactivated_at++ Timecop.travel(1.hour.from_now) { admin_user.deactivate! }++ expect(admin_user.reload.deactivated_at).to eq(first)+ end++ it 'ends the sessions of an account already marked deactivated' do+ admin_user.update_column(:deactivated_at, 1.day.ago)+ create(:refresh_token, :for_admin, user: admin_user)++ admin_user.deactivate!++ expect(Spree::RefreshToken.where(user: admin_user)).to be_empty+ end++ # Switching an account off must not depend on its other attributes+ # passing today's validations.+ it 'deactivates an account that no longer validates' do+ admin_user.update_column(:email, '')++ admin_user.deactivate!++ expect(admin_user.reload).to be_deactivated+ end++ it 'lets a reactivated account in again' do+ admin_user.deactivate!+ admin_user.reactivate!++ expect(admin_user.reload).not_to be_deactivated+ end+ end+describe '#can_be_deleted?' dosubject { admin_user.can_be_deleted? }diff --git a/spree/mcp/app/controllers/spree/api/v3/admin/mcp_controller.rb b/spree/mcp/app/controllers/spree/api/v3/admin/mcp_controller.rbindex 2e5bfeb9bd..742d36f89f 100644--- a/spree/mcp/app/controllers/spree/api/v3/admin/mcp_controller.rb+++ b/spree/mcp/app/controllers/spree/api/v3/admin/mcp_controller.rb@@ -151,9 +151,13 @@ module Spree@current_oauth_token = token if token&.accessible? && admin_audience_matches?(token)end+ # This endpoint resolves its own caller rather than through+ # AdminAuthentication, so it refuses a deactivated account itself:+ # the tools that run in this process would otherwise act as an+ # account that has been switched off.def oauth_resource_ownerowner = current_oauth_token.resource_owner- owner if owner.is_a?(Spree.admin_user_class)+ owner if owner.is_a?(Spree.admin_user_class) && !account_deactivated?(owner)end# The error text is what both the model and the person read, so itdiff --git a/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rb b/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rbindex c3c6863220..949c37b6d8 100644--- a/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rb+++ b/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rb@@ -69,6 +69,33 @@ RSpec.describe 'Admin MCP endpoint', type: :request doexpect(response).to have_http_status(:unauthorized)end+ # Deactivation revokes the account's tokens; this is the check that+ # still refuses one that survived, as on the rest of the Admin API.+ context 'when the owner has been deactivated without the token being revoked' do+ before do+ token+ admin.update_column(:deactivated_at, Time.current)+ end++ it 'refuses to list tools' do+ post_with_token(token)++ expect(response).to have_http_status(:unauthorized)+ end++ # Product status moves run in this process, not through the Admin API,+ # so the endpoint's own check is the only thing between the token and+ # the write.+ it 'refuses an in-process write' do+ product = create(:product, store: store, status: 'active')++ post_with_token(token, 'tools/call', { name: 'products_archive', arguments: { 'product' => product.prefixed_id } })++ expect(response).to have_http_status(:unauthorized)+ expect(product.reload.status).to eq('active')+ end+ end+# Parsing the bearer header must not backtrack: this header arrives# unauthenticated, so a pathological value is free to send.it 'parses a bearer header of many spaces without stalling' do