Search code examples
ruby-on-railsrubyauthorizationpundit

Rails 6 - Pundit "policy wrapper"


I am a little stuck with Pundit: It feels that the solution should be easy - but I am not getting it. Actually I have a bunch of models which are all dependent on one main model. My main model is a script. The script has many roles, many scenes, many costumes, etc. Additionally it has some joined connections like scene.roles. I simply want to authorize the user who created the script to do everything (adding roles, deleting scenes, just everything that is in the scope of her own script) and everybody else to do (and see) nothing. Do I need to create a policy for every model or can I just (re-)use somehow one "script policy"?

How would an authorization look like in a dependent controller (i.e. 'index' in roles or 'new' in scenes)?

The authentication is handled by Device. A user must be logged in to see or do anything. This is my first post on stack overflow, happy to join the community:-)


Solution

  • When calling the authorize method in your controller, you can specify the policy class:

    authorize @model, policy_class: ScriptPolicy
    

    I find that this solution generates less boilerplate files.

    To authorize a scope:

    scenes = policy_scope(Scene, policy_scope_class: ScriptPolicy::Scope)

    By the way, this is all covered in pundit's README: https://github.com/varvet/pundit