Vitaly's approach looks like a good solution, but it has a serious error that gives the administrator access to everyone who is trying to log in, even if their credentials are incorrect. (Conducting this as an answer in the hope that he will receive support, and people do not blindly accept the โrightโ answer with its lack of security)
First, a couple of functional tests (for 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 will fail because session[:admin]
set to true, even if the password is incorrect.
Here is my code to set session[:admin]
correctly and run both tests:
private def authenticate authenticate_or_request_with_http_basic do |user_name, password| session[:admin] = (user_name == "name" && password == "pass") end end
source share