Sha256: 73736d097d5e8fd313c929351ca5780feac82a3e0c152e9d9abe8bd62ca6759a

Contents?: true

Size: 1.09 KB

Versions: 4

Compression:

Stored size: 1.09 KB

Contents

module AccessGranted
  module Policy
    attr_accessor :roles

    def initialize(user)
      @user          = user
      @roles         = []
      configure
    end

    def configure
    end

    def role(name, conditions_or_klass = nil, conditions = nil, &block)
      name = name.to_sym
      if roles.select {|r| r.name == name }.any?
        raise DuplicateRole, "Role '#{name}' already defined"
      end
      r = if conditions_or_klass.is_a?(Class) && conditions_or_klass <= AccessGranted::Role
        conditions_or_klass.new(name, conditions, @user, block)
      else
        Role.new(name, conditions_or_klass, @user, block)
      end
      roles << r
      r
    end

    def can?(action, subject = nil)
      roles.each do |role|
        next unless role.applies_to?(@user)
        permission = role.find_permission(action, subject)
        return permission.granted if permission
      end
      false
    end

    def cannot?(*args)
      !can?(*args)
    end

    def authorize!(action, subject)
      if cannot?(action, subject)
        raise AccessDenied
      end
      subject
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
access-granted-1.0.4 lib/access-granted/policy.rb
access-granted-1.0.3 lib/access-granted/policy.rb
access-granted-1.0.2 lib/access-granted/policy.rb
access-granted-1.0.1 lib/access-granted/policy.rb