Sha256: b15b1f894051f509180f3cd5f291c690bf8322cd53c9eba2b6ed53a9f43fbf36

Contents?: true

Size: 1.59 KB

Versions: 22

Compression:

Stored size: 1.59 KB

Contents

# Public: represents permissions of the current request user against
# the resource and resource class.
#
# Examples
#
#   class Post
#     include Garage::Authorizable
#
#     def build_permissions(perms, other)
#       perms.permits! :read
#       perms.permits! :write if owner == other
#     end
#
#     def self.build_permissions(perms, other, target)
#       if target[:user]
#         perms.permits! :read, :write if target[:user] == other
#       else
#         perms.permits! :read, :write
#       end
#     end
#   end
require "garage/permission"

module Garage
  class Permissions
    attr_accessor :user, :resource_class

    def initialize(user, resource_class, permissions = { read: :forbidden, write: :forbidden })
      @user = user
      @resource_class = resource_class
      @perms = permissions
    end

    def authorize!(action)
      exists?          or raise PermissionError.new(user, action, resource_class, :not_found)
      permits?(action) or raise PermissionError.new(user, action, resource_class, :forbidden)
    end

    def for(action)
      Permission.new(@user, action, @perms[action])
    end

    def deleted!
      @perms[:deleted] = true
    end

    def exists?
      !@perms[:deleted]
    end

    def permits!(*actions)
      actions.each do |action|
        @perms[action] = :ok
      end
    end

    def forbids!(*actions)
      actions.each do |action|
        @perms[action] = :forbidden
      end
    end

    def permits?(action)
      self.for(action).allowed?
    end

    def readable?
      permits? :read
    end

    def writable?
      permits? :write
    end
  end
end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
the_garage-2.8.2 lib/garage/permissions.rb
the_garage-2.8.1 lib/garage/permissions.rb
the_garage-2.8.0 lib/garage/permissions.rb
the_garage-2.7.0 lib/garage/permissions.rb
the_garage-2.6.1 lib/garage/permissions.rb
the_garage-2.6.0 lib/garage/permissions.rb
the_garage-2.5.0 lib/garage/permissions.rb
the_garage-2.4.4 lib/garage/permissions.rb
the_garage-2.4.3 lib/garage/permissions.rb
the_garage-2.4.2 lib/garage/permissions.rb
the_garage-2.4.1 lib/garage/permissions.rb
the_garage-2.4.0 lib/garage/permissions.rb
the_garage-2.3.3 lib/garage/permissions.rb
the_garage-2.3.2 lib/garage/permissions.rb
the_garage-2.3.1 lib/garage/permissions.rb
the_garage-2.3.0 lib/garage/permissions.rb
the_garage-2.2.0 lib/garage/permissions.rb
the_garage-2.1.0 lib/garage/permissions.rb
the_garage-2.0.3 lib/garage/permissions.rb
the_garage-2.0.2 lib/garage/permissions.rb