Laravel 5.4 secure documents by user permission

I have a Laravel project where users have roles with permissions (I am using Zizaco / entrust ) and the application is only available to the logged in user.

The application stores uploaded documents, but these documents should not be available for public viewing, on the other hand, these documents should be available depending on the permission of users.

My question is how to go in this case, how to protect documents in the user permission function?

+3


source to share


1 answer


I'm not sure if this helps, but you can create a dedicated controller to load / show the document where you can check the permissions of the actual user.

In the Entrust documentation, you can check if the user should see the document:

$user->hasRole('owner'); //returns boolean

      

So, you can use this code from below in your controller:

$user = User::where('username', '=', 'Mark')->first();    
$pathToFile = Storage::get('file.pdf');
if ($user->hasRole('admin'))
{
    return response()->download($pathToFile); //if you want to display a file, then change download to file
}
else
{
    abort(403, 'Unauthorized action.');
}

      



Remember to add this line to your controller:

use Zizaco\Entrust\Traits\EntrustUserTrait;

      

You can read more about the answers here: https://laravel.com/docs/5.4/responses and the files here: https://laravel.com/docs/5.4/filesystem


Take a look here for a short syntax that will help you implement file loading in routes.php without creating a new controller. https://github.com/Zizaco/entrust#short-syntax-route-filter

+1


source







All Articles