<?php

$logid = 'OAuth1';

$path = ini_get('include_path');
$path =  dirname(dirname(__FILE__)).'/lib' . PATH_SEPARATOR . $path;
ini_set('include_path', $path);

require_once("message.php");
require_once("/var/www/lib/util.php");

define('TPLFILE', 'idmap.tpl');

function display($message, $error = false) {
    $smarty = new Smarty();
    $smarty->template_dir = 'templates';
    $smarty->compile_dir = 'templates_c';
    $smarty->assign('message', $message);
    $smarty->assign('error', $error);
    $smarty->display(TPLFILE);
}

$conf = parse_ini_file("/var/www/conf/oauth1.conf");
if (empty($conf)) {
    $log->crit(logformat("Can't read oauth1.conf"));
    display(OAUTH_ERR_001, true);
    exit(1);
}

require_once("config.php");

if (!isset($_GET['oauth1'])) {
    $log->err(logformat("Can't get session id"));
    display(OAUTH_ERR_002, true);
    exit(1);
}

session_id($_GET['oauth1']);
session_start();
$requestorid = null;
$client_id = null;
if (isset($_SESSION['expires']) && $_SESSION['expires'] > time()) {
    $requestorid = $_SESSION['requestorid'];
    $client_id = $_SESSION['client_id'];
}
session_destroy();

if (!$requestorid) {
    $log->err(logformat("Can't get requestor id"));
    display(OAUTH_NML_002);
    exit(1);
}

require_once('/usr/share/simplesamlphp/www/_include.php');

require_once('SimpleSAML/Utilities.php');
require_once('SimpleSAML/Session.php');
require_once('SimpleSAML/XHTML/Template.php');

/* Load simpleSAMLphp, configuration and metadata */
$config = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getInstance();
if (!isset($session) || !$session->isValid('saml2') ) {
  $params = array('RelayState' => SimpleSAML_Utilities::selfURL());
  if (isset($_GET['tenant'])) {
    $params['tenant'] = $_GET['tenant'];
  }
  SimpleSAML_Utilities::redirect(
    '/' . $config->getBaseURL() .
    'saml2/sp/initSSO.php',
    $params
    );
}

$nameid = $session->getNameID();
$userid = $nameid['value'];
if (!$userid) {
    $log->err(logformat("User isn't authenticated"));
    display(OAUTH_ERR_002, true);
    exit(1);
}
$password = $session->getAttribute('seciossEncryptedPassword');
if (is_array($password)) {
    $password = $password[0];
}

$prop = array($conf['requestorcol'] => $requestorid,
              'client_id' => $client_id,
              'expires' => time() + $conf['expires'],
              'password' => $password
        );
$login = new AutoLogin('DB', $conf);
$rc = $login->setUser($userid, true);
if (PEAR::isError($rc)) {
    if ($rc->getCode() != AUTO_LOGIN_NO_USER) {
        $log->err(logformat("Can't get user object: ". $rc->getMessage()));
        display(OAUTH_ERR_001, true);
        exit(1);
    }

    $rc = $login->storage->add($userid, $prop);
    if (PEAR::isError($rc)) {
        $log->err(logformat("Can't add user: ".$rc->getMessage()));
        display(OAUTH_ERR_001, true);
        exit(1);
    }
} else {
    $rc = $login->storage->setProp($prop);
    if (PEAR::isError($rc)) {
        $log->err(logformat("Can't update user: ".$rc->getMessage()));
        display(OAUTH_ERR_002, true);
        exit(1);
    }
}

display(OAUTH_NML_001);
exit(0);

?>
