[英]Prevent authenticated user to view other users profile on Laravel 5
I want to use Laravel 5 AuthServiceProvider
to prevent logged in user to view other users profile. 我想使用Laravel 5
AuthServiceProvider
阻止登录的用户查看其他用户的个人资料。 I'm using route like this user/1
. 我正在使用像
user/1
这样的路由。 How can I compare if the logged in user ID is match with the ID in the URL. 如何比较登录的用户ID是否与URL中的ID匹配。 If not then can't proceed.
如果没有,则无法继续。
Here's the following code I'm trying in my AuthServiceProvider
: 这是我在
AuthServiceProvider
尝试的以下代码:
$gate->define('view-profile', function($user, $id) {
return Auth::user()->id === $id;
});
However, the above code doesn't work as I can't pass the correct ID from the URL. 但是,由于无法从URL传递正确的ID,因此上述代码无效。 Can anyone please help?
谁能帮忙吗?
Here's the code I've in my controller: 这是我在控制器中的代码:
if (Gate::denies('view-post', [Auth::user()->id, (int) $id])) {
return abort(403);
} else {
return 'success';
}
Just to let all of you know that I've figured it out myself using Gate::forUser()
method. 只是让大家知道我已经使用
Gate::forUser()
方法自己弄清楚了。 Here's the relevant code which I hope anyone may find helpful: 这是相关的代码,希望对您有所帮助:
In AuthServiceProvider
: 在
AuthServiceProvider
:
$gate->define('view-post', function($user, $id) {
return $user->id === (int) $id;
});
In your particular Controller
: 在您的特定
Controller
:
$user = Auth::user();
if(Gate::forUser($user)->allows('view-post', $id)) {
return 'true';
}
return abort(403, trans('Sorry, not sorry!'));
If you route user controller with user, then user/1 will route the user controller show function, and in show function you can check your authentication user with id: 如果用user路由用户控制器,则user / 1将路由用户控制器的show函数,在show function中,您可以使用id检查身份验证用户:
Function show ($id)
{
if ( Auth::user()->id == $id) {
//your code here
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.