Commit 10c07226 authored by Nick Thomas's avatar Nick Thomas

Enable Warden for the Grape API

The practical effect of this commit is to make the API check the Rails session
cookie for authentication details. If the cookie is present and valid, it will
be used to authenticate.

The API now has several authentication options for users. They follow in this
order of precedence:

* Authentication token
* Personal access token
* OAuth2 Bearer token (Doorkeeper - application access)
* Rails session cookie
parent 5db3bc64
...@@ -12,13 +12,30 @@ module API ...@@ -12,13 +12,30 @@ module API
nil nil
end end
def private_token
params[PRIVATE_TOKEN_PARAM] || env[PRIVATE_TOKEN_HEADER]
end
def warden
env['warden']
end
# Check the Rails session for valid authentication details
def find_user_from_warden
warden ? warden.authenticate : nil
end
def find_user_by_private_token def find_user_by_private_token
token_string = (params[PRIVATE_TOKEN_PARAM] || env[PRIVATE_TOKEN_HEADER]).to_s token = private_token
User.find_by_authentication_token(token_string) || User.find_by_personal_access_token(token_string) return nil unless token.present?
User.find_by_authentication_token(token) || User.find_by_personal_access_token(token)
end end
def current_user def current_user
@current_user ||= (find_user_by_private_token || doorkeeper_guard) @current_user ||= find_user_by_private_token
@current_user ||= doorkeeper_guard
@current_user ||= find_user_from_warden
unless @current_user && Gitlab::UserAccess.new(@current_user).allowed? unless @current_user && Gitlab::UserAccess.new(@current_user).allowed?
return nil return nil
......
...@@ -36,11 +36,36 @@ describe API::Helpers, api: true do ...@@ -36,11 +36,36 @@ describe API::Helpers, api: true do
params.delete(API::Helpers::SUDO_PARAM) params.delete(API::Helpers::SUDO_PARAM)
end end
def warden_authenticate_returns(value)
warden = double("warden", authenticate: value)
env['warden'] = warden
end
def doorkeeper_guard_returns(value)
allow_any_instance_of(self.class).to receive(:doorkeeper_guard){ value }
end
def error!(message, status) def error!(message, status)
raise Exception raise Exception
end end
describe ".current_user" do describe ".current_user" do
subject { current_user }
describe "when authenticating via Warden" do
before { doorkeeper_guard_returns false }
context "fails" do
it { is_expected.to be_nil }
end
context "succeeds" do
before { warden_authenticate_returns user }
it { is_expected.to eq(user) }
end
end
describe "when authenticating using a user's private token" do describe "when authenticating using a user's private token" do
it "returns nil for an invalid token" do it "returns nil for an invalid token" do
env[API::Helpers::PRIVATE_TOKEN_HEADER] = 'invalid token' env[API::Helpers::PRIVATE_TOKEN_HEADER] = 'invalid token'
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment