Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Devise sign in error message behaviour

Can anyone give any pointers to how we can customise Devise so that if an unauthenticated user visits the root_url, they are redirected to /users/sign_in but not shown the "You need to sign in or sign up before continuing." error message?

To expand further: we want that message to be shown if the user tries to visit a 'deeper' URL (/controller/restricted_action) directly without first authenticating, but for someone with the app bookmarked as www.app.com we just want to redirect them straight to the login page without any error being shown.

Had a look around through the SessionsController (to ascertain whether a custom controller could work) and various other places, but can't see a place or how we can override the behaviour in this way.

Any advice appreciated!

like image 460
iam Avatar asked Feb 26 '26 13:02

iam


1 Answers

This should remove the flash alert message if redirected from "/" to "/users/sign_in".

class ApplicationController < ActionController::Base
  before_action :keep_previous_url
  before_action :no_unauthenticated_alert_if_redirected_from_root

  def keep_previous_url
    session[:previous_url] = request.fullpath
  end

  def no_unauthenticated_alert_if_redirected_from_root
    if request.fullpath == "/users/sign_in" && session[:previous_url] == "/"
      flash.now.alert = nil
    end
  end
end
like image 193
Anthony Smith Avatar answered Feb 28 '26 14:02

Anthony Smith