laravel - 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
解决方案
"$this->comment->post_id" 是什么意思?如果它表示该特定帖子的 id,则有权访问该帖子的人将收到通知。从 post_id 获取 author_id 并在 'post-'.author_id 上广播。
推荐阅读
- php - 如何仅在 woocommerce 的商店页面上显示有货的变体?
- php - php 正在验证一个无效的 url URL
- vue.js - Vue-CLI的逐步调试
- php - Android应用程序解码来自PHP MySql数据库的JSON响应,没有特殊字符
- r - 如何使用 R 对 NeuralNet 模型使用分类/因子输入
- javascript - PropTypes 给我一个字符串类型错误
- agda - 为什么将 Size 定义为参数与索引时的处理方式不同?
- spring - 使用 @ResponseBody 返回 BigDecimal 精度丢失
- permissions - 如何查看 Android 10 中权限的分组方式
- javascript - 如何使用 Javascript 从 URL 获取视频格式