Skip to content

Instantly share code, notes, and snippets.

@ahmadshah
Last active July 29, 2016 10:43
Show Gist options
  • Select an option

  • Save ahmadshah/385603348a78c91a41c26e2c20f21185 to your computer and use it in GitHub Desktop.

Select an option

Save ahmadshah/385603348a78c91a41c26e2c20f21185 to your computer and use it in GitHub Desktop.
Access Control List
module Guard
class Authorize
attr_reader :user, :roles
def initialize(user)
build_user_roles(user)
end
def authorities(role)
raise StandardError, "User is not associated to #{role} role" unless self.is? role
@roles.fetch role
end
def is?(role)
@roles.has_key? role
end
def is_not?(role)
if self.is? role
false
else
true
end
end
def can?(authority)
@authorities_list.include? authority
end
def cannot?(authority)
if self.can? authority
false
else
true
end
end
private
def build_user_roles(user)
@user = user
@roles = Hash.new
@authorities_list = []
@user.roles.each do |role|
role_name = role.name.downcase.parameterize('_').to_sym
authorities = role.authorities.map &:to_sym
@roles[role_name] = authorities
@authorities_list << authorities
end
@authorities.flatten!
end
end
end
require 'rails_helper'
require 'guard/authorize'
RSpec.describe Guard::Authorize do
let(:user_roles) { { foobar: [:create, :read, :update, :destroy] } }
let(:user) { double('user') }
let(:roles) { double('roles') }
let(:authorize) { create_authorize }
def create_authorize
allow(user).to receive(:roles).and_return(roles)
allow(roles).to receive(:each).and_yield(role = double('role'))
allow(role).to receive(:name).and_return('Foobar')
allow(role).to receive(:authorities).and_return(['create', 'read', 'update', 'destroy'])
Guard::Authorize.new(user)
end
context '#user' do
it 'return user instance variable value' do
expect(authorize.user).to eq(user)
end
end
context '#roles' do
it 'return roles instance variable value' do
expect(authorize.roles).to eq(user_roles)
end
end
context '#is?' do
it 'return true' do
expect(authorize.is? :foobar).to eq(true)
end
it 'return false' do
expect(authorize.is? :bar).to eq(false)
end
end
context '#is_not?' do
it 'return true' do
expect(authorize.is_not? :bar).to eq(true)
end
it 'return false' do
expect(authorize.is_not? :foobar).to eq(false)
end
end
context '#authorities' do
it 'return available authorities' do
expect(authorize.authorities :foobar).to eq([:create, :read, :update, :destroy])
end
it 'raise exception' do
expect{authorize.authorities :foo}.to raise_exception(StandardError, 'User is not associated to foo role')
end
end
context '#can?' do
it 'return true' do
expect(authorize.can? :create).to eq(true)
end
it 'return false' do
expect(authorize.can? :bar).to eq(false)
end
end
context '#cannot?' do
it 'return true' do
expect(authorize.cannot? :bar).to eq(true)
end
it 'return false' do
expect(authorize.cannot? :update).to eq(false)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment