chaps-io / access-granted

Multi-role and whitelist based authorization gem for Rails (and not only Rails!)
MIT License
774 stars 41 forks source link

Allow passing custom exception message for authorize! #50

Closed lokeshdevnani closed 6 years ago

lokeshdevnani commented 6 years ago

Sometimes, there is a need for specifying a message along with the authorization of an action. This message is useful as it provides some feedback to the consumer of the action. In some cases, it also acts as a documentation which makes it clear as to why this authorization was introduced.

Usage

The message passed along with authorize! will be accessible on the exception object thrown if the authorization fails.

class PostsController
  def show
    @post = Post.find(params[:id])
    authorize! :read, @post, 'You do not have access to this post'
    render json: { post: @post }
  rescue AccessGranted::AccessDenied => e
    render json: { error: e.message }, status: :forbidden
  end
end

This PR allows authorize! method to optionally take a third argument specifying the custom exception message

jrochkind commented 6 years ago

I wonder, how could this be done supporting i18n too?

pokonski commented 6 years ago

Hey @lokeshdevnani, thanks for the contribution! This is a good addition :)

@jrochkind it looks like you already can pass anything as message, not necessarily a string. So you could pass a custom object/hash that has i18n key and additional options (for interpolation etc) and use that in the rescue_from block or a view to catch the exception and render message however you want.

This is because I don't really want to add any run-time dependencies, they instantly make any project much much harder to maintain in the long run.


@lokeshdevnani can you please also add an example usage for this in the README?

lokeshdevnani commented 6 years ago

Thanks @pokonski. Already added one example. Please let me know if you think more detailed description is required.

pokonski commented 6 years ago

Heh of course you did, I completely missed it :fearful: Thanks!

lokeshdevnani commented 6 years ago

@pokonski :+1: Thanks for the quick response