What we will use:
- CanCan - Authorization Gem for Ruby on Rails (https://github.com/ryanb/cancan)
- Response module (will be covered later)
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:
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
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