Introducing YippieMove '09. Easy email transfers. Now open for all destinations.

Recently we hooked up with Zendesk for our support system. We hooked up its Remote Authentication API so that our customers could use their YippieMove logins in our support system as well. Jon Gales provided a great recipe for doing this in Django which we kicked off with, making some minor updates too. Only one problem remained: if an account had international characters in the first or the last name, Chinese, Japanese, and so on, the code would error out.

Here’s what the error looks like in practice:

Traceback (most recent call last):

File "/usr/local/lib/python2.5/site-packages/django/core/handlers/base.py", line 86, in get_response
response = callback(request, *callback_args, **callback_kwargs)
...
hash = md5('%s %+s%s%s%s' % (first, last, u.email, settings.ZENDESK_TOKEN, timestamp)).hexdigest()

UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 2: ordinal not in range(128)

The problem is that md5().hexdigest() only works on byte strings. If you give it a unicode string it will try to .encode('ascii') it, which works fine as long as there are no international characters in the string.

The solution is simple: just explicitly UTF encode the source string. The Zendesk documentation did not mention what encoding they use themselves but my first guess would have been UTF-8, which turned out to be right. So with that in mind here is our current version of Jon Gales’ Zendesk Remote Authentication snippet for Django:

@never_cache
@login_required
def authorize(request):
  try:
    timestamp = request.GET['timestamp']
  except KeyError:
    raise Http404

  u = request.user

  from hashlib import md5

  first = u.first_name
  last = u.last_name
  if not first and not last:
    first = "Yippie"
    last = "Mover"

  data = u'%s %+s%s%s%s' % (first, last, u.email, settings.ZENDESK_TOKEN, 
    timestamp)
  hash = md5(data.encode('utf-8')).hexdigest()

  url = u"%s/access/remote/?name=%s %s&email=%s&timestamp=%s&hash=%s" % (
    settings.ZENDESK_URL, first, last, u.email, timestamp, hash)

  return HttpResponseRedirect(url)

Notice that we feed a unicode URL to HttpResponseRedirect – Django is smart enough to do the right thing when encoding the URL.

Author: Tags: , , , ,

© 2006-2009 WireLoad, LLC.
Logo photo by William Picard. Theme based on BlueMod © 2005 - 2009 FrederikM.de, based on blueblog_DE by Oliver Wunder.
Sitemap