Exemplo n.º 1
0
def complete(request,
             email=None,
             confirmed=True,
             on_success=None,
             on_failure=None,
             failure_template='openid_consumer/failure.html'):
    on_success = on_success or default_on_success
    on_failure = on_failure or default_on_failure

    consumer = Consumer(request.session, DjangoOpenIDStore())
    #dummydebug
    #for r in request.GET.items():
    #    print r

    # JanRain library raises a warning if passed unicode objects as the keys,
    # so we convert to bytestrings before passing to the library
    query_dict = dict([(k.encode('utf8'), v) for k, v in request.GET.items()])

    url = get_url_host(request) + request.path
    openid_response = consumer.complete(query_dict, url)
    if openid_response.status == SUCCESS:
        return on_success(request,
                          openid_response.identity_url,
                          openid_response,
                          confirmed=confirmed,
                          email=email)
    elif openid_response.status == CANCEL:
        return on_failure(request, _('The request was cancelled'),
                          failure_template)
    elif openid_response.status == FAILURE:
        return on_failure(request, openid_response.message, failure_template)
    elif openid_response.status == SETUP_NEEDED:
        return on_failure(request, _('Setup needed'), failure_template)
    else:
        assert False, "Bad openid status: %s" % openid_response.status
Exemplo n.º 2
0
def complete(request,
             on_success=None,
             on_failure=None,
             failure_template='user/login.html'):
    on_success = on_success or default_on_success
    on_failure = on_failure or default_on_failure

    consumer = Consumer(request.session, DjangoOpenIDStore())
    # JanRain library raises a warning if passed unicode objects as the keys,
    # so we convert to bytestrings before passing to the library
    query_dict = dict([
        (k, v) for k, v in request.GET.items(
        )  # (k.encode('utf8'), v.encode('utf8')) for k, v in request.GET.items()
    ])

    url = get_url_host(request) + request.path
    openid_response = consumer.complete(query_dict, url)

    if openid_response.status == SUCCESS:
        return on_success(request, openid_response.identity_url,
                          openid_response)
    elif openid_response.status == CANCEL:
        return on_failure(request, _(u'Авторизация была отменена'),
                          failure_template)
    elif openid_response.status == FAILURE:
        return on_failure(request, openid_response.message, failure_template)
    elif openid_response.status == SETUP_NEEDED:
        return on_failure(request, _('Setup needed'), failure_template)
    else:
        assert False, "Bad openid status: %s" % openid_response.status
Exemplo n.º 3
0
def begin(request,
          sreg=None,
          extension_args=None,
          redirect_to=None,
          on_failure=None):

    on_failure = on_failure or default_on_failure

    if request.GET.get('logo'):
        # Makes for a better demo
        return HttpResponse(OPENID_LOGO_BASE_64.decode('base64'),
                            mimetype='image/gif')

    extension_args = extension_args or {}
    if sreg:
        extension_args['sreg.optional'] = sreg
    trust_root = getattr(settings, 'OPENID_TRUST_ROOT',
                         get_url_host(request) + '/')
    redirect_to = redirect_to or getattr(
        settings,
        'OPENID_REDIRECT_TO',
        # If not explicitly set, assume current URL with complete/ appended
        get_full_url(request).split('?')[0] + 'complete/')
    # In case they were lazy...
    if not redirect_to.startswith('http://'):
        redirect_to = get_url_host(request) + redirect_to

    if request.GET.get('next') and is_valid_next_url(request.GET['next']):
        if '?' in redirect_to:
            join = '&'
        else:
            join = '?'
        redirect_to += join + 'next=' + urllib.urlencode(request.GET['next'])

    user_url = request.POST.get('openid_url', None)
    if not user_url:
        return render('openid_signin.html', {'action': request.path})

    if xri.identifierScheme(user_url) == 'XRI' and getattr(
            settings, 'OPENID_DISALLOW_INAMES', False):
        return on_failure(request, 'i-names are not supported')

    consumer = Consumer(request.session, DjangoOpenIDStore())
    try:
        auth_request = consumer.begin(user_url)
    except DiscoveryFailure:
        return on_failure(request, "The OpenID was invalid")

    # Add extension args (for things like simple registration)
    for name, value in extension_args.items():
        namespace, key = name.split('.', 1)
        auth_request.addExtensionArg(namespace, key, value)

    redirect_url = auth_request.redirectURL(trust_root, redirect_to)
    return HttpResponseRedirect(redirect_url)
Exemplo n.º 4
0
def complete(request, on_success=None, on_failure=None):
    on_success = on_success or default_on_success
    on_failure = on_failure or default_on_failure
    
    consumer = Consumer(request.session, DjangoOpenIDStore())
    openid_response = consumer.complete(dict(request.GET.items()))
    
    if openid_response.status == SUCCESS:
        return on_success(request, openid_response.identity_url, openid_response)
    elif openid_response.status == CANCEL:
        return on_failure(request, 'The request was cancelled')
    elif openid_response.status == FAILURE:
        return on_failure(request, openid_response.message)
    elif openid_response.status == SETUP_NEEDED:
        return on_failure(request, 'Setup needed')
    else:
        assert False, "Bad openid status: %s" % openid_response.status
Exemplo n.º 5
0
def begin(request,
          confirmed=True,
          redirect_to=None,
          on_failure=None,
          user_url=None,
          template_name='openid_consumer/signin.html'):
    on_failure = on_failure or default_on_failure
    trust_root = getattr(settings, 'OPENID_TRUST_ROOT',
                         get_url_host(request) + '/')
    # foo derbis.
    redirect_to = redirect_to or getattr(
        settings,
        'OPENID_REDIRECT_TO',
        # If not explicitly set, assume current URL with complete/ appended
        get_full_url(request).split('?')[0] + 'complete/')
    # In case they were lazy...
    if not redirect_to.startswith('http://') or redirect_to.startswith(
            'https://'):
        redirect_to = get_url_host(request) + redirect_to

    if request.GET.get('next') and is_valid_next_url(request.GET['next']):
        if '?' in redirect_to:
            join = '&'
        else:
            join = '?'
        redirect_to += join + urlencode({'next': request.GET['next']})
    if not user_url:
        user_url = request.REQUEST.get('openid_url', None)

    if not user_url:
        request_path = request.path
        if request.GET.get('next'):
            request_path += '?' + urlencode({'next': request.GET['next']})

        return render(template_name, {
            'action': request_path,
        }, RequestContext(request))

    if xri.identifierScheme(user_url) == 'XRI' and getattr(
            settings, 'OPENID_DISALLOW_INAMES', False):
        return on_failure(request, _('i-names are not supported'))

    consumer = Consumer(request.session, DjangoOpenIDStore())
    try:
        auth_request = consumer.begin(user_url)
    except DiscoveryFailure:
        return on_failure(request, _('The OpenID was invalid'))

    sreg = getattr(settings, 'OPENID_SREG', False)

    if sreg:
        s = SRegRequest()
        for sarg in sreg:
            if sarg.lower().lstrip() == "policy_url":
                s.policy_url = sreg[sarg]
            else:
                for v in sreg[sarg].split(','):
                    s.requestField(
                        field_name=v.lower().lstrip(),
                        required=(sarg.lower().lstrip() == "required"))
        auth_request.addExtension(s)

    pape = getattr(settings, 'OPENID_PAPE', False)

    if pape:
        if openid.__version__ <= '2.0.0' and openid.__version__ >= '2.1.0':
            raise ImportError, 'For pape extension you need python-openid 2.1.0 or newer'
        p = PapeRequest()
        for parg in pape:
            if parg.lower().strip() == 'policy_list':
                for v in pape[parg].split(','):
                    p.addPolicyURI(v)
            elif parg.lower().strip() == 'max_auth_age':
                p.max_auth_age = pape[parg]
        auth_request.addExtension(p)

    ax = getattr(settings, 'OPENID_AX', [])

    if ax:
        axr = AXFetchRequest()
        for i in ax:
            axr.add(
                AttrInfo(i['type_uri'], i['count'], i['required'], i['alias']))
        auth_request.addExtension(axr)

    redirect_url = auth_request.redirectURL(trust_root, redirect_to)
    return HttpResponseRedirect(redirect_url)
Exemplo n.º 6
0
def begin(request,
          redirect_to=None,
          on_failure=None,
          template_name='user/login.html',
          lj_url=None):

    if 'yandex_button' in request.POST:
        openid_url = settings.YANDEX_OPENID_URL
    #elif 'myopenid_button' in request.POST:
    #    openid_url = settings.MYOPENID_OPENID_URL
    elif lj_url:
        openid_url = lj_url
    else:
        openid_url = None

    on_failure = on_failure or default_on_failure

    trust_root = getattr(settings, 'OPENID_TRUST_ROOT',
                         get_url_host(request) + '/')

    # foo derbis.
    redirect_to = redirect_to or getattr(
        settings,
        'OPENID_REDIRECT_TO',
        # If not explicitly set, assume current URL with complete/ appended
        get_full_url(request).split('?')[0] + 'complete/')
    '''
    # In case they were lazy...
    if not redirect_to.startswith('http://') or redirect_to.startswith('https://'):
        redirect_to =  get_url_host(request) + redirect_to
    '''

    if request.GET.get('next') and is_valid_next_url(request,
                                                     request.GET['next']):
        if '?' in redirect_to:
            join = '&'
        else:
            join = '?'
        redirect_to += join + urllib.urlencode({'next': request.GET['next']})

    user_url = openid_url

    if not user_url:
        request_path = request.path
        if request.GET.get('next'):
            request_path += '?' + urllib.urlencode(
                {'next': request.GET['next']})

        return render(template_name, {
            'action': request_path,
            'message': 'Error',
        },
                      context_instance=RequestContext(request))

    if xri.identifierScheme(user_url) == 'XRI' and getattr(
            settings, 'OPENID_DISALLOW_INAMES', False):
        return on_failure(request, _(u'i-names не поддерживаются'))

    consumer = Consumer(request.session, DjangoOpenIDStore())

    try:
        auth_request = consumer.begin(user_url)
    except DiscoveryFailure:
        return on_failure(request, _(u'Неверный OpenID'))

    sreg = getattr(settings, 'OPENID_SREG', False)

    if sreg:
        s = oidsreg.SRegRequest()
        for sarg in sreg:
            if sarg.lower().lstrip() == "policy_url":
                s.policy_url = sreg[sarg]
            else:
                for v in sreg[sarg].split(','):
                    s.requestField(
                        field_name=v.lower().lstrip(),
                        required=(sarg.lower().lstrip() == "required"))
        auth_request.addExtension(s)

    pape = getattr(settings, 'OPENID_PAPE', False)

    if pape:
        if openid.__version__ < '2.1.0':
            raise ImportError, 'For pape extension you need python-openid 2.1.0 or newer'
        p = oidpape.Request()
        for parg in pape:
            if parg.lower().strip() == 'policy_list':
                for v in pape[parg].split(','):
                    p.addPolicyURI(v)
            elif parg.lower().strip() == 'max_auth_age':
                p.max_auth_age = pape[parg]
        auth_request.addExtension(p)

    ax = getattr(settings, 'OPENID_AX', False)

    if ax:
        if openid.__version__ < '2.1.0':
            raise ImportError, 'For ax extension you need python-openid 2.1.0 or newer'
        axr = oidax.FetchRequest()
        for i in ax:
            axr.add(
                oidax.AttrInfo(i['type_uri'], i['count'], i['required'],
                               i['alias']))
        auth_request.addExtension(axr)

    redirect_url = auth_request.redirectURL(trust_root, redirect_to)

    return HttpResponseRedirect(redirect_url)