Laravel-使用身份验证限制某些下载


Laravel - Restrict certain downloads using authentication

假设我想制作一个应用程序,用户可以将私人文件上传到基于laravel的网站。我不想让他们的文件公开,但我希望他们能够在登录后下载文件。

所以我需要验证他们是否已经登录,以及他们是否有正确的帐户ID来下载特定的文件。如何创建此限制?

我一直在四处寻找http://laravel.com/docs没有成功,通过谷歌搜索,我只能获得一些普通的PHP示例,但集成到laravel中似乎很混乱,你建议我用哪种方式?

我可能在脑子里把情况弄得过于复杂了,也许我可以在数据库中制作一个带有帐户id和文件路径的表,并使用Response::download($pathToFile);不允许使用.htaccess限制上传的文件文件夹?

(假设laravels Response::download方法绕过.htaccess)但即使这样做,最好还是找到一种没有.htaccess想法的方法?

编辑我想我只会将文件作为blob存储在数据库中,然后从那里加载它。这样我就可以轻松地进行授权验证。

您所要做的就是将文件存储在专用目录(例如/app/files)中并设置正确的头文件。

    $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);

我刚刚遇到这个,也许它也能帮助到别人。我用它来"保护"我的PDF文档,只允许登录用户使用。

我把我的文件放在存储/公用文件夹之外(所以公用文件夹无法访问)。控制器受到构造函数中的"auth"中间件的保护。

public function grab_file($hash)
    {
        $file = Publication::where('hash', $hash)->first();
        if ($file) {
            return Response::download(storage_path('app/publications/' . $file->filename), null, [
                'Cache-Control' => 'no-cache, no-store, must-revalidate',
                'Pragma' => 'no-cache',
                'Expires' => '0',
            ], null);
        } else {
            return abort(404);
        }
}

路线为;

Route::get('/user/file/{hash}', 'UserController@grab_file');

其中发布存储了对文件的哈希引用。通过这种方式,用户无法"查看"实际文件的位置。

"无缓存"标题确保浏览器不会缓存PDF。我这样做是因为注销后,您仍然可以访问该文件。

您可以使用基于模式的过滤器来限制对下载页面的访问

Route::filter('download', function()
{
    //here you check if the user is logged in
    if(!Auth::check()){
        return 'you should be logged in to access the download page';
    }
});
Route::when('download/*', 'download'); 

查看文档以了解更多详细信息