【问题标题】:Restrict page if Auth::user()->id != user_id using middleware如果 Auth::user()->id != user_id 使用中间件限制页面
【发布时间】:2023-03-18 07:35:01
【问题描述】:

我使用中间件来限制非管理员访问管理页面,并且我可以通过使用策略来限制具有其他用户的“患者”列表的页面,但如果我使用策略。我必须在每个函数中重复代码 can() 方法。如果我使用中间件检查 url 中的 user_id 是否 == Auth::user()->id。我不需要重复这个,但是我如何从我的中间件的 url 中获取 user_id?

路线

Route::get('/patients/{patient}', 'PatientController@edit')

我现在拥有的

PatientPolicy

public function view(User $user, Patient $patient)
    {
        // does this patient belong to user
        return $user->id == $patient->user_id;
    }

病人控制器

public function edit(Patient $patient)
    {
        // authenticate logged in user
        $user = auth()->user();

        // can the loged in user do this?(policy)
        if($user->can('update', $patient)){
            return view('patient.edit-patient', compact('patient', 'user'));
        }
        return view('403');
    }

我应该在中间件中拥有什么

用户中间件

/**
 * @param $request
 * @param Closure $next
 * @return mixed
 */
public static function handle($request, Closure $next)
{
    if (Auth::check() && Auth::user()->id == User::patients()->user_id) {
        return $next($request);
    } else {
        return redirect()->route('login');
    }
}

有人知道如何检查路由 user_id 中的 {患者} 是否 == 登录的 user()->id 吗?

【问题讨论】:

    标签: laravel middleware restrict


    【解决方案1】:

    由于您已将 Illuminate\Http\Request 对象注入到中间件中的 handle 函数中,因此从 url 获取患者 ID 非常简单:

    /**
     * @param $request
     * @param Closure $next
     * @return mixed
     */
    public static function handle($request, Closure $next)
    {
        $patientId = $request->patient; // patient id from url!
    
        $patient = Patient::find($patientId);
    
        if (!$patient) {
            return redirect()->back()->with(['message' => 'Patient not found!']);
        }
    
        if (Auth::check() && (int) Auth::user()->id === (int) $patient->id) {
            return $next($request);
        } else {
            return redirect()->route('login');
        }
    }
    

    【讨论】:

    • 哦,是的!这对我帮助很大,但我确实需要稍微调整一下。因为 find 获取所有患者的列表,但我只需要限制不属于该用户的 1 位患者的页面。所以我将发布我如何修复它,感谢您的帮助。
    【解决方案2】:

    谢谢@Leorent,

    你的回答对我帮助很大,这就是它的解决方法

    路线

    Route::get('/patients/{patient}', 'PatientController@show')->middleware('user');

    用户中间件

    public static function handle($request, Closure $next)
        {
            $patientId = $request->patient->user_id; // user_id from patient in url!
    
            if (Auth::check() && (int) Auth::user()->id == $patientId) {
                return $next($request);
            } else {
                return redirect()->route('403');
            }
        }
    

    再次感谢!

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 2015-06-29
      • 1970-01-01
      • 2020-01-21
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-15
      相关资源
      最近更新 更多