Question

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?

Was it helpful?

Solution 2

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('/');
    }
});

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top