from urllib import urlencode
import urlparse

from django.shortcuts import Http404, redirect
from django.contrib.auth.views import logout
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required

from vumi.utils import load_class_by_string

from go.base.utils import vumi_api


def token(request, token):
    # We only need the redis manager here, but it's saner to get a whole
    # vumi_api and not worry about all the setup magic.
    api = vumi_api()
    token_data = api.token_manager.get(token)
    if not token_data:
        raise Http404

    user_id = int(token_data['user_id'])
    redirect_to = token_data['redirect_to']
    system_token = token_data['system_token']

    # If we're authorized and we're the same user_id then redirect to
    # where we need to be
    if not user_id or request.user.id == user_id:
        path, _, qs = redirect_to.partition('?')
        params = urlparse.parse_qs(qs)
        # since the token can be custom we prepend the size of the user_token
        # to the token being forwarded so the view handling the `redirect_to`
        # can lookup the token and verify the system token.
        params.update({'token': '%s-%s%s' % (len(token), token, system_token)})
        return redirect('%s?%s' % (path, urlencode(params)))

    # If we got here then we need authentication and the user's either not
    # logged in or is logged in with a wrong account.
    if request.user.is_authenticated():
        logout(request)
        messages.info(request, 'Wrong account for this token.')
    return redirect('%s?%s' % (reverse('auth_login'), urlencode({
        'next': reverse('token', kwargs={'token': token}),
        })))


@login_required
def token_task(request):
    api = request.user_api.api

    token = request.GET.get('token')
    token_data = api.token_manager.verify_get(token)
    if not token_data:
        raise Http404

    params = token_data['extra_params']
    callback_name = params['callback_name']
    callback_args = params['callback_args']
    callback_kwargs = params['callback_kwargs']
    return_to = params['return_to']
    message = params['message']
    message_level = params['message_level']

    callback = load_class_by_string(callback_name)
    callback(*callback_args, **callback_kwargs)
    messages.add_message(request, message_level, message)
    return redirect(return_to)

[((18, 10, 18, 20), 'go.base.utils.vumi_api', 'vumi_api', ({}, {}), '()', False, 'from go.base.utils import vumi_api\n'), ((65, 15, 65, 50), 'vumi.utils.load_class_by_string', 'load_class_by_string', ({(65, 36, 65, 49): 'callback_name'}, {}), '(callback_name)', False, 'from vumi.utils import load_class_by_string\n'), ((67, 4, 67, 57), 'django.contrib.messages.add_message', 'messages.add_message', ({(67, 25, 67, 32): 'request', (67, 34, 67, 47): 'message_level', (67, 49, 67, 56): 'message'}, {}), '(request, message_level, message)', False, 'from django.contrib import messages\n'), ((68, 11, 68, 30), 'django.shortcuts.redirect', 'redirect', ({(68, 20, 68, 29): 'return_to'}, {}), '(return_to)', False, 'from django.shortcuts import Http404, redirect\n'), ((31, 17, 31, 38), 'urlparse.parse_qs', 'urlparse.parse_qs', ({(31, 35, 31, 37): 'qs'}, {}), '(qs)', False, 'import urlparse\n'), ((41, 8, 41, 23), 'django.contrib.auth.views.logout', 'logout', ({(41, 15, 41, 22): 'request'}, {}), '(request)', False, 'from django.contrib.auth.views import logout\n'), ((42, 8, 42, 63), 'django.contrib.messages.info', 'messages.info', ({(42, 22, 42, 29): 'request', (42, 31, 42, 62): '"""Wrong account for this token."""'}, {}), "(request, 'Wrong account for this token.')", False, 'from django.contrib import messages\n'), ((43, 31, 43, 52), 'django.core.urlresolvers.reverse', 'reverse', ({(43, 39, 43, 51): '"""auth_login"""'}, {}), "('auth_login')", False, 'from django.core.urlresolvers import reverse\n'), ((36, 41, 36, 58), 'urllib.urlencode', 'urlencode', ({(36, 51, 36, 57): 'params'}, {}), '(params)', False, 'from urllib import urlencode\n'), ((44, 16, 44, 57), 'django.core.urlresolvers.reverse', 'reverse', (), '', False, 'from django.core.urlresolvers import reverse\n')]