本文介绍了Laravel阻止用户编辑/查看其他用户的资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的laravel应用中,我有多个用户帐户,这些帐户具有分配给他们的资源.例如说付款".要编辑或查看付款,用户可以访问/payment/edit/{payment}路线(其中payment是付款ID).

In my laravel app I have multiple user accounts who have resources that are assigned to them. Say, for example, a "payment". To edit or view a payment a user would visit the /payment/edit/{payment} route (where payment is the payment ID).

尽管我有一个auth过滤器来阻止未登录的用户访问此页面,但是没有什么可以阻止的,例如,用户1不能编辑用户2的付款.

Although I have an auth filter to stop un-logged in users from accessing this page there is nothing to stop, for example, user 1 from editing user 2's payment.

用户可以使用过滤器检查付款(或任何其他资源)属于哪个用户吗?

Is there a filter I can user that checks which user a payment (or any other resource) belongs to prevent this kind of issue?

[我正在使用Laravel的模型绑定,该绑定会自动获取路线指定的模型,而不是我雄辩地将其获取到控制器中.]

[I am using Laravel's model bindings which automatically fetches the model specified by the route rather than me get it in the controller using eloquent.]

推荐答案

默认情况下不存在此类过滤器,但是您可以轻松创建一个过滤器(取决于数据库的设置方式).在app/filters.php中,您可以执行以下操作:

No such filter exists by default, however you can easily create one (depending on how your database is set up). Within app/filters.php, you may do something like this:

Route::filter('restrictPermission', function($route)
{
    $payment_id = $route->parameter('payment');

    if (!Auth::user()->payments()->find($payment_id)) return Redirect::to('/');
});

这会将当前登录用户的pay_id(在您的数据库中)与传递到路由中的{payment}参数进行比较.显然,根据数据库的设置方式(例如,如果payment_id在单独的表中),您需要更改条件.

This compares the currently logged in user's payment_id (in your database) to the {payment} argument passed into the route. Obviously, depending on how your database is set up (for instance if the payment_id is in a separate table) you need to change the conditional.

然后,将过滤器应用于您的路线:

Then, apply the filter to your route:

Route::get('/payment/edit/{payment}', array('before' => 'restrictPermission'));

这篇关于Laravel阻止用户编辑/查看其他用户的资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 15:29