简体   繁体   中英

Laravel 4 Prevent Authenticated users from viewing other user profiles

I am wondering how in laravel 4 the following is possible. I have a filter to check if a user is authenticate on all routes that have user/*. My filter works as it is suppose to but lets say that a user is logged in their url will look something like this user/id . How do I prevent an authenticated user from viewing another user?

another approach is to change your urls.. why have url like user/{id} ? just change it to for example

 user/profile

and inside the controller do something like:

$user = Auth::user();

that way the user just cant fake is id.. i only use urls with the id in the admin area where i need to edit some user:

/admin/{id}/edit

In your Auth filter you can access the route parameter ( 'user/{id}' ) and can check logged in user's id with the id passed in the url like

Route::filter('auth', function($route)
{
    // get the id from rouqe
    $id = $route->getParameter('id');
    if( Auth::check() && Auth::user()->id != $id) {
        // not authenticated user, so access is denied
        return Redirect::to('/');
    }
});

If it is a blanket policy that a user can only view their own profile then could you just check that the id from user/{id} route matches the current user id from the login session, eg. in the profile controller something like:

public function getProfile($profile_id) {
    if (Auth::user()->id != $profile_id) {
        //this is not your profile - don't be nosey!
    } else {
        //have you got nothing better to do than look at yourself all day!
    }
}

Glen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM