<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2018 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace LifeStyle\SamlAuthBundle\Security\Firewall;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Firewall\ListenerInterface;
use JMS\Serializer\Serializer;
use LifeStyle\SamlAuthBundle\Security\Authentication\Token\SamlToken;
use LifeStyle\SamlAuthBundle\Services\SamlService;
use LifeStyle\SamlAuthBundle\Configuration\SamlConfig;
use LifeStyle\SamlAuthBundle\Model\UserApplication\Application as UserApplication;
use LifeStyle\SamlAuthBundle\Model\UserData\User as UserDto;
use FOS\UserBundle\Security\LoginManagerInterface;
/**
 * Class SamlListener
 * @package LifeStyle\SamlAuthBundle\Security\Firewall
 */
class SamlListener implements ListenerInterface
{
    /**
     * @var TokenStorageInterface
     */
    protected $tokenStorage;

    /**
     * @var AuthenticationManagerInterface
     */
    protected $authenticationManager;

    /**
     * @var SamlService
     */
    private $samlService;

    /**
     * @var Serializer
     */
    private $serializer;

    /**
     * @var SamlConfig;
     */
    private $config;

    /**
     * SamlListener constructor.
     * @param TokenStorageInterface $tokenStorage
     * @param AuthenticationManagerInterface $authenticationManager
     * @param SamlService $samlService
     * @param Serializer $serializer
     * @param SamlConfig $config
     */
    public function __construct(
        TokenStorageInterface $tokenStorage,
        AuthenticationManagerInterface $authenticationManager,
        SamlService $samlService,
        Serializer $serializer,
        SamlConfig $config
    ) {
        $this->tokenStorage = $tokenStorage;
        $this->authenticationManager = $authenticationManager;
        $this->samlService = $samlService;
        $this->serializer = $serializer;
        $this->config = $config;
    }

    /**
     *
     * @param GetResponseEvent $event
     */
    public function handle(GetResponseEvent $event)
    {
        $saml = $this->samlService->getSimpleSaml();
        if (!$saml->isAuthenticated()) {
            $saml->login();
        }

        $attributes = $saml->getAttributes();
        $user = $this->parseSamlData($attributes);
        $token = $this->mapUserToToken($user);

        try {
            $authToken = $this->authenticationManager->authenticate($token);
            $this->tokenStorage->setToken($authToken);
        } catch (AuthenticationException $e) {
            $token = $this->tokenStorage->getToken();
            if ($token instanceof SamlToken) {
                $this->tokenStorage->setToken(null);
            }
            $response = new Response();
            $response->setStatusCode(Response::HTTP_FORBIDDEN);
            $event->setResponse($response);
        }
    }


    /**
     * Parses the data in the SAML response array into the user DTO
     *
     * @param array $samlData
     * @return UserDto
     */
    private function parseSamlData($samlData)
    {
        // init base user data with the SAML response data
        $userDto = new UserDto();
        $userDto->setFromSamlResponse($samlData);

        // parse all given user application data into the DTO
        foreach ($samlData as $key => $entry) {
            if ((strlen($key) > 13) && (substr($key, 0, 13) == 'application::')) {
                $appName = substr($key, 13, 256);
                $appJson = (is_array($entry) && (count($entry) > 0)) ? $entry[0] : $entry;
                try {
                    // parse the JSON data for the user app into the UserApplication object
                    $appData = $this->serializer->deserialize($appJson, UserApplication::class, 'json');
                } catch (\Exception $exception) {
                    // something went bad during deserialization
                    // for now, lets silently ignore it at this point, so the rest can continue, and just set
                    // the data for this app to an empty object - this way we don't break anything and
                    // authentication/role assignement will actually work as intended.
                    $appData = new UserApplication();
                }
                // now add everything, incl. the original JSON to our user DTO
                $userDto->addUserApplication($appName, $appData);
                $userDto->addUserApplicationJSON($appJson);
            }
        }

        return $userDto;
    }

    /**
     * Returns a propperly filled token from the user DTO
     *
     * @param UserDto $userDto
     * @return SamlToken
     */
    private function mapUserToToken(UserDto $userDto)
    {
        $token = new SamlToken();

        $token->setUser($userDto->getUsername());
        $token->userName = $userDto->getUsername();
        $token->email = $userDto->getEmail();
        $token->firstname = $userDto->getFirstname();
        $token->lastname = $userDto->getLastname();
        $token->userId = $userDto->getUserId();
        $token->appData = $userDto->getUserApplication($this->config->getIdpAppName());
        $token->userData = $userDto;
        //we need MFA and the application UserWsAdministrator

        return $token;
    }
}
