简体   繁体   English

Laravel - 在 Middleware Auth 中包含资产

[英]Laravel - Include assets on Middleware Auth

Inside my app, exist a route group called admin , any route inside this group call two resources: public/css/admin.css and public/js/admin.js , but any unauthenticated user has access to these files.在我的应用程序中,存在一个名为admin的路由组,该组内的任何路由都调用两个资源: public/css/admin.csspublic/js/admin.js ,但任何未经public/js/admin.js验证的用户都可以访问这些文件。 How can I include these files inside the Auth Middleware?如何将这些文件包含在 Auth 中间件中?

My admin routes:我的管理员路线:

Route::group(['prefix' => 'admin', 'middleware' => ['auth']], function () {
    Route::get('/', 'Admin\IndexController@index')->name('panel');

    Route::group(['prefix' => 'users'], function() {});

    Route::group(['prefix' => 'settings'], function() {});

    Route::fallback('Admin\ExceptionController@exception');
});

My resources links:我的资源链接:

http://localhost:3000/css/admin.css
http://localhost:3000/js/admin.js

My resources links should be:我的资源链接应该是:

http://localhost:3000/admin/css/admin.css
http://localhost:3000/admin/js/admin.js

If I just create the folder admin inside the public folder I just got a 403 error...如果我只是在public文件夹中创建文件夹admin ,我只会收到 403 错误...

What can I do about it?我该怎么办?

I suppose you are using it because you don't want unauthenticated users to know the contents of these css/js files. 我想你正在使用它,因为你不希望未经身份验证的用户知道这些css / js文件的内容。 You shouldn't have any sensitive information in your css/js files, so there is no problem on serving them. 您的css / js文件中不应包含任何敏感信息,因此服务它们没有问题。

Otherwise, if you want to limit access to a file you should make the file download through PHP. 否则,如果要限制对文件的访问,则应通过PHP下载文件。 For example you could have the file outside you public folder and make it conditional downloadable through a method that gets file contents and serves for download. 例如,您可以将文件放在公共文件夹之外,并通过获取文件内容并供下载的方法使其可以条件下载。

You should can make that public admin folder though, check file permissions and file ownership. 您应该可以创建该公共管理文件夹,检查文件权限和文件所有权。

Update: Now we'll use storage instead of public directory. 更新:现在我们将使用存储而不是公共目录。

Although I agree that you should not have any sensitive info in your css/js files but if you really want to serve the files to authenticated users you can do it with this work around. 虽然我同意您不应该在css / js文件中包含任何敏感信息,但如果您确实要将文件提供给经过身份验证的用户,则可以使用此方法来完成此操作。

NOTE: I have made the project publicaly avaiable on git so you can clone from there if you want. 注意:我已经在git上公开了这个项目,所以你可以根据需要从那里克隆。 Git Repo Git Repo

  1. Create a directory for admin assets with permission 755 使用权限755为管理资产创建目录
  2. Create a helper function to serve admin assets. 创建帮助程序功能以提供管理资产。
  3. Make the helper function available in blade. 使刀片中的辅助功能可用。
  4. Link the assets using the helper function in order to first authenticate and then serve the file. 使用帮助程序功能链接资产,以便首先进行身份验证,然后提供文件。

Basic Idea : 基本理念

  • The basic idea is to have a directory which no one can access via browser. 基本思想是拥有一个无人可以通过浏览器访问的目录。
  • Authenticate the user 验证用户
  • Copy the files from protected directory. 从受保护的目录中复制文件。
  • Paste the files in a new directory ( in storage ) only associated with the authenticated user. 将文件粘贴到仅与经过身份验证的用户关联的新目录( 存储中 )中。
  • Delete the associated directory on user logout. 在用户注销时删除关联的目录。

Implementation : 实施

  1. Created a directory called admin_assets in public directory. 公共目录中创建了一个名为admin_assets的目录。
  2. Change the permission of the directory to 755 . 将目录的权限更改为755
  3. Created a helper class named CommonHelper , and write functions to serve and delete admin assets. 创建了一个名为CommonHelper的辅助类,并编写了用于提供删除管理资产的函数。
  4. Served the assets with these helper functions as following: 使用以下辅助函数为资产提供服务:

<link href="{{ asset( CommonHelper::serveAdminAssets('app.css', '/css/') ) }}" rel="stylesheet">

  1. Deleted the files at logout. 注销时删除了文件。

