Module: Authorization::AuthorizationInModel

Defined in:
lib/declarative_authorization_padrino/in_model.rb

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object

:nodoc:



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/declarative_authorization_padrino/in_model.rb', line 4

def self.included(base) # :nodoc:
  base.module_eval do
    # Activates model security for the current model.  Then, CRUD operations
    # are checked against the authorization of the current user.  The
    # privileges are :+create+, :+read+, :+update+ and :+delete+ in the
    # context of the model.  By default, :+read+ is not checked because of
    # performance impacts, especially with large result sets.
    # 
    #   class User < ActiveRecord::Base
    #     using_access_control
    #   end
    #   
    # If an operation is not permitted, a Authorization::AuthorizationError
    # is raised.
    #
    # To activate model security on all models, call using_access_control
    # on ActiveRecord::Base
    #   ActiveRecord::Base.using_access_control
    # 
    # Available options
    # [:+context+] Specify context different from the models table name.
    # [:+include_read+] Also check for :+read+ privilege after find.
    #
    def self.using_access_control (options = {})
      options = {
        :context => nil,
        :include_read => false
      }.merge(options)

      class_eval do
        [:create, :update, [:destroy, :delete]].each do |action, privilege|
          send(:"before_#{action}") do |object|
            Authorization::Engine.instance.permit!(privilege || action,
              :object => object, :context => options[:context])
          end
        end
        
        if options[:include_read]
          # after_find is only called if after_find is implemented
          after_find do |object|
            Authorization::Engine.instance.permit!(:read, :object => object,
              :context => options[:context])
          end
        end

        def self.using_access_control?
          true
        end
      end
    end
  end
end