SlideShare a Scribd company logo
1 of 45
The 12th Round of ROR Lab.



Action Controller
    Overview

        May 12th, 2012

        Hyoseong Choi
          ROR Lab.
A Controller

• RESTful applications
• like an orchestra conductor
• as a middle man btw models and views


                                    ROR Lab.
A Controller

• RESTful applications
• like an orchestra conductor
• as a middle man btw models and views


                                    ROR Lab.
A Controller

• RESTful applications
• like an orchestra conductor
• as a middle man btw models and views


                                    ROR Lab.
Methods & Actions
• A “class” has methods
• A controller < ApplicationController
• public methods => “action” <= routing



                                     ROR Lab.
Parameters
• Two kinds of parameters
 - Query string
 - Post data
• by params hash
• “Routing” parameters

                            ROR Lab.
Parameters
• default_url_options


  class PostsController < ApplicationController
    # The options parameter is the hash passed in to 'url_for'
    def default_url_options(options)
      {:locale => I18n.locale}
    end
  end



                                                                 ROR Lab.
Session
           stateless => stateful

   ActionDispatch::Session::CookieStore
• ActiveRecord::SessionStore
• ActionDispatch::Session::CacheStore
• ActionDispatch::Session::MemCacheStore


                                     ROR Lab.
Session
                  Accessing the Session


       class LoginsController < ApplicationController
  # "Create" a login, aka "log the user in"
  def create
    if user = User.authenticate(params[:username], params[:password])
      # Save the user ID in the session so it can be used in
      # subsequent requests
      session[:current_user_id] = user.id
      redirect_to root_url
    end
  end
end




                                                                        ROR Lab.
Session
               Removing a Session Key


      class LoginsController < ApplicationController
  # "Delete" a login, aka "log the user out"
  def destroy
    # Remove the user id from the session
    @_current_user = session[:current_user_id] = nil
    redirect_to root_url
  end
end




                                                       ROR Lab.
Session
                  Flash


• cleared with each request
• only available in the next request
• useful for storing error messages etc

                                          ROR Lab.
Session
                                Flash




redirect_to root_url, :notice => "You have successfully logged out"




                                                                      ROR Lab.
Session
 Flash




          ROR Lab.
Session
                               Flash
                          flash.keep

class MainController < ApplicationController
  # Let's say this action corresponds to root_url, but you want
  # all requests here to be redirected to UsersController#index.
  # If an action sets the flash and redirects here, the values
  # would normally be lost when another redirect happens, but you
  # can use 'keep' to make it persist for another request.
  def index
    # Will persist all flash values.
    flash.keep
 
    # You can also use a key to keep only some kind of value.
    # flash.keep(:notice)
    redirect_to users_url
  end
end




                                                                    ROR Lab.
Session
                                Flash
                             flash.now

class ClientsController < ApplicationController
  def create
    @client = Client.new(params[:client])
    if @client.save
      # ...
    else
      flash.now[:error] = "Could not save client"
      render :action => "new"
    end
  end
end




                                                   ROR Lab.
Cookies
•   persisted across request and even sessions

      class CommentsController < ApplicationController
        def new
          # Auto-fill the commenter's name if it has been stored in a cookie
          @comment = Comment.new(:name => cookies[:commenter_name])
        end
       
        def create
          @comment = Comment.new(params[:comment])
          if @comment.save
            flash[:notice] = "Thanks for your comment!"
            if params[:remember_name]
              # Remember the commenter's name.
              cookies[:commenter_name] = @comment.name
            else
              # Delete cookie for the commenter's name cookie, if any.
              cookies.delete(:commenter_name)
            end
            redirect_to @comment.article
          else
            render :action => "new"
          end
        end
      end




                                                                              ROR Lab.
Cookies
•   to delete a cookie value



                  cookies.delete(:key)




                                         ROR Lab.
xml & json data

class UsersController < ApplicationController
  def index
    @users = User.all
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @users}
      format.json { render :json => @users}
    end
  end
end




                                                ROR Lab.
Filters

before    Action    after



           around




                            ROR Lab.
