【问题标题】:Enforce Global Scope Across all models在所有模型中实施全局范围
【发布时间】:2019-06-22 16:15:27
【问题描述】:

我们正在开发一个基于 Laravel Spark 的应用程序。作为其中的一部分,我们希望将资源与特定团队联系起来。

我知道我们可以添加一个全局范围,例如:

<?php


namespace App\Scopes;

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class TeamScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('team_id', '=',Auth()->user()->currentTeam->id );
    }
}

但根据文档,我们必须将其添加到我们想要限制的每个模型中,如下所示:

protected static function boot()
{
    parent::boot();
    static::addGlobalScope(new TeamScope);
}

我的问题是有可能创建未来的模型而忘记应用此代码。哪个会给我们带来安全漏洞?

有什么方法可以全面执行范围?

【问题讨论】:

    标签: laravel eloquent laravel-spark


    【解决方案1】:

    您可以创建自己的基础模型,并具有未来模型将扩展的所需全局范围。

    【讨论】:

      【解决方案2】:

      您应该使用引导功能创建特征。名为 BelongsToTeam 的特征。

      并且在所有模型中仅添加:使用 BelongsToTeam;

      【讨论】:

      • 这仍然有同样的问题,如果有人忘记添加特征,那么该模型可以跨团队访问
      【解决方案3】:

      我不确定是否有办法全局添加范围。

      在我的特定应用程序中,我们不得不为模型添加更多职责。所以我们创建了一个 BaseModel 类来扩展 Laravel 的 Illuminate\Database\Eloquent\Model

      所有新模型然后扩展 BaseModel 而不是 Laravel 的模型。

      <?php
      
      namespace App;
      
      use Illuminate\Database\Eloquent\Model;
      
      class BaseModel extends Model
      {
          protected static function boot()
          {
              parent::boot();
              static::addGlobalScope(new TeamScope);
          }
      
      }
      

      例如:

      <?php
      
      namespace App;
      
      class Attribute extends BaseModel
      {
      
      }
      

      你也可以有一个特性,你可以使用它来将此范围添加到你的模型中。例如:

      trait HasTeamScope
      {
          protected static function boot()
              {
                  parent::boot();
                  static::addGlobalScope(new TeamScope);
              }
          }
      }
      

      ...然后您可以轻松地在您的模型中重复使用它。

      例如:

      <?php
      
      namespace App;
      
      class Attribute extends BaseModel
      {
          use HasTeamScope;
      }
      

      现在,根据您的问题,您可能还会忘记在第一个实例中扩展 BaseModel 或在创建新模型时在第二个实例中添加 Trait。

      要解决这个问题,您可以轻松地 create a new command to produce models 使用您自己的存根(它扩展 BaseModel 或在您创建新模型时添加特征)

      【讨论】:

      • 是的,我考虑过这两个选项。我想我希望能有一颗神奇的子弹让它成为无法忘记的东西。我们现在添加了一个命令来生成模型。谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-24
      • 2012-04-29
      • 2013-01-26
      • 1970-01-01
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多