Multiple connections in ActionCable
Asked Answered
L

1

14

I have two devise authentication models in my app and want to create a chat amongst them. Can someone help me write the connection for the users? Below is what I have. I wanted to check if I can have two connections reject the connections for different users based on their individual logins. Any help is appreciated.

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

    def connect
      self.current_user = find_verified_user
      self.current_supplier = find_verified_supplier
    end

    private
      def find_verified_user
        if current_user = env['warden'].user('user')
          current_user
        end
      end

      def find_verified_supplier
        if current_supplier = env['warden'].user('supplier')
          current_supplier
        else
          reject_unauthorized_connection
        end
      end
  end
end
Lodestone answered 16/1, 2017 at 9:2 Comment(0)
T
5

Adapting a bit from this tutorial:

# app/channels/application_cable/connection.rb

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

    def connect
      find_verified
    end

    protected

    def find_verified
      setup_user     if verified_user
      setup_supplier if verified_supplier

      reject_unauthorized_connection unless [current_supplier, current_user].any?
    end

    def verified_user
      cookies.signed['user.expires_at'].present? &&
        cookies.signed['user.expires_at'] > Time.zone.now
    end

    def verified_supplier
      cookies.signed['supplier.expires_at'].present? &&
        cookies.signed['supplier.expires_at'] > Time.zone.now
    end

    def setup_supplier
      self.current_supplier = Supplier.find_by(id: cookies.signed['supplier.id'])
      logger.add_tags 'ActionCable', "#{current_supplier.model_name.name} #{current_supplier.id}"
    end

    def setup_user
      self.current_user = User.find_by(id: cookies.signed['user.id'])
      logger.add_tags 'ActionCable', "#{current_user.model_name.name} #{current_user.id}"
    end
  end
end

And:

# config/initializers/warden_hooks.rb

Warden::Manager.after_set_user do |user, auth, opts|
  scope = opts[:scope]
  auth.cookies.signed["#{scope}.id"] = user.id
  auth.cookies.signed["#{scope}.expires_at"] = 30.minutes.from_now
end

Warden::Manager.before_logout do |_user, auth, opts|
  scope = opts[:scope]
  auth.cookies.signed["#{scope}.id"] = nil
  auth.cookies.signed["#{scope}.expires_at"] = nil
end
Teeny answered 16/3, 2018 at 4:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.