I have Token entity that store api_key
and have one-to-one relation to User entity :
AppBundle\Entity\Token:
type: entity
table: null
oneToOne:
user:
targetEntity: User
id:
id:
type: integer
id: true
generator:
strategy: AUTO
fields:
apiKey:
type: string
length: 255
dateCreated:
type: datetime
column: date_created
dateExpired:
type: datetime
column: date_expired
I'm using simple_preauth
listener for login. When login is successful, I call TokenGenerator service on my login page:
public function loginAction()
{
$user = $this->get('security.token_storage')->getToken()->getUser();
if ($user instanceof User) {
$apiKey = $this->get('app_bundle.token_generator')->createApiKey()->getApiKey();
return new Response($apiKey);
}
throw new AuthenticationException('Authentication failed');
}
TokenGenerator returns api key, that I can use for authentication on another pages. But also this service save api_key
into Token table:
use Doctrine\ORM\EntityRepository as TokenRepository;
use Doctrine\ORM\EntityManager;
use AppBundle\Entity\Token;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class TokenGenerator
{
private $user;
public function __construct(
EntityManager $em,
TokenRepository $tokenRepository,
TokenStorageInterface $tokenStorage
) {
$this->em = $em;
$this->tokenRepository = $tokenRepository;
$this->tokenStorage = $tokenStorage;
}
public function getApiKey()
{
return $this->apiKey;
}
public function createApiKey()
{
$this->apiKey = password_hash(
uniqid(mt_rand(), true), PASSWORD_DEFAULT, array('cost' => '10')
);
$this->user = $this->tokenStorage->getToken()->getUser();
$currentApiKey = $this->tokenRepository->findOneBy(array('user' => $this->user));
if ($currentApiKey) {
$this->em->remove($currentApiKey);
$this->em->flush();
}
$this->saveApiKey();
return $this;
}
private function saveApiKey()
{
$token = new Token();
$dateCreated = new \DateTime("now");
$dateExpired = new \DateTime($dateCreated->format("Y/m/d H:i:s") . "+1 day");
$token->setApiKey($this->apiKey);
$token->setDateCreated($dateCreated);
$token->setDateExpired($dateExpired);
$token->setUser($this->user);
$this->em->persist($token);
$this->em->flush();
}
}
But when I call $this->saveApiKey()
I have strange bug: my User password
in database become empty.
When I debugged this issue, I notice, that salt
not recreated after password
disappearing.
I also tried to remove one-to-one relation, (update db and clear cache, of course), but even Token table has no relation to User, I got changing password
to empty after saving Token to db.
When $this->saveApiKey()
not call, all is OK.
Please, help me to catch this weird bug. Thanks a lot for any help!