Filters
class ApplicationController < ActionController::Base
  before_filter :require_login
 
  private
 
  def require_login
    unless logged_in?
      flash[:error] = "You must be logged in to access this section"
      redirect_to new_login_url # halts request cycle
    end
  end
 
  # The logged_in? method simply returns true if the user is logged
  # in and false otherwise. It does this by "booleanizing" the
  # current_user method we created previously using a double ! operator.
  # Note that this is not common in Ruby and is discouraged unless you
  # really mean to convert something into true or false.
  def logged_in?
    !!current_user
  end
end




                                                                           ROR Lab.
Filters
• skip_before_filter
 class LoginsController < ApplicationController
   skip_before_filter :require_login, :only => [:new, :create]
 end




                                                                ROR Lab.
Filters
• around_filter
 class ChangesController < ActionController::Base
   around_filter :wrap_in_transaction, :only => :show
  
   private
  
   def wrap_in_transaction
     ActiveRecord::Base.transaction do
       begin
         yield
       ensure
         raise ActiveRecord::Rollback
       end
     end
   end
 end




                                                       ROR Lab.
Filters

• Three Ways to User Filters
 - a private method
 - a block
 - a class

                               ROR Lab.
Filters
• Using a Block in more simple cases
  class ApplicationController < ActionController::Base
    before_filter do |controller|
      redirect_to new_login_url unless controller.send(:logged_in?)
    end
  end




                                                                      ROR Lab.
Filters
• Using a Class in more complex cases
  class ApplicationController < ActionController::Base
    before_filter LoginFilter
  end
   
  class LoginFilter
    def self.filter(controller)
      unless controller.send(:logged_in?)
        controller.flash[:error] = "You must be logged in"
        controller.redirect_to controller.new_login_url
      end
    end
  end




                                                            ROR Lab.
CSRF

• Site to site hacking
• First step for this with non-GET request
  :create/update/destroy

• RESTful default to protect CSRF
• Nevertheless, non-GET request still
  vulnerable


                                         ROR Lab.
CSRF
•   To add a non-guessable token with form helpers

    <%= form_for @user do |f| %>
      <%= f.text_field :username %>
      <%= f.text_field :password %>
    <% end %>




    <form accept-charset="UTF-8" action="/users/1" method="post">
    <input type="hidden"
           value="67250ab105eb5ad10851c00a5621854a23af5489"
           name="authenticity_token"/>
    <!-- fields -->
    </form>




                                                                    ROR Lab.
CSRF
•   form_authenticity_token in custom Ajax calls

    <%= form_for @user do |f| %>
      <%= f.text_field :username %>
      <%= f.text_field :password %>
    <% end %>




    <form accept-charset="UTF-8" action="/users/1" method="post">
    <input type="hidden"
           value="67250ab105eb5ad10851c00a5621854a23af5489"
           name="authenticity_token"/>
    <!-- fields -->
    </form>




                                                                    ROR Lab.
Request & Response
     Objects

• Two methods in every controller
 - `request` method => request object
 - `response` method => response object

                                  ROR Lab.
Request Objects




              ROR Lab.
Request Objects

• Three hash parameters for request objects
 - path_parameters
 - query_parameters : query string
 - request_parameters : post data

                                      ROR Lab.
Response Objects




• like in an `after` filter
                             ROR Lab.
Response Objects




 response.headers["Content-Type"] = "application/pdf"




                                                        ROR Lab.
HTTP
Authentications




              ROR Lab.
HTTP
  Authentications
• Two types
 - Basic authentication
     : using base 64 encoding
 -   Digest authentication
     : using MD5 encoding


                                ROR Lab.
HTTP
  Authentications
• Basic authentication
   class AdminController < ApplicationController
     http_basic_authenticate_with :name => "humbaba", :password => "5baa61e4"
   end




                                                                                ROR Lab.
HTTP
  Authentications
• Digest authentication
   class AdminController < ApplicationController
     USERS = { "lifo" => "world" }
    
     before_filter :authenticate
    
     private
    
     def authenticate
       authenticate_or_request_with_http_digest do |username|
         USERS[username]
       end
     end




                                                                ROR Lab.
