Set ssl_allowed/ssl_required for all pages in Rails 2?

痴心易碎 提交于 2019-12-11 06:36:32

问题


I found that AJAX calls were not working on my Rails site when a page was using SSL/HTTPS. I worked around this by adding

ssl_allowed :action1, :action2, :actionN

to the controllers involved.

I foresee this being a pain and prone to bugs in the future, as I'll indubitably forget to add an action to the ssl_allowed list.

Is there a way to turn on ssl_allowed/ssl_required globally in the [ssl_requirement][1] gem, for all actions of every controller in my site? I tried adding the following to ApplicationController, but that did not work:

ssl_allowed :all

回答1:


If you'd rather not depend on a forked plugin, you can override ssl_allowed? in your controller:

 class ApplicationController < ActionController::Base
    ...
    private

    def ssl_allowed?
       true
    end
 end

EDIT: This does not do what I thought it did. Instead of disabling redirects to http for pages that are not specified ssl_required, it short circuts the whole redirect process to do nothing. This is very bad. The code:

 def ensure_proper_protocol
   return true if ssl_allowed?

   if ssl_required? && !request.ssl?
     redirect_to "https://" + request.host + request.request_uri
     flash.keep
     return false
   elsif request.ssl? && !ssl_required?
     redirect_to "http://" + request.host + request.request_uri
     flash.keep
     return false
   end
 end

Adding the ssl_allowed? method like this would only be the answer if the code instead read:

def ensure_proper_protocol
  if ssl_required? && !request.ssl?
    redirect_to "https://" + request.host + request.request_uri
    flash.keep
    return false
  elsif request.ssl? && !ssl_required? && !ssl_allowed?
    redirect_to "http://" + request.host + request.request_uri
    flash.keep
    return false
  end
end



回答2:


I found grosser's ssl_requirement fork at github (link) which enables "ssl_allowed :all" and replaced my copy of the gem with that version. Now I'm using "ssl_allowed :all" in my ApplicationController and nowhere else. Exactly what I wanted.



来源:https://stackoverflow.com/questions/4961374/set-ssl-allowed-ssl-required-for-all-pages-in-rails-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!