Opekunov/laravel-centrifugo-broadcaster

presence error (invalid token)

Opened this issue · 0 comments

image
SCR-20240516-eokz
SCR-20240516-eouc
SCR-20240516-eowj

`

    const centrifuge = new Centrifuge("ws://192.168.1.15:8000/connection/websocket", {
        token: "xxxxxxxxxxxx"
    });

    centrifuge.on('connecting', function(ctx) {
        console.log(`connecting: ${ctx.code}, ${ctx.reason}`);
    }).on('connected', function(ctx) {
        console.log(`connected over ${ctx.transport}`);
    }).on('disconnected', function(ctx) {
        console.log(`disconnected: ${ctx.code}, ${ctx.reason}`);
    }).connect();

    const subscribeTokenEndpoint = 'http://centrifugo.test/broadcasting/auth'

    // Important: In this example, getting a subscription token is implemented through basic fetch() without passing parameters to identify the user in your Laravel application. Use methods appropriate for your application
    function customGetToken(endpoint, ctx) {
        return new Promise((resolve, reject) => {
            fetch(endpoint, {
            method: 'POST',
            headers: new Headers({ 'Content-Type': 'application/json' }),
            body: JSON.stringify(ctx)
            })
            .then(res => {
                if (!res.ok) {
                throw new Error(`Unexpected status code ${res.status}`);
                }
                return res.json();
            })
            .then(data => {
                resolve(data.token);
            })
            .catch(err => {
                reject(err);
            });
        });
    }

    // Set the subscription
    const sub = centrifuge.newSubscription('presence-public:chats', {
        getToken: function (ctx) {
            return customGetToken(subscribeTokenEndpoint, ctx);
        },
    })
    sub.subscribe();
    
    sub.presenceStats().then(function(resp) {
        console.log(resp);
    }, function(err) {
        console.log('presence error', err);
    });
    // const sub = centrifuge.newSubscription("public:chats");

    sub.on('publication', function(ctx) {
        console.log(`subscribing: ${ctx.data.value}`);
    }).on('subscribing', function(ctx) {
        console.log(`subscribing: ${ctx.code}, ${ctx.reason}`);
    }).on('subscribed', function(ctx) {
        console.log('subscribed', ctx);
    }).on('unsubscribed', function(ctx) {
        console.log(`unsubscribed: ${ctx.code}, ${ctx.reason}`);
    }).subscribe();

`

`
Broadcast::channel('presence-public:chats', function () {
return true;
});

`

`
public function broadcastOn()
{
return new Channel('presence-public:chats');
// return new PrivateChannel('public:chats');
// return new PresenceChannel('public:chats');
}

`