Question

I have implemented redirect_to_back method in my ApplicationController for users that are not signed in (from this blogpost:

def redirect_to_back_or_default(default = root_url)
  if request.env["HTTP_REFERER"].present? and request.env["HTTP_REFERER"] != request.env["REQUEST_URI"]
      redirect_to :back
  else
    redirect_to dashboard_url
  end
end

and I'm using in sessions_controller#create:

if @user && @user.authenticate(params[:password])
  sign_in(@user)
  redirect_to_back_or_default(dashboard_url)
 else
   ...

The problem is, this only works if the request is coming from the application and not if it is a direct link, like in an email.

Is there a solution for this?

Was it helpful?

Solution

I would recommend altering how you accomplish this. If you follow the flow below I think it will produce the results you're looking for:

  1. User arrives at URL (either by clicking link in email or typing it or whatever) but is not yet authenticated.
  2. Store the URL that the user is at in the session
  3. Redirect to the sign-in controller/action
  4. After authenticating the user look in the session for where you stored the arrival URL
  5. If present redirect to that URL (and clear stored URL out of the session) otherwise redirect to dashboard_url (it won't be present if someone navigates directly to the sign-in controller/action).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top