Skip to content

Open-source event management and ticket selling platform — perfect for concerts, conferences, and everything in between 🎟️ If you find this project helpful, please consider giving us a star ⭐️

Feature: Adds test for login, logout, forgot-password and reset-password (#544)

Jakob3e4a4f53ffe9
diff --git a/backend/app/Http/Actions/Accounts/CreateAccountAction.php b/backend/app/Http/Actions/Accounts/CreateAccountAction.php
index f5c6fbda0..4804fb663 100644
--- a/backend/app/Http/Actions/Accounts/CreateAccountAction.php
+++ b/backend/app/Http/Actions/Accounts/CreateAccountAction.php
@@ -17,6 +17,7 @@ use HiEvents\Services\Application\Handlers\Account\Exceptions\AccountRegistratio
use HiEvents\Services\Application\Handlers\Auth\DTO\LoginCredentialsDTO;
use HiEvents\Services\Application\Handlers\Auth\LoginHandler;
use HiEvents\Services\Application\Locale\LocaleService;
+use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;
use Throwable;
@@ -54,6 +55,10 @@ class CreateAccountAction extends BaseAuthAction
throw ValidationException::withMessages([
'email' => $e->getMessage(),
]);
+ } catch (DecryptException $e) {
+ throw ValidationException::withMessages([
+ 'invite_token' => __('Invalid invite token'),
+ ]);
} catch (AccountRegistrationDisabledException) {
return $this->errorResponse(
message: __('Account registration is disabled'),
diff --git a/backend/app/Http/Actions/Auth/ResetPasswordAction.php b/backend/app/Http/Actions/Auth/ResetPasswordAction.php
index 6e7b25d89..583e7bfa7 100644
--- a/backend/app/Http/Actions/Auth/ResetPasswordAction.php
+++ b/backend/app/Http/Actions/Auth/ResetPasswordAction.php
@@ -2,6 +2,7 @@
namespace HiEvents\Http\Actions\Auth;
+use HiEvents\Exceptions\InvalidPasswordResetTokenException;
use HiEvents\Exceptions\PasswordInvalidException;
use HiEvents\Http\Actions\BaseAction;
use HiEvents\Http\Request\Auth\ResetPasswordRequest;
@@ -37,6 +38,8 @@ class ResetPasswordAction extends BaseAction
throw ValidationException::withMessages([
'current_password' => $exception->getMessage(),
]);
+ } catch (InvalidPasswordResetTokenException $e) {
+ throw new ResourceNotFoundException($e->getMessage());
}
return $this->jsonResponse(
diff --git a/backend/app/Models/Account.php b/backend/app/Models/Account.php
index 729c3edde..1baed3b12 100644
--- a/backend/app/Models/Account.php
+++ b/backend/app/Models/Account.php
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace HiEvents\Models;
use HiEvents\DomainObjects\Enums\Role;
+use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
@@ -12,6 +13,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
class Account extends BaseModel
{
use SoftDeletes;
+ use HasFactory;
public function users(): BelongsToMany
{
diff --git a/backend/app/Models/User.php b/backend/app/Models/User.php
index 2165e3603..688f5fb07 100644
--- a/backend/app/Models/User.php
+++ b/backend/app/Models/User.php
@@ -10,6 +10,7 @@ use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
+use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\HasOneThrough;
@@ -27,6 +28,7 @@ class User extends BaseModel implements AuthenticatableContract, AuthorizableCon
use Authorizable;
use CanResetPassword;
use MustVerifyEmail;
+ use HasFactory;
/** @var array */
protected $guarded = [];
diff --git a/backend/app/Services/Application/Handlers/Auth/ForgotPasswordHandler.php b/backend/app/Services/Application/Handlers/Auth/ForgotPasswordHandler.php
index 10ec0f793..159b172a5 100644
--- a/backend/app/Services/Application/Handlers/Auth/ForgotPasswordHandler.php
+++ b/backend/app/Services/Application/Handlers/Auth/ForgotPasswordHandler.php
@@ -8,7 +8,7 @@ use HiEvents\Repository\Interfaces\PasswordResetTokenRepositoryInterface;
use HiEvents\Repository\Interfaces\UserRepositoryInterface;
use HiEvents\Services\Infrastructure\TokenGenerator\TokenGeneratorService;
use Illuminate\Database\DatabaseManager;
-use Illuminate\Mail\Mailer;
+use Illuminate\Contracts\Mail\Mailer;
use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Throwable;
diff --git a/backend/app/Services/Application/Handlers/Auth/ResetPasswordHandler.php b/backend/app/Services/Application/Handlers/Auth/ResetPasswordHandler.php
index bd9a84d57..fd0c8f782 100644
--- a/backend/app/Services/Application/Handlers/Auth/ResetPasswordHandler.php
+++ b/backend/app/Services/Application/Handlers/Auth/ResetPasswordHandler.php
@@ -3,14 +3,15 @@
namespace HiEvents\Services\Application\Handlers\Auth;
use HiEvents\DomainObjects\UserDomainObject;
+use HiEvents\Exceptions\PasswordInvalidException;
use HiEvents\Mail\User\ResetPasswordSuccess;
use HiEvents\Repository\Interfaces\PasswordResetTokenRepositoryInterface;
use HiEvents\Repository\Interfaces\UserRepositoryInterface;
use HiEvents\Services\Application\Handlers\Auth\DTO\ResetPasswordDTO;
use HiEvents\Services\Domain\Auth\ResetPasswordTokenValidateService;
+use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Database\DatabaseManager;
use Illuminate\Hashing\HashManager;
-use Illuminate\Mail\Mailer;
use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Throwable;
@@ -38,6 +39,10 @@ class ResetPasswordHandler
$resetToken = $this->passwordTokenValidateService->validateAndFetchToken($resetPasswordData->token);
$user = $this->validateUser($resetToken->getEmail());
+ if ($this->checkNewPasswordIsOldPassword($user, $resetPasswordData->password)) {
+ throw new PasswordInvalidException(__('New password must be different from the old password.'));
+ }
+
$this->resetUserPassword($user->getId(), $resetPasswordData->password);
$this->deleteResetToken($resetToken->getEmail());
$this->logResetPasswordSuccess($user);
@@ -45,6 +50,11 @@ class ResetPasswordHandler
});
}
+ private function checkNewPasswordIsOldPassword(UserDomainObject $user, string $newPassword): bool
+ {
+ return $this->hashManager->check($newPassword, $user->getPassword());
+ }
+
private function validateUser(string $email): UserDomainObject
{
$user = $this->userRepository->findFirstWhere(['email' => $email]);
@@ -72,7 +82,7 @@ class ResetPasswordHandler
$this->passwordResetTokenRepository->deleteWhere(['email' => $email]);
}
- private function logResetPasswordSuccess($user): void
+ private function logResetPasswordSuccess(UserDomainObject $user): void
{
$this->logger->info('Password reset successfully', [
'user_id' => $user->getId(),
diff --git a/backend/database/factories/AccountFactory.php b/backend/database/factories/AccountFactory.php
new file mode 100644
index 000000000..2968b4325
--- /dev/null
+++ b/backend/database/factories/AccountFactory.php
@@ -0,0 +1,73 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Database\Factories;
+
+use HiEvents\Helper\IdHelper;
+use Illuminate\Database\Eloquent\Factories\Factory;
+
+/**
+ * @extends \Illuminate\Database\Eloquent\Factories\Factory<\HiEvents\Models\Account>
+ */
+class AccountFactory extends Factory
+{
+ /**
+ * Define the model's default state.
+ *
+ * @return array<string, mixed>
+ */
+ public function definition(): array
+ {
+ $currencies = include base_path('data/currencies.php');
+
+ return [
+ 'name' => fake()->name(),
+ 'email' => fake()->unique()->safeEmail(),
+ 'timezone' => fake()->timezone(),
+ 'currency_code' => fake()->randomElement(array_values($currencies)),
+ 'short_id' => IdHelper::shortId(IdHelper::ACCOUNT_PREFIX),
+ 'account_configuration_id' => 1, // Default account configuration is first entry
+ ];
+ }
+
+ /**
+ * Indicate that the model's stripe account id is set.
+ */
+ public function stripeAccount(): self
+ {
+ return $this->state(fn(array $attributes) => [
+ 'stripe_account_id' => fake()->stripeConnectAccountId(),
+ ]);
+ }
+
+ /**
+ * Indicate that the model's stripe account connection setup is complete.
+ */
+ public function stripeConnectSetupComplete(bool $isComplete = true): self
+ {
+ return $this->state(fn(array $attributes) => [
+ 'stripe_connect_setup_complete' => $isComplete,
+ ]);
+ }
+
+ /**
+ * Indicate that the model is verified.
+ */
+ public function verified(): self
+ {
+ return $this->state(fn(array $attributes) => [
+ 'account_verified_at' => now(),
+ ]);
+ }
+
+ /**
+ * Indicate that the model has been manually verified.
+ */
+ public function manuallyVerified(): self
+ {
+ return $this->state(fn(array $attributes) => [
+ 'is_manually_verified' => true,
+ ]);
+ }
+}
diff --git a/backend/database/factories/UserFactory.php b/backend/database/factories/UserFactory.php
index 3bf15dfe8..849bc48d5 100644
--- a/backend/database/factories/UserFactory.php
+++ b/backend/database/factories/UserFactory.php
@@ -1,9 +1,16 @@
-x<?php
+<?php
+
+declare(strict_types=1);
namespace Database\Factories;
+use HiEvents\DomainObjects\Enums\Role;
+use HiEvents\DomainObjects\Status\UserStatus;
+use HiEvents\Locale;
+use HiEvents\Models\Account;
+use HiEvents\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
-use Illuminate\Support\Str;
+use Illuminate\Support\Facades\Hash;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\HiEvents\Core\Models\User>
@@ -18,21 +25,59 @@ class UserFactory extends Factory
public function definition(): array
{
return [
- 'name' => fake()->name(),
+ 'first_name' => fake()->firstName(),
+ 'last_name' => fake()->lastName(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
- 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
- 'remember_token' => Str::random(10),
+ 'password' => Hash::make(fake()->password(16)),
+ 'timezone' => fake()->timezone(),
+ 'locale' => fake()->randomElement(Locale::getSupportedLocales()),
];
}
+ public function pendingEmail(?string $email = null): self
+ {
+ return $this->state(fn(array $attributes) => [
+ 'pending_email' => $email ?? fake()->unique()->safeEmail(),
+ ]);
+ }
+
+ /**
+ * Set the user's password.
+ */
+ public function password(string $password): static
+ {
+ return $this->state(fn(array $attributes) => [
+ 'password' => Hash::make($password),
+ ]);
+ }
+
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
- return $this->state(fn (array $attributes) => [
+ return $this->state(fn(array $attributes) => [
'email_verified_at' => null,
]);
}
+
+ /**
+ * Saves an Account to the database and attaches it to the user.
+ */
+ public function withAccount(): static
+ {
+ return $this->afterCreating(function (User $user): void {
+ $account = Account::factory()->verified()->create();
+ $account->timezone = $user->timezone;
+ $account->name = $user->first_name . ($user->last_name ? ' ' . $user->last_name : '');
+ $account->email = strtolower($user->email);
+
+ $user->accounts()->attach($account, [
+ 'role' => Role::ADMIN,
+ 'status' => UserStatus::ACTIVE,
+ 'is_account_owner' => true,
+ ]);
+ });
+ }
}
diff --git a/backend/tests/Feature/Auth/LoginTest.php b/backend/tests/Feature/Auth/LoginTest.php
new file mode 100644
index 000000000..ee7ce5feb
--- /dev/null
+++ b/backend/tests/Feature/Auth/LoginTest.php
@@ -0,0 +1,95 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Tests\Feature;
+
+use Illuminate\Foundation\Testing\DatabaseTruncation;
+use HiEvents\Models\AccountConfiguration;
+use HiEvents\Models\User;
+use Tests\TestCase;
+
+class LoginTest extends TestCase
+{
+ use DatabaseTruncation;
+
+ private const API_PREFIX = '';
+ private const LOGIN_ROUTE = self::API_PREFIX . '/auth/login';
+ private const LOGOUT_ROUTE = self::API_PREFIX . '/auth/logout';
+ private const USERS_ME_ROUTE = self::API_PREFIX . '/users/me';
+
+ public function setUp(): void
+ {
+ parent::setUp();
+ AccountConfiguration::firstOrCreate(['id' => 1], [
+ 'id' => 1,
+ 'name' => 'Default',
+ 'is_system_default' => true,
+ 'application_fees' => json_encode(['percentage' => 1.5, 'fixed' => 0]),
+ ]);
+ }
+
+ public function test_login_with_valid_credentials(): void
+ {
+ $password = fake()->password(16);
+ $user = User::factory()->password($password)->withAccount()->create();
+
+ $response = $this->postJson(self::LOGIN_ROUTE, [
+ 'email' => $user->email,
+ 'password' => $password,
+ ]);
+
+ $response->assertCookie('token');
+ $response->assertHeader('X-Auth-Token');
+ $response->assertJsonStructure([
+ 'token',
+ 'token_type',
+ 'expires_in',
+ 'user',
+ 'accounts'
+ ]);
+
+ // removes warning "This test did not perform any assertions"
+ $this->assertTrue(true);
+ }
+
+ public function test_login_with_invalid_credentials(): void
+ {
+ $password = fake()->password(16);
+ $user = User::factory()->password($password)->withAccount()->create();
+
+ $response = $this->postJson(self::LOGIN_ROUTE, [
+ 'email' => $user->email,
+ 'password' => 'invalid_password',
+ ]);
+
+ $response->assertStatus(401);
+ $response->assertCookieMissing('token');
+ $response->assertHeaderMissing('X-Auth-Token');
+ }
+
+
+ public function test_logout(): void
+ {
+ $password = fake()->password(16);
+ $user = User::factory()->password($password)->withAccount()->create();
+
+ $response = $this->postJson(self::LOGIN_ROUTE, [
+ 'email' => $user->email,
+ 'password' => $password,
+ ]);
+ $response->assertCookie('token');
+
+ $response2 = $this->postJson(self::LOGOUT_ROUTE, [], [
+ 'Authorization' => 'Bearer ' . $response->headers->get('X-Auth-Token'),
+ ]);
+ $response2->assertStatus(200);
+ $response2->assertCookieExpired('token');
+
+ // try to use the expired token
+ $response3 = $this->getJson(self::USERS_ME_ROUTE, [
+ 'Authorization' => 'Bearer ' . $response->headers->get('X-Auth-Token'),
+ ]);
+ $response3->assertStatus(401);
+ }
+}
diff --git a/backend/tests/Feature/Auth/RegisterTest.php b/backend/tests/Feature/Auth/RegisterTest.php
new file mode 100644
index 000000000..cd7e4fa81
--- /dev/null
+++ b/backend/tests/Feature/Auth/RegisterTest.php
@@ -0,0 +1,165 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Tests\Feature;
+
+use HiEvents\Models\Account;
+use HiEvents\Models\AccountConfiguration;
+use HiEvents\Models\User;
+use Illuminate\Foundation\Testing\DatabaseTruncation;
+use Illuminate\Support\Facades\Config;
+use Tests\TestCase;
+
+class RegisterTest extends TestCase
+{
+ use DatabaseTruncation;
+
+ private const API_PREFIX = '';
+ private const REGISTER_ROUTE = self::API_PREFIX . '/auth/register';
+
+ public function setUp(): void
+ {
+ parent::setUp();
+ AccountConfiguration::firstOrCreate(['id' => 1], [
+ 'id' => 1,
+ 'name' => 'Default',
+ 'is_system_default' => true,
+ 'application_fees' => json_encode(['percentage' => 1.5, 'fixed' => 0]),
+ ]);
+ }
+
+ public function test_register_user(): void
+ {
+ $password = fake()->password(16);
+ $user = User::factory()->password($password)->make([
+ 'email' => fake()->unique()->safeEmail()
+ ]);
+ $account = Account::factory()->make();
+
+ Config::set('app.disable_registration', false);
+
+ $response = $this->post(self::REGISTER_ROUTE, [
+ 'first_name' => $user->first_name,
+ 'last_name' => $user->last_name,
+ 'email' => $user->email,
+ 'password' => $password,
+ 'password_confirmation' => $password,
+ 'timezone' => $user->timezone,
+ 'currency_code' => $account->currency_code,
+ 'locale' => $user->locale,
+ 'invite_token' => null,
+ ]);
+
+ $response->assertStatus(201);
+
+ $userFromDB = User::where('email', $user->email)->first();
+ $accountFromDB = Account::where('email', $user->email)->first();
+
+ $this->assertNotNull($userFromDB);
+ $this->assertNotNull($accountFromDB);
+
+ $this->assertDatabaseHas('account_users', [
+ 'account_id' => $accountFromDB->id,
+ 'user_id' => $userFromDB->id,
+ ]);
+
+ // registered user got logged in
+ $response->assertCookie('token');
+ $response->assertHeader('X-Auth-Token');
+ }
+
+ public function test_registration_disabled(): void
+ {
+ $password = fake()->password(16);
+ $user = User::factory()->make();
+ $account = Account::factory()->make();
+
+ Config::set('app.disable_registration', true);
+
+ $response = $this->post(self::REGISTER_ROUTE, [
+ 'first_name' => $user->first_name,
+ 'last_name' => $user->last_name,
+ 'email' => $user->email,
+ 'password' => $password,
+ 'password_confirmation' => $password,
+ 'timezone' => $user->timezone,
+ 'currency_code' => $account->currency_code,
+ 'locale' => $user->locale,
+ 'invite_token' => null,
+ ]);
+
+ $response->assertStatus(403);
+ }
+
+ public function test_register_user_with_duplicate_data(): void
+ {
+ $user = User::factory()->make();
+ $account = Account::factory()->make();
+ $password = fake()->password(16);
+ $data = [
+ 'first_name' => $user->first_name,
+ 'last_name' => $user->last_name,
+ 'email' => $user->email,
+ 'password' => $password,
+ 'password_confirmation' => $password,
+ 'timezone' => $user->timezone,
+ 'currency_code' => $account->currency_code,
+ 'locale' => $user->locale,
+ 'invite_token' => null,
+ ];
+
+ Config::set('app.disable_registration', false);
+
+ $response = $this->post(self::REGISTER_ROUTE, $data);
+ $response->assertStatus(201);
+
+ $this->refreshApplication();
+ Config::set('app.disable_registration', false);
+
+ $response2 = $this->post(self::REGISTER_ROUTE, $data, ['Accept' => 'application/json']);
+ $response2->assertJsonValidationErrors(['email']);
+ }
+
+ public function test_register_user_with_invalid_data(): void
+ {
+ $user = User::factory()->make();
+ $account = Account::factory()->make();
+ $password = fake()->password(16);
+ $data = [
+ 'first_name' => $user->first_name,
+ 'last_name' => $user->last_name,
+ 'email' => $user->email,
+ 'password' => $password,
+ 'password_confirmation' => $password,
+ 'timezone' => $user->timezone,
+ 'currency_code' => $account->currency_code,
+ 'locale' => $user->locale,
+ ];
+ Config::set('app.disable_registration', false);
+
+ // valid currency code but not supported by application (north corean won)
+ $response = $this->post(
+ self::REGISTER_ROUTE,
+ [...$data, 'currency_code' => 'KPW'],
+ ['Accept' => 'application/json']
+ );
+ $response->assertJsonValidationErrors(['currency_code']);
+
+ // valid locale but not supported by application (tigriyna)
+ $response = $this->post(
+ self::REGISTER_ROUTE,
+ [...$data, 'locale' => 'ti_ER'],
+ ['Accept' => 'application/json']
+ );
+ $response->assertJsonValidationErrors(['locale']);
+
+ // invalid invite_token
+ $response = $this->post(
+ self::REGISTER_ROUTE,
+ [...$data, 'invite_token' => 'aaaaaa'],
+ ['Accept' => 'application/json']
+ );
+ $response->assertJsonValidationErrors(['invite_token']);
+ }
+}
diff --git a/backend/tests/Feature/Auth/ResetPasswordTest.php b/backend/tests/Feature/Auth/ResetPasswordTest.php
new file mode 100644
index 000000000..23c49b3d1
--- /dev/null
+++ b/backend/tests/Feature/Auth/ResetPasswordTest.php
@@ -0,0 +1,152 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Tests\Feature;
+
+use HiEvents\Mail\User\ForgotPassword;
+use HiEvents\Mail\User\ResetPasswordSuccess;
+use HiEvents\Models\AccountConfiguration;
+use HiEvents\Models\User;
+use Illuminate\Foundation\Testing\DatabaseTruncation;
+use Illuminate\Support\Facades\Mail;
+use ReflectionClass;
+use Tests\TestCase;
+
+class ResetPasswordTest extends TestCase
+{
+ use DatabaseTruncation;
+
+ private const API_PREFIX = '';
+ private const RESET_PASSWORD_ROUTE = self::API_PREFIX . '/auth/reset-password';
+ private const FORGOT_PASSWORD_ROUTE = self::API_PREFIX . '/auth/forgot-password';
+
+ public function setUp(): void
+ {
+ parent::setUp();
+ AccountConfiguration::firstOrCreate(['id' => 1], [
+ 'id' => 1,
+ 'name' => 'Default',
+ 'is_system_default' => true,
+ 'application_fees' => json_encode(['percentage' => 1.5, 'fixed' => 0]),
+ ]);
+ }
+
+ public function test_forgot_password_with_valid_email(): void
+ {
+ $user = User::factory()->withAccount()->create();
+ Mail::fake();
+
+ $response = $this->postJson(self::FORGOT_PASSWORD_ROUTE, [
+ 'email' => $user->email,
+ ]);
+
+ $response->assertStatus(200);
+ Mail::assertQueued(ForgotPassword::class, function ($mail) use ($user) {
+ return $mail->hasTo($user->email);
+ });
+ }
+
+ public function test_forgot_password_with_invalid_email(): void
+ {
+ User::factory()->withAccount()->create();
+ Mail::fake();
+
+ $response = $this->postJson(self::FORGOT_PASSWORD_ROUTE, [
+ 'email' => '[email protected]',
+ ]);
+
+ $response->assertStatus(200);
+ Mail::assertNotSent(ForgotPassword::class);
+ }
+
+ public function test_reset_password_with_valid_token(): void
+ {
+ $user = User::factory()->withAccount()->create();
+ Mail::fake();
+
+ $response = $this->postJson(self::FORGOT_PASSWORD_ROUTE, [
+ 'email' => $user->email,
+ ]);
+ $response->assertStatus(200);
+
+ $mails = Mail::queued(ForgotPassword::class);
+ $this->assertNotEmpty($mails);
+ /** @var ForgotPassword $email */
+ $email = $mails->last();
+
+ // extract the token from the email
+ $reflection = new ReflectionClass($email);
+ $tokenProperty = $reflection->getProperty('token');
+ $tokenProperty->setAccessible(true);
+ $token = $tokenProperty->getValue($email);
+
+ $response2 = $this->getJson(self::RESET_PASSWORD_ROUTE . '/' . urlencode($token));
+ // assert token is valid
+ $response2->assertStatus(204);
+
+ $password = fake()->password(16);
+ $response3 = $this->postJson(self::RESET_PASSWORD_ROUTE . '/' . urlencode($token), [
+ 'password' => $password,
+ 'password_confirmation' => $password,
+ ]);
+ $response3->assertStatus(200);
+
+ Mail::assertQueued(ResetPasswordSuccess::class);
+ }
+
+ public function test_reset_password_with_invalid_token(): void
+ {
+ $user = User::factory()->withAccount()->create();
+ Mail::fake();
+
+ // create a token in database
+ $response = $this->postJson(self::FORGOT_PASSWORD_ROUTE, [
+ 'email' => $user->email,
+ ]);
+ $response->assertStatus(200);
+
+ $response2 = $this->getJson(self::RESET_PASSWORD_ROUTE . '/' . 'invalid_token');
+ $response2->assertStatus(404);
+
+ $password = fake()->password(16);
+
+ $response3 = $this->postJson(self::RESET_PASSWORD_ROUTE . '/' . 'invalid_token', [
+ 'password' => $password,
+ 'password_confirmation' => $password,
+ ]);
+ $response3->assertStatus(404);
+
+ Mail::assertNotQueued(ResetPasswordSuccess::class);
+ }
+
+ public function test_reset_password_with_old_password(): void
+ {
+ $password = fake()->password(16);
+ $user = User::factory()->password($password)->withAccount()->create();
+ Mail::fake();
+
+ $response = $this->postJson(self::FORGOT_PASSWORD_ROUTE, [
+ 'email' => $user->email,
+ ]);
+ $response->assertStatus(200);
+
+ $mails = Mail::queued(ForgotPassword::class);
+ $this->assertNotEmpty($mails);
+ /** @var ForgotPassword $email */
+ $email = $mails->last();
+
+ // extract the token from the email
+ $reflection = new ReflectionClass($email);
+ $tokenProperty = $reflection->getProperty('token');
+ $tokenProperty->setAccessible(true);
+ $token = $tokenProperty->getValue($email);
+
+ $response2 = $this->postJson(self::RESET_PASSWORD_ROUTE . '/' . urlencode($token), [
+ 'password' => $password,
+ 'password_confirmation' => $password,
+ ]);
+
+ $response2->assertJsonValidationErrors('current_password');
+ }
+}