Files
many-notes/app/Livewire/Forms/ResetPasswordForm.php
T
2025-01-26 18:57:20 +00:00

89 lines
2.4 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Livewire\Forms;
use App\Models\User;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules;
use Livewire\Attributes\Locked;
use Livewire\Form;
final class ResetPasswordForm extends Form
{
#[Locked]
public string $token = '';
public string $email = '';
public string $password = '';
public string $password_confirmation = '';
/**
* @return array<string, list<mixed>>
*/
public function rules(): array
{
return [
'token' => ['required'],
'email' => ['required', 'string', 'email'],
'password' => ['required', 'string', 'confirmed', Rules\Password::defaults()],
];
}
public function setToken(string $token): void
{
$this->token = $token;
}
public function setEmail(string $email): void
{
$this->email = $email;
}
/**
* Reset the password for the given user.
*/
public function resetPassword(): bool
{
$this->validate();
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
/** @var array<string, string> $credentials */
$credentials = $this->only('email', 'password', 'password_confirmation', 'token');
/** @var string $status */
$status = Password::reset(
$credentials,
function (User $user): void {
$user->forceFill([
'password' => Hash::make($this->password),
'remember_token' => Str::random(60),
])->save();
event(new PasswordReset($user));
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
if ($status !== Password::PASSWORD_RESET) {
$this->addError('email', __($status));
return false;
}
Session::flash('status', __($status));
return true;
}
}