How to allow connection to laravel-echo-server (redis + socket.io) in the vue components only to authorized users?

You have an application with a correspondence between users and the opportunity to publish articles in real-time (websocket). Application SPA, a Passport Laravel authentication using the token, respectively, to each request the header needs to be attached to the token.
When you log in VUEX is called mutation, which saves the token in local storage and changes the state of whether the user is logged into the system. (state.isLoggedIn)
loginUser(state, data) {
 state.isLoggedIn = true; 
 localStorage.setItem('token', data.access_token); 
 },

For ordinary axios requests through the interceptor adds a header with the token to each request:
axios.interceptors.request.use(function (config) { 
 config.headers.Authorization = 'Bearer' + localStorage.getItem('token');
 return config;
 }, function (err) { 
 return Promise.reject(err);
 });

In the file app.js configuring laravel-echo-server:
import Echo from "laravel-echo"
window.io = require('socket.io-client');
window.Echo = new Echo({
 broadcaster: 'socket.io',
 host: window.location.hostname + ':6001',
 auth: {
 headers: {
 Authorization: 'Bearer' + localStorage.getItem('token')
},
},
});

In BroadcastServiceProvider:
Broadcast::routes(['middleware' => ['auth api']]);
Accordingly, if the user is authenticated for the first time, it is not yet in the store localStorage.getItem('token') and the server will kill it (you will Have to refresh the page).
The vue instance is created like this:
const app = new Vue({
 el: '#app',
router,
store
 components: {
MainApp
},
});

There is an idea to create a watcher in MainApp vue-component which monitors the status of in vuex (state.isLoggedIn) and then there to cause code settings for laravel-echo-server, though a bit do not understand how to implement it. There might be any way?
Update: At the moment, managed to implement so maybe there is a way without using a watcher?
watch: {
 isLoggedIn: function (val) {
 if (val === true) {
 window.Echo = new Echo({
 broadcaster: 'socket.io',
 host: window.location.hostname + ':6001',
 auth: {
 headers: {
 Authorization: 'Bearer' + localStorage.getItem('token')
},
},
});
 window.Echo.private('room.' + this.user_id)
 .listen('PrivateChat', ({data}) => {
...
}
})
}
}
 }
June 3rd 19 at 19:04
0 answer

Find more questions by tags LaravelVue.js