Streaming & File
   Downloads
 require "prawn"
 class ClientsController < ApplicationController
   # Generates a PDF document with information on the client and
   # returns it. The user will get the PDF as a file download.
   def download_pdf
     client = Client.find(params[:id])
     send_data generate_pdf(client),
               :filename => "#{client.name}.pdf",
               :type => "application/pdf",
               :disposition => "attachement"
   end
  
   private
  
   def generate_pdf(client)
     Prawn::Document.new do
       text client.name, :align => :center
       text "Address: #{client.address}"
       text "Email: #{client.email}"
     end.render
   end
 end




send_data                                                          ROR Lab.
Streaming & File
   Downloads
class ClientsController < ApplicationController
  # Stream a file that has already been generated and stored on disk.
  def download_pdf
    client = Client.find(params[:id])
    send_file("#{Rails.root}/files/clients/#{client.id}.pdf",
              :filename => "#{client.name}.pdf",
              :type => "application/pdf")
  end




send_file                                                               ROR Lab.
Streaming & File
                          Downloads
in a RESTful application


                            require "prawn"
                            class ClientsController < ApplicationController
                             
                              def show
                                @client = Client.find(params[:id])
                             
                                respond_to do |format|
                                  format.html
                                  format.pdf { render :pdf => generate_pdf(@client) }
                                end
                              end

                              private
                             
                              def generate_pdf(client)
                                Prawn::Document.new do
                                  text client.name, :align => :center
                                  text "Address: #{client.address}"
                                  text "Email: #{client.email}"
                                end.render
                              end
                            end




                           send_file                                                     ROR Lab.
Streaming & File
                          Downloads
                             • in config/initializer/mime_types.rb
in a RESTful application




                           send_file                            ROR Lab.
Parameter
        Filtering
• in config/application.rb
config.filter_parameters << :password




                                      ROR Lab.
Rescue
class ApplicationController < ActionController::Base
  rescue_from User::NotAuthorized, :with => :user_not_authorized
 
  private
 
  def user_not_authorized
    flash[:error] = "You don't have access to this section."
    redirect_to :back
  end
end
 
class ClientsController < ApplicationController
  # Check that the user has the right authorization to access clients.
  before_filter :check_authorization
 
  # Note how the actions don't have to worry about all the auth stuff.
  def edit
    @client = Client.find(params[:id])
  end
 
  private
 
  # If the user is not authorized, just throw the exception.
  def check_authorization
    raise User::NotAuthorized unless current_user.admin?
  end




                                                                         ROR Lab.
Force HTTPS
       protocol
class DinnerController
  force_ssl
end



class DinnerController
  force_ssl :only => :cheeseburger
  # or
  force_ssl :except => :cheeseburger
end




 # Force all access to the app over SSL, use Strict-Transport-Security, and use
secure cookies.
 config.force_ssl = true


                                                                                  ROR Lab.
감사합니다.

More Related Content

What's hot

Web注入+http漏洞等描述
Web注入+http漏洞等描述Web注入+http漏洞等描述
Web注入+http漏洞等描述
fangjiafu
 
Using Ruby on Rails with legacy Oracle databases
Using Ruby on Rails with legacy Oracle databasesUsing Ruby on Rails with legacy Oracle databases
Using Ruby on Rails with legacy Oracle databases
Raimonds Simanovskis
 

What's hot (18)

Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with Jasmine
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with Jest
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit Testing
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
 
PHP Unit Testing
PHP Unit TestingPHP Unit Testing
PHP Unit Testing
 
Jasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishyJasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishy
 
Scaladays 2014 introduction to scalatest selenium dsl
Scaladays 2014   introduction to scalatest selenium dslScaladays 2014   introduction to scalatest selenium dsl
Scaladays 2014 introduction to scalatest selenium dsl
 
Web注入+http漏洞等描述
Web注入+http漏洞等描述Web注入+http漏洞等描述
Web注入+http漏洞等描述
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015
 
JAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & JasmineJAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & Jasmine
 
Tdd iPhone For Dummies
Tdd iPhone For DummiesTdd iPhone For Dummies
Tdd iPhone For Dummies
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails Apps
 
Laravel 5 Annotations: RESTful API routing
Laravel 5 Annotations: RESTful API routingLaravel 5 Annotations: RESTful API routing
Laravel 5 Annotations: RESTful API routing
 
Clean tests good tests
Clean tests   good testsClean tests   good tests
Clean tests good tests
 
