Diego says:

I’ve duplicated the code a little, I do think that there is a better way of doing this but my solution was to add some extra logic in the authorize method of the Application Controller.

I now looks like the following

 def authorize
        if User.count.zero?
          redirect_to new_user_path unless session[:new_user]
          return
        end

        unless User.find_by_id(session[:user_id])
          if request.format == Mime::HTML
            redirect_to login_url, notice: "Please log in" 
          elsif
            if user = authenticate_with_http_basic do |u, p|
                  finded_user = User.find_by_name(u)
                  finded_user.authenticate(p) if finded_user
              end
              session[:user_id] = user.id
            elsif
              render :status => 403, :text => "login failed" and return
            end
          end
        end
      end

I really wanted to redirect to SessionController to do the password check but I couldn’t figure it out how to do it.

Anonymous says:

Taken from http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic.html – Simple Digest example

In products_controller.rb:

class ProductsController < ApplicationController
  skip_before_filter :authorize, :only => [:who_bought]
  before_filter :authorize_digest, :only => [:who_bought]
  ...

In application_controller.rb:

require 'digest/md5'
class ApplicationController < ActionController::Base
  REALM = "SuperSecret" 
  USERS = { "test1" => "1234", #plain text password
            "test2" => Digest::MD5.hexdigest(["test2", REALM, "1234"].join(":")) }  #ha1 digest password

...

def authorize_digest
  authenticate_or_request_with_http_digest(REALM) do |username|
    USERS[username]
  end
end  

Then try http://localhost:3000/products/1/who_bought.atom using the credentials test1/1234 or test2/1234.

Pierre says Alike Diego’s solution.

http://localhost:3000/products/2/who_bought.xml will ask for the http password, other pages redirect to the login page.


def authorize
  unless request.format == Mime::HTML
    authenticate_or_request_with_http_basic do |n, p|
      user = User.find_by_name(n)
      if user and user.authenticate(p)
        session[:user_id] = user.id
      end
    end
  else
    return if User.count.zero?

    unless User.find_by_id(session[:user_id])
      redirect_to login_url, notice: "Please log in" 
    end
  end
end