1

I am trying to implement notification using the action cable in Rails 5.

After reading the tutorial for the Action cable, which work on the session & Cookies based Authentication to receive the notification for the current logged in user.

module ApplicationCable
  class Connection < ActionCable::Connection::Base
   identified_by :current_user

  def connect
    self.current_user = find_verified_user
    logger.add_tags 'ActionCable', current_user.username
  end

  protected

  def find_verified_user
    if verified_user = env['warden'].session(:user)
      verified_user
    else
      reject_unauthorized_connection
    end
  end
end

In the find_verified_user , I am not able to get the user object from the session.

Can anyone help me, to authenticate the user in action cable.

Hard Developer
  • 309
  • 1
  • 3
  • 12
  • Don't use the session for ActionCable, see this answer: https://stackoverflow.com/questions/32025897/authenticating-using-actioncable#answer-32207192 – murb Oct 06 '16 at 10:54

2 Answers2

1

If your session_store (config/initializers/session_store.rb) uses :cookie_store, then you can read the session from encrypted cookies:

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      if user = User.find_by(id: session[:user_id])
        self.current_user = user
      else
        reject_unauthorized_connection
      end
    end

    private

      def session
        key = Rails.application.config.session_options.fetch(:key)
        cookies.encrypted[key]&.symbolize_keys || {}
      end
  end
end
caiguanhao
  • 444
  • 1
  • 4
  • 12
0

Because you have not access to session, you must use cookie:

1) Go to your_app/config/initializers/session_store.rb and paste this code:

Rails.application.config.session_store :cookie_store, key: 'your_super_secret_code'

2) After anywhere you can get user id:

 key = Rails.application.config.session_options.fetch(:key)
 cookies.encrypted[key]&.symbolize_keys || {}

 User.find(cookies["warden.user.user.key"][0][0])

Example for session: How can I find a devise user by it's session id?

Community
  • 1
  • 1
artamonovdev
  • 2,260
  • 1
  • 29
  • 33