Spatie用户权限-属于许多公司,解决方案反馈

我遇到的情况是,用户可以属于许多团队/公司,并且在该团队/公司内,他们可以具有不同的角色和权限,具体取决于他们所登录的角色和权限。我已经提出了以下解决方案,希望得到一些反馈!

注意:目前,我仅使用具有Spatie权限的model_has_roles表,并始终使用$user->can('Permission')来检查权限。

  1. 我们的公司模型具有以下关系和方法
class Company extends Model
{
    public function owner(): HasOne
    {
        return $this->hasOne(User::class,'id','user_id');
    }

    public function users(): BelongsToMany
    {
        return $this->belongsToMany(
            User::class,'company_users','company_id','user_id'
        )->using(CompanyUser::class);
    }

    public function addTeamMember(User $user)
    {
        $this->users()->detach($user);

        $this->users()->attach($user);
    }
}
  1. 我们修改了枢轴模型以具有Spatie HasRoles特征。这使我们可以为CompanyUser分配一个角色,而不是Auth User。您还需要指定默认的Guard或Spatie权限Squarks。
class CompanyUser extends Pivot
{
    use HasRoles;

    protected $guard_name = 'web';
}
  1. 在用户模型上,我创建了HasCompanies特性。这提供了关系,并提供了将角色分配给新公司用户的方法。此外,它会覆盖gate can()方法。

用户可以属于许多公司,但一次只能拥有一个活跃的公司(即他们正在查看的公司)。我们使用current_company_id列对此进行定义。

同样重要的是要确保数据透视表ID被拉过(这将不是标准的),因为这是我们在Spatie model_has_roles table中所使用的。

trait HasCompanies
{
    public function companies(): HasMany
    {
        return $this->hasMany(Company::class);
    }

    public function currentCompany(): HasOne
    {
        return $this->hasOne(Company::class,'current_company_id');
    }

    public function teams(): BelongsToMany
    {
        return $this->belongsToMany(
            Company::class,'user_id','company_id'
        )->using(CompanyUser::class)->withPivot('id');
    }

    public function switchCompanies(Company $company): void
    {
        $this->current_company_id = $company->id;
        $this->save();
    }

    private function companyWithPivot(Company $company)
    {
        return $this->teams()->where('companies.id',$company->id)->first();
    }

    public function assignRolesForCompany(Company $company,...$roles)
    {
        if($company = $this->companyWithPivot($company)){
            /** @var CompanyUser $companyUser */
            $companyUser = $company->pivot;
            $companyUser->assignRole($roles);
            return;
        }

        throw new Exception('Roles could not be assigned to company user');
    }

    public function hasRoleForCurrentCompany(string $roles,Company $company = null,string $guard = null): bool
    {
        if(! $company){
            if(! $company = $this->currentCompany){
                throw new Exception('Cannot check role for current company because it has not been set');
            }
        }

        if($company = $this->companyWithPivot($company)){
            /** @var CompanyUser $companyUser */
            $companyUser = $company->pivot;
            return $companyUser->hasRole($roles,$guard);
        }

        return false;
    }

    public function can($ability,$arguments = []): bool
    {
        if(isset($this->current_company_id)){
            /** @var CompanyUser $companyUser */
            $companyUser = $this->teams()->where('companies.id',$this->current_company_id)->first()->pivot;

            if($companyUser->hasPermissionTo($ability)){
                return true;
            }

            // Still run through the gate as this will check for gate bypass
            return app(Gate::class)->forUser($this)->check('N/A',[]);
        }

        return app(Gate::class)->forUser($this)->check($ability,$arguments);
    }
}

现在我们可以执行以下操作:

  1. 创建角色和权限
/** @var Role $ownerRoll */
$ownerRoll = Role::create(['name' => 'Owner']);

/** @var Permission $permission */
$permission = Permission::create([
    'name' => 'Create Company','guard_name' => 'web',]);

$ownerRoll->givePermissionTo($permission);
  1. 使用拥有的用户创建新公司,然后将该公司切换为该所有者的活跃公司。
public function store(CompanyStoreRequest $request)
{
    DB::transaction(function () use($request) {
        /** @var User $owner */
        $owner = User::findOrFail($request->user_id);

        /** @var Company $company */
        $company = $owner->companies()->create($request->validated());
        $company->addTeamMember($owner);

        $owner->assignRolesForCompany($company,'Owner');
        $owner->switchCompanies($company);
    });

    return redirect()->back();
}

所有这些都有效,我主要担心的是:

  1. 我们正在覆盖can方法。可能还有其他未捕获的授权方法/门功能。

  2. 我们有2组model_permissions。 Auth用户和公司用户。我认为我需要进行一些检查,以确保仅将正确类型的用户分配给角色。在此阶段,所有管理员用户都将具有分配给其auth用户的权限,而拥有公司的任何用户都应仅对公司用户模型具有权限

fw513598031 回答:Spatie用户权限-属于许多公司,解决方案反馈

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3144396.html

大家都在问