/**
 * Requires commons codec library for Base-64 encoding the HTTP
 * basic authentication header:
 * http://commons.apache.org/codec/
 * 
 * Alternatively, you can use the javax.mail library:
 * javax.mail.internet.MimeUtility;
 */
package com.example;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;

 /**
 * 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: private static final String REST_USERNAME = "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 private static final String REST_API_KEY statement and replace the empty string in the sample below with 
 * your REST API Client Secret.
 * For example:  private static final String REST_API_KEY = "mySecretApiPassword";
 */

public class SaasTokenExchangeExampleServlet
    extends HttpServlet
{
    private static final String REST_USERNAME = "${restAuthUsername}";

    // Specified at http://admin.pingidentity.com
    //private static final String REST_API_KEY = "";
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
    {
        String token = req.getParameter("tokenid");
        String agentId = req.getParameter("agentid");
        String tokenResolutionUrl = String.format("https://sso.connect.pingidentity.com/sso/TXS/2.0/2/%s", token);
        URL url = new URL(tokenResolutionUrl);
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
        String authValue = REST_USERNAME + ":" +  REST_API_KEY;
        String basicAuthHeader = "Basic " + new String(Base64.encodeBase64((authValue).getBytes()));
        urlConnection.setRequestProperty("Authorization", basicAuthHeader);
        String agentidCookie = "agentid=" + agentId;
        urlConnection.setRequestProperty("Cookie", agentidCookie);
        InputStream is = urlConnection.getInputStream();
        Properties properties = new Properties();
        properties.load(is);
        String username = properties.getProperty("pingone.subject");
        String idpId = properties.getProperty("pingone.idp.id");
        createUserSession(resp, username, idpId);
    }

    /**
     * Implement me! Must validate that subject belongs to this idpId
     * @param resp - The response to create the user session with
     * @param user - The userid of the user doing SSO authentication into your application
     * @param idpid - The idpid of the user's organization where they have authenticated
     */
    private void createUserSession(HttpServletResponse resp, String user, String idpid) throws IOException
    {
        resp.setContentType("text/html");
        user = user.replace("<", "&lt;");
        user = user.replace(">", "&gt;");
        resp.getOutputStream().println("<p>Welcome, " + user + "</p>");
    }
}