disqus / DISQUS-API-Recipes

Cook all the things!
288 stars 132 forks source link

Python 3 #12

Open ghost opened 10 years ago

ghost commented 10 years ago

@ryanvalentin,

Please, provide Python 3 compatible example... https://github.com/disqus/DISQUS-API-Recipes/blob/master/sso/python/sso.py

I confused with encode/decode...

Cristoph commented 8 years ago

Python3:

import base64
import hashlib
import hmac
import json
import time

DISQUS_SECRET_KEY = '123456'
DISQUS_PUBLIC_KEY = 'abcdef'

def get_disqus_sso():
    # create a JSON packet of our data attributes
    data = json.dumps({
        'id': user['id'],
        'username': user['username'],
        'email': user['email'],
    })
    # encode the data to base64
    message = base64.b64encode(data.encode('utf-8')).decode()
    # generate a timestamp for signing the message
    timestamp = int(time.time())

    key = DISQUS_SECRET_KEY.encode('utf-8')
    msg = ('%s %s' % (message, timestamp)).encode('utf-8')
    digestmod = hashlib.sha1

    # generate our hmac signature
    sig = hmac.HMAC(key, msg, digestmod).hexdigest()

# return a script tag to insert the sso message
    return """<script type="text/javascript">
    var disqus_config = function() {
        this.page.remote_auth_s3 = "%(message)s %(sig)s %(timestamp)s";
        this.page.api_key = "%(pub_key)s";
    }
    </script>""" % dict(
        message=message,
        timestamp=timestamp,
        sig=sig,
        pub_key=DISQUS_PUBLIC_KEY,
    )