Skip to content

Commit

Permalink
refactor: remove exception for already hashed
Browse files Browse the repository at this point in the history
The function will break the classic Auth::attempt method probabily
because a save will be performed on the user table
  • Loading branch information
beliven-fabrizio-gortani committed Jan 15, 2025
1 parent dd36466 commit fae4ed2
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 24 deletions.
13 changes: 0 additions & 13 deletions src/Exceptions/PasswordAlreadyHashedException.php

This file was deleted.

20 changes: 11 additions & 9 deletions src/PasswordHistory.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace Beliven\PasswordHistory;

use Beliven\PasswordHistory\Exceptions\PasswordAlreadyHashedException;
use Beliven\PasswordHistory\Exceptions\PasswordInHistoryException;
use Beliven\PasswordHistory\Models\PasswordHash;
use Illuminate\Database\Eloquent\Model;
Expand Down Expand Up @@ -43,17 +42,20 @@ public function addPasswordToHistory(Model $model, string $newPassword): ?Passwo
{
$historyDepth = config('password-history.depth');

if (Hash::isHashed($newPassword)) {
throw new PasswordAlreadyHashedException;
}
return DB::transaction(function () use ($model, $newPassword, $historyDepth) {
$isHashed = Hash::isHashed($newPassword);

if ($this->hasPasswordInHistory($model, $newPassword)) {
throw new PasswordInHistoryException;
}
if ($isHashed) {
return null;
}

return DB::transaction(function () use ($model, $newPassword, $historyDepth) {
if ($this->hasPasswordInHistory($model, $newPassword)) {
throw new PasswordInHistoryException;
}

$newPassword = Hash::make($newPassword);
$password_instance = new PasswordHash;
$password_instance->hash = Hash::make($newPassword);
$password_instance->hash = $newPassword;
$password_instance->model()->associate($model);
$password_instance->save();

Expand Down
10 changes: 8 additions & 2 deletions tests/PasswordHistoryTest.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
<?php

use Beliven\PasswordHistory\Entities\Enums\DomainErrorsEnum;
use Beliven\PasswordHistory\Exceptions\PasswordAlreadyHashedException;
use Beliven\PasswordHistory\Exceptions\PasswordInHistoryException;
use Beliven\PasswordHistory\Facades\PasswordHistory as PasswordHistoryFacade;
use Beliven\PasswordHistory\Models\PasswordHash;
Expand Down Expand Up @@ -191,7 +190,14 @@
$model->password = $passwordHash;
$model->id = 123;
$model->save();
})->throws(PasswordAlreadyHashedException::class, DomainErrorsEnum::PASSWORD_ALREADY_HASHED->message());

$this->assertDatabaseMissing('password_hashes', [
'model_type' => get_class($model),
'model_id' => $model->id,
]);

expect($model->password)->toBe($passwordHash);
});

it('should not save any history hash using null value', function () {
$model = new TestModelWithTrait;
Expand Down

0 comments on commit fae4ed2

Please sign in to comment.