src/EventSubscriber/AdminAuthSubscriber.php line 23

Open in your IDE?
  1. <?php
  2. /**
  3.  * User: Quentin
  4.  * Date: 20/10/2018
  5.  * Time: 19:09
  6.  */
  7. namespace App\EventSubscriber;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpKernel\Event\RequestEvent;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. use function Symfony\Component\String\s;
  12. class AdminAuthSubscriber implements EventSubscriberInterface {
  13.     public static function getSubscribedEvents() {
  14.         return array(
  15.             KernelEvents::REQUEST => 'onKernelRequest',
  16.         );
  17.     }
  18.     public function onKernelRequest(RequestEvent $e) {
  19.         if (!s($e->getRequest()->getPathInfo())->startsWith('/admin')) {
  20.             return;
  21.         }
  22.         $authUser 'adminsh';
  23.         $authPassword 'Redact!onSH2021';
  24.         /** @see http://php.net/manual/fr/features.http-auth.php#73386 */
  25.         $valid_passwords = array($authUser => $authPassword);
  26.         $valid_users array_keys($valid_passwords);
  27.         $user $_SERVER['PHP_AUTH_USER'] ?? null;
  28.         $pass $_SERVER['PHP_AUTH_PW'] ?? null;
  29.         $validated = (in_array($user$valid_users)) && ($pass == $valid_passwords[$user]);
  30.         if (!$validated) {
  31.             header('WWW-Authenticate: Basic realm="Admin"');
  32.             header('HTTP/1.0 401 Unauthorized');
  33.             die ("Not authorized");
  34.         }
  35.     }
  36. }