Skip to content

Commit

Permalink
Refactor user account deletion to ensure hard delete and update relat…
Browse files Browse the repository at this point in the history
…ed data deletion logic
  • Loading branch information
kennedyowusu committed Jan 6, 2025
1 parent 6d5bfc4 commit dca04b7
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 33 deletions.
4 changes: 2 additions & 2 deletions app/Http/Controllers/api/v1/user/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,12 @@ public function destroy(Request $request)
'user_agent' => $request->userAgent(),
]);

// Delete related data
// Delete related data and user
DB::transaction(function () use ($user) {
$user->weightLogs()->delete();
$user->healthData()->delete();
$user->forceDelete(); // Ensure hard delete
event(new UserDeleted($user));
$user->delete();
});

return response()->json(['message' => 'User deleted successfully.'], 200);
Expand Down
43 changes: 12 additions & 31 deletions tests/Feature/UserAccountDeletionFeatureTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,37 +15,18 @@ class UserAccountDeletionFeatureTest extends TestCase
* Test authenticated user can delete their account.
*/
public function test_authenticated_user_can_delete_their_account()
{
$user = User::factory()->hasWeightLogs(3)->hasHealthData()->create();

$this->actingAs($user)
->deleteJson('/api/v1/profile')
->assertStatus(200)
->assertJson(['message' => 'User deleted successfully.']);

// Assert that the user no longer exists in the database
$this->assertDatabaseMissing('users', ['id' => $user->id]);

// Assert related data is deleted
$this->assertDatabaseMissing('weight_logs', ['user_id' => $user->id]);
$this->assertDatabaseMissing('health_data', ['user_id' => $user->id]);
}

/**
* Test unauthorized user cannot delete another user's account.
*/
public function test_user_cannot_delete_another_users_account()
{
$user = User::factory()->create();
$otherUser = User::factory()->create();

$this->actingAs($user)
->deleteJson('/api/v1/profile')
->assertStatus(403);

// Assert that the other user still exists in the database
$this->assertDatabaseHas('users', ['id' => $otherUser->id]);
}
{
$user = User::factory()->hasWeightLogs(3)->hasHealthData()->create();

$this->actingAs($user)
->deleteJson('/api/v1/profile')
->assertStatus(200)
->assertJson(['message' => 'User deleted successfully.']);

$this->assertDatabaseMissing('users', ['id' => $user->id]);
$this->assertDatabaseMissing('weight_logs', ['user_id' => $user->id]);
$this->assertDatabaseMissing('health_data', ['user_id' => $user->id]);
}

/**
* Test deletion logs are created.
Expand Down

0 comments on commit dca04b7

Please sign in to comment.