Skip to content

Instantly share code, notes, and snippets.

@max-power
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save max-power/b0f08d3abffc532d676c to your computer and use it in GitHub Desktop.
Save max-power/b0f08d3abffc532d676c to your computer and use it in GitHub Desktop.
Super simple policy authentication.
Gem::Specification.new do |s|
s.name = 'policy-authorization'
s.version = '0.0.2'
s.platform = Gem::Platform::RUBY
s.author = 'Kevin Melchert'
s.email = 'kevin.melchert@gmail.com'
s.summary = 'Super simple policy authentication.'
s.description = 'Super simple policy authentication.'
s.files = ['authorization.rb']
s.test_file = 'authorization_helper_spec.rb'
s.require_path = '.'
end
module Authorization
Error = Class.new(StandardError)
Policy = Struct.new(:resource, :user)
module Helpers
private
def authorize!(user, action, resource)
raise Authorization::Error unless can?(user, action, resource)
end
def can?(user, action, resource)
policy(resource, user).public_send :"#{action}?"
end
def policy(resource, user)
Object.const_get("#{resource.class}Policy").new(resource, user)
end
end
end
# -*- encoding: utf-8 -*-
require 'rubygems'
require 'bundler/setup'
require 'minitest/autorun'
require 'minitest/spec'
require 'authorization'
User = Struct.new(:name)
Post = Struct.new(:user)
PostPolicy = Struct.new(:post, :user) do
def view? true; end
def delete? false; end
def own?
post.user == user
end
end
describe Authorization::Helpers do
before do
@user = User.new('Mr. Fox')
@post = Post.new(@user)
end
include Authorization::Helpers
describe 'can?' do
it 'should return true if user can access a resource' do
can?(@user, :view, @post).must_equal true
end
it 'should return false if user cannot access a resource' do
can?(@user, :delete, @post).must_equal false
end
end
describe 'authorize!' do
it 'should do nothing if user can access a resource' do
authorize!(@user, :view, @post).must_equal nil
end
it 'should raise error if user cannot access a resource' do
proc { authorize!(@user, :delete, @post) }.must_raise Authorization::Error
end
end
describe 'policy' do
it 'should return the policy instance' do
policy(@post, @user).must_be_instance_of PostPolicy
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment