Last active
June 27, 2019 11:20
-
-
Save ismarsantos/fe67a3d96a6a66e3cbf58277391ad243 to your computer and use it in GitHub Desktop.
ActionCable User Identified
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://github.com/rails/rails/issues/30917#issuecomment-337895075 | |
# Common connection class | |
# 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 | |
return User.find_by(id: cookies.signed['user.id']) | |
end | |
end | |
end | |
# Channel for authenticated user | |
# app/channels/user_notification_channel.rb | |
class UserNotificationChannel < ApplicationCable::Channel | |
def subscribed | |
reject and return if current_user.blank? | |
stream_for current_user | |
end | |
def unsubscribed | |
end | |
end | |
# Channel for anonymous user | |
# app/channels/chat_channel.rb | |
class ChatChannel < ApplicationCable::Channel | |
def subscribed | |
@connection_token = SecureRandom.hex(36) | |
stream_from "chat_channel_#{@connection_token}" | |
end | |
def unsubscribed | |
end | |
end | |
# It works, but it's probably not the best solution. Moving the user identification to the UserNotificationChannel is not possible due to the absence of cookies in ApplicationCable::Channel. | |
# Any hint for a cleaner and more performant pattern is much appreciated. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment