I develop a Ruby on Rails 5.1 application using ActionCable. User authentification via Devise works fine for several channels. Now, I want to add a second type of channels which does not require any user authentification. More precisely, I would like to enable anonymous website visitors to chat with support staff.
My current implementation of ApplicationCable::Connection
for authenticated users looks like this:
# app/channels/application_cable/connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
end
protected
def find_verified_user
user = User.find_by(id: cookies.signed['user.id'])
return user if user
fail 'User needs to be authenticated.'
end
end
end
Anonymous users will be identified by some random UUID (SecureRandom.urlsafe_base64
).
Question:
How do I best add this new type of channels? Could I add a boolean flag require_authentification
somewhere, override it in my inherited channel class for anonymous communication, and switch the identification method in Connection
depending on this attribute? Or would I rather have to implement a completely new module, say AnonymousApplicationCable
?
subscribed
method. It works, but it's not ideal. – Condorcet