Module: Merb::AuthenticationMixin

Included in:
Controller
Defined in:
lib/merb-core/controller/mixins/authentication.rb

Defined Under Namespace

Classes: BasicAuthentication

Instance Method Summary collapse

Instance Method Details

#basic_authentication(realm = "Application", &authenticator) ⇒ Object

Attempts to authenticate the user via HTTP Basic authentication. Takes a block with the username and password, if the block yields false the authentication is not accepted and :halt is thrown.

If no block is passed, basic_authentication, the request and authenticate methods can be chained. These can be used to independently request authentication or confirm it, if more control is desired.

Parameters

realm<~to_s>

The realm to authenticate against. Defaults to ‘Application’.

&authenticator

A block to check if the authentication is valid.

Returns

Merb::AuthenticationMixin::BasicAuthentication

Examples

class Application < Merb::Controller

  before :authenticate

  protected

  def authenticate
    basic_authentication("My App") do |username, password|
      password == "secret"
    end
  end

end

class Application < Merb::Controller

  before :authenticate

  def authenticate
    user = basic_authentication.authenticate do |username, password|
      User.authenticate(username, password)
    end

    if user
      @current_user = user
    else
      basic_authentication.request
    end
  end

end

If you need to request basic authentication inside an action you need to use the request! method.

Example

class Sessions < Application

  def new
    case content_type
    when :html
      render

    else
     user = basic_authentication.authenticate do |username, password|
       User.authenticate(username, password)
     end

     if user
       display(user)
     else
       basic_authentication.request
     end
    end
  end

end

:api: public



79
80
81
# File 'lib/merb-core/controller/mixins/authentication.rb', line 79

def basic_authentication(realm = "Application", &authenticator)
  @_basic_authentication ||= BasicAuthentication.new(self, realm, &authenticator)
end