The Dark Art of Rails Plugins (2008)
The Dark Art of Rails Plugins (2008)The Dark Art of Rails Plugins (2008)
The Dark Art of Rails Plugins (2008)
 
Using Ruby on Rails with legacy Oracle databases
Using Ruby on Rails with legacy Oracle databasesUsing Ruby on Rails with legacy Oracle databases
Using Ruby on Rails with legacy Oracle databases
 
Lecture5
Lecture5Lecture5
Lecture5
 

Viewers also liked

Let's Learn Ruby - Basic
Let's Learn Ruby - BasicLet's Learn Ruby - Basic
Let's Learn Ruby - Basic
Eddie Kao
 
Introduction to html
Introduction to htmlIntroduction to html
Introduction to html
vikasgaur31
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web Architecture
Chamnap Chhorn
 

Viewers also liked (14)

Let's Learn Ruby - Basic
Let's Learn Ruby - BasicLet's Learn Ruby - Basic
Let's Learn Ruby - Basic
 
Swift distributed tracing method and tools v2
Swift distributed tracing method and tools v2Swift distributed tracing method and tools v2
Swift distributed tracing method and tools v2
 
Control review for iOS
Control review for iOSControl review for iOS
Control review for iOS
 
September2011aftma
September2011aftmaSeptember2011aftma
September2011aftma
 
Ruby on Rails testing with Rspec
Ruby on Rails testing with RspecRuby on Rails testing with Rspec
Ruby on Rails testing with Rspec
 
jQuery For Beginners - jQuery Conference 2009
jQuery For Beginners - jQuery Conference 2009jQuery For Beginners - jQuery Conference 2009
jQuery For Beginners - jQuery Conference 2009
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
Web application architecture
Web application architectureWeb application architecture
Web application architecture
 
Introduction to html
Introduction to htmlIntroduction to html
Introduction to html
 
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho PolutaInfinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web Architecture
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Forever
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 

Similar to Action Controller Overview, Season 1

Action Controller Overview, Season 2
Action Controller Overview, Season 2Action Controller Overview, Season 2
Action Controller Overview, Season 2
RORLAB
 
Active Record Query Interface (2), Season 1
Active Record Query Interface (2), Season 1Active Record Query Interface (2), Season 1
Active Record Query Interface (2), Season 1
RORLAB
 
Intro to-rails-webperf
Intro to-rails-webperfIntro to-rails-webperf
Intro to-rails-webperf
New Relic
 
Lucene for Solr Developers
Lucene for Solr DevelopersLucene for Solr Developers
Lucene for Solr Developers
Erik Hatcher
 
HES2011 - joernchen - Ruby on Rails from a Code Auditor Perspective
HES2011 - joernchen - Ruby on Rails from a Code Auditor PerspectiveHES2011 - joernchen - Ruby on Rails from a Code Auditor Perspective
HES2011 - joernchen - Ruby on Rails from a Code Auditor Perspective
Hackito Ergo Sum
 

Similar to Action Controller Overview, Season 1 (20)

Action Controller Overview, Season 2
Action Controller Overview, Season 2Action Controller Overview, Season 2
Action Controller Overview, Season 2
 
Rails antipatterns
Rails antipatternsRails antipatterns
Rails antipatterns
 
Rails antipattern-public
Rails antipattern-publicRails antipattern-public
Rails antipattern-public
 
Active Record Form Helpers, Season 1
Active Record Form Helpers, Season 1Active Record Form Helpers, Season 1
Active Record Form Helpers, Season 1
 
Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
 
Rails 3 (beta) Roundup
Rails 3 (beta) RoundupRails 3 (beta) Roundup
Rails 3 (beta) Roundup
 
Routing 1, Season 1
Routing 1, Season 1Routing 1, Season 1
Routing 1, Season 1
 
Rails Security
Rails SecurityRails Security
Rails Security
 
Rupicon 2014 Action pack
Rupicon 2014 Action packRupicon 2014 Action pack
Rupicon 2014 Action pack
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Active Record Query Interface (2), Season 1
Active Record Query Interface (2), Season 1Active Record Query Interface (2), Season 1
Active Record Query Interface (2), Season 1
 
Intro to-rails-webperf
Intro to-rails-webperfIntro to-rails-webperf
Intro to-rails-webperf
 
