首页 文章

如何阻止Auth用户在laravel中使用非auth用户权限访问自己的页面?

提问于
浏览
0

我的laravel应用程序是一个社交媒体网站 . 这是访问另一个laravel用户 Profiles 的路线

Route::get('/dashboard/{id}', [
'uses' => 'UserController@getProfile',
'as' => 'profile.index',
'middleware' => 'auth'
]);

它工作得很好 . 但是,我发现了一个错误,当我将Auth用户的ID输入到路径中时,我会被带到同一页面,然后我可以将自己添加为朋友,我不希望这种情况发生 . 如果我正在访问我自己的 Profiles ,我宁愿被带回主屏幕 .

这是控制器:

public function getProfile($id)
{

    if(Auth::user() === $id)
        redirect('dashboard');

    $user = User::where('id', $id)->first();

    $posts = Post::where("dash_id", "=", $user->id)->latest()->paginate(3);
    $photos = Photo::paginate(6);
    return view('profile.index',compact('user','posts', 'photos'));

}

我试图让它重定向到'dashboard'而不是'profile.index',如果它是Auth用户的页面,而不是像普通的非身份验证配置文件那样拉起来,但似乎无法让它工作 . 关于如何修复这个小bug的任何想法?

2 回答

  • 0

    您通过 Auth::user() 获取用户实例,而不仅仅是用户ID . 您正在将实例与数值进行比较 . 不起作用 . 您必须使用 Auth::id()Auth::user()->id 才能获取登录用户的ID . 以下代码适用于您的情况 .

    public function getProfile($id)
    {
    
        if(Auth::id() == $id)
        {
            redirect('dashboard');
        }
        else
        {
            $user = User::where('id', $id)->first();
            $posts = Post::where("dash_id", "=", $user->id)->latest()->paginate(3);
            $photos = Photo::paginate(6);
            return view('profile.index',compact('user','posts', 'photos'));
        }
    }
    

    如果有帮助,请告诉我!

  • 0

    您尝试将当前用户对象与请求ID进行比较,请尝试以下代码:

    public function getProfile($id)
    {
        if(Auth::id() === $id) {
            redirect('dashboard');
        }
    
        $user = User::where('id', $id)->first();
    
        $posts = Post::where("dash_id", "=", $user->id)->latest()->paginate(3);
        $photos = Photo::paginate(6)
    
        return view('profile.index',compact('user','posts', 'photos'));
    }
    

相关问题