Files
Verde-Web/tests/Feature/Api/V1/Auth/ChangePasswordTest.php

85 lines
3.1 KiB
PHP

<?php
namespace Tests\Feature\Api\V1\Auth;
use App\Models\User;
use Database\Seeders\RoleSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;
class ChangePasswordTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->seed(RoleSeeder::class);
}
public function test_user_can_change_password_with_correct_current(): void
{
$user = User::factory()->create([
'password' => Hash::make('OldPassword1'),
'status' => User::STATUS_ACTIVE,
]);
$token = $user->createToken('phpunit');
$response = $this->withHeader('Authorization', 'Bearer '.$token->plainTextToken)
->postJson('/api/v1/me/password', [
'current_password' => 'OldPassword1',
'password' => 'NewPassword1',
'password_confirmation' => 'NewPassword1',
]);
$response->assertOk()->assertJsonPath('data.password_changed', true);
$this->assertTrue(Hash::check('NewPassword1', $user->fresh()->password));
}
public function test_wrong_current_password_rejected(): void
{
$user = User::factory()->create(['password' => Hash::make('OldPassword1')]);
$token = $user->createToken('phpunit');
$this->withHeader('Authorization', 'Bearer '.$token->plainTextToken)
->postJson('/api/v1/me/password', [
'current_password' => 'WrongOne1',
'password' => 'NewPassword1',
'password_confirmation' => 'NewPassword1',
])->assertStatus(422);
}
public function test_new_password_must_differ_from_current(): void
{
$user = User::factory()->create(['password' => Hash::make('SamePassword1')]);
$token = $user->createToken('phpunit');
$this->withHeader('Authorization', 'Bearer '.$token->plainTextToken)
->postJson('/api/v1/me/password', [
'current_password' => 'SamePassword1',
'password' => 'SamePassword1',
'password_confirmation' => 'SamePassword1',
])->assertStatus(422);
}
public function test_change_password_revokes_other_sessions(): void
{
$user = User::factory()->create(['password' => Hash::make('OldPassword1')]);
$current = $user->createToken('current-device');
$other1 = $user->createToken('phone');
$other2 = $user->createToken('tablet');
$this->withHeader('Authorization', 'Bearer '.$current->plainTextToken)
->postJson('/api/v1/me/password', [
'current_password' => 'OldPassword1',
'password' => 'NewPassword1',
'password_confirmation' => 'NewPassword1',
])->assertOk();
$this->assertDatabaseHas('personal_access_tokens', ['id' => $current->accessToken->id]);
$this->assertDatabaseMissing('personal_access_tokens', ['id' => $other1->accessToken->id]);
$this->assertDatabaseMissing('personal_access_tokens', ['id' => $other2->accessToken->id]);
}
}