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
nil
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
token_string = (params[PRIVATE_TOKEN_PARAM] || env[PRIVATE_TOKEN_HEADER]).to_s
User.find_by_authentication_token(token_string) || User.find_by_personal_access_token(token_string)
token = private_token
return nil unless token.present?
User.find_by_authentication_token(token) || User.find_by_personal_access_token(token)
end
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?
return nil
......
......@@ -36,11 +36,36 @@ describe API::Helpers, api: true do
params.delete(API::Helpers::SUDO_PARAM)
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)
raise Exception
end
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
it "returns nil for an invalid token" do
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