before_filter :authenticate
# Basic authentication:
def authenticate
authenticate_or_request_with_http_basic { |u, p|
u == "root" && p == "alpine"
}
end
# ...or digest (hashed) authentication:
# uses the ha1 hash (username:realm:password)
def authenticate_by_digest
realm = "Secret3000"
users = {
"rsc" => Digest::MD5.hexdigest("rsc:#{realm}:passwordhere")
}
authenticate_or_request_with_http_digest(realm) { |user|
users[user]
}
end
# For integration tests
def test_access
auth = ActionController::HttpAuthentication::Basic.encode_credentials(user, pass)
get "/notes/1.xml", nil, 'HTTP_AUTHORIZATION' => auth
end
# Token auth
is_logged_in = authenticate_with_http_token do |token, options|
token == our_secret_token
end
request_http_token_authentication unless is_logged_in
Filters
# Filter with callbacks
before_filter :authenticate
before_filter :authenticate, except: [:login]
before_filter :authenticate, only: [:login]
def authenticate
redirect_to login_url unless controller.logged_in?
end
# Filter with inline
before_filter do |controller|
redirect_to login_url unless controller.logged_in?
end
# Filter with external classes
before_filter LoginFilter
class LoginFilter
def self.filter(controller) ...; end
end
# Filter exceptions
skip_before_filter :require_login, only: [:new, :create]
# Before/after filters
around_filter :wrap_in_transaction
def wrap_in_transaction(&blk)
ActiveRecord::Base.transaction { yield }
end
default_url_options
# The options parameter is the hash passed in to 'url_for'
def default_url_options(options)
{:locale => I18n.locale}
end
respond_to
respond_to do |format|
format.html
format.xml { render xml: @users }
format.json { render json: @users }
format.js # Will be executed by the browser
end
Special hashes
session[:user_id] = nil
flash[:notice] = "Hello" # Gets flushed on next request
flash.keep # Persist flash values
flash.now[:error] = "Boo" # Available on the same request
cookies[:hello] = "Hi"
params[:page]
# params is a combination of:
query_parameters
path_parameters
request_parameters
Top comments (0)