I need to restrict the access to some parts of the application depending on the user logged in. I mean for example to let a user edit only its own posts on a blog application.
Is there a better approach than in every function of the controller, if the user is not the owner of the required post, redirect to some error page?
For example if my routes are /post/{post_id}/edit
, /post/{post_id}/preview
, /post/{post_id}/delete
, can I somehow declare a general function in the PostController like:
if(Post::find($post_id)->user_id != Auth::user()->id){
return View::make('access-error');
}
Thanks!
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);
}
You could throw a 401 error and catch it elsewhere to display a custom page
App::abort(401);
I think this one will be very helpful, https://github.com/Zizaco/entrust/tree/1.0
You can create Roles
$owner = new Role;
$owner->name = 'Owner';
$owner->save();
$admin = new Role;
$admin->name = 'Admin';
$admin->save();
Now we just need to add permissions to those Roles.
$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));
Now we can check for roles and permissions simply by doing:
$user->hasRole("Owner"); // false
$user->hasRole("Admin"); // true
$user->can("manage_posts"); // true
$user->can("manage_users"); // false
and also,
Route::filter('manage_posts', function()
{
if (! Entrust::can('manage_posts') ) // Checks the current user
{
return Redirect::to('admin');
}
});