<?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  2019 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 */

namespace SimpleSAML\Module\lifestyle\Auth;

use SimpleSAML\Auth\State;
use SimpleSAML\Configuration;
use SimpleSAML\Error\BadRequest;
use SimpleSAML\Error\NoState;
use SimpleSAML\Locale\Language;
use SimpleSAML\Module;
use SimpleSAML\Module\core\Auth\UserPassBase;
use SimpleSAML\Module\lifestyle\Utils\UrlBuilder;
use SimpleSAML\Utils\HTTP;

/**
 * Class PasswordReset
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 * @package SimpleSAML\Module\lifestyle\Auth
 */
class PasswordReset
{
    /**
     * @var string
     */
    private $authStateId;

    /**
     * Mfa constructor.
     * @param string $authStateId
     */
    private function __construct($authStateId)
    {
        $this->authStateId = $authStateId;
    }

    /**
     * @return PasswordReset
     * @throws BadRequest
     */
    public static function createFromRequest()
    {
        if (!array_key_exists('AuthState', $_REQUEST)) {
            throw new BadRequest('Missing AuthState parameter.');
        }
        return new self($_REQUEST['AuthState']);
    }

    /**
     * @param string $username
     * @param string $userGuid
     * @param string $resetPasswordToken
     * @throws NoState
     */
    public function redirect($username, $userGuid, $resetPasswordToken)
    {
        // Re-Load state from current request
        $state = State::loadState($this->authStateId, UserPassBase::STAGEID);

        // This forces form autofill after return from password reset service
        $state['forcedUsername'] = $username;

        // Store current state and use core login entry-point as return url to restart authentication process
        $returnUrl = HTTP::addURLParameters(
            Module::getModuleURL('core/loginuserpass.php'),
            ['AuthState' => State::saveState($state, UserPassBase::STAGEID)]
        );

        $configuration = Configuration::getInstance();
        $urlBuilder = new UrlBuilder(
            $configuration,
            $_REQUEST['AuthState'],
            (new Language($configuration))->getLanguage()
        );

        HTTP::submitPOSTData(
            $urlBuilder->getPasswordResetUrl(),
            [
                'guid' => $userGuid,
                'token' => $resetPasswordToken,
                'returnUrl' => $returnUrl,
            ]
        );

        /* The previous function never returns, so this code is never executed. */
        assert(false);
    }
}
