Setting up SSL https for Rails3

March 7th, 2012 rupert No comments

1. Generate your server.crt and server.key first.

For local development, a self-signed certificate is adequate. For production, we can buy from Thawte, Verisign, the CArtels, etc.

% openssl genrsa -des3 -out server.key 1024
% openssl req -new -key server.key -out server.csr
% openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Notes: Ensure that you use x509 because if we use the other one (PK something), then apache2 complains that it can’t load it, invalid tags.

The certificate (server.crt) should have the proper tags (BEGIN and END) as shown below.

-----BEGIN CERTIFICATE-----
MIIDBjCCAe4CCQDCzcL5z8chBzANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJB
......+OAFfG2MvIeawg==
-----END CERTIFICATE-----

2. Setup your Apache2 properly

- Ensure that you have mod_ssl loaded

LoadModule ssl_module libexec/apache22/mod_ssl.so

- Enusure that you are listening to 80 and 443.

Listen 80
Listen 443

Very Important Note: Please note that if you are not listening to these ports you might get “Connection Refused” messages. Please make sure that your Listen directives match your directives.

<VirtualHost 192.168.10.1:80>
   ServerAdmin rupert@2rmobile.com
   ServerName foo.2rmobile.com
   ServerAlias foo.2rmobile.com
 
   DocumentRoot "/path/to/rails/app/public"
   <Directory "/path/to/rails/app/public">
      #Options Indexes MultiViews
      AllowOverride None
      Order allow,deny
      Allow from all
   </Directory>
 
   CustomLog /var/log/httpd/myapp.log combinedio
   LogLevel warn
</VirtualHost>
 
<VirtualHost 192.168.10.1:443>
   ServerAdmin rupert@2rmobile.com
   ServerName foo.2rmobile.com
   ServerAlias foo.2rmobile.com
 
   DocumentRoot "/path/to/rails/app/public"
   <Directory "/path/to/rails/app/public">
      #Options Indexes MultiViews
      AllowOverride None
      Order allow,deny
      Allow from all
   </Directory>
 
   CustomLog /var/log/httpd/myapp.log combinedio
   LogLevel warn
 
   SSLEngine on
   SSLCertificateFile /path/to/certs/server.crt
   SSLCertificateKeyFile /path/to/certs/server.key
</VirtualHost>

Restart! Hopefully, apache2 will load with ssl support. If not, do some googling.

% /usr/local/etc/rc.d/apache22 restart #freebsd
Performing sanity check on apache22 configuration:
Syntax OK
Stopping apache22.
Waiting for PIDS: 89044.
Performing sanity check on apache22 configuration:
Syntax OK
Starting apache22.
% tail -f /var/log/apache2/httpd-access.log
...."Apache/2.2.15 (FreeBSD) mod_ssl/2.2.15 OpenSSL/0.9.8q DAV/2 PHP/5.2.14 with Suhosin-Patch Phusion_Passenger/3.0.11 (internal dummy connection)"

3. Configure Rails3.0.10 for rack/ssl support.
Read this http://collectiveidea.com/blog/archives/2010/11/29/ssl-with-rails/. If you’re on Rails3.1? you didn’t read this http://collectiveidea.com/blog/archives/2010/11/29/ssl-with-rails/..

Gemfile

gem 'rack-ssl', :require => 'rack/ssl'

production.rb

require 'rack/ssl'
 
