devise icon indicating copy to clipboard operation
devise copied to clipboard

Rails 7: logout redirect not working

Open collimarco opened this issue 3 years ago • 21 comments

Set this in application_controller.rb:

  def after_sign_out_path_for scope
    root_path
  end

You expect the logout to redirect the user to root.

However Devise returns a redirect with status 302, which does not work with Turbo.

All redirects must return 303 (i.e. status: :see_other) in order to work with Turbo.

This should be fixed in Devise in order to work with Rails 7.

Related: https://github.com/rails/rails/issues/44170

collimarco avatar Jan 17 '22 10:01 collimarco

Not only the redirect for logout, but also the other redirects should use the status 303 in order to work with Turbo.

(The only other alternative would be to make Turbo accept the 302, but from the related issue linked above it seems that Rails team won't fix that)

collimarco avatar Jan 17 '22 10:01 collimarco

Also note that by using 302, after logout response, you also get an "extra" DELETE request to root path, which results in a 404.

This is quite scary, since you get an unexpected DELETE request on random path!

collimarco avatar Jan 17 '22 11:01 collimarco

I think this is related to https://github.com/heartcombo/devise/pull/5453

While the PR isn't merged I would just disable turbo on devise views

marcelolx avatar Jan 17 '22 14:01 marcelolx

You have to change from:

<%= link_to "Sign out", destroy_user_session_path, method: delete %>

to

<%= link_to "Sign out", destroy_user_session_path, data: { turbo_method: :delete" } %>

designium avatar Jan 19 '22 19:01 designium

@designium Yes, sure, I already use the correct code for Turbo... However there is the bug described in the original post.

collimarco avatar Jan 19 '22 20:01 collimarco

@collimarco I have found simple hotfix

# app/controllers/sessions_controller.rb
class SessionsController < Devise::SessionsController
  def respond_to_on_destroy
    respond_to do |format|
      format.all { head :no_content }
      format.any(*navigational_formats) { redirect_to after_sign_out_path_for(resource_name), status: :see_other}
    end
  end
end
# config/routes.rb
Rails.application.routes.draw do
  # ...
  devise_for :users, controllers: { sessions: 'sessions' }
  # ...
end

You just need add status: :see_other (303) to redirect_to method arguments to make it works correctly

rzepetor avatar Jan 20 '22 20:01 rzepetor

I fixed this as follows:

<%= link_to("Log out", destroy_user_session_path, method: :delete, data: { turbo_method: :delete }) %>
module Users
  class SessionsController < Devise::SessionsController
    def destroy
      super do
        # Turbo requires redirects be :see_other (303); so override Devise default (302)
        return redirect_to after_sign_out_path_for(resource_name), status: :see_other
      end
    end
  end
end

mattbrictson avatar Jan 26 '22 20:01 mattbrictson

@mattbrictson you can also add notice: I18n.t('devise.sessions.signed_out') to show the successful sign out message

return redirect_to after_sign_out_path_for(resource_name), status: :see_other, notice: I18n.t('devise.sessions.signed_out')

MattBudz avatar Feb 04 '22 17:02 MattBudz

I just notice that when you are using a button to log out: <%= button_to "Log Out", destroy_user_session_path, method: :delete %> the the redirect works as expected and the user is taken to the root_path. However as soon as you are using a link things are not working (mostly due to the status issue mentioned above).

spaquet avatar Feb 21 '22 19:02 spaquet

Also, overriding the after_sign_out_path_for(resource_or_scope) method in the ApplicationController does not work when using a link... so there is no way to fix this issue without first fixing the status problem.

spaquet avatar Feb 21 '22 19:02 spaquet

any news?

francesco-loreti avatar May 18 '22 13:05 francesco-loreti

nope...

spaquet avatar May 27 '22 01:05 spaquet

This worked for me initially:

<%= link_to "Logout", destroy_user_session_path, data: { turbo_method: :delete } %>

But after making these turbo changes (to fix an unrelated issue of some bootstrap javascripts not working) from:

// app/javascript/application.js
import "@hotwired/turbo-rails"

to this

// app/javascript/application.js
import { Turbo } from "@hotwired/turbo-rails"
Turbo.session.drive = false

then logout broke.

However, this worked:

<%= button_to "Log out", destroy_user_session_path, method: :delete, data: { turbo: false } %>

Hope it's useful.

stevecondylios avatar Jun 09 '22 17:06 stevecondylios

I ended up with this which makes a mini form:

<%= button_to "Logout", destroy_user_session_path, method: :delete, form: {  data: { turbo: :false } } %>

kluzny avatar Jul 02 '22 02:07 kluzny

It works for me <%= button_to 'Logout', destroy_user_session_path, method: :delete, form: {turbolink: false} %>

sergiy-koshoviy avatar Jul 05 '22 22:07 sergiy-koshoviy

Looking at the patch by @mattbrictson I see it looks really similar to the PR here https://github.com/heartcombo/devise/pull/5410

Genkilabs avatar Aug 18 '22 18:08 Genkilabs

Disabling Turbo is the wrong answer here. This issue is specific to an incorrect redirect being returned by Devise::SessionController.

My Selenium tests fail like this:

2) Authentication as a User allows a user to Log In and Out
     Failure/Error: raise ActionController::RoutingError, "No route matches [#{env['REQUEST_METHOD']}] #{env['PATH_INFO'].inspect}"
     
     ActionController::RoutingError:
       No route matches [DELETE] "/"

The Rails log will follow a pattern similar to this:

Started DELETE "/users/sign_out" for 127.0.0.1 at 2022-09-02 17:00:43 -0600
Processing by Devise::SessionsController#destroy as TURBO_STREAM
  User Load (1.6ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
Redirected to http://127.0.0.1:57460/
Completed 302 Found in 10ms (ActiveRecord: 1.6ms | Allocations: 1787)
Started DELETE "/" for 127.0.0.1 at 2022-09-02 17:00:43 -0600

The issue is that Turbo is attempting to render after_sign_out_path with the incorrect HTTP Verb (DELETE, in this case). You want your Devise controller to respond with HTTP 303 See Other. Solutions that override Devise's default behavior, such as @mattbrictson's, should be used.

I fixed this as follows:

<%= link_to("Log out", destroy_user_session_path, method: :delete, data: { turbo_method: :delete }) %>
module Users
  class SessionsController < Devise::SessionsController
    def destroy
      super do
        # Turbo requires redirects be :see_other (303); so override Devise default (302)
        return redirect_to after_sign_out_path_for(resource_name), status: :see_other
      end
    end
  end
end

Don't forget to update your routes, too:

  devise_for :users, controllers: {
    sessions: 'users/sessions'
  }

None of the other replies actually fix the OP's original issue.

danielricecodes avatar Sep 03 '22 00:09 danielricecodes

module Users
  class SessionsController < Devise::SessionsController
    def destroy
      super do
        # Turbo requires redirects be :see_other (303); so override Devise default (302)
        return redirect_to after_sign_out_path_for(resource_name), status: :see_other
      end
    end
  end
end

I'm sorry, can anyone - maybe @mattbrictson or @danielricecodes - tell me, where to put that?

Thanks in advance.

d33pjs avatar Sep 11 '22 18:09 d33pjs

This issue is not specific to Turbo, it's how the Fetch API behaves: when the HTTP status is 302, the browser will send another request to the redirect URL using the same HTTP method as the initial request. Turbo wraps the Fetch API, but I ran into the same issue in our app which doesn't use Turbo.

In our case we solved this by changing the HTTP method for the sign out route from DELETE to GET.

In config/initializers/devise.rb:

  # The default HTTP method used to sign out a resource. Default is :delete.
  config.sign_out_via = :get

Then you can use a regular link in your view, no Turbo/JS needed at all:

<%= link_to "Sign Out", destroy_user_session_path %>

Alternatively, you can keep using a DELETE route (preferable, since GET routes with side-effects are kind of icky) and use a form rather than a link:

<%= button_to "Sign Out", destroy_user_session_path, method: :delete %>

This also requires no Turbo/JS, though you'll probably want to sprinkle some CSS to make the button look like a regular link.

olivier-thatch avatar Sep 15 '22 00:09 olivier-thatch

@Havoc85

You need to generate or create an inherited Devise controller for sessions first. You can do that by running the following command (assuming that "user" is your Devise model):

rails generate devise:controllers users -c=sessions

Uncomment the destroy method in the new file that gets created and place the above code inside the method.

Don't forget to update your Devise routes for the changes to take effect.

florianfelsing avatar Sep 21 '22 12:09 florianfelsing

@Havoc85

You need to generate or create an inherited Devise controller for sessions first. You can do that by running the following command (assuming that "user" is your Devise model):

rails generate devise:controllers users -c=sessions

Uncomment the destroy method in the new file that gets created and place the above code inside the method.

Don't forget to update your Devise routes for the changes to take effect.

Thank you for that description! That helps a lot.

d33pjs avatar Sep 21 '22 13:09 d33pjs

@Havoc85

You need to generate or create an inherited Devise controller for sessions first. You can do that by running the following command (assuming that "user" is your Devise model):

rails generate devise:controllers users -c=sessions

Uncomment the destroy method in the new file that gets created and place the above code inside the method.

Don't forget to update your Devise routes for the changes to take effect.

I followed all the instruction and still face with the actionController::RoutingError (No route matches [GET] "/users/sign_out"): Not sure if there is anyway to find the root cause

***solved just because changing to the correct resource_name

Alertzero avatar Oct 23 '22 12:10 Alertzero

This worked for me initially:

<%= link_to "Logout", destroy_user_session_path, data: { turbo_method: :delete } %>

But after making these turbo changes (to fix an unrelated issue of some bootstrap javascripts not working) from:

// app/javascript/application.js
import "@hotwired/turbo-rails"

to this

// app/javascript/application.js
import { Turbo } from "@hotwired/turbo-rails"
Turbo.session.drive = false

then logout broke.

However, this worked:

<%= button_to "Log out", destroy_user_session_path, method: :delete, data: { turbo: false } %>

Hope it's useful.

👍 Thanks

jx-bamboo avatar Nov 18 '22 08:11 jx-bamboo

false

Not a correct way because we want to use turbo

Alertzero avatar Dec 11 '22 12:12 Alertzero

My solution:

sessions_controller.rb

class Users::SessionsController < Devise::SessionsController
  def destroy
    super do
      # Turbo requires redirects be :see_other (303); so override Devise default (302)
      return redirect_to new_user_session_path, status: :see_other, notice: I18n.t("devise.sessions.signed_out")
    end
  end
end
<%= link_to "Sign out", "/users/sign_out", method: :delete, data: { turbo_method: :delete, turbo_confirm: 'Are you sure?' } %>

revskill10 avatar Dec 29 '22 19:12 revskill10

<%= button_to "Sign Out", destroy_user_session_path, method: :delete %> Did not work.

<%= button_to "Log out", destroy_user_session_path, method: :delete, data: { turbo: false } %> Did work; thank you @stevecondylios

However, I ended up using @revskill10 's solution as I wanted use a link_to rather than a button. Thanks everyone for your wisdom!

johnpitchko avatar Feb 02 '23 04:02 johnpitchko

Hey, you're all welcome to try this new branch and see if that works for you out of the box: https://github.com/heartcombo/devise/pull/5548. Please see the description on how to get things setup, and report back if you run into any issues. Thanks.

carlosantoniodasilva avatar Feb 02 '23 12:02 carlosantoniodasilva

data: { turbo_method: :delete }

Using the first line of codes works perfectly for me! Thank you! I highly recommend everyone to have a try.

jinyuanwong avatar Feb 04 '23 08:02 jinyuanwong

Setting config.navigational_formats = ['*/*', :html, :turbo_stream] in devise.rb seemed to work for me

marcbest avatar Feb 09 '23 11:02 marcbest

The main branch should contain all that's necessary for fully working with Turbo now, which should fix this. A new version will be released soon, but feel free to test it out from the main branch in the meantime, and report back on any issues. Thanks.

carlosantoniodasilva avatar Feb 09 '23 21:02 carlosantoniodasilva