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 publishable key authentication to Store API
Damian Legawieca8e240a4684e
diff --git a/api/app/controllers/concerns/spree/api/v3/api_key_authentication.rb b/api/app/controllers/concerns/spree/api/v3/api_key_authentication.rbnew file mode 100644index 0000000000..5388406c13--- /dev/null+++ b/api/app/controllers/concerns/spree/api/v3/api_key_authentication.rb@@ -0,0 +1,55 @@+module Spree+ module Api+ module V3+ module ApiKeyAuthentication+ extend ActiveSupport::Concern++ included do+ attr_reader :current_api_key+ end++ def authenticate_api_key!+ @current_api_key = current_store.api_keys.active.publishable.find_by(token: extract_api_key)++ unless @current_api_key+ render_error(+ code: ErrorHandler::ERROR_CODES[:invalid_token],+ message: 'Valid API key required',+ status: :unauthorized+ )+ return false+ end++ Spree::ApiKeyTouchJob.perform_later(@current_api_key.id)+ true+ end++ def authenticate_secret_key!+ @current_api_key = current_store.api_keys.active.secret.find_by(token: extract_api_key)++ unless @current_api_key+ render_error(+ code: ErrorHandler::ERROR_CODES[:invalid_token],+ message: 'Valid secret API key required',+ status: :unauthorized+ )+ return false+ end++ Spree::ApiKeyTouchJob.perform_later(@current_api_key.id)+ true+ end++ def admin_context?+ @current_api_key&.secret? || current_user&.try(:spree_admin?, current_store)+ end++ private++ def extract_api_key+ request.headers['X-Spree-Api-Key'].presence || params[:api_key]+ end+ end+ end+ end+enddiff --git a/api/app/controllers/concerns/spree/api/v3/authentication.rb b/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rbsimilarity index 56%rename from api/app/controllers/concerns/spree/api/v3/authentication.rbrename to api/app/controllers/concerns/spree/api/v3/jwt_authentication.rbindex 802a1c8c3a..b2b8523265 100644--- a/api/app/controllers/concerns/spree/api/v3/authentication.rb+++ b/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb@@ -1,11 +1,14 @@module Spreemodule Apimodule V3- module Authentication+ module JwtAuthenticationextend ActiveSupport::Concerninclude Spree::Api::V3::ErrorHandler+ USER_TYPE_CUSTOMER = 'customer'.freeze+ USER_TYPE_ADMIN = 'admin'.freeze+included doattr_reader :current_userend@@ -16,7 +19,7 @@ module Spreereturn unless token.present?payload = decode_jwt(token)- @current_user = Spree.user_class.find(payload['user_id'])+ @current_user = find_user_from_payload(payload)rescue JWT::DecodeError, JWT::ExpiredSignature, ActiveRecord::RecordNotFound => eRails.logger.debug { "JWT authentication failed: #{e.message}" }@current_user = nil@@ -32,6 +35,21 @@ module Spreeendend+ protected++ # Generate a JWT token for a user+ # @param user [Object] The user to generate a token for+ # @param expiration [Integer] Time in seconds until expiration (default 24 hours)+ # @return [String] The JWT token+ def generate_jwt(user, expiration: 24.hours.to_i)+ payload = {+ user_id: user.id,+ user_type: determine_user_type(user),+ exp: Time.current.to_i + expiration+ }+ JWT.encode(payload, jwt_secret, 'HS256')+ end+privatedef extract_token@@ -50,6 +68,26 @@ module Spreedef jwt_secretRails.application.credentials.jwt_secret_key || ENV['JWT_SECRET_KEY'] || Rails.application.secret_key_baseend++ def find_user_from_payload(payload)+ user_id = payload['user_id']+ user_type = payload['user_type'] || USER_TYPE_CUSTOMER++ case user_type+ when USER_TYPE_ADMIN+ Spree.admin_user_class.find(user_id)+ else+ Spree.user_class.find(user_id)+ end+ end++ def determine_user_type(user)+ if user.is_a?(Spree.admin_user_class)+ USER_TYPE_ADMIN+ else+ USER_TYPE_CUSTOMER+ end+ endendendenddiff --git a/api/app/controllers/concerns/spree/api/v3/store/authentication.rb b/api/app/controllers/concerns/spree/api/v3/store/authentication.rbdeleted file mode 100644index 49b9f26953..0000000000--- a/api/app/controllers/concerns/spree/api/v3/store/authentication.rb+++ /dev/null@@ -1,33 +0,0 @@-module Spree- module Api- module V3- module Store- # This concern provides helper methods for generating JWT tokens- # For authentication verification, see Spree::Api::V3::Authentication- module Authentication- extend ActiveSupport::Concern-- protected-- # Generate a JWT token for a user- # @param user [Spree.user_class] The user to generate a token for- # @param expiration [Integer] Time in seconds until expiration (default 24 hours)- # @return [String] The JWT token- def generate_jwt(user, expiration: 24.hours.to_i)- payload = {- user_id: user.id,- exp: Time.current.to_i + expiration- }- JWT.encode(payload, jwt_secret, 'HS256')- end-- private-- def jwt_secret- Rails.application.credentials.jwt_secret_key || ENV['JWT_SECRET_KEY'] || Rails.application.secret_key_base- end- end- end- end- end-enddiff --git a/api/app/controllers/spree/api/v3/base_controller.rb b/api/app/controllers/spree/api/v3/base_controller.rbindex b5c865975b..c21b39c251 100644--- a/api/app/controllers/spree/api/v3/base_controller.rb+++ b/api/app/controllers/spree/api/v3/base_controller.rb@@ -8,13 +8,14 @@ module Spreeinclude Spree::Core::ControllerHelpers::Storeinclude Spree::Core::ControllerHelpers::Localeinclude Spree::Core::ControllerHelpers::Currency- include Spree::Api::V3::Authentication+ include Spree::Api::V3::JwtAuthentication+ include Spree::Api::V3::ApiKeyAuthenticationinclude Spree::Api::V3::ErrorHandlerinclude Spree::Api::V3::HttpCachinginclude Spree::Api::V3::ResourceSerializerinclude Pagy::Method- # Optional authentication by default+ # Optional JWT authentication by defaultbefore_action :authenticate_userprotecteddiff --git a/api/app/controllers/spree/api/v3/store/auth_controller.rb b/api/app/controllers/spree/api/v3/store/auth_controller.rbindex 474b006b21..5c0b61a4ac 100644--- a/api/app/controllers/spree/api/v3/store/auth_controller.rb+++ b/api/app/controllers/spree/api/v3/store/auth_controller.rb@@ -2,9 +2,7 @@ module Spreemodule Apimodule V3module Store- class AuthController < BaseController- include Spree::Api::V3::Storefront::Authentication-+ class AuthController < Store::BaseControllerskip_before_action :authenticate_user, only: [:create, :register, :oauth_callback]before_action :require_authentication!, only: [:refresh]diff --git a/api/app/controllers/spree/api/v3/store/base_controller.rb b/api/app/controllers/spree/api/v3/store/base_controller.rbnew file mode 100644index 0000000000..183354efb5--- /dev/null+++ b/api/app/controllers/spree/api/v3/store/base_controller.rb@@ -0,0 +1,19 @@+module Spree+ module Api+ module V3+ module Store+ class BaseController < Spree::Api::V3::BaseController+ # Require publishable API key for all Store API requests+ before_action :authenticate_api_key!++ protected++ # Store API always uses store context (not admin)+ def admin_context?+ false+ end+ end+ end+ end+ end+end