Ruby on Rails 3 Cookie, Session, Flash & Authentication

Cookies

Set/get cookie in a controller

# Retrieve cookie with name "uid"
u_name = cookies[:uid]

# Set cookie
cookies[:uid] = u_name

# Delete a cookie
cookies.delete(:uid)

Set path and expiration

cookies[:uid] = { :value => "some value", :path => '/', :expires => 24.hours.from_now }

Options

:path
:expires
:domain

Session

Get Rails session value

value = session[:campaign]
@my_user ||= session[:user_id] && User.find(session[:user_id])

Set Rails session value

session[:campaign] = value

Remove a session value

session[:campaign] = nil

Reset session data

reset_session

Session configuration: By default, cookie is used to implement user session

config/initializers/session_store.rb
LmsParser::Application.config.session_store :cookie_store, :key => '_lms_parser_session'

To set the domain name for the session cookie

LmsParser::Application.config.session_store :cookie_store, :key => '_lms_parser_session' :domain => "web.com"

Rails Flash

Flash

  • A special session data that its data will be valid only for the next request
  • Good for saving a message to be displayed in the next request
  • In particular. when the controller redirect the browser to another URL using redirect_to
if @account.save    # Save successfully
  flash[:notice] = 'Account was successfully created.'
  redirect_to @account
Layout File
...
<body>

<p style="color: green"><%= flash[:notice] %></p>

<%= yield %>

</body>

Keep the flash data again for the next request

flash.keep

Allow the flash data available to the current request

flash.now[:error] = "Error message"

Http Basic Authentication

class SecureController < ApplicationController
  before_filter :basic_authenticate

  private
  def basic_authenticate
    authenticate_or_request_with_http_basic do |username, password|
      username=="my_user" && password=="some_password"
    end
  end
end

Application wide

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  ...

  private
  def basic_authenticate
    authenticate_or_request_with_http_basic do |username, password|
      username==LmsParser::Application.config.username && password==LmsParser::Application.config.password
    end
  end
end
  • Set LmsParser::Application.config.username in an initializer file or replace it with DB logic
class AccountsController < ApplicationController
  before_filter :basic_authenticate, :except => [:index, :show]

Security

If Session Fixation is an concern:

  • Call reset_session in SessionsController's create action
    • However, previous session information will be lost.
  • Record the source IP when a session is created
    • Verify it for every requests and deny access if the information does not match
    • Nevertheless, this is not fool proof since some ISV providers use proxy IP as the source IP
Document generated by Confluence on Apr 04, 2011 10:52