Verified Commit 020e0444 authored by James Edwards-Jones's avatar James Edwards-Jones Committed by Paul Slaughter

PersonalAccessToken methods to lookup project restrictions

parent 94214896
......@@ -34,6 +34,14 @@ class PersonalAccessToken < ActiveRecord::Base
!revoked? && !expired?
end
def restricted_by_resource?
token_resources.exists?
end
def allows_resource?(resource)
!restricted_by_resource? || token_resources.allowing_resource(resource).present?
end
def self.redis_getdel(user_id)
Gitlab::Redis::SharedState.with do |redis|
token = redis.get(redis_shared_state_key(user_id))
......
......@@ -4,4 +4,8 @@ class TokenResource < ActiveRecord::Base
validates :personal_access_token, presence: true
validates :project, presence: true
def self.allowing_resource(resource)
where(project: resource)
end
end
......@@ -133,4 +133,39 @@ describe PersonalAccessToken do
expect(personal_access_token.errors[:scopes].first).to eq "can only contain available scopes"
end
end
describe "restricted_by_resource?" do
it "is true when the token is scoped to specific projects" do
token = create(:personal_access_token, projects: [create(:project)])
expect(token).to be_restricted_by_resource
end
it "is false when no projects are linked" do
expect(described_class.new).not_to be_restricted_by_resource
expect(create(:personal_access_token)).not_to be_restricted_by_resource
end
end
describe "allows_resource?" do
it "is true when the token isn't restricted by resource" do
subject = create(:personal_access_token)
expect(subject.allows_resource?(create(:project))).to eq true
end
context "when restricted to a project" do
let(:allowed_project) { create(:project) }
subject { create(:personal_access_token, projects: [allowed_project]) }
it "is true for projects the token grants access to" do
expect(subject.allows_resource?(allowed_project)).to eq true
end
it "is false for projects to which access isn't allowed" do
expect(subject.allows_resource?(create(:project))).to eq false
end
end
end
end
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