module Authorizable::Controller

Private Class Methods

alias_action(action) click to toggle source
# File lib/authorizable/controller.rb, line 118
def self.alias_action(action)
  if action == :update
    action = :edit
  elsif action == :edit
    action = :update
  elsif action == :create
    action = :new
  elsif action == :new
    action = :create
  end

  action
end
parameters_are_valid?(config) click to toggle source

@see @authorizable for options @return [Boolean]

# File lib/authorizable/controller.rb, line 134
def self.parameters_are_valid?(config)
  config.each do |action, settings|
    if !settings[:target]
      # permission is required
      if !settings[:permission]
        raise ArgumentError.new(I18n.t('authorizable.permission_required'))
      end
    end

    # redirect_path is always required
    redirect_path = settings[:redirect_path]
    if !redirect_path
      raise ArgumentError.new(I18n.t('authorizable.redirect_path_required'))
    else
      if !redirect_path.is_a?(Proc)
        raise ArgumentError.new(I18n.t("authorizable.redirect_path_must_be_proc"))
      end
    end
  end
end

Private Instance Methods

authorizable_authorized?() click to toggle source
# File lib/authorizable/controller.rb, line 57
def authorizable_authorized?
  result = false
  action = params[:action].to_sym

  if !self.class.authorizable_config[action]
    action = Authorizable::Controller.alias_action(action)
  end

  settings_for_action = self.class.authorizable_config[action]

  return true unless settings_for_action.present?

  defaults = {
    user: current_user,
    permission: "can_#{action.to_s}?",
    message: I18n.t('authorizable.not_authorized'),
    flash_type: :alert
  }

  options = defaults.merge(settings_for_action)

  # run permission
  if options[:target]
    object = instance_variable_get("@#{options[:target]}")
    result = options[:user].send(options[:permission], object)
  else
    result = options[:user].send(options[:permission])
  end

  # redirect
  unless result
    authorizable_respond_with(
      options[:flash_type],
      options[:message],
      options[:redirect_path]
    )

    # halt
    return false
  end

  # proceed with execution
  true
end
authorizable_respond_with(flash_type, message, path) click to toggle source
# File lib/authorizable/controller.rb, line 103
def authorizable_respond_with(flash_type, message, path)
  flash[flash_type] = message

  respond_to do |format|
    format.html{
      path = self.instance_eval(&path)
      redirect_to path
    }
    format.json{
      render json: {}, status: 401
    }
  end

end