<?php
namespace Platform\SecurityBundle\Doctrine\Login;
use Cms\CoreBundle\Model\Search\SearchableTrait;
use Cms\CoreBundle\Util\DateTimeUtils;
use Cms\CoreBundle\Util\Doctrine\EntityRepository;
use Cms\TenantBundle\Entity\Tenant;
use DateTime;
use Platform\SecurityBundle\Entity\Login\Attempt;
/**
* Class AttemptRepository
*
* @package Platform\SecurityBundle\Doctrine\Login
*
* @method Attempt findExact($id);
*/
class AttemptRepository extends EntityRepository
{
use SearchableTrait;
/**
* @param string $uid
* @return Attempt|null
*/
public function findOneByUid(string $uid): ?Attempt
{
return $this->findOneBy([
'uid' => $uid,
]);
}
/**
* @param Tenant $tenant
* @param string|null $ip
* @return int
*/
public function countLastHourFailed(Tenant $tenant, ?string $ip = null)
{
// create the builder
$qb = $this->_em->createQueryBuilder()
->select('COUNT(attempts)')
->from($this->_entityName, 'attempts')
->where('attempts.status = false')
->andWhere('attempts.tenant = :tenant')
->setParameter('tenant', $tenant)
->andWhere('attempts.createdAt >= :date')
->setParameter('date', DateTimeUtils::beforeCurrent('PT1H'));
if ( ! empty($ip)) {
$qb->andWhere('attempts.ip = :ip')
->setParameter('ip', $ip);
}
// run it
return intval($this->querySingleScalar($qb)[0]);
}
/**
* @param DateTime $startDate
* @param DateTime $endDate
* @return int
*/
public function countLoginsByDateInterval(DateTime $startDate, DateTime $endDate)
{
// need to get login attempts for all tenants
$tenantFilter = $this->_em->getFilters()->getFilter('tenant_filter');
$this->_em->getFilters()->disable('tenant_filter');
// create the builder
$qb = $this->createQueryBuilder('attempts')
->select('COUNT(attempts)')
->where('attempts.status = :status')
->andWhere('attempts.createdAt >= :startDate')
->andWhere('attempts.createdAt < :endDate')
->setParameters(array(
'status' => true,
'startDate' => $startDate,
'endDate' => $endDate,
))
;
$result = $this->querySingleScalar($qb);
// I'm not sure that this is necessary, but theoretically this can affect further queries with tenant params
$this->_em->getFilters()
->enable('tenant_filter')
->setParameter('id', $tenantFilter->getParameter('id'))
;
return intval($result[0]);
}
}