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

use SimpleSAML\Auth\State;
use SimpleSAML\Configuration;
use SimpleSAML\Error\BadRequest;
use SimpleSAML\Module\core\Auth\UserPassBase;
use SimpleSAML\Module\lifestyle\Auth\Mfa;
use SimpleSAML\Utils\HTTP;
use SimpleSAML\XHTML\Template;

if (!array_key_exists('AuthState', $_REQUEST)) {
    throw new BadRequest('Missing AuthState parameter.');
}
$authStateId = $_REQUEST['AuthState'];

// sanitize the input
$sid = State::parseStateID($authStateId);
if (!is_null($sid['url'])) {
    HTTP::checkURLAllowed($sid['url']);
}

/* Retrieve the authentication state. */
$state = State::loadState($authStateId, UserPassBase::STAGEID);

$errorCode = null;
$errorParams = null;
$mfaToken = '';

// Handle form request
if (isset($_REQUEST['mfa_token'])) {
    try {
        Mfa::createFromRequest()->handleMfaLogin($_REQUEST['mfa_token']);
    } catch (\SimpleSAML\Error\Error $e) {
        /* MFA Login failed. Extract error code and parameters, to display the error. */
        $errorCode = $e->getErrorCode();
        $errorParams = $e->getParameters();
    }
}

$globalConfig = Configuration::getInstance();
$t = new Template($globalConfig, 'core:loginmfa.php');
$t->data['stateparams'] = array('AuthState' => $authStateId);

$t->data['errorcode'] = $errorCode;
$t->data['errorparams'] = $errorParams;
$t->data['mfa_token'] = $mfaToken;
$t->data['mfa_qr_code'] = isset($state['MfaQrCode']) ? $state['MfaQrCode'] : false;

$t->show();
exit();
