Skip to content

Instantly share code, notes, and snippets.

@dmytrotkk
Created November 17, 2017 13:44
Show Gist options
  • Save dmytrotkk/b08cabc603e66b86cf894a4f19e76e18 to your computer and use it in GitHub Desktop.
Save dmytrotkk/b08cabc603e66b86cf894a4f19e76e18 to your computer and use it in GitHub Desktop.
Checking permissions in Rails

Checking permissions in Rails

What we will use:

Let's just start with an example

Let's suppose that you have a method do_something, which could be preformed only by user who's matching permissions view_payment_info, if options[:some_key] isn't blank and payment with field something == options[:some_key] exists.

In that case it would be great to move all requires checks in the separated method, which will trigger actual do_something only if all conditions are met.

So, here we go:

service.rb
def do_something_by_user(user, options)

  # check inputs 
  return Response.set_error("bad_input", "opt_is_blank", "some_key is blank") if options[:some_key].blank?

  # check object presence
  payment = Payment.get_by_something(options[:some_key])
  return Response.set_error("bad_input", "payment_not_found", "Payment not found") if payment.nil?

  # check permissions
  unless user.can? :view_payment_info, payment
    return Response.res_error("forbidden", "view_node_error", 'No permissions to view this node')
  end

  # and only after all checks:
  do_something(options)
end


def do_something(options)
  # do work
end
myability.rb
module Core
  class Myability
    include CanCan::Ability

    def initialize(user)
      can :view_payment_info, Payment do |payment|
        user.access_id == payment.security_group.access_id
      end
    end
    
  end
end

CanCan setup covered here: https://github.com/ryanb/cancan/wiki/Defining-Abilities

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment