2019-07-30 15:12:31 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Models\Concerns;
|
|
|
|
|
|
|
|
use App\Events\EncryptUserPassword;
|
2019-12-14 11:10:37 +08:00
|
|
|
use Illuminate\Support\Arr;
|
2019-07-30 15:12:31 +08:00
|
|
|
|
|
|
|
trait HasPassword
|
|
|
|
{
|
2020-05-11 11:17:00 +08:00
|
|
|
public function verifyPassword(string $raw)
|
2019-07-30 15:12:31 +08:00
|
|
|
{
|
|
|
|
// Compare directly if any responses is returned by event dispatcher
|
|
|
|
if ($result = $this->getEncryptedPwdFromEvent($raw, $this)) {
|
|
|
|
return hash_equals($this->password, $result); // @codeCoverageIgnore
|
|
|
|
}
|
|
|
|
|
|
|
|
return app('cipher')->verify($raw, $this->password, config('secure.salt'));
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Try to get encrypted password from event dispatcher.
|
|
|
|
*/
|
2020-05-11 11:17:00 +08:00
|
|
|
public function getEncryptedPwdFromEvent(string $raw)
|
2019-07-30 15:12:31 +08:00
|
|
|
{
|
|
|
|
$responses = event(new EncryptUserPassword($raw, $this));
|
2019-08-15 23:27:29 +08:00
|
|
|
|
2019-07-30 15:12:31 +08:00
|
|
|
return Arr::get($responses, 0);
|
|
|
|
}
|
|
|
|
|
2020-05-11 11:17:00 +08:00
|
|
|
public function changePassword(string $password): bool
|
2019-07-30 15:12:31 +08:00
|
|
|
{
|
|
|
|
$responses = event(new EncryptUserPassword($password, $this));
|
2019-12-13 10:56:16 +08:00
|
|
|
$hash = Arr::get($responses, 0);
|
|
|
|
if (empty($hash)) {
|
|
|
|
$hash = app('cipher')->hash($password, config('secure.salt'));
|
|
|
|
}
|
|
|
|
$this->password = $hash;
|
2019-08-15 23:27:29 +08:00
|
|
|
|
2019-07-30 15:12:31 +08:00
|
|
|
return $this->save();
|
|
|
|
}
|
|
|
|
}
|