5

Expose method to check if a location is safe to redirect to by dmcge · Pull Requ...

 2 years ago
source link: https://github.com/rails/rails/pull/43327
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Copy link

Contributor

dmcge commented on Sep 28

edited

Unsafe URL protection in Rails 7 is great. If you try to redirect somewhere dodgy, your whole action blows up. But there are cases when you don’t that. You sometimes want to redirect to a fallback location.

class SignInsController < ApplicationController
  def create
    if SignIn.authenticate(sign_in_params)
      redirect_to return_url
    else
      render :new, status: :unprocessable_entity
    end
  end

  private
    def return_url
      url_from(params[:return_to]) || root_url
    end
end

You’d have to implement this currently by either (a) calling private API (_url_host_allowed?) or (b) rescuing from the error raised and re-redirecting. Option (b) doesn’t feel quite right to me. Now you have to implement redirecting twice, but you only wanted to change the redirect location. This PR makes (a) viable by promoting a method to public API.

(An alternative is to add another option to redirect_to. I started there but couldn’t come up with anything.)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK