mercredi 13 juin 2018

Laravel 5.6 download file ajax

I have a REST API in Laravel 5.6

The users can upload theirs file in a non-public folder.

My problem is that now I want to let the user download the file only if the JWT token is valid and if the user has the right privilege.

My actual code is the following:

jquery:

$.ajaxSetup({
    headers: {
        'Authorization': 'Bearer ' + token
});

$.get('/api//download?' + $.param({
     file: encodeURIComponent(fileNonPublicPath) //e.g. company_id/file.pdf
}))
.done((data) => {
     console.log('file content', data);
})
.fail((err) => {
      console.error(err);
});

Laravel Controller:

$file = urldecode($request->input('file'));
$user = JWTAuth::toUser($request->token);
if(checkUserRole($user,$file){
   $pathToFile = Storage::disk('documents')->getDriver()->getAdapter()->applyPathPrefix($file);
   $finfo = finfo_open(FILEINFO_MIME_TYPE);
   $mime = finfo_file($finfo, $pathToFile);
   finfo_close($finfo);
   $headers = array('Content-Type' => $mime,);
   return response()->download($pathToFile, 'originalfilename', $headers);
}
return response()->json([], 403); //forbidden

This code is working fine except that the browser receive the content of the file in ajax and then the user cannot download it.

What is the solution not compromising the security of the stored files?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2JNDKbv
via IFTTT

Aucun commentaire:

Enregistrer un commentaire