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.

You may also like:

If you want to work with me or hire me? Contact me

You can follow me or connect with me:

Or get new content delivered directly to your inbox.

Join 5,047 other subscribers

I wrote a book:

Stack of copies of How to Hire and Manage Remote Teams

How to Hire and Manage Remote Teams, where I distill all the techniques I’ve been using to build and manage distributed teams for the past 10 years.

I write about:

announcement blogging book book review book reviews books building Sano Business C# Clojure ClojureScript Common Lisp database Debian Esperanto Git ham radio history idea Java Kubuntu Lisp management Non-Fiction OpenID programming Python Radio Society of Great Britain Rails rant re-frame release Ruby Ruby on Rails Sano science science fiction security self-help Star Trek technology Ubuntu web Windows WordPress

I’ve been writing for a while:

Mastodon