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
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])
In case you use devise-jwt you could use following inside your connection.rb to find_verified_user 🎊
This file contains 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
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 |
Top comments (2)
THANK YOU!
You're welcome