Cws::Application.configure do
  config.middleware.insert_before ActionDispatch::Cookies, Rack::SSL
  #config.middleware.insert_before ActionDispatch::Cookies, Rack::SSL, :exclude => proc { |env| env['HTTPS'] != 'on' }
 
  # Settings specified here will take precedence over those in config/application.rb
 
  # The production environment is meant for finished, "live" apps.
  # Code is not reloaded between requests
  config.cache_classes = true
 
  # Full error reports are disabled and caching is turned on
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true
 
  # Specifies the header that your server uses for sending files
  config.action_dispatch.x_sendfile_header = "X-Sendfile"
 
  # For nginx:
  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
 
  # If you have no front-end server that supports something like X-Sendfile,
  # just comment this out and Rails will serve the files
 
  # See everything in the log (default is :info)
  # config.log_level = :debug
 
  # Use a different logger for distributed setups
  # config.logger = SyslogLogger.new
 
  # Use a different cache store in production
  # config.cache_store = :mem_cache_store
 
  # Disable Rails's static asset server
  # In production, Apache or nginx will already do this
  config.serve_static_assets = false
 
  # Enable serving of images, stylesheets, and javascripts from an asset server
  # config.action_controller.asset_host = "http://assets.example.com"
 
  # Disable delivery errors, bad email addresses will be ignored
  # config.action_mailer.raise_delivery_errors = false
 
  # Enable threaded mode
  # config.threadsafe!
 
  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation can not be found)
  config.i18n.fallbacks = true
 
  # Send deprecation notices to registered listeners
  config.active_support.deprecation = :notify
 
  config.action_mailer.default_url_options = { :host => 'whatever' }
end

If you want to have http and https working on both sites, then you can use

config.middleware.insert_before ActionDispatch::Cookies, Rack::SSL, :exclude => proc { |env| env['HTTPS'] != 'on' }

4. Test time!
- On Safari, ensure you blow away your cache.

Safari > Reset
Safari > Empty Cache

If you go to your http://server.website.com/ then it should redirect https://server.website.com/

Note:
- If you see a “Connection Refused” or ERROR bad URI or ERROR bad Request-Line, then ensure that it’s not an apache2 misconfiguration! I got apache2 listening to 80 only but have two virtual hosts. Not easy to see especially if you have the virtual hosts included.

- In Google Chrome, if you get a green icon lock then it fine.
trusted.png

Categories: rails Tags: , ,

devise limit one session per user at a time

February 23rd, 2012 rupert Comments off

A user can only be signed in a single session at a time. This means if he logged in to computer A then afterwards he logged in to computer B, then computer A times out. The original question was solved in http://stackoverflow.com/questions/7068919/devise-limit-one-session-per-user-at-a-time

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery
 
  before_filter :authenticate_user!, :check_concurrent_session, :store_location
 
  ... 
  def check_concurrent_session
    if is_already_logged_in?
      sign_out_and_redirect(current_user)
    end
  end
 
  def is_already_logged_in?
    current_user && !(session[:token] == current_user.login_token)
  end
 
  def after_sign_out_path_for(resource)
    loggedout_path
  end
 
end

app/controllers/sessions_controller.rb

class SessionsController < Devise::SessionsController
 
  skip_before_filter :check_concurrent_session
 
  def create
    super
    set_login_token
  end
 
  private
  def set_login_token
    token = Devise.friendly_token
    session[:token] = token
    current_user.login_token = token
    current_user.save
  end
 
end

app/controllers/static_controller.rb

class StaticController < ApplicationController
  skip_before_filter :authenticate_user!
end

app/views/sessions/new.html.erb

<div id="application">
 
 <nav id="secondary">
    <ul>
      <li class="current"><%= link_to "Log In", new_user_session_path %></li>
      <%- if devise_mapping.recoverable? && controller_name != 'passwords' %>
        <li><%= link_to "Forgot Password", new_password_path(resource_name) %></li>
      <% end -%>
    </ul>
  </nav>
 
  <section id="content">
 
    <%= semantic_form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %>
      <section>
        <%= f.input :username %>
      </section>
 
      <section>
        <%= f.input :password %>
      </section>
 
      <%= f.buttons do %>
        <%= f.commit_button :label => "Login", :button_html => { :class => "button primary submit"} %>
      <% end %>
 
      <br/>
    <% end %>
 
    <%= render :partial => 'layouts/devise/devise_error_messages' %>
 
  </section>
 
</div>

app/views/static/loggedout.html.erb

<section id="content">
 
  <h1>Logged Out</h1>
 
  <hr/>
 
  <p>This is not an error page but an indication that you have lost your session.</p>
 
  <p><b>So why are you here?</b></p>
 
  <ul>
    <li>- You have successfully logged out after clicking the "Logout" button.</li>
    <li>- You logged in to another machine so we logged this session out. We don't want to have multiple logins everywhere for security purposes.</li>
    <li>- You have been inactive for a while, we logged this session out.</li>
  </ul>
 
  <p><b><%= link_to "Login", new_user_session_path, :class => "button" %></b></p>
</section>

config/routes.rb

  devise_for :users, :controllers => { :sessions => "sessions" }
 
  ..
  match "loggedout" => "static#loggedout"
 end

db/migrate/20120223022102_add_login_token_to_users.rb

class AddLoginTokenToUsers < ActiveRecord::Migration
  def self.up
    PgTools.restore_default_search_path
 
    change_table "users" do |t|
      t.string "login_token"
    end
  end
 
  def self.down
    PgTools.restore_default_search_path
 
    change_table "users" do |t|
      t.remove "login_token"
    end
  end
end
Categories: rails Tags: ,

freebsd + jdk + geoserver

February 10th, 2012 rupert Comments off

1. Install java

% cd /usr/ports/java/jdk16
% make

Installing java on freebsd is not fully automated, you will be prompted to download files

IMPORTANT: To build the JDK 1.6.0 port, you should have at least
2.5Gb of free disk space in the build area!
 
 
 Due to licensing restrictions, certain files must be fetched manually.
 
 Please download the Update 3 Source from
 http://www.java.net/download/jdk6/6u3/promoted/b05/jdk-6u3-fcs-src-b05-jrl-24_sep_2007.jar
 and the Source Binaries from
 http://www.java.net/download/jdk6/6u3/promoted/b05/jdk-6u3-fcs-bin-b05-jrl-24_sep_2007.jar
 and the Mozilla Headers from
 http://www.java.net/download/jdk6/6u3/promoted/b05/jdk-6u3-fcs-mozilla_headers-b05-unix-24_sep_2007.jar
 .
 
 Please open http://www.oracle.com/technetwork/java/javase/downloads/index.html
 in a web browser and follow the "Download" link for
 "JDK DST Timezone Update Tool - 1_3_45" to obtain the
 time zone update file, tzupdater-1_3_45-2011n.zip.
 
 Please download the patchset, bsd-jdk16-patches-4.tar.bz2, from
 http://www.eyesbeyond.com/freebsddom/java/jdk16.html.
 
 Please place the downloaded file(s) in /usr/ports/distfiles 
 and restart the build.
 
*** Error code 1
 
Stop in /usr/ports/java/jdk16.
*** Error code 1
 
Stop in /usr/ports/java/jdk16.
*** Error code 1

These files are:

% cd /usr/ports/distfiles
% wget http://www.java.net/download/jdk6/6u3/promoted/b05/jdk-6u3-fcs-src-b05-jrl-24_sep_2007.jar
% wget http://www.java.net/download/jdk6/6u3/promoted/b05/jdk-6u3-fcs-bin-b05-jrl-24_sep_2007.jar
% wget http://www.java.net/download/jdk6/6u3/promoted/b05/jdk-6u3-fcs-mozilla_headers-b05-unix-24_sep_2007.jar
% # download manually tzupdater-1_3_45-2011n.zip from http://www.oracle.com/technetwork/java/javase/downloads/index.html
% # download manually bsd-jdk16-patches-4.tar.bz2 from http://www.eyesbeyond.com/freebsddom/java/jdk16.html

2. Run make

% cd /usr/ports/java/jdk16
% make
% make install

3. Install geoserver

% cd /usr/ports/graphics/geoserver
% make
% make install

4. Startup geoserver

% vim /etc/rc.conf
geoserver_enable=YES
% /usr/local/etc/rc.d/geoserver start

5. Browse http://127.0.0.1:8080/geoserver/

Categories: freebsd, geoserver, linux Tags: , ,

freebsd + apache + php

February 10th, 2012 rupert Comments off

1. Install apache22

% cd /usr/ports/www/apache22
% make config
% make install clean
% vim /etc/rc.conf
apache22_enable=YES
/usr/local/etc/rc.d/apache22 start

2. Install php52

% cd /usr/ports/lang/php52
% make config #enable APACHE module
% make
% make install clean
Installing PHP CLI binary:        /usr/local/bin/
Installing PHP CLI man page:      /usr/local/man/man1/
Installing PHP CGI binary: /usr/local/bin/
Installing build environment:     /usr/local/lib/php/build/
Installing header files:          /usr/local/include/php/
Installing helper programs:       /usr/local/bin/
  program: phpize
  program: php-config
....
      This port has installed the following files which may act as network
      servers and may therefore pose a remote security risk to the system.
/usr/local/libexec/apache22/libphp5.so
/usr/local/bin/php
/usr/local/bin/php-cgi
...

enable_apache.png

3 Configure Apache for php

% vim /usr/local/etc/apache22/httpd.conf
LoadModule php5_module        libexec/apache22/libphp5.so
<IfModule dir_module>
    DirectoryIndex index.html index.php
</IfModule>
<IfModule mime_module>
    AddType application/x-httpd-php .php
    AddType application/x-httpd-php-source .phps
</IfModule>
Categories: freebsd Tags:

please install libyaml and reinstall your ruby.

February 8th, 2012 rupert Comments off
/Users/rupert/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/yaml.rb:56:in `<top (required)>':
It seems your ruby installation is missing psych (for YAML output).
To eliminate this warning, please install libyaml and reinstall your ruby.
~% rvm remove ruby-1.9.3-p0
Removing /Users/rupert/.rvm/src/ruby-1.9.3-p0...
Removing /Users/rupert/.rvm/rubies/ruby-1.9.3-p0...
Removing ruby-1.9.3-p0 aliases...
Removing ruby-1.9.3-p0 wrappers...
Removing ruby-1.9.3-p0 environments...
Removing ruby-1.9.3-p0 binaries...
~% rvm list
rvm rubies
 
   ruby-1.8.7-p302 [ x86_64 ]
   ruby-1.9.2-p0 [ x86_64 ]
=> ruby-1.9.2-p180 [ x86_64 ]
~% rvm install ruby-1.9.3-p0
/Users/rupert/.rvm/rubies/ruby-1.9.3-p0, this may take a while depending on your cpu(s)...
 
ruby-1.9.3-p0 - #fetching 
ruby-1.9.3-p0 - #extracting ruby-1.9.3-p0 to /Users/rupert/.rvm/src/ruby-1.9.3-p0
ruby-1.9.3-p0 - #extracted to /Users/rupert/.rvm/src/ruby-1.9.3-p0
ruby-1.9.3-p0 - #configuring 
ruby-1.9.3-p0 - #compiling 
ruby-1.9.3-p0 - #installing 
ruby-1.9.3-p0 - updating #rubygems for /Users/rupert/.rvm/gems/ruby-1.9.3-p0@global
ruby-1.9.3-p0 - updating #rubygems for /Users/rupert/.rvm/gems/ruby-1.9.3-p0
ruby-1.9.3-p0 - adjusting #shebangs for (gem).
ruby-1.9.3-p0 - #importing default gemsets (/Users/rupert/.rvm/gemsets/)
~% rvm list
 
rvm rubies
 
   ruby-1.8.7-p302 [ x86_64 ]
   ruby-1.9.2-p0 [ x86_64 ]
=> ruby-1.9.2-p180 [ x86_64 ]
   ruby-1.9.3-p0 [ x86_64 ]
~% rvm use ruby-1.9.3-p0
Using /Users/rupert/.rvm/gems/ruby-1.9.3-p0
~/current[master]% gem list
 
*** LOCAL GEMS ***
 
rake (0.9.2.2)
rubygems-update (1.8.15)
Categories: ruby Tags: ,