# This example uses Django 1.3, but can be converted for use in any
# web framework.
# Requires: 
#     * Python 2.6.x or 2.7.x
#         * (If using Python 2.4.x or 2.5.x, replace json with simplejson)
#     * Python's socket module must be built with SSL support. 
#         * For more info: http://www.python.org/doc//current/library/httplib.html
#

from django.http import HttpResponse
import httplib
import base64
import json # new in python 2.6 -- use simplejson if python < 2.6
import ssl
import socket
import os

# Download from http://curl.haxx.se/ca/cacert.pem, place in folder
CERT_FILE = os.path.join(os.path.dirname(__file__), 'cacert.pem')

# HTTPSConnection with SSL certificate validation
class ValidHTTPSConnection(httplib.HTTPSConnection):
    default_port = httplib.HTTPS_PORT

    def __init__(self, *args, **kwargs):
        httplib.HTTPConnection.__init__(self, *args, **kwargs)

    def connect(self):
        sock = socket.create_connection((self.host, self.port),
                                        self.timeout, self.source_address)
        if (self._tunnel_host):
            self.sock = sock
            self._tunnel()
        self.sock = ssl.wrap_socket(sock, ca_certs=CERT_FILE,
                                    cert_reqs=ssl.CERT_REQUIRED)

# Implement me!

def getIdpId():
    return "testidp.admin.pingidentity.com"

#
# 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 the empty string in the sample below with your REST API Client Secret.
# For example:  restApiKey = "mySecretApiPassword"
# 
# 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: credential = base64.b64encode("5f6ce45e-1a00-488e-8519-7c9946cb6379" + restApiKey)
#

def handleSso(request):
    tokenid = request.GET.__getitem__('tokenid')
    agentid = request.GET.__getitem__('agentid')
    
    restApiKey = ""
    credential = base64.b64encode("${restAuthUsername}:" + restApiKey)
    print(credential)
    headers = {
        "Accept": "application/json",
        "Authorization": "Basic " + credential,
        "Cookie": "agentid=" + agentid,
    }

    conn = ValidHTTPSConnection("sso.connect.pingidentity.com", 443)
    conn.request("GET", "/sso/TXS/2.0/1/" + tokenid, headers = headers)
    response = conn.getresponse()
    if (response.status != 200):
        raise Exception("Bad resonse: {0} {1} {2} {3}".format(response.status, response.reason, response.read(), response.msg))
    attributes = json.loads(response.read())
    subject=attributes['pingone.subject']
    idpid=attributes['pingone.idp.id']
    #
    # Implement me! You will need to use subject and idpid to create a user
    # session on your application. In this example, we just write the subject
    # directly to the response stream.
    #
    return HttpResponse("Welcome, {0}!".format(subject))