简体   繁体   English

阻止经过身份验证的用户查看Laravel 5上的其他用户配置文件

[英]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.

相关问题 使用Sentry 2,让Authenticated User查看Laravel 4中其他用户的配置文件 - Let Authenticated User view the profile of other users in Laravel 4 using Sentry 2 Laravel 4阻止经过身份验证的用户查看其他用户配置文件 - Laravel 4 Prevent Authenticated users from viewing other user profiles 如何防止用户表单输入其他用户个人资料 - How to prevent user form entering other users profile 其他用户如何在octobercms中查看用户的个人资料详细信息? - How can other users view a user's profile details in octobercms? 创建中间件以防止用户在laravel 5.1中操纵其他用户的信息 - Create middleware to prevent a user manipulates the information of other users in laravel 5.1 Laravel 5无法从视图中获取经过身份验证的用户 - Laravel 5 Can not get authenticated user from view Laravel-重定向经过身份验证的用户 - Laravel - Redirect authenticated users Laravel - 获取经过身份验证的用户 - Laravel - Get the Authenticated users 我正在尝试从经过身份验证的用户配置文件的用户表中传递用户的 ID - I am trying to pass the id of a user from the users table from an authenticated users profile 导航到其他用户的个人资料(laravel 5.2) - navigating to other user's profile (laravel 5.2)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM