We've moved discussions to Discord

Current user in broadcasted turbo stream.

Zmago Devetak
When I'm using current_user or current_account with turbo stream it returns nil. Is there a easy solution to overcome this? 

*** Devise::MissingWarden Exception: Devise could not find the `Warden::Proxy` instance on your request environment.
Make sure that your application is loading Devise and Warden as expected and that the `Warden::Manager` middleware is present in your middleware stack.
If you are seeing this on one of your tests, ensure that your tests are either executing the Rails middleware stack or that your tests are using the `Devise::Test::ControllerHelpers` module to inject the `request.env['warden']` object for you.


eg: 
<%= turbo_frame_tag task do %>
  <div class="flex justify-between mb-4 px-3" id="<%= dom_id(task) %>">
    <h1 class="h3">
      <%= link_to t('.project_name', name: project.name), project_path(project) %> > <%= medium.name %>
    </h1>
    <div class="mr-2">
      <% if policy(task).edit? %>
        <%= link_to edit_project_task_path(project, task), class: "btn btn-small btn-primary", title: "Edit" do %>
          <%= fa_icon "pencil-alt", weight: "fas" %>
        <% end %>
      <% end %>
      <% if policy(task).destroy? %>
        <%= link_to [project, task], title: t("delete"), class: "btn btn-small btn-danger", method: :delete, data: { confirm: t("are_you_sure") } do %>
          <%= fa_icon "trash-alt" %>
        <% end %>
      <% end %>
    </div>
  </div>
<% end %>

on the first load the policy is resolved, but when the delayed worked process the broadcast the policy which relies on current_user/account don't work properly. Is it possible to set the current user to the broadcast event?
Scott Harvey
I hit up against this same issue and I found a couple of posts that helped me solve it.

https://discuss.hotwire.dev/t/authentication-and-devise-with-broadcasts/1752/2

https://blog.cloud66.com/making-hotwire-and-devise-play-nicely-with-viewcomponents/

Basically you can't access Current inside a template that is rendered as part of a turbo stream.

Instead you need to update your template to pass in the current_user or current_account

Then you update your model to manually set those values when rendering the partial to the turbo stream.

So in my model I originally had

broadcasts_to :lesson

Which I changed to this:

after_create_commit :broadcast_create_to_lesson

def broadcast_create_to_lesson
  user = Current.account.account_users.find_by(user: Current.user)
  return nil unless user

  broadcast_append_to(lesson, locals: { user: user, lesson_message: self })
end

You would also need to add an after_update_commit and an after_destroy_commit as needed.

Hope that helps!
Zmago Devetak
hey! Yes it helps, thank you!
Notifications
You’re not receiving notifications from this thread.