<?php

/**
 * Requires libcurl to be installed. For more info, see:
 * http://us.php.net/manual/en/book.curl.php
 */

/**
 * Create a new user session for this user, identified by "$username",
 * by the identity provider identified by "$idpId"
 *
 * Implement me!! Must validate that subject belongs to this idpId
 */
 
 /**
 * The restAuthUsername value is the REST API Client ID (a GUID) automatically assigned to your account in the PingOne admin portal 
 * on the Account > Integration page.
 * You will need to replace the restAuthUsername value in "${restAuthUsername}" in the sample below with your REST API Client ID. 
 * For example: $restAuthUsername = '5f6ce45e-1a00-488e-8519-7c9946cb6379';
 *
 * The restApiKey value is the REST API Client Secret (the password/secret associated with your REST API Client ID). You will need
 * to uncomment the $restApiKey statement and replace 'Specify me at https://admin.pingidentity.com/' in the sample below with 
 * your REST API Client Secret.
 * For example:  $restApiKey = 'mySecretApiPassword';
 */

function createUserSession($username, $idpid)
{
   echo "<p>Welcome, ".strip_tags($username)."</p>";
}

$tokenid = $_GET['tokenid'];
$agentid = $_GET['agentid'];

$restAuthUsername = '${restAuthUsername}';
//$restApiKey = 'Specify me at https://admin.pingidentity.com/';

$sso_service = "https://sso.connect.pingidentity.com/sso/TXS/2.0/1/$tokenid";
$c = curl_init($sso_service);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($c, CURLOPT_COOKIE, "agentid=$agentid;");
curl_setopt($c, CURLOPT_USERPWD, "$restAuthUsername:$restApiKey");
$response = curl_exec($c);
curl_close($c);
$responseData = json_decode($response, true);

createUserSession($responseData['pingone.subject'],
        $responseData['pingone.idp.id']);
?>