【问题标题】:How to filter attributes in expand model due to user priveleges in Yii2 REST API由于 Yii2 REST API 中的用户权限,如何过滤扩展模型中的属性
【发布时间】:2020-09-12 16:33:00
【问题描述】:

在示例中,我有 ActiveRecords 模型 Client 和 Invoice。

class Client {
    public function getInvoices()
    {
        return $this->hasMany(Invoice::class, ['id' => 'invoice_id']);
    }

    public function extraFields() : array
    {
        return ['invoices'];
    }
}
class Invoice
{
    public static function getSuperSecretAttributes()
    {
        // attributes visible only for users with specific RBAC roles
        return ['secret_attribute'];
    }
}

我的目标是设置“secretAttributes”仅对具有 RBAC 角色“admin”的用户可见。 对 API 的示例请求是:

http://somehost/clients/1?expand=invoices

{
  "client_id" : 1,
  // ...
  "invoices" : [
      {
          "id" : 1,
          // ...
          "secret_attribute" : "foo"
      }
  ]
}

我得到了客户端模型属性,其中包含“secret_attribute”的扩展发票。 通过覆盖/yii/rest/Serializer::serializeModel(),很容易从客户端过滤“secretAttributes”,示例伪代码:

if (! user-has-role(Rbac::ROLE_ADMIN)) {
    foreach (model::getSuperSecretAttributes() as $attributeName) {
        unset(model[$attributeName]);
    }
}

但是如何处理相关模型中的秘密属性呢? 如何在不访问模型中的会话的情况下将其过滤掉?

【问题讨论】:

  • 怎么样?在那里你只得到字符串“发票”,你可以过滤掉整个发票模型,而不是选择发票属性。对 Invoice 属性的访问在模型中的 toArray() 方法中,但它是模型,不应该触及用户会话。

标签: php rest yii2 filtering privileges


【解决方案1】:

Yii2 是一个强者。 您所要做的就是覆盖 Invoice 模型中的 fields() 函数。

public function fields()
{
    $fields = parent::fields();
    if (\Yii::$app->user->isGuest || !\Yii::$app->user->can('see-secret-stuff-rule')) {
        unset($fields['secret_invoice'], $fields['other_sensitive_field'] /*, ... */);
    }
    return $fields;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多