Skip to content

Commit

Permalink
fix: Update use last login using DQL to prevent optimistic lock (dvsa…
Browse files Browse the repository at this point in the history
  • Loading branch information
wadedvsa authored Apr 22, 2024
1 parent 8b8db0e commit dfa8c54
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 25 deletions.
11 changes: 3 additions & 8 deletions app/api/module/Api/src/Domain/CommandHandler/Auth/Login.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Dvsa\Olcs\Api\Domain\CommandHandler\Auth;

use DateTime;
use Dvsa\Olcs\Api\Domain\Command\Result;
use Dvsa\Olcs\Api\Domain\CommandHandler\AbstractCommandHandler;
use Dvsa\Olcs\Api\Domain\CommandHandler\Auth\Exception\UserHasNoOrganisationException;
Expand Down Expand Up @@ -125,16 +126,10 @@ public function handleCommand(CommandInterface $command): Result
return $this->result;
}

/**
* Updates the last_login_at for a given user to NOW().
*
* @return User
* @throws RuntimeException
*/
protected function updateUserLastLoginAt(User $user): User
{
$user->setLastLoginAt(new \DateTime());
$this->getRepo()->save($user);
$this->getRepo()->updateLastLogin($user, new DateTime(), $user);

return $user;
}

Expand Down
32 changes: 15 additions & 17 deletions app/api/module/Api/src/Domain/Repository/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -413,25 +413,23 @@ public function fetchUsersWithoutLastLoginTime(): \Iterator
return $qb->getQuery()->iterate();
}

/**
* @return mixed
* @throws \Exception
*/
public function updateLastLogin(Entity $user, DateTime $lastLoginAt, Entity $lastModifiedBy)
public function updateLastLogin(Entity $user, DateTime $lastLoginAt, Entity $lastModifiedBy): void
{
$qb = $this->getEntityManager()->createQueryBuilder();

$qb
->update(Entity::class, 'u')
->set('u.lastLoginAt', ':lastLoginAt')
->set('u.lastModifiedOn', ':lastModifiedOn')
->set('u.lastModifiedBy', ':lastModifiedBy')
->andWhere($qb->expr()->eq('u.id', ':id'))
->setParameter('lastLoginAt', $lastLoginAt)
->setParameter('id', $user->getId())
->setParameter('lastModifiedBy', $lastModifiedBy->getId())
->setParameter('lastModifiedOn', new DateTime());

return $qb->getQuery()->execute();
$qb->update(Entity::class, 'u')
->set('u.lastLoginAt', ':lastLoginAt')
->set('u.lastModifiedOn', ':lastModifiedOn')
->set('u.lastModifiedBy', ':lastModifiedBy')
->set('u.version', 'u.version + 1')
->where('u.id = :id')
->setParameter('id', $user->getId())
->setParameter('lastLoginAt', $lastLoginAt)
->setParameter('lastModifiedBy', $lastModifiedBy->getId())
->setParameter('lastModifiedOn', new DateTime());

$qb->getQuery()->execute();

$this->refresh($user);
}
}

0 comments on commit dfa8c54

Please sign in to comment.