Rails 4.0
Rails 4.0Rails 4.0
Rails 4.0
 
Lucene for Solr Developers
Lucene for Solr DevelopersLucene for Solr Developers
Lucene for Solr Developers
 
Rails Performance
Rails PerformanceRails Performance
Rails Performance
 
HES2011 - joernchen - Ruby on Rails from a Code Auditor Perspective
HES2011 - joernchen - Ruby on Rails from a Code Auditor PerspectiveHES2011 - joernchen - Ruby on Rails from a Code Auditor Perspective
HES2011 - joernchen - Ruby on Rails from a Code Auditor Perspective
 
Robotframework
RobotframeworkRobotframework
Robotframework
 
6 tips for improving ruby performance
6 tips for improving ruby performance6 tips for improving ruby performance
6 tips for improving ruby performance
 
Advantages of Rails Framework
Advantages of Rails FrameworkAdvantages of Rails Framework
Advantages of Rails Framework
 

More from RORLAB

Active Support Core Extension (3)
Active Support Core Extension (3)Active Support Core Extension (3)
Active Support Core Extension (3)
RORLAB
 
Active Support Core Extension (2)
Active Support Core Extension (2)Active Support Core Extension (2)
Active Support Core Extension (2)
RORLAB
 
Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2
RORLAB
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2
RORLAB
 
Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2
RORLAB
 
ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2
RORLAB
 
Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2
RORLAB
 

More from RORLAB (20)

Getting Started with Rails (4)
Getting Started with Rails (4) Getting Started with Rails (4)
Getting Started with Rails (4)
 
Getting Started with Rails (3)
Getting Started with Rails (3) Getting Started with Rails (3)
Getting Started with Rails (3)
 
Getting Started with Rails (2)
Getting Started with Rails (2)Getting Started with Rails (2)
Getting Started with Rails (2)
 
Getting Started with Rails (1)
Getting Started with Rails (1)Getting Started with Rails (1)
Getting Started with Rails (1)
 
Self join in active record association
Self join in active record associationSelf join in active record association
Self join in active record association
 
Asset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on RailsAsset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on Rails
 
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
 
Active Support Core Extension (3)
Active Support Core Extension (3)Active Support Core Extension (3)
Active Support Core Extension (3)
 
Active Support Core Extension (2)
Active Support Core Extension (2)Active Support Core Extension (2)
Active Support Core Extension (2)
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)
 
Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2
 
Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2
 
ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2
 
Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2
 
Active Record Association (2), Season 2
Active Record Association (2), Season 2Active Record Association (2), Season 2
Active Record Association (2), Season 2
 
ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2
 
ActiveRecord Callbacks & Observers, Season 2
ActiveRecord Callbacks & Observers, Season 2ActiveRecord Callbacks & Observers, Season 2
ActiveRecord Callbacks & Observers, Season 2
 
ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2
 
Rails Database Migration, Season 2
Rails Database Migration, Season 2Rails Database Migration, Season 2
Rails Database Migration, Season 2
 

Recently uploaded

Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 

Recently uploaded (20)

PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 

