Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if the user is authorized (HTTP Basic Authentication, Rails 3.0.9)

I'm using HTTP Basic Authentication with Rails 3.0.9 and I need to check if the user is authorized to show some elements in my html.erb files. How can I do that?

like image 850
Vitaly Avatar asked Oct 03 '11 15:10

Vitaly


1 Answers

Vitaly's approach looks like a good solution, but has a serious bug that grants admin access to anyone who attempts to login, even if their credentials are incorrect. (Posting this as an answer in hopes that it gets upvoted and people don't blindly accept the "correct" answer with its security flaw)

First, a couple functional tests (on actions that require authentication):

test "admin is set with correct credentials" do
  @request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials("user", "pass")
  get :index
  assert_response 200
  assert_equal true, session[:admin]
end

test "admin isn't set with incorrect credentials" do
  @request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials("user", "incorrect")
  get :index
  assert_response 401
  assert_not_equal true, session[:admin]
end

If you run this with Vitaly's code, the second test fails because session[:admin] is being set to true, even though the password is incorrect.

Here's my code to properly set session[:admin] and make both tests pass:

private
def authenticate
  authenticate_or_request_with_http_basic do |user_name, password|
    session[:admin] = (user_name == "name" && password == "pass")
  end
end
like image 107
Coomer Avatar answered Sep 19 '22 10:09

Coomer