#!/usr/bin/env python
#
# Simple SSL server to process Salesforce callback
# Generate your self signed cert like this
#
# openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes
# A few requirements::
# pip install cherrypy bottle pyopenssl

import urlparse
import os
import sys
import json
from bottle import Bottle, route, run, request, server_names, ServerAdapter
from sforce import COMMONS as c
from sforce.auth import request_phase, authorize_phase, access_phase

# Define our remote app credentials and callback uri
c['client_key'] = os.environ['SFKEY']
c['client_secret'] = os.environ['SFSECRET']
c['callback_uri'] = 'https://localhost:4443/callback'
c['sandbox'] = True

# from http://dgtool.blogspot.com.au/2011/12/ssl-encryption-in-python-bottle.html
# need to support SSL on localhost b/c Salesforce requires it
class MySSLCherry(ServerAdapter):
    def run(self, handler):
        from cherrypy import wsgiserver
        server = wsgiserver.CherryPyWSGIServer((self.host, self.port), handler)
        cert = 'server.pem'
        server.ssl_certificate = cert
        server.ssl_private_key = cert
        try:
            server.start()
        finally:
            server.stop()

server_names['mysslcherry'] = MySSLCherry

app = Bottle()

creds = os.path.join(os.path.expanduser('~'),".sfcreds.json")

@app.route('/')
def index():
    request_phase(c)
    return "<a href=%s>Authorize</a>" % (authorize_phase(c),)

@app.route('/callback')
def docallback():
    verifier = request.query.oauth_verifier
    access_phase(c, verifier)
    json_data = open(creds, 'w')
    json.dump({'oauth_token': c['oauth_token'],
               'oauth_token_secret': c['oauth_token_secret'],
               'oauth_consumer_key': c['client_key']}, json_data)
    json_data.close()
    return "Authenticated and tokens saved in file: %s" % (creds,)

if os.path.exists(creds):
    print("Credentials file exist already, remove to re-auth.")
    sys.exit(1)
else:
    run(app, host='localhost', port=4443, server='mysslcherry')

sys.exit(0)

# vim: syntax=python
