首页 > 解决方案 > Laravel 在尝试订阅私人频道时不检查授权

问题描述

我刚开始使用laravel 广播,遇到了一个问题。我正在使用 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];
    }
}

路线/频道.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

标签: laravelbroadcastpusher

解决方案


"$this->comment->post_id" 是什么意思?如果它表示该特定帖子的 id,则有权访问该帖子的人将收到通知。从 post_id 获取 author_id 并在 'post-'.author_id 上广播。


推荐阅读