Action Controller Overview, Season 1

  • 1. The 12th Round of ROR Lab. Action Controller Overview May 12th, 2012 Hyoseong Choi ROR Lab.
  • 2. A Controller • RESTful applications • like an orchestra conductor • as a middle man btw models and views ROR Lab.
  • 3. A Controller • RESTful applications • like an orchestra conductor • as a middle man btw models and views ROR Lab.
  • 4. A Controller • RESTful applications • like an orchestra conductor • as a middle man btw models and views ROR Lab.
  • 5. Methods & Actions • A “class” has methods • A controller < ApplicationController • public methods => “action” <= routing ROR Lab.
  • 6. Parameters • Two kinds of parameters - Query string - Post data • by params hash • “Routing” parameters ROR Lab.
  • 7. Parameters • default_url_options class PostsController < ApplicationController   # The options parameter is the hash passed in to 'url_for'   def default_url_options(options)     {:locale => I18n.locale}   end end ROR Lab.
  • 8. Session stateless => stateful ActionDispatch::Session::CookieStore • ActiveRecord::SessionStore • ActionDispatch::Session::CacheStore • ActionDispatch::Session::MemCacheStore ROR Lab.
  • 9. Session Accessing the Session class LoginsController < ApplicationController   # "Create" a login, aka "log the user in"   def create     if user = User.authenticate(params[:username], params[:password])       # Save the user ID in the session so it can be used in       # subsequent requests       session[:current_user_id] = user.id       redirect_to root_url     end   end end ROR Lab.
  • 10. Session Removing a Session Key class LoginsController < ApplicationController   # "Delete" a login, aka "log the user out"   def destroy     # Remove the user id from the session     @_current_user = session[:current_user_id] = nil     redirect_to root_url   end end ROR Lab.
  • 11. Session Flash • cleared with each request • only available in the next request • useful for storing error messages etc ROR Lab.
  • 12. Session Flash redirect_to root_url, :notice => "You have successfully logged out" ROR Lab.
  • 13. Session Flash ROR Lab.
  • 14. Session Flash flash.keep class MainController < ApplicationController   # Let's say this action corresponds to root_url, but you want   # all requests here to be redirected to UsersController#index.   # If an action sets the flash and redirects here, the values   # would normally be lost when another redirect happens, but you   # can use 'keep' to make it persist for another request.   def index     # Will persist all flash values.     flash.keep       # You can also use a key to keep only some kind of value.     # flash.keep(:notice)     redirect_to users_url   end end ROR Lab.
  • 15. Session Flash flash.now class ClientsController < ApplicationController   def create     @client = Client.new(params[:client])     if @client.save       # ...     else       flash.now[:error] = "Could not save client"       render :action => "new"     end   end end ROR Lab.
  • 16. Cookies • persisted across request and even sessions class CommentsController < ApplicationController   def new     # Auto-fill the commenter's name if it has been stored in a cookie     @comment = Comment.new(:name => cookies[:commenter_name])   end     def create     @comment = Comment.new(params[:comment])     if @comment.save       flash[:notice] = "Thanks for your comment!"       if params[:remember_name]         # Remember the commenter's name.         cookies[:commenter_name] = @comment.name       else         # Delete cookie for the commenter's name cookie, if any.         cookies.delete(:commenter_name)       end       redirect_to @comment.article     else       render :action => "new"     end   end end ROR Lab.
  • 17. Cookies • to delete a cookie value cookies.delete(:key) ROR Lab.
  • 18. xml & json data class UsersController < ApplicationController   def index     @users = User.all     respond_to do |format|       format.html # index.html.erb       format.xml  { render :xml => @users}       format.json { render :json => @users}     end   end end ROR Lab.
  • 19. Filters before Action after around ROR Lab.
  • 20. Filters class ApplicationController < ActionController::Base   before_filter :require_login     private     def require_login     unless logged_in?       flash[:error] = "You must be logged in to access this section"       redirect_to new_login_url # halts request cycle     end   end     # The logged_in? method simply returns true if the user is logged   # in and false otherwise. It does this by "booleanizing" the   # current_user method we created previously using a double ! operator.   # Note that this is not common in Ruby and is discouraged unless you   # really mean to convert something into true or false.   def logged_in?     !!current_user   end end ROR Lab.
  • 21. Filters • skip_before_filter class LoginsController < ApplicationController   skip_before_filter :require_login, :only => [:new, :create] end ROR Lab.
  • 22. Filters • around_filter class ChangesController < ActionController::Base   around_filter :wrap_in_transaction, :only => :show     private     def wrap_in_transaction     ActiveRecord::Base.transaction do       begin         yield       ensure         raise ActiveRecord::Rollback       end     end   end end ROR Lab.
  • 23. Filters • Three Ways to User Filters - a private method - a block - a class ROR Lab.
  • 24. Filters • Using a Block in more simple cases class ApplicationController < ActionController::Base   before_filter do |controller|     redirect_to new_login_url unless controller.send(:logged_in?)   end end ROR Lab.
  • 25. Filters • Using a Class in more complex cases class ApplicationController < ActionController::Base   before_filter LoginFilter end   class LoginFilter   def self.filter(controller)     unless controller.send(:logged_in?)       controller.flash[:error] = "You must be logged in"       controller.redirect_to controller.new_login_url     end   end end ROR Lab.
  • 26. CSRF • Site to site hacking • First step for this with non-GET request :create/update/destroy • RESTful default to protect CSRF • Nevertheless, non-GET request still vulnerable ROR Lab.
  • 27. CSRF • To add a non-guessable token with form helpers <%= form_for @user do |f| %>   <%= f.text_field :username %>   <%= f.text_field :password %> <% end %> <form accept-charset="UTF-8" action="/users/1" method="post"> <input type="hidden"        value="67250ab105eb5ad10851c00a5621854a23af5489"        name="authenticity_token"/> <!-- fields --> </form> ROR Lab.
  • 28. CSRF • form_authenticity_token in custom Ajax calls <%= form_for @user do |f| %>   <%= f.text_field :username %>   <%= f.text_field :password %> <% end %> <form accept-charset="UTF-8" action="/users/1" method="post"> <input type="hidden"        value="67250ab105eb5ad10851c00a5621854a23af5489"        name="authenticity_token"/> <!-- fields --> </form> ROR Lab.
  • 29. Request & Response Objects • Two methods in every controller - `request` method => request object - `response` method => response object ROR Lab.
  • 30. Request Objects ROR Lab.
  • 31. Request Objects • Three hash parameters for request objects - path_parameters - query_parameters : query string - request_parameters : post data ROR Lab.
  • 32. Response Objects • like in an `after` filter ROR Lab.
  • 35. HTTP Authentications • Two types - Basic authentication : using base 64 encoding - Digest authentication : using MD5 encoding ROR Lab.
  • 36. HTTP Authentications • Basic authentication class AdminController < ApplicationController   http_basic_authenticate_with :name => "humbaba", :password => "5baa61e4" end ROR Lab.
  • 37. HTTP Authentications • Digest authentication class AdminController < ApplicationController   USERS = { "lifo" => "world" }     before_filter :authenticate     private     def authenticate     authenticate_or_request_with_http_digest do |username|       USERS[username]     end   end ROR Lab.
  • 38. Streaming & File Downloads require "prawn" class ClientsController < ApplicationController   # Generates a PDF document with information on the client and   # returns it. The user will get the PDF as a file download.   def download_pdf     client = Client.find(params[:id])     send_data generate_pdf(client),               :filename => "#{client.name}.pdf",               :type => "application/pdf", :disposition => "attachement"   end     private     def generate_pdf(client)     Prawn::Document.new do       text client.name, :align => :center       text "Address: #{client.address}"       text "Email: #{client.email}"     end.render   end end send_data ROR Lab.
  • 39. Streaming & File Downloads class ClientsController < ApplicationController   # Stream a file that has already been generated and stored on disk.   def download_pdf     client = Client.find(params[:id])     send_file("#{Rails.root}/files/clients/#{client.id}.pdf",               :filename => "#{client.name}.pdf",               :type => "application/pdf")   end send_file ROR Lab.
  • 40. Streaming & File Downloads in a RESTful application require "prawn" class ClientsController < ApplicationController     def show     @client = Client.find(params[:id])       respond_to do |format|       format.html       format.pdf { render :pdf => generate_pdf(@client) }     end   end   private     def generate_pdf(client)     Prawn::Document.new do       text client.name, :align => :center       text "Address: #{client.address}"       text "Email: #{client.email}"     end.render   end end send_file ROR Lab.
  • 41. Streaming & File Downloads • in config/initializer/mime_types.rb in a RESTful application send_file ROR Lab.
  • 42. Parameter Filtering • in config/application.rb config.filter_parameters << :password ROR Lab.
  • 43. Rescue class ApplicationController < ActionController::Base   rescue_from User::NotAuthorized, :with => :user_not_authorized     private     def user_not_authorized     flash[:error] = "You don't have access to this section."     redirect_to :back   end end   class ClientsController < ApplicationController   # Check that the user has the right authorization to access clients.   before_filter :check_authorization     # Note how the actions don't have to worry about all the auth stuff.   def edit     @client = Client.find(params[:id])   end     private     # If the user is not authorized, just throw the exception.   def check_authorization     raise User::NotAuthorized unless current_user.admin?   end ROR Lab.
  • 44. Force HTTPS protocol class DinnerController   force_ssl end class DinnerController   force_ssl :only => :cheeseburger   # or   force_ssl :except => :cheeseburger end # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. config.force_ssl = true ROR Lab.
  • 46.   ROR Lab.

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n