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
Authentication strategies 🔒
Damian Legawiec7253a0b114c5
diff --git a/api/app/controllers/spree/api/v3/storefront/auth_controller.rb b/api/app/controllers/spree/api/v3/storefront/auth_controller.rbindex 9cdc93ee37..336a86b77a 100644--- a/api/app/controllers/spree/api/v3/storefront/auth_controller.rb+++ b/api/app/controllers/spree/api/v3/storefront/auth_controller.rb@@ -5,21 +5,33 @@ module Spreeclass AuthController < BaseControllerinclude Spree::Api::V3::Storefront::Authentication- skip_before_action :authenticate_user, only: [:create, :register]+ skip_before_action :authenticate_user, only: [:create, :register, :oauth_callback]before_action :require_authentication!, only: [:refresh]# POST /api/v3/storefront/auth/login+ # Supports multiple authentication providers via :provider param+ # Examples:+ # { "provider": "email", "email": "...", "password": "..." }+ # { "provider": "google", "id_token": "..." }def create- user = Spree.user_class.find_by(email: params[:email])+ strategy = authentication_strategy+ return unless strategy # Error already rendered by determine_strategy- if user&.valid_password?(params[:password])+ result = strategy.authenticate++ if result.success?+ user = result.valuetoken = generate_jwt(user)render json: {token: token,user: user_serializer.new(user, serializer_context).as_json}else- render json: { error: 'Invalid email or password' }, status: :unauthorized+ render_error(+ code: ERROR_CODES[:authentication_failed],+ message: result.error,+ status: :unauthorized+ )endend@@ -47,6 +59,35 @@ module Spree}end+ # POST /api/v3/storefront/auth/oauth/callback+ # OAuth callback endpoint for server-side OAuth flows+ # Example: { "provider": "google", "code": "authorization_code" }+ def oauth_callback+ # This endpoint is designed for OAuth flows where the server+ # exchanges the authorization code for an access token+ # For client-side flows, use the regular /login endpoint with id_token++ strategy = authentication_strategy+ return unless strategy # Error already rendered by determine_strategy++ result = strategy.authenticate++ if result.success?+ user = result.value+ token = generate_jwt(user)+ render json: {+ token: token,+ user: user_serializer.new(user, serializer_context).as_json+ }+ else+ render_error(+ code: ERROR_CODES[:authentication_failed],+ message: result.error,+ status: :unauthorized+ )+ end+ end+protecteddef serializer_context@@ -58,6 +99,34 @@ module Spreeprivate+ def authentication_strategy+ strategy_class = determine_strategy+ strategy_class.new(+ params: params,+ request_env: request.headers.env,+ user_class: Spree.user_class+ )+ end++ def determine_strategy+ provider = params[:provider].presence || 'email'+ provider_key = provider.to_sym++ # Retrieve pre-loaded strategy class from configuration+ strategy_class = Rails.application.config.spree.authentication_strategies[provider_key]++ unless strategy_class+ render_error(+ code: ERROR_CODES[:invalid_provider],+ message: "Unsupported authentication provider: #{provider}",+ status: :bad_request+ )+ return nil+ end++ strategy_class+ end+def registration_paramsparams.require(:user).permit(:email, :password, :password_confirmation, :first_name, :last_name)enddiff --git a/api/config/routes.rb b/api/config/routes.rbindex 3352398f40..dfa36db275 100644--- a/api/config/routes.rb+++ b/api/config/routes.rb@@ -225,6 +225,7 @@ Spree::Core::Engine.add_routes dopost 'auth/login', to: 'auth#create'post 'auth/register', to: 'auth#register'post 'auth/refresh', to: 'auth#refresh'+ post 'auth/oauth/callback', to: 'auth#oauth_callback'# ===== STORE & CONFIGURATION (Public) =====get 'store', to: 'stores#current'diff --git a/core/app/models/concerns/spree/user_methods.rb b/core/app/models/concerns/spree/user_methods.rbindex 9e6786781d..4982b6e8dd 100644--- a/core/app/models/concerns/spree/user_methods.rb+++ b/core/app/models/concerns/spree/user_methods.rb@@ -40,6 +40,7 @@ module Spreehas_many :gift_cards, class_name: 'Spree::GiftCard', foreign_key: :user_id, dependent: :destroyhas_many :customer_group_users, class_name: 'Spree::CustomerGroupUser', foreign_key: :user_id, as: :user, dependent: :destroyhas_many :customer_groups, through: :customer_group_users, class_name: 'Spree::CustomerGroup'+ has_many :identities, class_name: 'Spree::UserIdentity', as: :user, dependent: :destroybelongs_to :ship_address, class_name: 'Spree::Address', optional: truebelongs_to :bill_address, class_name: 'Spree::Address', optional: truediff --git a/core/app/models/spree/authentication/strategies/base_strategy.rb b/core/app/models/spree/authentication/strategies/base_strategy.rbnew file mode 100644index 0000000000..6b332ab0ec--- /dev/null+++ b/core/app/models/spree/authentication/strategies/base_strategy.rb@@ -0,0 +1,55 @@+module Spree+ module Authentication+ module Strategies+ class BaseStrategy+ attr_reader :params, :request_env, :user_class++ def initialize(params:, request_env:, user_class: nil)+ @params = params+ @request_env = request_env+ @user_class = user_class || Spree.user_class+ end++ # Returns Result object with user on success+ # @return [Spree::ServiceModule::Result]+ def authenticate+ raise NotImplementedError, 'Subclass must implement #authenticate'+ end++ # Returns provider identifier (e.g., 'google', 'email')+ # @return [String]+ def provider+ raise NotImplementedError, 'Subclass must implement #provider'+ end++ protected++ # Success result with user+ def success(user)+ Spree::ServiceModule::Result.new(success: true, value: user)+ end++ # Failure result with error message+ def failure(message)+ Spree::ServiceModule::Result.new(success: false, error: message)+ end++ # Find user by email+ def find_user_by_email(email)+ user_class.find_by(email: email)+ end++ # Find or create user identity+ def find_or_create_user_from_oauth(provider:, uid:, info:, tokens: {})+ Spree::UserIdentity.find_or_create_from_oauth(+ provider: provider,+ uid: uid,+ info: info,+ tokens: tokens,+ user_class: user_class+ )+ end+ end+ end+ end+enddiff --git a/core/app/models/spree/authentication/strategies/email_password_strategy.rb b/core/app/models/spree/authentication/strategies/email_password_strategy.rbnew file mode 100644index 0000000000..3d5db32992--- /dev/null+++ b/core/app/models/spree/authentication/strategies/email_password_strategy.rb@@ -0,0 +1,47 @@+module Spree+ module Authentication+ module Strategies+ class EmailPasswordStrategy < BaseStrategy+ def authenticate+ email = params[:email]+ password = params[:password]++ return failure('Email is required') if email.blank?+ return failure('Password is required') if password.blank?++ user = find_user_by_email(email)+ return failure('Invalid email or password') unless user++ if validate_password(user, password)+ success(user)+ else+ failure('Invalid email or password')+ end+ rescue => e+ Rails.logger.error "EmailPasswordStrategy authentication failed: #{e.message}"+ failure('Authentication failed')+ end++ def provider+ 'email'+ end++ private++ def validate_password(user, password)+ # Try Devise's valid_password? method first (most common)+ if user.respond_to?(:valid_password?)+ user.valid_password?(password)+ # Fallback to authenticate method (for has_secure_password)+ elsif user.respond_to?(:authenticate)+ user.authenticate(password).present?+ else+ # No password authentication available+ Rails.logger.warn "User class #{user.class} does not implement password authentication"+ false+ end+ end+ end+ end+ end+enddiff --git a/core/app/models/spree/authentication/strategies/google_strategy.rb b/core/app/models/spree/authentication/strategies/google_strategy.rbnew file mode 100644index 0000000000..af82d15557--- /dev/null+++ b/core/app/models/spree/authentication/strategies/google_strategy.rb@@ -0,0 +1,67 @@+module Spree+ module Authentication+ module Strategies+ class GoogleStrategy < BaseStrategy+ def authenticate+ id_token = params[:id_token]+ return failure('Google ID token is required') if id_token.blank?++ # Verify Google ID token+ payload = verify_google_token(id_token)+ return failure('Invalid Google token') unless payload++ # Extract user info from Google payload+ info = {+ email: payload['email'],+ first_name: payload['given_name'],+ last_name: payload['family_name']+ }++ # Find or create user with identity+ user = find_or_create_user_from_oauth(+ provider: provider,+ uid: payload['sub'],+ info: info,+ tokens: {+ access_token: id_token,+ expires_at: Time.at(payload['exp'])+ }+ )++ success(user)+ rescue => e+ Rails.logger.error "GoogleStrategy authentication failed: #{e.message}"+ failure('Google authentication failed')+ end++ def provider+ 'google'+ end++ private++ def verify_google_token(token)+ # This requires google-id-token gem or similar+ # For production, use: Google::Auth::IDTokens.verify_oidc(token, aud: google_client_id)+ # For now, return a basic implementation that developers can override++ if defined?(Google::Auth::IDTokens)+ Google::Auth::IDTokens.verify_oidc(token, aud: google_client_id)+ else+ # Fallback for development - decode without verification+ # WARNING: This should never be used in production!+ Rails.logger.warn 'Google token verification skipped - install google-id-token gem for production'+ JWT.decode(token, nil, false).first+ end+ rescue => e+ Rails.logger.error "Google token verification failed: #{e.message}"+ nil+ end++ def google_client_id+ ENV['GOOGLE_CLIENT_ID'] || Rails.application.credentials.dig(:google, :client_id)+ end+ end+ end+ end+enddiff --git a/core/app/models/spree/user_identity.rb b/core/app/models/spree/user_identity.rbnew file mode 100644index 0000000000..eac4263ed1--- /dev/null+++ b/core/app/models/spree/user_identity.rb@@ -0,0 +1,77 @@+module Spree+ class UserIdentity < Spree::Base+ belongs_to :user, polymorphic: true, optional: false++ validates :provider, presence: true+ validates :uid, presence: true, uniqueness: { scope: [:provider, :user_type] }++ # Providers+ PROVIDERS = %w[email google facebook github apple].freeze++ validates :provider, inclusion: { in: PROVIDERS }++ # Store provider-specific data+ # info: JSON field with provider-specific data (name, avatar, etc)+ # access_token: encrypted OAuth access token+ # refresh_token: encrypted OAuth refresh token+ # expires_at: token expiration timestamp++ # Find or create user from OAuth data+ def self.find_or_create_from_oauth(provider:, uid:, info:, tokens: {}, user_class: nil)+ user_class ||= Spree.user_class+ user_type = user_class.name++ identity = find_by(provider: provider, uid: uid, user_type: user_type)++ if identity+ # Update existing identity with fresh tokens+ identity.update(+ info: info,+ access_token: tokens[:access_token],+ refresh_token: tokens[:refresh_token],+ expires_at: tokens[:expires_at]+ )+ identity.user+ else+ # Create new user and identity+ create_user_from_oauth(+ provider: provider,+ uid: uid,+ info: info,+ tokens: tokens,+ user_class: user_class+ )+ end+ end++ def self.create_user_from_oauth(provider:, uid:, info:, tokens: {}, user_class: nil)+ user_class ||= Spree.user_class++ user = user_class.create!(+ email: info[:email] || generate_temp_email(provider, uid),+ password: SecureRandom.hex(32), # Random password for OAuth users+ first_name: info[:first_name],+ last_name: info[:last_name]+ )++ user.identities.create!(+ provider: provider,+ uid: uid,+ info: info,+ access_token: tokens[:access_token],+ refresh_token: tokens[:refresh_token],+ expires_at: tokens[:expires_at]+ )++ user+ end++ def self.generate_temp_email(provider, uid)+ "#{provider}-#{uid}@temporary.example.com"+ end++ def expired?+ expires_at && expires_at < Time.current+ end+ end+enddiff --git a/core/db/migrate/20250923141900_create_spree_user_identities.rb b/core/db/migrate/20250923141900_create_spree_user_identities.rbnew file mode 100644index 0000000000..f73ebe30e1--- /dev/null+++ b/core/db/migrate/20250923141900_create_spree_user_identities.rb@@ -0,0 +1,17 @@+class CreateSpreeUserIdentities < ActiveRecord::Migration[7.0]+ def change+ create_table :spree_user_identities do |t|+ t.references :user, polymorphic: true, null: false, index: true+ t.string :provider, null: false+ t.string :uid, null: false+ t.json :info+ t.string :access_token+ t.string :refresh_token+ t.datetime :expires_at++ t.timestamps+ end++ add_index :spree_user_identities, [:provider, :uid, :user_type], unique: true, name: 'index_spree_user_identities_on_provider_uid_user_type'+ end+enddiff --git a/core/lib/spree/core.rb b/core/lib/spree/core.rbindex 9797afedc9..9455ee2b94 100644--- a/core/lib/spree/core.rb+++ b/core/lib/spree/core.rb@@ -18,6 +18,7 @@ require 'awesome_nested_set'require 'cancan'require 'countries/global'require 'friendly_id'+require 'jwt'require 'monetize'require 'mobility'require 'name_of_person'diff --git a/core/lib/spree/core/engine.rb b/core/lib/spree/core/engine.rbindex a4abe2a7ee..642335d3c8 100644--- a/core/lib/spree/core/engine.rb+++ b/core/lib/spree/core/engine.rb@@ -29,7 +29,8 @@ module Spree:analytics_events,:analytics_event_handlers,:integrations,- :subscribers)+ :subscribers,+ :authentication_strategies)SpreeCalculators = Struct.new(:shipping_methods, :tax_rates, :promotion_actions_create_adjustments, :promotion_actions_create_item_adjustments)PromoEnvironment = Struct.new(:rules, :actions)PricingEnvironment = Struct.new(:rules)@@ -304,6 +305,12 @@ module SpreeSpree::InvitationEmailSubscriber,Spree::ProductMetricsSubscriber]++ # Pre-load authentication strategy classes to avoid reflection at request time+ Rails.application.config.spree.authentication_strategies = {+ email: Spree::Authentication::Strategies::EmailPasswordStrategy,+ google: Spree::Authentication::Strategies::GoogleStrategy+ }endinitializer 'spree.promo.register.promotions.actions' do |app|diff --git a/core/lib/spree/testing_support/factories/user_identity_factory.rb b/core/lib/spree/testing_support/factories/user_identity_factory.rbnew file mode 100644index 0000000000..fd1aa575b0--- /dev/null+++ b/core/lib/spree/testing_support/factories/user_identity_factory.rb@@ -0,0 +1,56 @@+FactoryBot.define do+ factory :user_identity, class: Spree::UserIdentity do+ association(:user, factory: :user)+ provider { 'email' }+ sequence(:uid) { |n| "user_#{n}" }+ info { { email: user.email } }+ access_token { nil }+ refresh_token { nil }+ expires_at { nil }++ trait :google do+ provider { 'google' }+ sequence(:uid) { |n| "google_#{n}" }+ access_token { 'google_access_token' }+ refresh_token { 'google_refresh_token' }+ expires_at { 1.hour.from_now }+ info do+ {+ email: user.email,+ first_name: user.first_name,+ last_name: user.last_name+ }+ end+ end++ trait :facebook do+ provider { 'facebook' }+ sequence(:uid) { |n| "facebook_#{n}" }+ access_token { 'facebook_access_token' }+ info do+ {+ email: user.email,+ first_name: user.first_name,+ last_name: user.last_name+ }+ end+ end++ trait :github do+ provider { 'github' }+ sequence(:uid) { |n| "github_#{n}" }+ access_token { 'github_access_token' }+ info do+ {+ email: user.email,+ first_name: user.first_name,+ last_name: user.last_name+ }+ end+ end++ trait :expired do+ expires_at { 1.hour.ago }+ end+ end+enddiff --git a/core/spec/models/spree/authentication/strategies/base_strategy_spec.rb b/core/spec/models/spree/authentication/strategies/base_strategy_spec.rbnew file mode 100644index 0000000000..d7a9bff800--- /dev/null+++ b/core/spec/models/spree/authentication/strategies/base_strategy_spec.rb@@ -0,0 +1,127 @@+require 'spec_helper'++describe Spree::Authentication::Strategies::BaseStrategy do+ let(:params) { { email: '[email protected]', password: 'secret' } }+ let(:request_env) { {} }+ let(:user_class) { Spree.user_class }++ subject(:strategy) do+ described_class.new(params: params, request_env: request_env, user_class: user_class)+ end++ describe '#initialize' do+ it 'sets params' do+ expect(strategy.params).to eq(params)+ end++ it 'sets request_env' do+ expect(strategy.request_env).to eq(request_env)+ end++ it 'sets user_class' do+ expect(strategy.user_class).to eq(user_class)+ end++ context 'when user_class is not provided' do+ subject(:strategy) do+ described_class.new(params: params, request_env: request_env)+ end++ it 'defaults to Spree.user_class' do+ expect(strategy.user_class).to eq(Spree.user_class)+ end+ end+ end++ describe '#authenticate' do+ it 'raises NotImplementedError' do+ expect { strategy.authenticate }.to raise_error(NotImplementedError, 'Subclass must implement #authenticate')+ end+ end++ describe '#provider' do+ it 'raises NotImplementedError' do+ expect { strategy.provider }.to raise_error(NotImplementedError, 'Subclass must implement #provider')+ end+ end++ describe '#success' do+ let(:user) { create(:user) }++ it 'returns a successful Result' do+ result = strategy.send(:success, user)++ expect(result).to be_a(Spree::ServiceModule::Result)+ expect(result).to be_success+ expect(result.value).to eq(user)+ end+ end++ describe '#failure' do+ let(:message) { 'Authentication failed' }++ it 'returns a failed Result' do+ result = strategy.send(:failure, message)++ expect(result).to be_a(Spree::ServiceModule::Result)+ expect(result).not_to be_success+ expect(result.error).to eq(message)+ end+ end++ describe '#find_user_by_email' do+ let!(:user) { create(:user, email: '[email protected]') }++ it 'finds user by email' do+ result = strategy.send(:find_user_by_email, '[email protected]')+ expect(result).to eq(user)+ end++ it 'returns nil when user not found' do+ result = strategy.send(:find_user_by_email, '[email protected]')+ expect(result).to be_nil+ end+ end++ describe '#find_or_create_user_from_oauth' do+ let(:provider) { 'google' }+ let(:uid) { '123456' }+ let(:info) { { email: '[email protected]', first_name: 'OAuth', last_name: 'User' } }+ let(:tokens) { { access_token: 'token123' } }++ it 'delegates to UserIdentity.find_or_create_from_oauth' do+ expect(Spree::UserIdentity).to receive(:find_or_create_from_oauth).with(+ provider: provider,+ uid: uid,+ info: info,+ tokens: tokens,+ user_class: user_class+ )++ strategy.send(:find_or_create_user_from_oauth,+ provider: provider,+ uid: uid,+ info: info,+ tokens: tokens)+ end++ it 'passes the user_class' do+ admin_user_class = Spree.admin_user_class+ admin_strategy = described_class.new(+ params: params,+ request_env: request_env,+ user_class: admin_user_class+ )++ expect(Spree::UserIdentity).to receive(:find_or_create_from_oauth).with(+ hash_including(user_class: admin_user_class)+ )++ admin_strategy.send(:find_or_create_user_from_oauth,+ provider: provider,+ uid: uid,+ info: info,+ tokens: tokens)+ end+ end+enddiff --git a/core/spec/models/spree/authentication/strategies/email_password_strategy_spec.rb b/core/spec/models/spree/authentication/strategies/email_password_strategy_spec.rbnew file mode 100644index 0000000000..d1877963bc--- /dev/null+++ b/core/spec/models/spree/authentication/strategies/email_password_strategy_spec.rb@@ -0,0 +1,145 @@+require 'spec_helper'++describe Spree::Authentication::Strategies::EmailPasswordStrategy do+ let(:user) { create(:user, email: '[email protected]', password: 'password123') }+ let(:params) { { email: '[email protected]', password: 'password123' } }+ let(:request_env) { {} }++ subject(:strategy) do+ described_class.new(params: params, request_env: request_env)+ end++ describe '#provider' do+ it 'returns email' do+ expect(strategy.provider).to eq('email')+ end+ end++ describe '#authenticate' do+ context 'with valid credentials' do+ before do+ user # ensure user exists+ # Mock password validation since LegacyUser doesn't have authentication+ allow(user).to receive(:valid_password?).with('password123').and_return(true)+ allow(strategy).to receive(:find_user_by_email).with('[email protected]').and_return(user)+ end++ it 'returns successful result with user' do+ result = strategy.authenticate++ expect(result).to be_success+ expect(result.value).to eq(user)+ end+ end++ context 'with invalid email' do+ let(:params) { { email: '[email protected]', password: 'password123' } }++ it 'returns failure result' do+ result = strategy.authenticate++ expect(result).not_to be_success+ expect(result.error).to eq('Invalid email or password')+ end+ end++ context 'with invalid password' do+ let(:params) { { email: '[email protected]', password: 'wrongpassword' } }++ before do+ user # ensure user exists+ # Mock password validation to return false for wrong password+ allow(user).to receive(:valid_password?).with('wrongpassword').and_return(false)+ allow(strategy).to receive(:find_user_by_email).with('[email protected]').and_return(user)+ end++ it 'returns failure result' do+ result = strategy.authenticate++ expect(result).not_to be_success+ expect(result.error).to eq('Invalid email or password')+ end+ end++ context 'when email is blank' do+ let(:params) { { email: '', password: 'password123' } }++ it 'returns failure result' do+ result = strategy.authenticate++ expect(result).not_to be_success+ expect(result.error).to eq('Email is required')+ end+ end++ context 'when email is missing' do+ let(:params) { { password: 'password123' } }++ it 'returns failure result' do+ result = strategy.authenticate++ expect(result).not_to be_success+ expect(result.error).to eq('Email is required')+ end+ end++ context 'when password is blank' do+ let(:params) { { email: '[email protected]', password: '' } }++ it 'returns failure result' do+ result = strategy.authenticate++ expect(result).not_to be_success+ expect(result.error).to eq('Password is required')+ end+ end++ context 'when password is missing' do+ let(:params) { { email: '[email protected]' } }++ it 'returns failure result' do+ result = strategy.authenticate++ expect(result).not_to be_success+ expect(result.error).to eq('Password is required')+ end+ end++ context 'when an error occurs' do+ before do+ allow(strategy).to receive(:find_user_by_email).and_raise(StandardError, 'Database error')+ end++ it 'logs the error and returns failure' do+ expect(Rails.logger).to receive(:error).with(/EmailPasswordStrategy authentication failed/)++ result = strategy.authenticate++ expect(result).not_to be_success+ expect(result.error).to eq('Authentication failed')+ end+ end+ end++ describe 'with custom user class' do+ let(:admin_user) { create(:admin_user, email: '[email protected]', password: 'admin123') }+ let(:params) { { email: '[email protected]', password: 'admin123' } }+ let(:user_class) { Spree.admin_user_class }++ subject(:strategy) do+ described_class.new(params: params, request_env: request_env, user_class: user_class)+ end++ it 'authenticates with admin user class' do+ admin_user # ensure admin user exists+ # Mock password validation for admin user+ allow(admin_user).to receive(:valid_password?).with('admin123').and_return(true)+ allow(strategy).to receive(:find_user_by_email).with('[email protected]').and_return(admin_user)++ result = strategy.authenticate++ expect(result).to be_success+ expect(result.value).to eq(admin_user)+ end+ end+enddiff --git a/core/spec/models/spree/authentication/strategies/google_strategy_spec.rb b/core/spec/models/spree/authentication/strategies/google_strategy_spec.rbnew file mode 100644index 0000000000..c499e34396--- /dev/null+++ b/core/spec/models/spree/authentication/strategies/google_strategy_spec.rb@@ -0,0 +1,230 @@+require 'spec_helper'++describe Spree::Authentication::Strategies::GoogleStrategy do+ let(:id_token) { 'valid_google_id_token' }+ let(:params) { { id_token: id_token } }+ let(:request_env) { {} }++ subject(:strategy) do+ described_class.new(params: params, request_env: request_env)+ end++ let(:google_payload) do+ {+ 'sub' => '123456789',+ 'email' => '[email protected]',+ 'given_name' => 'John',+ 'family_name' => 'Doe',+ 'exp' => 1.hour.from_now.to_i+ }+ end++ describe '#provider' do+ it 'returns google' do+ expect(strategy.provider).to eq('google')+ end+ end++ describe '#authenticate' do+ context 'with valid Google token' do+ before do+ allow(strategy).to receive(:verify_google_token).with(id_token).and_return(google_payload)+ end++ context 'when user does not exist' do+ it 'returns successful result with new user' do+ expect do+ result = strategy.authenticate+ expect(result).to be_success+ expect(result.value).to be_a(Spree.user_class)+ end.to change(Spree.user_class, :count).by(1)+ .and change(Spree::UserIdentity, :count).by(1)+ end++ it 'creates user with correct attributes' do+ result = strategy.authenticate+ user = result.value++ expect(user.email).to eq('[email protected]')+ expect(user.first_name).to eq('John')+ expect(user.last_name).to eq('Doe')+ end++ it 'creates identity with correct attributes' do+ result = strategy.authenticate+ user = result.value+ identity = user.identities.first++ expect(identity.provider).to eq('google')+ expect(identity.uid).to eq('123456789')+ expect(identity.access_token).to eq(id_token)+ expect(identity.expires_at).to be_within(1.second).of(Time.at(google_payload['exp']))+ end+ end++ context 'when user already exists with identity' do+ let!(:user) { create(:user, email: '[email protected]') }+ let!(:identity) do+ create(:user_identity, :google,+ user: user,+ uid: '123456789',+ access_token: 'old_token')+ end++ it 'returns successful result with existing user' do+ expect do+ result = strategy.authenticate+ expect(result).to be_success+ expect(result.value).to eq(user)+ end.not_to change(Spree.user_class, :count)+ end++ it 'updates identity tokens' do+ strategy.authenticate++ identity.reload+ expect(identity.access_token).to eq(id_token)+ expect(identity.expires_at).to be_within(1.second).of(Time.at(google_payload['exp']))+ end+ end+ end++ context 'with invalid Google token' do+ before do+ allow(strategy).to receive(:verify_google_token).with(id_token).and_return(nil)+ end++ it 'returns failure result' do+ result = strategy.authenticate++ expect(result).not_to be_success+ expect(result.error).to eq('Invalid Google token')+ end+ end++ context 'when id_token is blank' do+ let(:params) { { id_token: '' } }++ it 'returns failure result' do+ result = strategy.authenticate++ expect(result).not_to be_success+ expect(result.error).to eq('Google ID token is required')+ end+ end++ context 'when id_token is missing' do+ let(:params) { {} }++ it 'returns failure result' do+ result = strategy.authenticate++ expect(result).not_to be_success+ expect(result.error).to eq('Google ID token is required')+ end+ end++ context 'when an error occurs during authentication' do+ before do+ allow(strategy).to receive(:verify_google_token).and_raise(StandardError, 'Token verification error')+ end++ it 'logs the error and returns failure' do+ expect(Rails.logger).to receive(:error).with(/GoogleStrategy authentication failed/)++ result = strategy.authenticate++ expect(result).not_to be_success+ expect(result.error).to eq('Google authentication failed')+ end+ end+ end++ describe '#verify_google_token' do+ let(:client_id) { 'test_client_id' }++ before do+ allow(ENV).to receive(:[]).and_call_original+ allow(ENV).to receive(:[]).with('GOOGLE_CLIENT_ID').and_return(client_id)+ end++ context 'when Google::Auth::IDTokens is defined' do+ before do+ stub_const('Google::Auth::IDTokens', double)+ end++ it 'verifies token with Google library' do+ expect(Google::Auth::IDTokens).to receive(:verify_oidc).with(id_token, aud: client_id).and_return(google_payload)++ result = strategy.send(:verify_google_token, id_token)+ expect(result).to eq(google_payload)+ end++ context 'when verification fails' do+ before do+ allow(Google::Auth::IDTokens).to receive(:verify_oidc).and_raise(StandardError, 'Invalid token')+ end++ it 'logs error and returns nil' do+ expect(Rails.logger).to receive(:error).with(/Google token verification failed/)++ result = strategy.send(:verify_google_token, id_token)+ expect(result).to be_nil+ end+ end+ end++ context 'when Google::Auth::IDTokens is not defined' do+ it 'decodes token without verification and logs warning' do+ expect(Rails.logger).to receive(:warn).with(/Google token verification skipped/)+ allow(JWT).to receive(:decode).with(id_token, nil, false).and_return([google_payload])++ result = strategy.send(:verify_google_token, id_token)+ expect(result).to eq(google_payload)+ end+ end+ end++ describe '#google_client_id' do+ context 'when set in environment' do+ before do+ allow(ENV).to receive(:[]).and_call_original+ allow(ENV).to receive(:[]).with('GOOGLE_CLIENT_ID').and_return('env_client_id')+ end++ it 'returns environment variable value' do+ expect(strategy.send(:google_client_id)).to eq('env_client_id')+ end+ end++ context 'when set in credentials' do+ before do+ allow(ENV).to receive(:[]).with('GOOGLE_CLIENT_ID').and_return(nil)+ allow(Rails.application.credentials).to receive(:dig).with(:google, :client_id).and_return('credentials_client_id')+ end++ it 'returns credentials value' do+ expect(strategy.send(:google_client_id)).to eq('credentials_client_id')+ end+ end+ end++ describe 'with custom user class' do+ let(:admin_user_class) { Spree.admin_user_class }++ subject(:strategy) do+ described_class.new(params: params, request_env: request_env, user_class: admin_user_class)+ end++ before do+ allow(strategy).to receive(:verify_google_token).with(id_token).and_return(google_payload)+ end++ it 'creates user with admin user class' do+ result = strategy.authenticate++ expect(result).to be_success+ expect(result.value).to be_a(admin_user_class)+ end+ end+enddiff --git a/core/spec/models/spree/user_identity_spec.rb b/core/spec/models/spree/user_identity_spec.rbnew file mode 100644index 0000000000..cb80e7d5d4--- /dev/null+++ b/core/spec/models/spree/user_identity_spec.rb@@ -0,0 +1,229 @@+require 'spec_helper'++describe Spree::UserIdentity, type: :model do+ describe 'associations' do+ it { is_expected.to belong_to(:user).required }+ end++ describe 'validations' do+ subject { build(:user_identity) }++ it { is_expected.to validate_presence_of(:provider) }+ it { is_expected.to validate_presence_of(:uid) }+ it { is_expected.to validate_inclusion_of(:provider).in_array(Spree::UserIdentity::PROVIDERS) }++ describe 'uniqueness validation' do+ let(:user) { create(:user) }+ let!(:existing_identity) do+ create(:user_identity, user: user, provider: 'google', uid: '12345')+ end++ it 'validates uniqueness of uid scoped to provider and user_type' do+ duplicate = build(:user_identity, user: user, provider: 'google', uid: '12345')+ expect(duplicate).not_to be_valid+ expect(duplicate.errors[:uid]).to include('has already been taken')+ end++ it 'allows same uid for different providers' do+ different_provider = build(:user_identity, user: user, provider: 'facebook', uid: '12345')+ expect(different_provider).to be_valid+ end++ it 'allows same uid for different user types' do+ stub_const('Spree::AdminUser', Class.new(Spree.user_class))++ different_user_type = build(:user_identity, user_type: 'Spree::AdminUser', user_id: user.id, provider: 'google', uid: '12345')+ expect(different_user_type).to be_valid+ end+ end+ end++ describe '.find_or_create_from_oauth' do+ let(:provider) { 'google' }+ let(:uid) { '123456789' }+ let(:info) do+ {+ email: '[email protected]',+ first_name: 'John',+ last_name: 'Doe'+ }+ end+ let(:tokens) do+ {+ access_token: 'access_token_123',+ refresh_token: 'refresh_token_456',+ expires_at: 1.hour.from_now+ }+ end++ context 'when identity does not exist' do+ it 'creates a new user and identity' do+ expect do+ described_class.find_or_create_from_oauth(+ provider: provider,+ uid: uid,+ info: info,+ tokens: tokens+ )+ end.to change(Spree.user_class, :count).by(1)+ .and change(described_class, :count).by(1)+ end++ it 'sets user attributes from info' do+ user = described_class.find_or_create_from_oauth(+ provider: provider,+ uid: uid,+ info: info,+ tokens: tokens+ )++ expect(user.email).to eq('[email protected]')+ expect(user.first_name).to eq('John')+ expect(user.last_name).to eq('Doe')+ end++ it 'creates identity with tokens' do+ user = described_class.find_or_create_from_oauth(+ provider: provider,+ uid: uid,+ info: info,+ tokens: tokens+ )++ identity = user.identities.first+ expect(identity.provider).to eq('google')+ expect(identity.uid).to eq('123456789')+ expect(identity.access_token).to eq('access_token_123')+ expect(identity.refresh_token).to eq('refresh_token_456')+ expect(identity.expires_at).to be_within(1.second).of(tokens[:expires_at])+ end++ it 'generates temporary email if email is missing' do+ user = described_class.find_or_create_from_oauth(+ provider: provider,+ uid: uid,+ info: info.except(:email),+ tokens: tokens+ )++ expect(user.email).to eq('[email protected]')+ end++ it 'uses custom user class when provided' do+ admin_user_class = Spree.admin_user_class++ user = described_class.find_or_create_from_oauth(+ provider: provider,+ uid: uid,+ info: info,+ tokens: tokens,+ user_class: admin_user_class+ )++ expect(user).to be_a(admin_user_class)+ end+ end++ context 'when identity already exists' do+ let!(:user) { create(:user, email: '[email protected]') }+ let!(:identity) do+ create(:user_identity,+ user: user,+ provider: provider,+ uid: uid,+ access_token: 'old_token',+ refresh_token: 'old_refresh')+ end++ it 'does not create a new user' do+ expect do+ described_class.find_or_create_from_oauth(+ provider: provider,+ uid: uid,+ info: info,+ tokens: tokens+ )+ end.not_to change(Spree.user_class, :count)+ end++ it 'returns the existing user' do+ result = described_class.find_or_create_from_oauth(+ provider: provider,+ uid: uid,+ info: info,+ tokens: tokens+ )++ expect(result).to eq(user)+ end++ it 'updates identity tokens' do+ described_class.find_or_create_from_oauth(+ provider: provider,+ uid: uid,+ info: info,+ tokens: tokens+ )++ identity.reload+ expect(identity.access_token).to eq('access_token_123')+ expect(identity.refresh_token).to eq('refresh_token_456')+ expect(identity.expires_at).to be_within(1.second).of(tokens[:expires_at])+ end++ it 'updates identity info' do+ described_class.find_or_create_from_oauth(+ provider: provider,+ uid: uid,+ info: { email: '[email protected]', first_name: 'Jane' },+ tokens: tokens+ )++ identity.reload+ expect(identity.info).to include('email' => '[email protected]', 'first_name' => 'Jane')+ end+ end+ end++ describe '.create_user_from_oauth' do+ it 'creates user with random password' do+ user = described_class.create_user_from_oauth(+ provider: 'google',+ uid: '123',+ info: { email: '[email protected]', first_name: 'Test', last_name: 'User' },+ tokens: {}+ )++ expect(user.persisted?).to be_truthy+ expect(user.valid?).to be_truthy+ expect(user.password).to be_present+ end+ end++ describe '.generate_temp_email' do+ it 'generates email with provider and uid' do+ email = described_class.generate_temp_email('google', '123456')+ expect(email).to eq('[email protected]')+ end+ end++ describe '#expired?' do+ context 'when expires_at is nil' do+ subject { build(:user_identity, expires_at: nil) }++ it { is_expected.not_to be_expired }+ end++ context 'when expires_at is in the future' do+ subject { build(:user_identity, expires_at: 1.hour.from_now) }++ it { is_expected.not_to be_expired }+ end++ context 'when expires_at is in the past' do+ subject { build(:user_identity, expires_at: 1.hour.ago) }++ it { is_expected.to be_expired }+ end+ end+enddiff --git a/core/spree_core.gemspec b/core/spree_core.gemspecindex df7bef5d07..eb889579b4 100644--- a/core/spree_core.gemspec+++ b/core/spree_core.gemspec@@ -41,6 +41,7 @@ Gem::Specification.new do |s|s.add_dependency 'friendly_id', '~> 5.2', '>= 5.2.1's.add_dependency 'geocoder's.add_dependency 'highline', '>= 2', '< 4' # Necessary for the install generator+ s.add_dependency 'jwt', '~> 3.1's.add_dependency 'money', '~> 6.13's.add_dependency 'monetize', '~> 1.9's.add_dependency 'name_of_person', '~> 1.1'