never_had_a_name
never_had_a_name

Reputation: 93196

ruby on rails 3 question about before_filter

Could someone please explain for me what is happening here?

i feel like the documentation doesnt mention a lot or describe what is happening. it just say use this method like this.

what will happen if username and password are true, what will happen if false etc?

class AdminController < ApplicationController
  USERNAME, PASSWORD = "humbaba", "5baa61e4"

  before_filter :authenticate

  private

  def authenticate
    authenticate_or_request_with_http_basic do |username, password|
      username == USERNAME &&
      Digest::SHA1.hexdigest(password) == PASSWORD
    end
  end
end

thanks

Upvotes: 1

Views: 4189

Answers (2)

Max Chernyak
Max Chernyak

Reputation: 37367

There is standard authentication functionality built into every browser called "Basic HTTP Authentication". I'm sure you've seen a generic username/password dialog (styled as part of your operating system) show up on web pages. This is it.

It works as follows:

  • Browser sends GET request for a protected URL
  • Server sends 401 Response which means "Authorization Required"
  • Browser knows what it means and pops up a dialog box to the user with user/pass fields
  • When user submits, browser sends another GET request, but with Authorization header which contains base64 encoded username and password
  • Server checks, and if successful — sends back 200 success response with the content of requested page

In your before_filter you're simply telling Rails to perform all of the above song-and-dance when any controller action is accessed anywhere. Rails handles all the protocol communication described above for you.

In case of denied access, Rails sends back 403 Forbidden response, and browser has built-in way to show that.

To find out more: http://en.wikipedia.org/wiki/Basic_access_authentication

Upvotes: 1

Matchu
Matchu

Reputation: 85794

The before_filter method ensures that the private method authenticate is run before all requests.

authenticate_or_request_with_http_basic pops up the browser's "enter your username and password" box, and passes them into the block, as username and password, in this case.

If the block returns true (if the username and password match), the request proceeds to your more specific code. If the block returns false (the username and password don't match), the request is cut short, and an authentication failure page with the correct HTTP status code is returned. The browser may retry the request a few more times before showing the failure page.

Upvotes: 2

Related Questions