【问题标题】:Route restricting to that user and admin only路由仅限于该用户和管理员
【发布时间】:2017-06-28 07:21:17
【问题描述】:

我试图让用户只显示他们的报告。未通过身份验证的用户显示其他用户报告。但是,管理员可以显示所有用户报告。 我有这条路线:

Route::get('/showReport/{id}', 'CeciController@showReport');

我希望只有具有该报告 ID 的经过身份验证的用户和管理员才能访问此路由。如果我把它放在 auth 中间件组中,经过身份验证的用户可以访问其他用户报告。showReport/4showReport/5showReport/6。如果我把它放在管理中间件组下。即使是该 id 的经过身份验证的用户也无法访问它。如何实现?

查看:

Report for the month <b> {{$report->month}}: </b> <a href="{{url('/showReport', [$report->id])}}">Show Report Details</a>

这里是控制器:

public function showReport($id)
    {
        $report=Report::where('id',$id)->first();
        if($report)
        {
            return view('show_report')->with('report',$report);
        }      
    }

【问题讨论】:

    标签: laravel laravel-5.3


    【解决方案1】:

    您可以创建一个新的中间件并检查 Authenticated 用户的 id 是否与给定的 id 参数匹配:

    public function handle($request, Closure $next)
    {
        # Allow only if the user is admin or id matches
        $user = Auth::user();
        if ($this->isAdmin($user) or ($request->input('id') === $user->id)) {
            return $next($request);
        }
    
        return response('Unauthorized.', 401);
    }
    

    【讨论】:

    • 谢谢,但是$request->id是属于用户的report的id,实际上不是用户id。
    • 我使用 whereHas() 报告 ID 获得了用户 ID。
    • 我一直是愚蠢错误的拥护者;)感谢您的纠正
    猜你喜欢
    • 1970-01-01
    • 2016-05-09
    • 2015-08-19
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多