0
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                     ...
A Controller• RESTful applications• like an orchestra conductor• as a middle man btw models and views                     ...
A Controller• RESTful applications• like an orchestra conductor• as a middle man btw models and views                     ...
Methods & Actions• A “class” has methods• A controller < ApplicationController• public methods => “action” <= routing     ...
Parameters• Two kinds of parameters - Query string - Post data• by params hash• “Routing” parameters                      ...
Parameters• default_url_options  class PostsController < ApplicationController    # The options parameter is the hash pass...
Session           stateless => stateful   ActionDispatch::Session::CookieStore• ActiveRecord::SessionStore• ActionDispatch...
Session                  Accessing the Session       class LoginsController < ApplicationController  # "Create" a login, a...
Session               Removing a Session Key      class LoginsController < ApplicationController  # "Delete" a login, aka ...
Session                  Flash• cleared with each request• only available in the next request• useful for storing error me...
Session                                Flashredirect_to root_url, :notice => "You have successfully logged out"           ...
Session Flash          ROR Lab.
Session                               Flash                          flash.keepclass MainController < ApplicationController...
Session                                Flash                             flash.nowclass ClientsController < ApplicationCont...
Cookies•   persisted across request and even sessions      class CommentsController < ApplicationController        def new...
Cookies•   to delete a cookie value                  cookies.delete(:key)                                         ROR Lab.
xml & json dataclass UsersController < ApplicationController  def index    @users = User.all    respond_to do |format|    ...
Filtersbefore    Action    after           around                            ROR Lab.
Filtersclass ApplicationController < ActionController::Base  before_filter :require_login   private   def require_login    ...
Filters• skip_before_filter class LoginsController < ApplicationController   skip_before_filter :require_login, :only => [:n...
Filters• around_filter class ChangesController < ActionController::Base   around_filter :wrap_in_transaction, :only => :show...
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 |cont...
Filters• Using a Class in more complex cases  class ApplicationController < ActionController::Base    before_filter LoginFi...
CSRF• Site to site hacking• First step for this with non-GET request  :create/update/destroy• RESTful default to protect C...
CSRF•   To add a non-guessable token with form helpers    <%= form_for @user do |f| %>      <%= f.text_field :username %>  ...
CSRF•   form_authenticity_token in custom Ajax calls    <%= form_for @user do |f| %>      <%= f.text_field :username %>    ...
Request & Response     Objects• Two methods in every controller - `request` method => request object - `response` method =...
Request Objects              ROR Lab.
Request Objects• Three hash parameters for request objects - path_parameters - query_parameters : query string - request_p...
Response Objects• like in an `after` filter                             ROR Lab.
Response Objects response.headers["Content-Type"] = "application/pdf"                                                     ...
HTTPAuthentications              ROR Lab.
HTTP  Authentications• Two types - Basic authentication     : using base 64 encoding -   Digest authentication     : using...
HTTP  Authentications• Basic authentication   class AdminController < ApplicationController     http_basic_authenticate_wi...
HTTP  Authentications• Digest authentication   class AdminController < ApplicationController     USERS = { "lifo" => "worl...
Streaming & File   Downloads require "prawn" class ClientsController < ApplicationController   # Generates a PDF document ...
Streaming & File   Downloadsclass ClientsController < ApplicationController  # Stream a file that has already been generate...
Streaming & File                          Downloadsin a RESTful application                            require "prawn"    ...
Streaming & File                          Downloads                             • in config/initializer/mime_types.rbin a R...
Parameter        Filtering• in config/application.rbconfig.filter_parameters << :password                                    ...
Rescueclass ApplicationController < ActionController::Base  rescue_from User::NotAuthorized, :with => :user_not_authorized...
Force HTTPS       protocolclass DinnerController  force_sslendclass DinnerController  force_ssl :only => :cheeseburger  # ...
감사합니다.
Upcoming SlideShare
Loading in...5
×

Action Controller Overview, Season 1

1,535

Published on

The 12th of ROR Lab. Season1

0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,535
On Slideshare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
Downloads
11
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Transcript of "Action Controller Overview, Season 1"

    1. 1. The 12th Round of ROR Lab.Action Controller Overview May 12th, 2012 Hyoseong Choi ROR Lab.
    2. 2. A Controller• RESTful applications• like an orchestra conductor• as a middle man btw models and views ROR Lab.
    3. 3. A Controller• RESTful applications• like an orchestra conductor• as a middle man btw models and views ROR Lab.
    4. 4. A Controller• RESTful applications• like an orchestra conductor• as a middle man btw models and views ROR Lab.
    5. 5. Methods & Actions• A “class” has methods• A controller < ApplicationController• public methods => “action” <= routing ROR Lab.
    6. 6. Parameters• Two kinds of parameters - Query string - Post data• by params hash• “Routing” parameters ROR Lab.
    7. 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. 8. Session stateless => stateful ActionDispatch::Session::CookieStore• ActiveRecord::SessionStore• ActionDispatch::Session::CacheStore• ActionDispatch::Session::MemCacheStore ROR Lab.
    9. 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  endend ROR Lab.
    10. 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  endend ROR Lab.
    11. 11. Session Flash• cleared with each request• only available in the next request• useful for storing error messages etc ROR Lab.
    12. 12. Session Flashredirect_to root_url, :notice => "You have successfully logged out" ROR Lab.
    13. 13. Session Flash ROR Lab.
    14. 14. Session Flash flash.keepclass MainController < ApplicationController  # Lets 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  endend ROR Lab.
    15. 15. Session Flash flash.nowclass ClientsController < ApplicationController  def create    @client = Client.new(params[:client])    if @client.save      # ...    else      flash.now[:error] = "Could not save client"      render :action => "new"    end  endend ROR Lab.
    16. 16. Cookies• persisted across request and even sessions class CommentsController < ApplicationController   def new     # Auto-fill the commenters 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 commenters name.         cookies[:commenter_name] = @comment.name       else         # Delete cookie for the commenters name cookie, if any.         cookies.delete(:commenter_name)       end       redirect_to @comment.article     else       render :action => "new"     end   end end ROR Lab.
    17. 17. Cookies• to delete a cookie value cookies.delete(:key) ROR Lab.
    18. 18. xml & json dataclass 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  endend ROR Lab.
    19. 19. Filtersbefore Action after around ROR Lab.
    20. 20. Filtersclass 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  endend ROR Lab.
    21. 21. Filters• skip_before_filter class LoginsController < ApplicationController   skip_before_filter :require_login, :only => [:new, :create] end ROR Lab.
    22. 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. 23. Filters• Three Ways to User Filters - a private method - a block - a class ROR Lab.
    24. 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. 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. 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. 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. 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. 29. Request & Response Objects• Two methods in every controller - `request` method => request object - `response` method => response object ROR Lab.
    30. 30. Request Objects ROR Lab.
    31. 31. Request Objects• Three hash parameters for request objects - path_parameters - query_parameters : query string - request_parameters : post data ROR Lab.
    32. 32. Response Objects• like in an `after` filter ROR Lab.
    33. 33. Response Objects response.headers["Content-Type"] = "application/pdf" ROR Lab.
    34. 34. HTTPAuthentications ROR Lab.
    35. 35. HTTP Authentications• Two types - Basic authentication : using base 64 encoding - Digest authentication : using MD5 encoding ROR Lab.
    36. 36. HTTP Authentications• Basic authentication class AdminController < ApplicationController   http_basic_authenticate_with :name => "humbaba", :password => "5baa61e4" end ROR Lab.
    37. 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. 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 endsend_data ROR Lab.
    39. 39. Streaming & File Downloadsclass 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")  endsend_file ROR Lab.
    40. 40. Streaming & File Downloadsin 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. 41. Streaming & File Downloads • in config/initializer/mime_types.rbin a RESTful application send_file ROR Lab.
    42. 42. Parameter Filtering• in config/application.rbconfig.filter_parameters << :password ROR Lab.
    43. 43. Rescueclass ApplicationController < ActionController::Base  rescue_from User::NotAuthorized, :with => :user_not_authorized   private   def user_not_authorized    flash[:error] = "You dont have access to this section."    redirect_to :back  endend class ClientsController < ApplicationController  # Check that the user has the right authorization to access clients.  before_filter :check_authorization   # Note how the actions dont 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. 44. Force HTTPS protocolclass DinnerController  force_sslendclass DinnerController  force_ssl :only => :cheeseburger  # or  force_ssl :except => :cheeseburgerend # Force all access to the app over SSL, use Strict-Transport-Security, and usesecure cookies. config.force_ssl = true ROR Lab.
    45. 45. 감사합니다.
    46. 46.   ROR Lab.
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×