Security

How to secure your StimulusReflex app

GitHub stars GitHub forks Twitter follow

StimulusReflex leans on ActionCable for security, but here's a TLDR to get you going.

This should work with authentication solutions like Devise.

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :set_action_cable_identifier

  private

  def set_action_cable_identifier
    cookies.encrypted[:user_id] = current_user&.id
  end
end
module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      user_id = cookies.encrypted[:user_id]
      return reject_unauthorized_connection if user_id.nil?
      user = User.find_by(id: user_id)
      return reject_unauthorized_connection if user.nil?
      self.current_user = user
    end
  end
end
app/reflexes/example_reflex.rb
class ExampleReflex < StimulusReflex::Reflex
  delegate :current_user, to: :channel

  def do_suff
    current_user.first_name
  end
end

Last updated

Was this helpful?