Laravel - Restrict certain downloads using authentication

user2551614 picture user2551614 · Apr 21, 2014 · Viewed 8k times · Source

Lets say I want to make an application where users can upload private files to a laravel based website. I dont want to make their files available to public, but I want them to be able to download the files after they have logged in.

So I need to verify that they have logged in, and that they have the correct account ID to download a specific file. How can I create this restriction?

I have been looking around http://laravel.com/docs with no success, and with google search I was only able to obtain some vanilla PHP samples, but it seems messy to integrate into laravel, which way do you recommend me to do this?

I may be overcomplicating the situation in my head, perhaps I could make a table in database with account id and path to file, and use Response::download($pathToFile); And restricting the uploaded files folder with .htaccess no allow?

(Assuming laravels Response::download method bypasses .htaccess) But even if that work it would probably be best to find a way to do this without .htaccess thought?

Edit I guess I will just store the files in the database as blob, and load it from there. That way I can easily do authorisation validation.

Answer

vDk3 picture vDk3 · Jun 12, 2014

All you have to do is just store files in a private directory (eg. /app/files) and set correct headers.

    $name = 'name.zip';
    $file = '/app/files/name.zip';

    $header = array(
        'Content-Type' => 'application/octet-stream',
        'Content-Disposition' => 'attachment', 
        'Content-length' => filesize($file),
        'filename' => $name,
    );

    // auth code
    return Response::download($file, $name, $header);