Laravel access control using model objects

I need to restrict access to some parts of the application depending on the user's login. I mean, for example, so that the user can only edit their own posts in the blogging application.

Is there a better approach than in every controller function, if the user does not own the required message, redirects to the error page?

For example, if my routes /post/{post_id}/edit, /post/{post_id}/preview, /post/{post_id}/deleteif I could somehow call for a general function of PostController, for example:

if(Post::find($post_id)->user_id != Auth::user()->id){
    return View::make('access-error');
}

Thank!

+4
source share
3 answers

In your controller, you can do something like this:

public $check = ['edit', 'preview', 'delete'];

public function callAction($method, $parameters) {
    if(in_array($method, $this->check, true) && 
    $post_id = $parameters['post_id'] &&
    Post::find($post_id)->user_id != Auth::user()->id) {
        return View::make('access-error');
    }

    return parent::callAction($method, $parameters);
}
+1
source

, , https://github.com/Zizaco/entrust/tree/1.0

$owner = new Role;
$owner->name = 'Owner';
$owner->save();

$admin = new Role;
$admin->name = 'Admin';
$admin->save();

.

$managePosts = new Permission;
$managePosts->name = 'manage_posts';
$managePosts->display_name = 'Manage Posts';
$managePosts->save();

$manageUsers = new Permission;
$manageUsers->name = 'manage_users';
$manageUsers->display_name = 'Manage Users';
$manageUsers->save();

$owner->perms()->sync(array($managePosts->id,$manageUsers->id));
$admin->perms()->sync(array($managePosts->id));

:

$user->hasRole("Owner");    // false
$user->hasRole("Admin");    // true
$user->can("manage_posts"); // true
$user->can("manage_users"); // false

Route::filter('manage_posts', function()
{
    if (! Entrust::can('manage_posts') ) // Checks the current user
    {
        return Redirect::to('admin');
    }
});
+1

You can reset error 401 and catch it elsewhere to display a custom page

App::abort(401);

http://laravel.com/docs/4.2/errors#handling-404-errors

0
source

All Articles