From a4f2dcf7fd404491f6094f10f9e43adc465dd512 Mon Sep 17 00:00:00 2001 From: "Harry (hjbdev)" Date: Thu, 27 Mar 2025 13:40:25 +0000 Subject: [PATCH] profile test passes now --- .../Controllers/Settings/ProfileController.php | 8 ++++++++ app/Models/User.php | 9 ++++++++- tests/Feature/Settings/ProfileUpdateTest.php | 18 ++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/app/Http/Controllers/Settings/ProfileController.php b/app/Http/Controllers/Settings/ProfileController.php index 10f3d22..489249e 100644 --- a/app/Http/Controllers/Settings/ProfileController.php +++ b/app/Http/Controllers/Settings/ProfileController.php @@ -51,6 +51,14 @@ class ProfileController extends Controller $user = $request->user(); + if ($user->ownedOrganisations()->count()) { + return back()->withErrors(['password' => __('You must delete or transfer your organisations before you can delete your account.')]); + } + + if ($user->organisations()->count()) { + return back()->withErrors(['password' => __('You must leave your organisations before you can delete your account.')]); + } + Auth::logout(); $user->delete(); diff --git a/app/Models/User.php b/app/Models/User.php index e90897d..a409714 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -6,6 +6,8 @@ namespace App\Models; use App\Enums\OrganisationRole; use Illuminate\Database\Eloquent\Factories\HasFactory; +use Illuminate\Database\Eloquent\Relations\BelongsToMany; +use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; @@ -47,7 +49,12 @@ class User extends Authenticatable ]; } - public function organisations() + public function ownedOrganisations(): HasMany + { + return $this->hasMany(Organisation::class, 'owner_id'); + } + + public function organisations(): BelongsToMany { return $this->belongsToMany(Organisation::class) ->withPivot('role') diff --git a/tests/Feature/Settings/ProfileUpdateTest.php b/tests/Feature/Settings/ProfileUpdateTest.php index cdf17c2..500271c 100644 --- a/tests/Feature/Settings/ProfileUpdateTest.php +++ b/tests/Feature/Settings/ProfileUpdateTest.php @@ -50,9 +50,27 @@ test('email verification status is unchanged when the email address is unchanged expect($user->refresh()->email_verified_at)->not->toBeNull(); }); +test('user is prevented from deleting their account if they own organisations', function () { + $user = User::factory()->create(); + + $response = $this + ->actingAs($user) + ->delete('/settings/profile', [ + 'password' => 'password', + ]); + + $response + ->assertSessionHasErrors('password'); + + expect($user->fresh())->not->toBeNull(); +}); + test('user can delete their account', function () { $user = User::factory()->create(); + $user->ownedOrganisations()->delete(); + $user->organisations()->delete(); + $response = $this ->actingAs($user) ->delete('/settings/profile', [