Implement EnsureUserHasWorkspace Trait and Integrate into Controllers… (#741)
* Implement EnsureUserHasWorkspace Trait and Integrate into Controllers and Jobs - Introduced the EnsureUserHasWorkspace trait to ensure users have at least one workspace when they are detached from a workspace. - Integrated the trait into WorkspaceUserController to enforce workspace checks during user detachment. - Updated RemoveWorkspaceGuests job to utilize the new trait for ensuring users have a workspace after detachment. - Modified UserWorkspace model to call the ensureUserHasWorkspace method upon deletion, maintaining workspace integrity. These changes enhance user management by ensuring that users always have a workspace, improving overall application stability. * Add test --------- Co-authored-by: Julien Nahum <julien@nahum.net>
This commit is contained in:
34
api/app/Traits/EnsureUserHasWorkspace.php
Normal file
34
api/app/Traits/EnsureUserHasWorkspace.php
Normal file
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Traits;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
trait EnsureUserHasWorkspace
|
||||
{
|
||||
/**
|
||||
* Ensure a user has at least one workspace.
|
||||
* If they don't, create a new workspace for them.
|
||||
*/
|
||||
protected function ensureUserHasWorkspace(User $user): void
|
||||
{
|
||||
if ($user->workspaces()->count() === 0) {
|
||||
Log::info('Creating new workspace for user with no workspaces', [
|
||||
'user_id' => $user->id,
|
||||
'user_email' => $user->email,
|
||||
]);
|
||||
|
||||
$newWorkspace = Workspace::create([
|
||||
'name' => 'My Workspace',
|
||||
]);
|
||||
|
||||
$user->workspaces()->sync([
|
||||
$newWorkspace->id => [
|
||||
'role' => 'admin',
|
||||
],
|
||||
], false);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user