I’ve looked at the various ssl_requirement repositories out there. I concluded the most modern and maintained version is yardstick’s which is released as a gem called sslrequirement, but I’ve failed to use it properly. So I just did it by hand.
First, we need a simple method that will let us know whether SSL is enabled or not. We don’t want to redirect to SSL in development mode because it’ll fail. In the application controller I’ve created:
def ssl_enabled? !(Rails.env.development? || Rails.env.test?) end
Switching to SSL is not only a matter of redirecting. If you show a login or signup form in your homepage, like I do in Restraq, you want that to point to https even if the page was loaded as http. So I’ve added this helper method in the application controller:
def https ssl_enabled? ? "https://" : "http://" end helper_method :https
and then for the forms I just do this:
form_for ..., :url => session_url(resource_name, :protocol => https)
and
form_for ..., :url => registration_url(resource_name, :protocol => https)
And then the redirection part, which is a before filter in the application controller because I want to redirect when hitting Devise controllers:
def enforce_ssl_if_needed if request.protocol == "http://" && ssl_enabled? && (controller_name == "registrations" || controller_name == "sessions") redirect_to :protocol => https end return true end
and that’s it. I’m not actually testing it yet. For a similar solution with tests you might want to check out SSLShopper’s article about this.
Leave a Reply