DEV Community

Panos Dalitsouris
Panos Dalitsouris

Posted on

2 1

Get the current user in ActionCable

An easy way to get the current user using devise-jwt

When you “login”, devise-jwt returns an Authorization header with a token

Bearer eyJhbGciOiJIUzI1NiJ9.eyJpZCI6Miwic3ViIjoiMiIsInNjcCI6InVzZXIiLCJhdWQiOm51bGwsImlhdCI6MTU3MDM4OTcyNiwiZXhwIjoxNTcwMzkzMzI2LCJqdGkiOiI1NGZmY2YyOC1iNGFhLTQ3NDMtYTU5My1iOWJkYmIzNDRiOTIifQ.hcBKHd9n4r4s9-pHyshDyVm9zHnjF33SXXTQyGZljEY
Enter fullscreen mode Exit fullscreen mode

You probably already know that.

According to the docs if you are using cookies you can do the following to get the current user

verified_user = User.find_by(id: cookies.encrypted[:user_id])
Enter fullscreen mode Exit fullscreen mode

In case you use devise-jwt you could use following inside your connection.rb to find_verified_user 🎊

module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
end
protected
# @return [User]
def find_verified_user
unless request.headers.key?('Authorization') && request.headers['Authorization'].split(' ').size > 1
reject_unauthorized_connection
end
token = request.headers['Authorization'].split(' ')[1]
jwt = JWT.decode(token, Rails.application.credentials.jwt_key, true, algorithm: 'HS256', verify_jti: true)[0]
if (user = User.find(jwt['id']))
user
else
reject_unauthorized_connection
end
end
end
end
view raw connection.rb hosted with ❤ by GitHub

Top comments (2)

Collapse
 
dbaynes profile image
David Baynes

THANK YOU!

Collapse
 
panoscodes profile image
Panos Dalitsouris • Edited

You're welcome