Response.php 6.04 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
<?php

namespace Dotdigitalgroup\Email\Controller;

/**
 * @SuppressWarnings(PHPMD.NumberOfChildren)
 */
class Response extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Dotdigitalgroup\Email\Helper\Data
     */
    public $helper;

    /**
     * @var \Magento\Framework\Escaper
     */
    public $escaper;

    /**
     * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface
     */
    private $timezone;

    /**
     * @var \Dotdigitalgroup\Email\Model\ResourceModel\FailedAuth
     */
    private $failedAuthResource;

    /**
     * @var \Dotdigitalgroup\Email\Model\FailedAuthFactory
     */
    private $failedAuthFactory;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    private $storeManager;

    /**
     * @var \Dotdigitalgroup\Email\Helper\Config
     */
    private $configHelper;

    /**
     * Response constructor.
     * @param \Dotdigitalgroup\Email\Helper\Data $data
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\Escaper $escaper
     * @param \Dotdigitalgroup\Email\Helper\Config $configHelper
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Dotdigitalgroup\Email\Model\FailedAuthFactory $failedAuthFactory
     * @param \Dotdigitalgroup\Email\Model\ResourceModel\FailedAuth $failedAuthResource
     * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone
     */
    public function __construct(
        \Dotdigitalgroup\Email\Helper\Data $data,
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Escaper $escaper,
        \Dotdigitalgroup\Email\Helper\Config $configHelper,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Dotdigitalgroup\Email\Model\FailedAuthFactory $failedAuthFactory,
        \Dotdigitalgroup\Email\Model\ResourceModel\FailedAuth $failedAuthResource,
        \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone
    ) {
        $this->helper = $data;
        $this->escaper = $escaper;
        $this->timezone = $timezone;
        $this->storeManager = $storeManager;
        $this->configHelper = $configHelper;
        $this->failedAuthFactory = $failedAuthFactory;
        $this->failedAuthResource = $failedAuthResource;

        parent::__construct($context);
    }

    /**
     * Auth.
     */
    public function authenticate()
    {
        //in locked state
        if ($this->isAuthLocked()) {
            $this->sendUnauthorizedResponse();

            return false;
        }
        //passcode not valid.
        if (!$this->helper->auth($this->getRequest()->getParam('code'))) {
            $this->processFailedRequest();
            $this->sendUnauthorizedResponse();
            return false;
        }
        //ip is not allowed
        if (!$this->helper->isIpAllowed()) {
            $this->sendNoContentResponse();
            return false;
        }

        return true;
    }

    /**
     *
     */
    public function execute()
    {
    }

    /**
     * @return \Zend\Http\PhpEnvironment\Response
     */
    public function sendUnauthorizedResponse()
    {
        $this->getResponse()
            ->setHttpResponseCode(401)
            ->setHeader('Pragma', 'public', true)
            ->setHeader(
                'Cache-Control',
                'must-revalidate, post-check=0, pre-check=0',
                true
            )
            ->setHeader('Content-type', 'text/html; charset=UTF-8', true)
            ->setBody('<h1>401 Unauthorized</h1>');

        return $this->getResponse()->sendHeaders();
    }

    /**
     * @return \Zend\Http\PhpEnvironment\Response
     */
    public function sendNoContentResponse()
    {
        try {
            $this->getResponse()
                ->setHttpResponseCode(204)
                ->setHeader('Pragma', 'public', true)
                ->setHeader(
                    'Cache-Control',
                    'must-revalidate, post-check=0, pre-check=0',
                    true
                )
                ->setHeader('Content-type', 'text/html; charset=UTF-8', true);
            return $this->getResponse()->sendHeaders();
        } catch (\Exception $e) {
            $this->helper->log($e);
        }
    }

    /**
     * Register the failed attempt and set a lock with a 5min window if more then 5 request failed.
     */
    private function processFailedRequest()
    {
        $url = $this->_url->getCurrentUrl();
        $storeId = $this->storeManager->getStore()->getId();
        $failedAuth = $this->failedAuthFactory->create();
        $this->failedAuthResource->load($failedAuth, $storeId, 'store_id');
        $numOfFails = $failedAuth->getFailuresNum();
        $lastAttemptDate = $failedAuth->getLastAttemptDate();
        //set the first failed attempt
        if (!$failedAuth->getId()) {
            $failedAuth->setFirstAttemptDate(time());
        }

        //check the time for the last fail and update the records
        if ($numOfFails == \Dotdigitalgroup\Email\Model\FailedAuth::NUMBER_MAX_FAILS_LIMIT) {
            //ignore the resource is in a locked state
            if ($failedAuth->isLocked()) {
                $this->helper->log(sprintf('Resource locked time : %s ,store : %s', $lastAttemptDate, $storeId));
                return;
            } else {
                //reset with the first lock after the the lock expired
                $numOfFails = 0;
                $failedAuth->setFirstAttemptDate(time());
            }
        }
        try {
            $failedAuth->setFailuresNum(++$numOfFails)
                ->setStoreId($storeId)
                ->setUrl($url)
                ->setLastAttemptDate(time());
            $this->failedAuthResource->save($failedAuth);
        } catch (\Exception $e) {
            $this->helper->log($e);
        }
    }

    /**
     * @return bool
     */
    private function isAuthLocked()
    {
        $failedAuth = $this->failedAuthFactory->create();
        $storeId = $this->storeManager->getStore()->getId();
        $this->failedAuthResource->load($failedAuth, $storeId, 'store_id');

        return $failedAuth->isLocked();
    }
}