60 lines
2.0 KiB
PHP
60 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\State;
|
|
|
|
use ApiPlatform\Metadata\Operation;
|
|
use ApiPlatform\State\ProcessorInterface;
|
|
use App\Entity\User;
|
|
use App\Service\PasswordSetupService;
|
|
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
|
|
|
|
class UserPasswordHasher implements ProcessorInterface
|
|
{
|
|
public function __construct(
|
|
private ProcessorInterface $processor,
|
|
private UserPasswordHasherInterface $passwordHasher,
|
|
private PasswordSetupService $passwordSetupService
|
|
) {
|
|
}
|
|
|
|
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
|
|
{
|
|
if (!$data instanceof User) {
|
|
return $this->processor->process($data, $operation, $uriVariables, $context);
|
|
}
|
|
|
|
$isNewUser = !$data->getId();
|
|
$hasPlainPassword = !empty($data->getPlainPassword());
|
|
|
|
// Hash plain password if provided
|
|
if ($hasPlainPassword) {
|
|
$hashedPassword = $this->passwordHasher->hashPassword(
|
|
$data,
|
|
$data->getPlainPassword()
|
|
);
|
|
$data->setPassword($hashedPassword);
|
|
$data->eraseCredentials();
|
|
} elseif ($isNewUser) {
|
|
// New user without password - set temporary random password
|
|
$tempPassword = bin2hex(random_bytes(16));
|
|
$hashedPassword = $this->passwordHasher->hashPassword($data, $tempPassword);
|
|
$data->setPassword($hashedPassword);
|
|
}
|
|
|
|
// Process the user
|
|
$result = $this->processor->process($data, $operation, $uriVariables, $context);
|
|
|
|
// Send password setup email for new users without password
|
|
if ($isNewUser && !$hasPlainPassword) {
|
|
try {
|
|
$this->passwordSetupService->sendPasswordSetupEmail($data);
|
|
} catch (\Exception $e) {
|
|
// Log error but don't fail user creation
|
|
error_log('Failed to send password setup email: ' . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
}
|