Jason Spick
Jason Spick

Reputation: 6098

How do I send user specific data with socket.io and laravel?

I am not sure how to word this question right, but here I go. I have laravel, angular, node w/socket.io and I am also using JWT for authentication. My end goal is to be able to send real time update notifications to specific users. For the life of me, I cannot seem to get how the workflow would be.

My initial though was to send the jwt within the handshake and then use then in node to do http requests to get data, and then return said data. In another words, when a specific event is fired, node will already have the token, send request to laravel for specific information.

Can someone please explain to me how sending user specific data via socket.io in this architecture?

Upvotes: 0

Views: 1615

Answers (1)

Jason Spick
Jason Spick

Reputation: 6098

I found this great article : https://www.ukietech.com/blog/programming/step-by-step-instruction-of-setting-up-real-time-secure-broadcasting-with-laravel-5-1-socket-io-and-redis/

This set me on the right track.

First I need to pass in my JWT into the socket:

var socket = io('http://192.168.10.10:3000', {query: "Authorization="+$rootScope.$storage.satellizer_token});

Next I actually verify the token.. again. I know this may be overkill, but I want to know that what hits the socket is legit.

io.use(function(socket, next){
if (socket.handshake.query.Authorization) {

    var config = {
        url:'http://192.168.10.10/api/auth',
        headers:{
            Authorization:'Bearer '+socket.handshake.query.Authorization
        }
    };

    request.get(config,function(error,response,body){

        socket.userId = JSON.parse(body).id;
        next();
    });

}
// call next() with an Error if you need to reject the connection.
next(new Error('Authentication error'));

});

The request in this block of code returns a user object based on the authenticated token. Refer to JWTAuth for more.

Then on connection I will assign the user to a unique channel.

 io.on('connection',function(socket){
   socket.join('userNotifications.'+socket.userId);
    console.log('user joined room: userNotifications.'+socket.userId);
});

Then broadcast the event:

    notifications.on('pmessage', function(subscribed, channel, message) {
    var m = JSON.parse(message);
    io.emit(channel+":"+m.event, message);
});

Back on the client side I listen for the channel. the var user is the user id.

socket.on('userNotifications.'+ user+':App\\Events\\notifications', function(message){
                        console.log(message);
                    });

Upvotes: 1

Related Questions