Reputation: 1357
I am upgrading a Rails app to use websocket via Action Cable. For logging purposes, I need to get the client's IP address and the user agent who sends the socket message.
In the speak
method of MyChannel
class (app/channels/my_channel.rb
), I cannot access the session or the request.
Do you have any idea on how I can get user_agent
and the client IP address in this speak
method?
Upvotes: 1
Views: 1469
Reputation: 2656
To use the remote_ip
helper you can do this in your Channel:
ActionDispatch::Request.new(connection.env).remote_ip
Upvotes: 2
Reputation: 3183
ActionCable::Connection::Base
contains all information about the current connection environment (HTTP headers, rack process, etc), and you can access it via its env
attribute reader.
For example, here is how I get the User-Agent HTTP header which was used while establishing WebSocket connection:
user_agent = connection.env["HTTP_USER_AGENT"]
Note that I run this code from ApplicationCable::Channel
instance, where connection instance is available via connection
attribute
I couldn't find any documentation about it, but I believe it's safe since env
attribute is made publicly available (https://api.rubyonrails.org/v5.1.6/classes/ActionCable/Connection/Base.html#method-i-request). You can get the full list of the keys that this hash contains by running connection.env.keys
in console (when connection
instance is available, obviously).
Upvotes: 0
Reputation: 44
You may get this info from request in Connection object to which Channel belongs.
Upvotes: 0