Example #1
0
def like_mlkshk(request):
    if request.method != 'POST':
        resp = HttpResponse('POST is required', status=405, content_type='text/plain')
        resp['Allow'] = ('POST',)
        return resp

    user = request.user
    if not user.is_authenticated():
        return HttpResponse('Authentication required to response', status=400, content_type='text/plain')
    try:
        person = user.person
    except Person.DoesNotExist:
        return HttpResponse('Real reader account required to response', status=400, content_type='text/plain')

    try:
        post_id = request.POST['post']
    except KeyError:
        post_id = False
    if not post_id:
        return HttpResponse("Parameter 'post' is required", status=400, content_type='text/plain')

    like_url = 'https://mlkshk.com/api/sharedfile/%s/like' % post_id

    accounts = person.accounts.filter(service='mlkshk.com')
    for account in accounts:
        token, secret = account.authinfo.encode('utf8').split(':', 1)
        try:
            resp = call_mlkshk(like_url, method='POST', authtoken=token, authsecret=secret)
        except Exception, exc:
            log.warning("Error liking post %s for MLKSHK user %s: %s", post_id, account.display_name, str(exc))
            return HttpResponse('Error liking post: %s' % str(exc), status=400, content_type='text/plain')
Example #2
0
def complete_mlkshk(request):
    if 'error' in request.GET:
        raise ValueError("Received error code %r getting authorization code: %s" % (request.GET['error'], request.GET.get('error_description', '(no description)')))

    try:
        auth_code = request.GET['code']
    except KeyError:
        raise ValueError("Received no authorization code in response")

    token_params = {
        'grant_type': 'authorization_code',
        'code': auth_code,
        'redirect_uri': request.build_absolute_uri(reverse('complete-mlkshk')),
        'client_id': settings.MLKSHK_CONSUMER[0],
        'client_secret': settings.MLKSHK_CONSUMER[1],
    }
    h = httplib2.Http()
    resp, cont = h.request('https://mlkshk.com/api/token', method='POST', body=urlencode(token_params), headers={'Content-Type': 'application/x-www-form-urlencoded'})
    if resp.status != 200:
        raise ValueError("Unexpected HTTP response requesting token: %d %s" % (resp.status, resp.reason))

    token_data = json.loads(cont)
    if 'access_token' not in token_data:
        raise ValueError("Mlkshk token response contains no access token")

    # Schweet. Try asking who this is.
    authtoken = token_data['access_token'].encode('utf8')
    authsecret = token_data['secret'].encode('utf8')
    userinfo = call_mlkshk('https://mlkshk.com/api/user', authtoken=authtoken, authsecret=authsecret)

    person = None
    if not request.user.is_anonymous():
        person = request.user.person
    account = account_for_mlkshk_userinfo(userinfo)
    if request.user.is_anonymous():
        person = account.person
        if person.user is None:
            # AGH
            random_name = ''.join(choice(string.letters + string.digits) for i in range(20))
            while User.objects.filter(username=random_name).exists():
                random_name = ''.join(choice(string.letters + string.digits) for i in range(20))
            person.user = User.objects.create_user(random_name, '*****@*****.**' % random_name)
            person.save()

        person.user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request, person.user)
    else:
        # If the account already existed (because some other user follows
        # that account and had imported objects by them, say), "merge" it
        # onto the signed-in user. (This does mean you can intentionally
        # move an account by signing in as a different django User and re-
        # associating that account, but that's appropriate.)
        account.person = person

    account.authinfo = ':'.join((token_data['access_token'], token_data['secret']))
    account.save()

    return HttpResponseRedirect(reverse('home'))