<?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;

use LifeStyle\SamlAuthBundle\Entity\User;
use LifeStyle\SamlAuthBundle\Database\Data\User\Index as DatabaseManager;
use LifeStyle\SamlAuthBundle\Exceptions\InvalidUserObjectException;
use LifeStyle\SamlAuthBundle\Exceptions\SamlAuthExceptionInterface;
use LifeStyle\SamlAuthBundle\Exceptions\UserNotAuthenticatedExceptionInterface;
use LifeStyle\SamlAuthBundle\Security\User\SamlUser;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

/**
 * Class UserHandler
 *
 * @copyright  2017 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package LifeStyle\SamlAuthBundle
 */
class UserHandler implements UserHandlerInterface
{
    /**
     * @var DatabaseManager
     */
    private $databaseManager;

    /**
     * @var TokenStorageInterface
     */
    private $securityToken;

    /**
     * UserHandler constructor.
     * @param DatabaseManager $databaseManager
     * @param TokenStorageInterface $securityToken
     */
    public function __construct(DatabaseManager $databaseManager, TokenStorageInterface $securityToken)
    {
        $this->databaseManager = $databaseManager;
        $this->securityToken = $securityToken;
    }

    /**
     * Returns logged in user from database table frontend_user
     *
     * @return User|null
     * @throws SamlAuthExceptionInterface
     */
    public function getUser()
    {
        $samlUser = $this->getSamlUser();

        $user = $this->databaseManager->findUserByGuid($samlUser->getUserSamlData()->getUserGuid());
        if (null === $user) {
            $user = $this->databaseManager->createUser($samlUser->getUserSamlData());
        }

        return $user;
    }

    /**
     * Returns logged in user from SAML response
     *
     * @return SamlUser
     * @throws SamlAuthExceptionInterface
     */
    public function getSamlUser()
    {
        if (null === $token = $this->securityToken->getToken()) {
            throw new UserNotAuthenticatedExceptionInterface();
        }

        if (!is_object($user = $token->getUser())) {
            // e.g. anonymous authentication
            throw new UserNotAuthenticatedExceptionInterface();
        }

        if (!($user instanceof SamlUser)) {
            throw new InvalidUserObjectException(sprintf(
                'SAML-user should be instance of "%s" but is "%s"',
                SamlUser::class,
                get_class($user)
            ));
        }

        return $user;
    }
}
