feat: implement multi-tenancy and super admin impersonation with security banner
This commit is contained in:
45
app/Traits/BelongsToStructure.php
Normal file
45
app/Traits/BelongsToStructure.php
Normal file
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Traits;
|
||||
|
||||
use App\Models\Structure;
|
||||
use App\Models\Scopes\StructureScope;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
trait BelongsToStructure
|
||||
{
|
||||
/**
|
||||
* Boot the trait to apply the GlobalScope.
|
||||
*/
|
||||
protected static function bootBelongsToStructure()
|
||||
{
|
||||
static::addGlobalScope('structure', function (Builder $builder) {
|
||||
// On utilise la configuration injectée par le middleware plutôt que d'appeler auth()->user()
|
||||
// Cela évite la boucle infinie d'authentification lorsque le scope s'applique à la table `users`.
|
||||
$structureId = config('tenant.structure_id');
|
||||
if ($structureId !== null) {
|
||||
// Dans le cas spécifique de SQLite en mode de test, il faut parfois préciser la table.
|
||||
// Par sécurité on gère la jointure si besoin, mas ici on reste simple.
|
||||
$builder->where($builder->getModel()->getTable() . '.structure_id', $structureId);
|
||||
}
|
||||
});
|
||||
|
||||
static::creating(function ($model) {
|
||||
// Assigner automatiquement la structure_id sur les nouveaux enregistrements
|
||||
if (!$model->structure_id) {
|
||||
$structureId = config('tenant.structure_id');
|
||||
if ($structureId) {
|
||||
$model->structure_id = $structureId;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Define the relationship to Structure.
|
||||
*/
|
||||
public function structure()
|
||||
{
|
||||
return $this->belongsTo(Structure::class);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user