尝试订阅私人频道时,Laravel不检查授权

时间:2019-09-03 06:05:14

标签: laravel broadcast pusher

我刚开始使用laravel broadcasting,但是遇到了问题。我正在使用Pusher,并且想检查用户是否有权订阅私人频道。用户对帖子评论通知的访问权限已通过身份验证,但未经授权。我正在尝试仅将新评论的通知发送给帖子的作者,但是打开该帖子的所有经过身份验证的用户都将收到通知。我错过了什么还是什么?

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class NewCommentEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */

    public $comment;
    public function __construct($comment)
    {
        $this->comment = $comment;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('post-'.$this->comment->post_id);
    }

    public function broadcastAs()
    {
        return 'new-comment-event';
    }

    public function broadcastWith()
    {
        return ['comment' => $this->comment->comment];
    }
}

routes / channel.php:

<?php

use App\models\Post;

Broadcast::channel('App.User.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

Broadcast::channel('post-{id}', function ($user, $id) {
    return false;
    //return $user->id == Post::find($id)->author_id;
});

以及可见的JavaScript:

var pusher = new Pusher('904d58ankty8c8397d000', {

        authEndpoint: 'http://localhost/blog/public/broadcasting/auth',
        cluster: 'ap2',
        forceTLS: true,
        auth: {
            headers: {
              'X-CSRF-Token': "{{csrf_token()}}"
            }
        }
    });

    var privateChannel = pusher.subscribe("private-post-{{{$post->id}}}");
    privateChannel.bind('new-comment-event', function(data) {
        $('#post-comments').append('<p>'+data.comment+'</p>');
    });

以下是提供者代码:

public function boot()
    {
        Broadcast::routes(['middleware' => ['auth']]);

        require base_path('routes/channels.php');
    }

我使用的laravel版本是5.8

1 个答案:

答案 0 :(得分:0)

“ $ this->评论-> post_id”表示什么?如果它表示该特定帖子的ID,则有权访问该帖子的人都会收到通知。从post_id获取author_id,并在“ post-”。author_id上广播。