Skip to content

Commit

Permalink
Merge f80e20f into 2712250
Browse files Browse the repository at this point in the history
  • Loading branch information
cqr committed Jun 15, 2015
2 parents 2712250 + f80e20f commit d788df2
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 2 deletions.
34 changes: 32 additions & 2 deletions lib/rack/prx_auth/token_data.rb
Original file line number Diff line number Diff line change
@@ -1,15 +1,45 @@
module Rack
class PrxAuth
class TokenData
attr_reader :attributes, :authorized_resources, :scopes

def initialize(attrs = {})
@attributes = attrs
if attrs['aur']
@authorized_resources = unpack_aur(attrs['aur']).freeze
else
@authorized_resources = {}.freeze
end
if attrs['scope']
@scopes = attrs['scope'].split(' ').freeze
else
@scopes = [].freeze
end
end

attr_reader :attributes

def user_id
@attributes['sub']
end

def authorized?(resource, scope=nil)
if auth = authorized_resources[resource.to_s]
scope.nil? || (scopes + auth.split(' ')).include?(scope.to_s)
end
end

private

def unpack_aur(aur)
aur.clone.tap do |result|
unless result['$'].nil?
result.delete('$').each do |role, resources|
resources.each do |res|
result[res.to_s] = role
end
end
end
end
end
end
end
end
52 changes: 52 additions & 0 deletions test/rack/prx_auth/token_data_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
require 'test_helper'

describe Rack::PrxAuth::TokenData do
it 'pulls user_id from sub' do
token = Rack::PrxAuth::TokenData.new('sub' => 123)
token.user_id.must_equal 123
end

it 'pulls authorized_resources from aur' do
token = Rack::PrxAuth::TokenData.new('aur' => {'123' => 'admin'})
token.authorized_resources['123'].must_equal 'admin'
end

it 'unpacks compressed aur into authorized_resources' do
token = Rack::PrxAuth::TokenData.new('aur' => {
'123' => 'member',
'$' => {
'admin' => [456, 789, 1011]
}
})
token.authorized_resources['$'].must_be_nil
token.authorized_resources['789'].must_equal 'admin'
token.authorized_resources['123'].must_equal 'member'
end

describe '#authorized?' do
let(:token) { Rack::PrxAuth::TokenData.new('aur' => aur, 'scope' => scope) }
let(:scope) { 'read write purchase sell delete' }
let(:aur) { {'123' => 'admin', '456' => 'member' } }

it 'is authorized for scope in aur' do
assert token.authorized?(123, 'admin')
end

it 'is authorized for scope in scopes' do
assert token.authorized?(456, :delete)
end

it 'is not authorized across aur limits' do
assert !token.authorized?(123, :member)
end

it 'does not require a scope' do
assert token.authorized?(123)
end

it 'is unauthorized if it hasnt seen the resource' do
assert !token.authorized?(789)
end

end
end

0 comments on commit d788df2

Please sign in to comment.