Finally , as far as the user is logged in the files will be available for him/her, all files will be deleted from the folder once the user logs out. 最后 ,就用户登录而言,他/她可以使用文件,一旦用户注销,所有文件都将从文件夹中删除。

CommonHelper class: CommonHelper类:

<?php
/**
 *
 */
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class CommonHelper {
  public static function serveAdminAssets($fileName, $filePath) {

    if( Auth::check() ) {
      $adminAssetsBasePath = public_path().'/admin_assets';

      $source = $adminAssetsBasePath.$filePath.$fileName;

      $destDir = 'public/'.Auth::user()->id.$filePath;

      $dest = $destDir.$fileName;

      Storage::put($dest, file_get_contents($source));

      return Storage::url($dest);
    } else {
      return '';
    }
  }

  public static function removeAdminAssets($id) {

      $destDir = storage_path('app/public/'.Auth::user()->id);
      File::cleanDirectory($destDir);
      File::deleteDirectory($destDir);
  }
}
 ?>

Notes: 笔记:

  1. Remember, if you are using the local driver, all files that should be publicly accessible should be placed in the storage/app/public directory. 请记住,如果您使用的是本地驱动程序,则应该可以公开访问的所有文件都应放在storage / app / public目录中。 Furthermore, you should create a symbolic link at public/storage which points to the storage/app/public directory. 此外,您应该在public / storage处创建一个指向storage / app / public目录的符号链接。 Docs 文件

  2. Before deleting a directory you should empty it first. 在删除目录之前,您应该先清空它。

Here is an example that you can apply. 以下是您可以申请的示例。

Store your assets in storage directory. 将资产storagestorage目录中。

then you can check whether it is an admin or Not. 然后你可以检查它是否是管理员。

In your view you can u can inject the Admin Assets Like. 在您的视图中,您可以注入Admin Assets Like。

<script>
  {!! \Storage::disk('urdisk name')->get('admin.js'); !!}
</script>

for your css you can 为你的CSS你可以

 <style>
  {!! \Storage::disk('urdisk name')->get('admin.css'); !!}
</style>

Hope this helps 希望这可以帮助

For applying auth to the asset files you need to go through from the laravel, not by accessing the files using full path , you need to access css/js files via route so that laravel will be able to apply auth on each files inside route group. 要将auth应用于需要从laravel进行的资产文件,而不是通过使用完整路径访问文件,您需要通过路由访问css / js文件,以便laravel能够对路由组内的每个文件应用auth 。

PS Files must be saved inside storage folder, ie storage/admin.css PS文件必须保存在存储文件夹中,即storage/admin.css

Updated route group 更新了路线组

Route::group(['prefix' => 'admin', 'middleware' => ['auth']], function () {

Route::get('/', 'Admin\IndexController@index')->name('panel');

Route::get('{file}', 'StaticFileController@serveFile');

Route::group(['prefix' => 'users'], function() {});

Route::group(['prefix' => 'settings'], function() {});

Route::fallback('Admin\ExceptionController@exception');
});

Controller 调节器

namespace App\Http\Controllers;

use Illuminate\Http\Request;
Use Response;

use App\Http\Requests;

class StaticFileController extends Controller
{
    public function serveFile ($file)
    {

        $storagePath = storage_path($file);
        $mimeType = mime_content_type($storagePath);
        if( ! \File::exists($storagePath)){
            return view('errorpages.404');
        }
        $headers = array(
            'Content-Type' => $mimeType,
            'Content-Disposition' => 'inline; filename="'.$file.'"'
        );
        return Response::make(file_get_contents($storagePath), 200, $headers);

    }
}

Now your resources links would be 现在您的资源链接将是

http://localhost:3000/admin/css/admin.css
http://localhost:3000/admin/js/admin.js

Hope this helps 希望这可以帮助

For blade templates you can use the @auth directive.对于刀片模板,您可以使用@auth指令。

When you're including these files in your blade templates, you can wrap the script tag in an @auth directive and they'll only be rendered when the user is authenticated.当您将这些文件包含在刀片模板中时,您可以将脚本标记包装在@auth指令中,并且它们只会在用户通过身份验证时呈现。

Eg例如

@auth

<script src="{{ asset('path/to/your/js') }}"></script>

@endauth

There's also an optional parameter that allows you to set the guard you want to check for eg @auth('your-guard') .还有一个可选参数,允许您设置要检查的守卫,例如@auth('your-guard')

It's available in Laravel 5.5+它在 Laravel 5.5+ 中可用

Here's the documentation for a better overview of its use.这是更好地概述其使用的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM