为了账号安全,请及时绑定邮箱和手机立即绑定

通过 user_id 获取 Lighthouse GraphQL 数据所有权

通过 user_id 获取 Lighthouse GraphQL 数据所有权

PHP
猛跑小猪 2023-10-22 21:13:37
我有一个允许多个用户的应用程序。每个用户之间完全隔离;这意味着数据库中所有非用户的内容都有一个user_id列,并且只有登录用户才可以查看、更新或删除它们。此外,用户不能使用其他人的 user_id 创建行。有没有内置的方法可以用 Lumen/Lighthouse 来解决这个问题?这是我所做的,它有效,但我想知道我是否重新发明了轮子:每个模型都有一个user关系,如下所示:public function user(): BelongsTo{    return $this->belongsTo(User::class);}我在这些模型中添加了一个HasOwnerTrait,其中包含以下内容:public static function boot(){    parent::boot();    static::creating(function (Model $model) {        $model->user_id = Auth::user()->id;    });    static::saving(function (Model $model) {        if ($model->user_id !== Auth::user()->id) {            $exception = new ModelNotFoundException();            $exception->setModel(self::class, $model->id);            throw $exception;        }    });    static::deleting(function (Model $model) {        if ($model->user_id !== Auth::user()->id) {            $exception = new ModelNotFoundException();            $exception->setModel(self::class, $model->id);            throw $exception;        }    });}public function scopeIsOwner($query){    return $query->where('user_id', Auth::user()->id);}最后,在我的模式定义中:type Query {    recipes: [Recipe!]! @all(scopes: ["isOwner"])}type Mutation {    createRecipe(input: CreateRecipeInput! @spread): Recipe @create    updateRecipe(id: ID!, input: UpdateRecipeInput! @spread): Recipe @update    deleteRecipe(id: ID!): Recipe @delete}同样,这是可行的,但是是否需要像这样临时使用,或者是否有更好的方法?
查看完整描述

1 回答

?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

我认为你的解决方案很好,它节省了编写一大堆样板文件。一些小建议:

boot您可以将方法重命名为 ,从而使您的特征成为可引导特征,由框架自动调用bootHasOwnerTrait

也许可以考虑isOwner默认将作用域设置为活动状态。在 Laravel 中,这被容易混淆地称为全局作用域。这允许您省略显式命名范围,但如果您有一些不应应用的查询(例如统计信息),您仍然可以省略它。


查看完整回答
反对 回复 2023-10-22
  • 1 回答
  • 0 关注
  • 62 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信