Skip to content

Commit

Permalink
Integrate with Hotwire/Turbo by configuring error and response statuses
Browse files Browse the repository at this point in the history
Treat `:turbo_stream` request format as a navigational format, much like
HTML, so Devise/responders can work properly.

Allow configuring the `error_status` and `redirect_status` using the
latest responders features, via a new custom Devise responder, so we can
customize the both responses to match Hotwire/Turbo behavior, for
example with `422 Unprocessable Entity` and `303 See Other`,
respectively. The defaults aren't changing in Devise itself (yet), so it
still responds on errors cases with `200 OK`, and redirects on non-GET
requests with `302 Found`, but new apps are generated with the new
statuses and existing apps can opt-in. Please note that these defaults
might change in a future release of Devise.

PRs/Issues references:

#5545
#5529
#5516
#5499
#5487
#5467
#5440
#5410
#5340

#5542
#5530
#5519
#5513
#5478
#5468
#5463
#5458
#5448
#5446
#5439
  • Loading branch information
carlosantoniodasilva committed Jan 31, 2023
1 parent cddba28 commit 1947041
Show file tree
Hide file tree
Showing 19 changed files with 78 additions and 25 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

* enhancements
* Add support for Ruby 3.1/3.2.
* Add support for Hotwire + Turbo, default in Rails 7+.

### 4.8.1 - 2021-12-16

Expand Down
2 changes: 1 addition & 1 deletion Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ gem "rdoc"

gem "rails-controller-testing", github: "rails/rails-controller-testing"

gem "responders", "~> 3.0"
gem "responders", github: "heartcombo/responders", branch: "main"

group :test do
gem "nokogiri", "< 1.13"
Expand Down
14 changes: 10 additions & 4 deletions Gemfile.lock
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
GIT
remote: https://github.com/heartcombo/responders.git
revision: fb9f787055a7a842584ce351793b249676290090
branch: main
specs:
responders (3.0.1)
actionpack (>= 5.2)
railties (>= 5.2)

GIT
remote: https://github.com/rails/rails-controller-testing.git
revision: 351c0162df0771c0c48e6a5a886c4c2f0a5d1a74
Expand Down Expand Up @@ -189,9 +198,6 @@ GEM
rake (13.0.6)
rdoc (6.5.0)
psych (>= 4.0.0)
responders (3.0.1)
actionpack (>= 5.0)
railties (>= 5.0)
rexml (3.2.5)
ruby-openid (2.9.2)
ruby2_keywords (0.0.5)
Expand Down Expand Up @@ -231,7 +237,7 @@ DEPENDENCIES
rails (~> 7.0.0)
rails-controller-testing!
rdoc
responders (~> 3.0)
responders!
rexml
sqlite3 (~> 1.4)
timecop
Expand Down
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,25 @@ Please note: You will still need to add `devise_for` in your routes in order to
devise_for :users, skip: :all
```

### Hotwire/Turbo

Devise integrates with Hotwire/Turbo by treating such requests as navigational, and configuring certain responses for errors and redirects to match the expected behavior. New apps are generated with the following response configuration by default, and existing apps may opt-in by adding the config to their Devise initializers:

```ruby
Devise.setup do |config|
# ...
# When using Devise with Hotwire/Turbo, the http status for error responses
# and some redirects must match the following. The default in Devise for existing
# apps is `200 OK` and `302 Found respectively`, but new apps are generated with
# these new defaults that match Hotwire/Turbo behavior.
# Note: These might become the new default in future versions of Devise.
config.responder.error_status = :unprocessable_entity
config.responder.redirect_status = :see_other
end
```

_Note_: the above statuses configuration may become the default for Devise in a future release.

### I18n

Devise uses flash messages with I18n, in conjunction with the flash keys :notice and :alert. To customize your app, you can set up your locale file:
Expand Down
1 change: 1 addition & 0 deletions app/controllers/devise/confirmations_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ def show
set_flash_message!(:notice, :confirmed)
respond_with_navigational(resource){ redirect_to after_confirmation_path_for(resource_name, resource) }
else
# TODO: use `error_status` when the default changes to `:unprocessable_entity`.
respond_with_navigational(resource.errors, status: :unprocessable_entity){ render :new }
end
end
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/devise/registrations_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def destroy
Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)
set_flash_message! :notice, :destroyed
yield resource if block_given?
respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name) }
respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name), status: Devise.responder.redirect_status }
end

# GET /resource/cancel
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/devise/sessions_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def respond_to_on_destroy
# support returning empty response on GET request
respond_to do |format|
format.all { head :no_content }
format.any(*navigational_formats) { redirect_to after_sign_out_path_for(resource_name) }
format.any(*navigational_formats) { redirect_to after_sign_out_path_for(resource_name), status: Devise.responder.redirect_status }
end
end
end
1 change: 1 addition & 0 deletions app/controllers/devise/unlocks_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ def show
set_flash_message! :notice, :unlocked
respond_with_navigational(resource){ redirect_to after_unlock_path_for(resource) }
else
# TODO: use `error_status` when the default changes to `:unprocessable_entity`.
respond_with_navigational(resource.errors, status: :unprocessable_entity){ render :new }
end
end
Expand Down
1 change: 1 addition & 0 deletions app/controllers/devise_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ class DeviseController < Devise.parent_controller.constantize
end

prepend_before_action :assert_is_devise_resource!
self.responder = Devise.responder
respond_to :html if mimes_for_respond_to.empty?

# Override prefixes to consider the scoped view.
Expand Down
2 changes: 1 addition & 1 deletion app/views/devise/registrations/edit.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,6 @@

<h3>Cancel my account</h3>

<p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %></p>
<p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?", turbo_confirm: "Are you sure?" }, method: :delete %></p>

<%= link_to "Back", :back %>
2 changes: 1 addition & 1 deletion gemfiles/Gemfile-rails-6-0
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ gem "rdoc"

gem "rails-controller-testing", github: "rails/rails-controller-testing"

gem "responders", "~> 3.0"
gem "responders", github: "heartcombo/responders", branch: "main"

group :test do
gem "nokogiri", "< 1.13"
Expand Down
2 changes: 1 addition & 1 deletion gemfiles/Gemfile-rails-6-1
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ gem "activemodel-serializers-xml", github: "rails/activemodel-serializers-xml"

gem "rails-controller-testing", github: "rails/rails-controller-testing"

gem "responders", "~> 3.0"
gem "responders", github: "heartcombo/responders", branch: "main"

if RUBY_VERSION >= "3.1"
gem "net-smtp", require: false
Expand Down
2 changes: 1 addition & 1 deletion gemfiles/Gemfile-rails-main
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ gem "activemodel-serializers-xml", github: "rails/activemodel-serializers-xml"

gem "rails-controller-testing", github: "rails/rails-controller-testing"

gem "responders", "~> 3.0"
gem "responders", github: "heartcombo/responders", branch: "main"

group :test do
gem "nokogiri", "< 1.13"
Expand Down
10 changes: 9 additions & 1 deletion lib/devise.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ module Devise
module Controllers
autoload :Helpers, 'devise/controllers/helpers'
autoload :Rememberable, 'devise/controllers/rememberable'
autoload :Responder, 'devise/controllers/responder'
autoload :ScopedViews, 'devise/controllers/scoped_views'
autoload :SignInOut, 'devise/controllers/sign_in_out'
autoload :StoreLocation, 'devise/controllers/store_location'
Expand Down Expand Up @@ -217,7 +218,14 @@ module Test

# Which formats should be treated as navigational.
mattr_accessor :navigational_formats
@@navigational_formats = ["*/*", :html]
@@navigational_formats = ["*/*", :html, :turbo_stream]

# The default responder used by Devise, not meant to be changed directly,
# but you can customize status codes with:
# `config.responder.error_status`
# `config.responder.redirect_status`
mattr_accessor :responder
@@responder = Devise::Controllers::Responder

# When set to true, signing out a user signs out all other scopes.
mattr_accessor :sign_out_all_scopes
Expand Down
12 changes: 12 additions & 0 deletions lib/devise/controllers/responder.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# frozen_string_literal: true

module Devise
module Controllers
# Custom Responder to configure default statuses that only apply to Devise,
# and allow to integrate more easily with Hotwire/Turbo.
class Responder < ActionController::Responder
self.error_status = :ok if respond_to?(:error_status=)
self.redirect_status = :found if respond_to?(:redirect_status=)
end
end
end
6 changes: 4 additions & 2 deletions lib/devise/failure_app.rb
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,9 @@ def recall
end

flash.now[:alert] = i18n_message(:invalid) if is_flashing_format?
self.response = recall_app(warden_options[:recall]).call(request.env)
self.response = recall_app(warden_options[:recall]).call(request.env).tap { |response|
response[0] = Rack::Utils.status_code(Devise.responder.error_status)
}
end

def redirect
Expand Down Expand Up @@ -167,7 +169,7 @@ def scope_url
end

def skip_format?
%w(html */*).include? request_format.to_s
%w(html */* turbo_stream).include? request_format.to_s
end

# Choose whether we should respond in an HTTP authentication fashion,
Expand Down
18 changes: 10 additions & 8 deletions lib/generators/templates/devise.rb
Original file line number Diff line number Diff line change
Expand Up @@ -256,14 +256,14 @@

# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# :html should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ['*/*', :html]
# config.navigational_formats = ['*/*', :html, :turbo_stream]

# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
Expand Down Expand Up @@ -296,12 +296,14 @@
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'

# ==> Turbolinks configuration
# If your app is using Turbolinks, Turbolinks::Controller needs to be included to make redirection work correctly:
#
# ActiveSupport.on_load(:devise_failure_app) do
# include Turbolinks::Controller
# end
# ==> Hotwire/Turbo configuration
# When using Devise with Hotwire/Turbo, the http status for error responses
# and some redirects must match the following. The default in Devise for existing
# apps is `200 OK` and `302 Found respectively`, but new apps are generated with
# these new defaults that match Hotwire/Turbo behavior.
# Note: These might become the new default in future versions of Devise.
config.responder.error_status = :unprocessable_entity
config.responder.redirect_status = :see_other

# ==> Configuration for :registerable

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,6 @@

<h3>Cancel my account</h3>

<p>Unhappy? <%= link_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %></p>
<p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?", turbo_confirm: "Are you sure?" }, method: :delete %></p>

<%= link_to "Back", :back %>
4 changes: 2 additions & 2 deletions test/support/integration.rb
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ def sign_in_as_admin(options = {}, &block)
# account Middleware redirects.
#
def assert_redirected_to(url)
assert_includes [301, 302], @integration_session.status,
"Expected status to be 301 or 302, got #{@integration_session.status}"
assert_includes [301, 302, 303], @integration_session.status,
"Expected status to be 301, 302, or 303, got #{@integration_session.status}"

assert_url url, @integration_session.headers["Location"]
end
Expand Down

0 comments on commit 1947041

Please sign in to comment.