diff --git a/lib/auth/default_current_user_provider.rb b/lib/auth/default_current_user_provider.rb index 217132c4cf2..1eb90b22b7c 100644 --- a/lib/auth/default_current_user_provider.rb +++ b/lib/auth/default_current_user_provider.rb @@ -42,10 +42,12 @@ class Auth::DefaultCurrentUserProvider api_key = ApiKey.where(key: api_key_value).includes(:user).first if api_key.present? @env[API_KEY] = true + api_username = request["api_username"] if api_key.user.present? + raise Discourse::InvalidAccess.new if api_username && (api_key.user.username_lower != api_username.downcase) current_user = api_key.user - elsif api_username = request["api_username"] + elsif api_username current_user = User.where(username_lower: api_username.downcase).first end diff --git a/spec/controllers/application_controller_spec.rb b/spec/controllers/application_controller_spec.rb index 10ae983890a..4dbbcde1822 100644 --- a/spec/controllers/application_controller_spec.rb +++ b/spec/controllers/application_controller_spec.rb @@ -1,11 +1,6 @@ require 'spec_helper' describe 'api' do - before do - fake_key = SecureRandom.hex(32) - SiteSetting.stubs(:api_key).returns(fake_key) - end - describe PostsController do let(:user) do Fabricate(:user) @@ -22,11 +17,19 @@ describe 'api' do it 'allows users with api key to bookmark posts' do PostAction.expects(:act).with(user, post, PostActionType.types[:bookmark]).once put :bookmark, bookmarked: "true", post_id: post.id, api_key: api_key.key, format: :json + response.should be_success + end + + it 'raises an error with a user key that does not match an optionally specified username' do + PostAction.expects(:act).with(user, post, PostActionType.types[:bookmark]).never + put :bookmark, bookmarked: "true", post_id: post.id, api_key: api_key.key, api_username: 'made_up', format: :json + response.should_not be_success end it 'allows users with a master api key to bookmark posts' do PostAction.expects(:act).with(user, post, PostActionType.types[:bookmark]).once put :bookmark, bookmarked: "true", post_id: post.id, api_key: master_key.key, api_username: user.username, format: :json + response.should be_success end it 'disallows phonies to bookmark posts' do @@ -37,7 +40,6 @@ describe 'api' do end it 'disallows blank api' do - SiteSetting.stubs(:api_key).returns("") PostAction.expects(:act).with(user, post, PostActionType.types[:bookmark]).never lambda do put :bookmark, bookmarked: "true", post_id: post.id, api_key: "", api_username: user.username, format: :json