varvet / pundit

Minimal authorization through OO design and pure Ruby classes
MIT License
8.22k stars 625 forks source link

Support authorization error flash messages when using turbo frames and streams? #751

Closed nickjj closed 1 year ago

nickjj commented 1 year ago

In a perfect world I would like to do something like this:

  def user_not_authorized
    respond_to do |format|
      format.html do
        flash[:alert] = "You are not authorized to perform this action."
        redirect_back(fallback_location: root_path)
      end
      format.turbo_stream do
        flash.now[:alert] = "You are not authorized to perform this action."
        turbo_stream.prepend "flash", partial: "shared/flash"
      end
    end
  end

And then if someone tried to perform an action they can't do, they would get a flash message on their current page / frame without a redirect.

With the above code using Pundit v2.2.0, on authorization failure no alert message gets shown and no redirect happens. The request gets executed as the html format which I verified by printing a message to the terminal in that block.

As is Pundit doesn’t send the request as a turbo_stream so that format never gets a chance to execute. Is there a current workaround or official plans to support Hotwire Turbo Frames and Steams given it's a Rails 7 default?

Thanks!

wafcio commented 1 year ago

I think, it isn't connected with Pundit because of no view layer in this gem and the whole view part is on the application side.

nickjj commented 1 year ago

@wafcio there's documentation in https://github.com/varvet/pundit#rescuing-a-denied-authorization-in-rails referencing code that doesn't work in Rails when using Turbo. It could be useful to have an up to date example.

wafcio commented 1 year ago

@nickjj so it is only about adapting example code. It doesn't require any changes in gem.

rmaspero commented 1 year ago

Looks like in part the issue is that the format isn't set by the time the rescue from is called as per this SO.

laptopmutia commented 1 year ago

I think this issue is better of as an discussion or stackoverflow question its about how to not should do

pundit is just plain old ruby

currently turbo doesn't support rendering notice on redirect https://github.com/hotwired/turbo/issues/897

the best think you could do is implement 403 and do a full page reload https://turbo.hotwired.dev/handbook/drive#ensuring-specific-pages-trigger-a-full-reload this is the same problem as session timeout I think

and also the example in readme is taken from this I think

https://guides.rubyonrails.org/action_controller_overview.html#rescue-from

as for me I think currently my plan is just do full page render from public folder liek when rails handle 404 or 500

Burgestrand commented 1 year ago

I feel this is outside the scope of what Pundit wants to tell you to do. Moving this to a discussion instead.