parent
69a403fd68
commit
b3fab2a4b6
4 changed files with 98 additions and 5 deletions
@ -0,0 +1,35 @@ |
||||
<?php |
||||
|
||||
namespace App\Auth; |
||||
|
||||
use Illuminate\Auth\EloquentUserProvider; |
||||
use Illuminate\Contracts\Auth\Authenticatable; |
||||
|
||||
class CustomUserProvider extends EloquentUserProvider |
||||
{ |
||||
public function validateCredentials(Authenticatable $user, array $credentials): bool |
||||
{ |
||||
$plain = $credentials['password']; |
||||
$hashed = $user->getAuthPassword(); |
||||
|
||||
if ($this->isBcryptHash($hashed)) { |
||||
if ($this->hasher->check($plain, $hashed)) { |
||||
return true; |
||||
} |
||||
} else { |
||||
if (md5($plain) === $hashed) { |
||||
// Upgrade lên bcrypt |
||||
$user->password = $this->hasher->make($plain); |
||||
$user->save(); |
||||
return true; |
||||
} |
||||
} |
||||
|
||||
return false; |
||||
} |
||||
|
||||
protected function isBcryptHash($hashedPassword): bool |
||||
{ |
||||
return password_get_info($hashedPassword)['algo'] === PASSWORD_BCRYPT; |
||||
} |
||||
} |
@ -0,0 +1,49 @@ |
||||
<?php |
||||
|
||||
namespace App\Auth; |
||||
|
||||
use Laravel\Passport\Bridge\UserRepository; |
||||
use League\OAuth2\Server\Entities\ClientEntityInterface; |
||||
use Laravel\Passport\Bridge\User; |
||||
use Illuminate\Support\Facades\Hash; |
||||
use App\Models\User as UserModel; |
||||
|
||||
class PassportUserRepository extends UserRepository |
||||
{ |
||||
public function getUserEntityByUserCredentials( |
||||
$username, |
||||
$password, |
||||
$grantType, |
||||
ClientEntityInterface $clientEntity |
||||
) { |
||||
$user = UserModel::where('email', $username)->first(); |
||||
|
||||
if (!$user) { |
||||
return null; |
||||
} |
||||
|
||||
// Tránh lỗi Hash::check() với MD5 |
||||
if ($this->isBcryptHash($user->password)) { |
||||
if (Hash::check($password, $user->password)) { |
||||
return new User($user->id); |
||||
} |
||||
} else { |
||||
// Hash không phải bcrypt, kiểm tra MD5 thủ công |
||||
if (md5($password) === $user->password) { |
||||
// Nâng cấp mật khẩu lên bcrypt |
||||
$user->password = Hash::make($password); |
||||
$user->save(); |
||||
|
||||
return new User($user->id); |
||||
} |
||||
} |
||||
|
||||
return null; |
||||
} |
||||
|
||||
// Thêm method kiểm tra thuật toán hash |
||||
protected function isBcryptHash($hashedPassword): bool |
||||
{ |
||||
return password_get_info($hashedPassword)['algo'] === PASSWORD_BCRYPT; |
||||
} |
||||
} |
Loading…
Reference in new issue