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 documentation on custom authentication
Damian Legawiec6490e72c2ff2
diff --git a/core/lib/generators/spree/authentication/custom/custom_generator.rb b/core/lib/generators/spree/authentication/custom/custom_generator.rbnew file mode 100644index 0000000000..c0a439e278--- /dev/null+++ b/core/lib/generators/spree/authentication/custom/custom_generator.rb@@ -0,0 +1,49 @@+require 'rails/generators'++module Spree+ module Authentication+ class CustomGenerator < Rails::Generators::Base+ desc 'Set up a Spree installation with custom authentication'++ def self.source_paths+ paths = superclass.source_paths+ paths << File.expand_path('templates', __dir__)+ paths.flatten+ end++ def generate+ template 'authentication_helpers.rb.tt', 'lib/spree/authentication_helpers.rb'++ file_action = File.exist?('config/initializers/spree.rb') ? :append_file : :create_file+ send(file_action, 'config/initializers/spree.rb') do+ %Q{+ Rails.application.config.to_prepare do+ require_dependency 'spree/authentication_helpers'+ end\n}+ end++ user_class_file = Rails.root.join('app', 'models', "#{Spree.user_class.name.underscore}.rb")++ if File.exist?(user_class_file)+ inject_into_file user_class_file, after: "class #{Spree.user_class.name} < ApplicationRecord\n" do+ <<-RUBY+ # Spree modules+ include Spree::UserAddress+ include Spree::UserMethods+ include Spree::UserPaymentSource+ RUBY+ end+ say "Successfully added Spree user modules into #{user_class_file}"+ else+ say "Could not locate user model file at #{user_class_file}. Please add these lines manually:", :red+ say <<~RUBY+ # Spree modules+ include Spree::UserAddress+ include Spree::UserMethods+ include Spree::UserPaymentSource+ RUBY+ end+ end+ end+ end+enddiff --git a/core/lib/generators/spree/authentication/custom/templates/authentication_helpers.rb.tt b/core/lib/generators/spree/authentication/custom/templates/authentication_helpers.rb.ttnew file mode 100644index 0000000000..d3a4ad5b1f--- /dev/null+++ b/core/lib/generators/spree/authentication/custom/templates/authentication_helpers.rb.tt@@ -0,0 +1,50 @@+module Spree+ module AuthenticationHelpers+ def self.included(receiver)+ receiver.helper_method(+ :spree_current_user,+ :spree_login_path,+ :spree_signup_path,+ :spree_logout_path,+ :spree_forgot_password_path,+ :spree_edit_password_path,+ :spree_admin_login_path,+ :spree_admin_logout_path+ )+ end++ def spree_current_user+ current_user+ end++ def spree_login_path(opts = {})+ main_app.login_path(opts)+ end++ def spree_signup_path(opts = {})+ main_app.signup_path(opts = {})+ end++ def spree_logout_path(opts = {})+ main_app.logout_path(opts = {})+ end++ def spree_forgot_password_path(opts = {})+ main_app.forgot_password_path(opts)+ end++ def spree_edit_password_path(opts = {})+ main_app.spree_edit_password_path(opts)+ end++ def spree_admin_login_path(opts = {})+ spree_login_path(opts)+ end++ def spree_admin_logout_path(opts = {})+ spree_logout_path(opts)+ end+ end+end++ApplicationController.include Spree::AuthenticationHelpers if defined?(ApplicationController)\ No newline at end of filediff --git a/docs/developer/customization/authentication.mdx b/docs/developer/customization/authentication.mdxindex 7603aae5a8..6d81000930 100644--- a/docs/developer/customization/authentication.mdx+++ b/docs/developer/customization/authentication.mdx@@ -1,187 +1,87 @@---title: Authenticationdescription: Learn how to use a custom authentication setup with Spree-version: v4+version: v5----This guide covers using a custom authentication setup with Spree, such as one provided by your own application. This is ideal in situations where you want to handle the sign-in or sign-up flow of your application uniquely, outside the realms of what would be possible with Spree or you have an existing authentication with user accounts present.+If you installed Spree following the [Quickstart guide](/developer/quickstart), you can completely this step - you are all set and integrated with the [Devise](https://github.com/plataformatec/devise) gem.-This guide assumes that you have a pre-existing model inside your application that represents the users of your application already. This model could be provided by gems such as [Devise](https://github.com/plataformatec/devise). This guide also assumes that the application that this `User` model exists in is already a Spree application.+However if you're adding Spree to an existing application that has its own authentication system, you will need to follow these steps.-<Note>-This model **does not** need to be called `User`, but for the purposes of this guide the model we will be referring to **will** be called `User`. If your model is called something else, do some mental substitution wherever you see `User`.-</Note>+## Using Devise-To use your own authentication system with Spree, please follow these steps:+If you're currently using [Devise](https://github.com/plataformatec/devise) for authentication, you can follow the steps below to integrate Spree with your existing authentication system.-<AccordionGroup>- <Accordion title="1. Change the Spree.user_class">- To begin using your custom `User` class, you must first edit Spree's initializer located at `config/initializers/spree.rb` by changing this line:+Firstly set your `User` class as `Spree.user_class` in your `config/initializers/spree.rb` file:- ```ruby- Spree.user_class = 'Spree::User'- ```-- To this:-- ```ruby- Spree.user_class = 'User'- ```- </Accordion>-- <Accordion title="2. Update User model">- Next, you need to run the custom user generator for Spree which will create a migration that will add the necessary Spree fields to your users table.+```ruby+Spree.user_class = 'User'+```- Run this generator with this command:+Now, run the generator to setup Spree integration with Devise:- ```bash- bin/rails g spree:custom_user User- ```+```bash+bin/rails g spree:authentication:devise+```- This will tell the generator that you want to use the `User` class as the class that represents users in Spree. Run the new migration by running this:+This will create the a new file in `lib/spree/authentication_helpers.rb` that serves as a bridge between Spree and your existing authentication system routes. You can then use this file to customize the routes to your liking. It should automatically pick up standard Devise routes.- ```bash- bin/rails db:migrate- ```+Secondly, this generator will add necessary modules to your `User` model.- This generator will also create a file at `lib/spree/current_user_helpers.rb` which will be automatically included in your application's controllers allowing you to override the `spree_current_user` method to return the current user of the request.- </Accordion>- <Accordion title="3. Include User concerns in your User model">- In your User Model please include the following lines:+```ruby+# app/models/user.rb+class User < ApplicationRecord+ # ... your existing code ...++ include Spree::UserAddress+ include Spree::UserMethods+ include Spree::UserPaymentSource+end+```- ```ruby- include Spree::UserMethods- include Spree::UserAddress- include Spree::UserPaymentSource- ```+This will ensure that your `User` model can be used as a Spree user.- The first of these methods are the ones added for the `has_and_belongs_to_many` association called `spree_roles`. This association will retrieve all the roles that a user has for Spree.+This generator will also add 2 new lines to your Spree initializer file:- The second of these is the `spree_orders` association. This will return all orders associated with the user in Spree. There's also a `last_incomplete_spree_order` method which will return the last incomplete spree order for the user. This is used internal to Spree to persist order data across a user's login sessions.+```ruby+Devise.parent_controller = "Spree::StoreController"+Devise.parent_mailer = "Spree::BaseMailer"+```- The third and fourth associations are for address information for a user. When a user places an order, the address information for that order will be linked to that user so that it is available for subsequent orders.+This ensures that Devise will use Spree storefront layout for login/signup/etc and use Spree mailer layout for sending emails so they'll match your Storefront branding.- The next method is one called `has_spree_role?` which can be used to check if a user has a specific role. This method is used internally to Spree to check if the user is authorized to perform specific actions, such as accessing the admin section. Admin users of your system should be assigned the Spree admin role, like this:+If you have more complex setup, you can remove these lines and customize the routes and mailer in your own initializer file.- ```ruby- user = User.find_by(email: '[email protected]')- user.spree_roles << Spree::Role.where(name: 'admin').first_or_create- ```+## Using Custom Authentication- To test that this has worked, use the `has_spree_role?` method, like this:+If you're using a custom authentication system, you can follow the steps below to integrate Spree with your existing authentication system.- ```ruby- user.has_spree_role?('admin')- ```+Firstly set your `User` class as `Spree.user_class` in your `config/initializers/spree.rb` file:- If this returns `true`, then the user has admin permissions within Spree.- </Accordion>- <Accordion title="4. Customize Spree Authentication Helpers (Optional)">- <Note>- This step is required if you're using `spree_backend` and/or `spree_frontend` gems.- </Note>+```ruby+Spree.user_class = 'User'+```- Run a generator to create a file at `lib/spree/authentication_helpers.rb` which will contain the following code to help you do that:+Now, run the generator to setup Spree integration with your custom authentication system:- ```bash- bin/rails g spree:custom_authentication- ```+```bash+bin/rails g spree:authentication:custom+```- This will create a file at `lib/spree/authentication_helpers.rb` which will contain the following code to help you do that:+This will create the a new file in `lib/spree/authentication_helpers.rb` that serves as a bridge between Spree and your existing authentication system routes. You will need to customize this file to fit your needs.- ```ruby- module Spree- module AuthenticationHelpers- def self.included(receiver)- receiver.helper_method(- :spree_current_user,- :spree_login_path,- :spree_signup_path,- :spree_logout_path,- :spree_forgot_password_path,- :spree_edit_password_path,- :spree_admin_login_path,- :spree_admin_logout_path,- )- end+Secondly, this generator will add necessary modules to your `User` model.- def spree_current_user- current_user- end-- def spree_login_path(opts = {})- main_app.login_path(opts)- end-- def spree_signup_path(opts = {})- main_app.signup_path(opts)- end-- def spree_logout_path(opts = {})- main_app.logout_path(opts)- end-- def spree_forgot_password_path(opts = {})- main_app.forgot_password_path(opts)- end-- def spree_edit_password_path(opts = {})- main_app.edit_password_path(opts)- end-- def spree_admin_login_path(opts = {})- main_app.admin_login_path(opts)- end-- def spree_admin_logout_path(opts = {})- main_app.admin_logout_path(opts)- end- end- end- ```-- Each of the methods defined in this module return values that are the most common in Rails applications today, but you may need to customize them. In order, they are:-- * `spree_current_user` Used to tell Spree what the current user of a request is.- * `spree_login_path` The location of the login/sign in form in your application.- * `spree_signup_path` The location of the sign up form in your application.- * `spree_logout_path` The location of the logout feature of your application.- * `spree_forgot_password_path` The location to reset a user's password.- * `spree_edit_password_path` The location to edit a user's password.- * `spree_admin_login_path` The location of the login/sign in form for the admin panel.- * `spree_admin_logout_path` The location of the logout feature for the admin panel.-- URLs inside the helpers **must** have `main_app` prefixed if they are inside your application. This is because Spree will otherwise attempt to route these paths to the Spree engine, which does not exist. By prefixing with `main_app`, you tell it to look at the application's routes.-- You will need to define the `login_path`, `signup_path` and `logout_path` routes yourself, by using code like this inside your application's `config/routes.rb` if you're using Devise:-- ```ruby- devise_for :users- devise_scope :user do- get '/login', to: "devise/sessions#new"- get '/signup', to: "devise/registrations#new"- delete '/logout', to: "devise/sessions#destroy"- get '/forgot_password', to: "devise/passwords#new"- get '/edit_password', to: "devise/registrations#edit"- end- ```-- Of course, this code will be different if you're not using Devise. Simply **do not** use the `devise_scope` method and change the controllers and actions for these routes.-- You can also customize these methods inside `lib/spree/authentication_helpers.rb` to use the routing helper methods already provided by the authentication setup you have, if you wish.-- Any modifications made to `lib/spree/authentication_helpers.rb` while the server is running will require a restart, as with any other modification to other files in `lib`.- </Accordion>- <Accordion title="5. Remove Auth Devise gem">- The `spree_auth_devise` gem is not needed when using an existing application authentication unless the goal is to have two separate authentication methods.-- You can remove the `spree_auth_devise` gem by running this command:-- ```bash- bundle remove spree_auth_devise- ```- </Accordion>-</AccordionGroup>+```ruby+# app/models/user.rb+class User < ApplicationRecord+ # ... your existing code ...++ include Spree::UserAddress+ include Spree::UserMethods+ include Spree::UserPaymentSource+end+```## Admin Panel authenticationdiff --git a/docs/developer/customization/admin-panel.mdx b/docs/developer/customization/v4/admin-panel.mdxsimilarity index 98%rename from docs/developer/customization/admin-panel.mdxrename to docs/developer/customization/v4/admin-panel.mdxindex 0d7d22a445..11d287d3d2 100644--- a/docs/developer/customization/admin-panel.mdx+++ b/docs/developer/customization/v4/admin-panel.mdx@@ -1,4 +1,6 @@-# Admin Panel+<Warning>+ This section is only relevant for Spree 4+</Warning>Starting with Spree 4.7, we've introduced a new way of customizing the admin panel, that enables extensions to modify the admin panel UI without depending on the Deface gem. For Spree 4.6 and earlier, please see how to use [deface_overrides_tutorial.md](../advanced/deface_overrides_tutorial.md "mention") overrides.diff --git a/docs/developer/customization/v4/authentication.mdx b/docs/developer/customization/v4/authentication.mdxnew file mode 100644index 0000000000..9132df84be--- /dev/null+++ b/docs/developer/customization/v4/authentication.mdx@@ -0,0 +1,196 @@+---+title: Authentication+description: Learn how to use a custom authentication setup with Spree+version: v4+---++This guide covers using a custom authentication setup with Spree, such as one provided by your own application. This is ideal in situations where you want to handle the sign-in or sign-up flow of your application uniquely, outside the realms of what would be possible with Spree or you have an existing authentication with user accounts present.++This guide assumes that you have a pre-existing model inside your application that represents the users of your application already. This model could be provided by gems such as [Devise](https://github.com/plataformatec/devise). This guide also assumes that the application that this `User` model exists in is already a Spree application.++<Note>+This model **does not** need to be called `User`, but for the purposes of this guide the model we will be referring to **will** be called `User`. If your model is called something else, do some mental substitution wherever you see `User`.+</Note>++To use your own authentication system with Spree, please follow these steps:++<AccordionGroup>+ <Accordion title="1. Change the Spree.user_class">+ To begin using your custom `User` class, you must first edit Spree's initializer located at `config/initializers/spree.rb` by changing this line:++ ```ruby+ Spree.user_class = 'Spree::User'+ ```++ To this:++ ```ruby+ Spree.user_class = 'User'+ ```+ </Accordion>++ <Accordion title="2. Update User model">+ Next, you need to run the custom user generator for Spree which will create a migration that will add the necessary Spree fields to your users table.++ Run this generator with this command:++ ```bash+ bin/rails g spree:custom_user User+ ```++ This will tell the generator that you want to use the `User` class as the class that represents users in Spree. Run the new migration by running this:++ ```bash+ bin/rails db:migrate+ ```++ This generator will also create a file at `lib/spree/current_user_helpers.rb` which will be automatically included in your application's controllers allowing you to override the `spree_current_user` method to return the current user of the request.+ </Accordion>+ <Accordion title="3. Include User concerns in your User model">+ In your User Model please include the following lines:++ ```ruby+ include Spree::UserMethods+ include Spree::UserAddress+ include Spree::UserPaymentSource+ ```++ The first of these methods are the ones added for the `has_and_belongs_to_many` association called `spree_roles`. This association will retrieve all the roles that a user has for Spree.++ The second of these is the `spree_orders` association. This will return all orders associated with the user in Spree. There's also a `last_incomplete_spree_order` method which will return the last incomplete spree order for the user. This is used internal to Spree to persist order data across a user's login sessions.++ The third and fourth associations are for address information for a user. When a user places an order, the address information for that order will be linked to that user so that it is available for subsequent orders.++ The next method is one called `has_spree_role?` which can be used to check if a user has a specific role. This method is used internally to Spree to check if the user is authorized to perform specific actions, such as accessing the admin section. Admin users of your system should be assigned the Spree admin role, like this:++ ```ruby+ user = User.find_by(email: '[email protected]')+ user.spree_roles << Spree::Role.where(name: 'admin').first_or_create+ ```++ To test that this has worked, use the `has_spree_role?` method, like this:++ ```ruby+ user.has_spree_role?('admin')+ ```++ If this returns `true`, then the user has admin permissions within Spree.+ </Accordion>+ <Accordion title="4. Customize Spree Authentication Helpers (Optional)">+ <Note>+ This step is required if you're using **`spree_backend`** and/or `spree_frontend` gems.+ </Note>++ Run a generator to create a file at `lib/spree/authentication_helpers.rb` which will contain the following code to help you do that:++ ```bash+ bin/rails g spree:custom_authentication+ ```++ This will create a file at `lib/spree/authentication_helpers.rb` which will contain the following code to help you do that:++ ```ruby+ module Spree+ module AuthenticationHelpers+ def self.included(receiver)+ receiver.helper_method(+ :spree_current_user,+ :spree_login_path,+ :spree_signup_path,+ :spree_logout_path,+ :spree_forgot_password_path,+ :spree_edit_password_path,+ :spree_admin_login_path,+ :spree_admin_logout_path,+ )+ end++ def spree_current_user+ current_user+ end++ def spree_login_path(opts = {})+ main_app.login_path(opts)+ end++ def spree_signup_path(opts = {})+ main_app.signup_path(opts)+ end++ def spree_logout_path(opts = {})+ main_app.logout_path(opts)+ end++ def spree_forgot_password_path(opts = {})+ main_app.forgot_password_path(opts)+ end++ def spree_edit_password_path(opts = {})+ main_app.edit_password_path(opts)+ end++ def spree_admin_login_path(opts = {})+ main_app.admin_login_path(opts)+ end++ def spree_admin_logout_path(opts = {})+ main_app.admin_logout_path(opts)+ end+ end+ end+ ```++ Each of the methods defined in this module return values that are the most common in Rails applications today, but you may need to customize them. In order, they are:++ * `spree_current_user` Used to tell Spree what the current user of a request is.+ * `spree_login_path` The location of the login/sign in form in your application.+ * `spree_signup_path` The location of the sign up form in your application.+ * `spree_logout_path` The location of the logout feature of your application.+ * `spree_forgot_password_path` The location to reset a user's password.+ * `spree_edit_password_path` The location to edit a user's password.+ * `spree_admin_login_path` The location of the login/sign in form for the admin panel.+ * `spree_admin_logout_path` The location of the logout feature for the admin panel.++ URLs inside the helpers **must** have `main_app` prefixed if they are inside your application. This is because Spree will otherwise attempt to route these paths to the Spree engine, which does not exist. By prefixing with `main_app`, you tell it to look at the application's routes.++ You will need to define the `login_path`, `signup_path` and `logout_path` routes yourself, by using code like this inside your application's `config/routes.rb` if you're using Devise:++ ```ruby+ devise_for :users+ devise_scope :user do+ get '/login', to: "devise/sessions#new"+ get '/signup', to: "devise/registrations#new"+ delete '/logout', to: "devise/sessions#destroy"+ get '/forgot_password', to: "devise/passwords#new"+ get '/edit_password', to: "devise/registrations#edit"+ end+ ```++ Of course, this code will be different if you're not using Devise. Simply **do not** use the `devise_scope` method and change the controllers and actions for these routes.++ You can also customize these methods inside `lib/spree/authentication_helpers.rb` to use the routing helper methods already provided by the authentication setup you have, if you wish.++ Any modifications made to `lib/spree/authentication_helpers.rb` while the server is running will require a restart, as with any other modification to other files in `lib`.+ </Accordion>+ <Accordion title="5. Remove Auth Devise gem">+ The `spree_auth_devise` gem is not needed when using an existing application authentication unless the goal is to have two separate authentication methods.++ You can remove the `spree_auth_devise` gem by running this command:++ ```bash+ bundle remove spree_auth_devise+ ```+ </Accordion>+</AccordionGroup>++## Admin Panel authentication++By default Spree uses the same model for the admin panel as the storefront. However you can customize it to use a different model.++To do this, you need to add the following code to your `config/initializers/spree.rb` file:++```ruby+Spree.admin_user_class = 'AdminUser'+```++This will tell Spree to use the `AdminUser` model for the admin panel. You will need to create this model in your application and ensure that it includes the necessary Spree fields.diff --git a/docs/developer/customization/deface_overrides_tutorial.mdx b/docs/developer/customization/v4/deface.mdxsimilarity index 99%rename from docs/developer/customization/deface_overrides_tutorial.mdxrename to docs/developer/customization/v4/deface.mdxindex d581d66d2d..73f132ac2b 100644--- a/docs/developer/customization/deface_overrides_tutorial.mdx+++ b/docs/developer/customization/v4/deface.mdx@@ -1,11 +1,8 @@---title: Deface Overrides-section: advancedversion: v4----# Deface-<Warning>Using Deface is no longer recommended, we strongly encourage you to use other ways to customize Spree.</Warning>diff --git a/docs/developer/customization/images.mdx b/docs/developer/customization/v4/images.mdxsimilarity index 100%rename from docs/developer/customization/images.mdxrename to docs/developer/customization/v4/images.mdxdiff --git a/docs/mint.json b/docs/mint.jsonindex f43e8720ef..b2685ea2b5 100644--- a/docs/mint.json+++ b/docs/mint.json@@ -99,10 +99,10 @@{"group": "Customizing Spree",+ "version": "v5","pages": ["developer/customization/quickstart","developer/customization/authentication",- "developer/customization/images","developer/customization/checkout","developer/customization/permissions","developer/customization/dependencies",@@ -111,6 +111,23 @@]},+ {+ "group": "Customizing Spree",+ "version": "v4",+ "pages": [+ "developer/customization/quickstart",+ "developer/customization/v4/authentication",+ "developer/customization/images",+ "developer/customization/checkout",+ "developer/customization/permissions",+ "developer/customization/dependencies",+ "developer/customization/decorators",+ "developer/customization/routes",+ "developer/customization/v4/admin-panel",+ "developer/customization/v4/deface"+ ]+ },+{"group": "Extending Spree","pages": [