Пример #1
0
 def clean_openid_identifier(self):
     if 'openid_identifier' in self.cleaned_data:
         openid_identifier = self.cleaned_data['openid_identifier']
         if (xri.identifierScheme(openid_identifier) == 'XRI'
                 and conf.DISALLOW_INAMES):
             raise forms.ValidationError(_('i-names are not supported'))
         return self.cleaned_data['openid_identifier']
Пример #2
0
 def __init__(self, openid_, issued, attrs=None, sreg_=None, ax_resp={}):
     self.openid = openid_
     self.issued = issued
     self.attrs = attrs or {}
     self.sreg = sreg_ or {}
     self.ax_resp = ax_resp or {}
     self.is_iname = (xri.identifierScheme(openid_) == 'XRI')
Пример #3
0
 def clean_openid_url(self):
     """ test if openid is accepted """
     if "openid_url" in self.cleaned_data:
         openid_url = self.cleaned_data["openid_url"]
         if xri.identifierScheme(openid_url) == "XRI" and getattr(settings, "OPENID_DISALLOW_INAMES", False):
             raise forms.ValidationError(_("i-names are not supported"))
         return self.cleaned_data["openid_url"]
Пример #4
0
 def clean_openid_identifier(self):
     if 'openid_identifier' in self.cleaned_data:
         openid_identifier = self.cleaned_data['openid_identifier']
         if xri.identifierScheme(openid_identifier) == 'XRI' and getattr(
                 settings, 'OPENID_DISALLOW_INAMES', False):
             raise forms.ValidationError(_('i-names are not supported'))
         return self.cleaned_data['openid_identifier']
Пример #5
0
 def __init__(self, openid_, issued, attrs=None, sreg_=None):
     logging.debug('init janrain openid object')
     self.openid = openid_
     self.issued = issued
     self.attrs = attrs or {}
     self.sreg = sreg_ or {}
     self.is_iname = (xri.identifierScheme(openid_) == 'XRI')
Пример #6
0
def ask_openid(request, openid_url, redirect_to, on_failure=None,
        sreg_request=None):
    """ basic function to ask openid and return response """

    on_failure = on_failure or signin_failure
    
    trust_root = getattr(
        settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/'
    )
    if xri.identifierScheme(openid_url) == 'XRI' and getattr(
            settings, 'OPENID_DISALLOW_INAMES', False
    ):
        msg = _("i-names are not supported")
        return on_failure(request, msg)
    consumer = Consumer(request.session, DjangoOpenIDStore())
    try:
        auth_request = consumer.begin(openid_url)
    except DiscoveryFailure:
        msg = _("The OpenID %s was invalid" % openid_url)
        return on_failure(request, msg)

    if sreg_request:
        auth_request.addExtension(sreg_request)
    redirect_url = auth_request.redirectURL(trust_root, redirect_to)
    return HttpResponseRedirect(redirect_url)
Пример #7
0
 def __init__(self, openid, issued, attrs=None, sreg_=None, ax_=None):
     self.openid = openid
     self.issued = issued
     self.attrs = attrs or {}
     self.sreg = sreg_ or {}
     self.ax = ax_ or {}
     self.is_iname = (xri.identifierScheme(openid) == 'XRI')
Пример #8
0
def ask_openid(request, openid_url=None, next_url=None, on_failure=None):
    """ basic function to ask openid and return response """
    on_failure = on_failure or signin_failure
    sreg_request = sreg.SRegRequest(optional=["nickname", "email"])

    trust_root = getattr(settings, "OPENID_TRUST_ROOT", get_url_host(request) + "/")
    if xri.identifierScheme(openid_url) == "XRI" and getattr(settings, "OPENID_DISALLOW_INAMES", False):
        msg = _("i-names are not supported")
        logging.debug("openid failed because i-names are not supported")
        return on_failure(request, msg)
    consumer = Consumer(request.session, util.DjangoOpenIDStore())
    try:
        auth_request = consumer.begin(openid_url)
    except DiscoveryFailure:
        msg = _(u"OpenID %(openid_url)s is invalid" % {"openid_url": openid_url})
        logging.debug(msg)
        return on_failure(request, msg)

    logging.debug("openid seemed to work")
    if sreg_request:
        logging.debug("adding sreg_request - wtf it is?")
        auth_request.addExtension(sreg_request)

    redirect_to = "%s%s?%s" % (
        get_url_host(request),
        reverse("user_complete_openid_signin"),
        urllib.urlencode({"next": next_url}),
    )
    redirect_url = auth_request.redirectURL(trust_root, redirect_to)
    logging.debug("redirecting to %s" % redirect_url)
    return HttpResponseRedirect(redirect_url)
Пример #9
0
 def clean_openid_identifier(self):
     if 'openid_identifier' in self.cleaned_data:
         openid_identifier = self.cleaned_data['openid_identifier']
         if (xri.identifierScheme(openid_identifier) == 'XRI' and
                 getattr(settings, 'OPENID_DISALLOW_INAMES', False)):
             raise forms.ValidationError(_('i-names are not supported'))
         return self.cleaned_data['openid_identifier']
Пример #10
0
def ask_openid(
            request,
            openid_url,
            redirect_to,
            on_failure=None,
            sreg_request=None
        ):
    """ basic function to ask openid and return response """
    on_failure = on_failure or signin_failure
    
    trust_root = getattr(
        settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/'
    )
    if xri.identifierScheme(openid_url) == 'XRI' and getattr(
            settings, 'OPENID_DISALLOW_INAMES', False
    ):
        msg = _("i-names are not supported")
        logging.debug('openid failed because i-names are not supported')
        return on_failure(request, msg)
    consumer = Consumer(request.session, util.DjangoOpenIDStore())
    try:
        auth_request = consumer.begin(openid_url)
    except DiscoveryFailure:
        msg = _(u"OpenID %(openid_url)s is invalid" % {'openid_url':openid_url})
        logging.debug(msg)
        return on_failure(request, msg)

    logging.debug('openid seemed to work')
    if sreg_request:
        logging.debug('adding sreg_request - wtf it is?')
        auth_request.addExtension(sreg_request)
    redirect_url = auth_request.redirectURL(trust_root, redirect_to)
    logging.debug('redirecting to %s' % redirect_url)
    return HttpResponseRedirect(redirect_url)
Пример #11
0
 def clean_openid_identifier(self):
     if 'openid_identifier' in self.cleaned_data:
         openid_identifier = self.cleaned_data['openid_identifier']
         if (xri.identifierScheme(openid_identifier) == 'XRI'
                 and conf.DISALLOW_INAMES):
             raise forms.ValidationError(_('i-names are not supported'))
         return self.cleaned_data['openid_identifier']
Пример #12
0
def ask_openid(request,
               openid_url,
               redirect_to,
               on_failure=None,
               sreg_request=None):
    """ basic function to ask openid and return response """
    request.encoding = 'UTF-8'
    on_failure = on_failure or signin_failure

    trust_root = getattr(settings, 'OPENID_TRUST_ROOT',
                         get_url_host(request) + '/')
    if xri.identifierScheme(openid_url) == 'XRI' and getattr(
            settings, 'OPENID_DISALLOW_INAMES', False):
        msg = _("i-names are not supported")
        return on_failure(request, msg)
    consumer = Consumer(request.session, DjangoOpenIDStore())
    try:
        auth_request = consumer.begin(openid_url)
    except DiscoveryFailure:
        msg = _(u"OpenID %(openid_url)s is invalid" %
                {'openid_url': openid_url})
        return on_failure(request, msg)

    if sreg_request:
        auth_request.addExtension(sreg_request)
    redirect_url = auth_request.redirectURL(trust_root, redirect_to)
    return HttpResponseRedirect(redirect_url)
Пример #13
0
def ask_openid(request,
               openid_url,
               redirect_to,
               on_failure=None,
               sreg_request=None):
    """ basic function to ask openid and return response """
    on_failure = on_failure or signin_failure

    trust_root = getattr(settings, 'OPENID_TRUST_ROOT',
                         get_url_host(request) + '/')
    if xri.identifierScheme(openid_url) == 'XRI' and getattr(
            settings, 'OPENID_DISALLOW_INAMES', False):
        msg = _("i-names are not supported")
        logging.debug('openid failed because i-names are not supported')
        return on_failure(request, msg)
    consumer = Consumer(request.session, util.DjangoOpenIDStore())
    try:
        auth_request = consumer.begin(openid_url)
    except DiscoveryFailure:
        msg = _(u"OpenID %(openid_url)s is invalid" %
                {'openid_url': openid_url})
        logging.debug(msg)
        return on_failure(request, msg)

    logging.debug('openid seemed to work')
    if sreg_request:
        logging.debug('adding sreg_request - wtf it is?')
        auth_request.addExtension(sreg_request)
    redirect_url = auth_request.redirectURL(trust_root, redirect_to)
    logging.debug('redirecting to %s' % redirect_url)
    return HttpResponseRedirect(redirect_url)
Пример #14
0
 def __init__(self, openid_, issued, attrs=None, sreg_=None):
     logging.debug('init janrain openid object')
     self.openid = openid_
     self.issued = issued
     self.attrs = attrs or {}
     self.sreg = sreg_ or {}
     self.is_iname = (xri.identifierScheme(openid_) == 'XRI')
Пример #15
0
 def __init__(self, openid_, issued, attrs=None, sreg_=None, ax_=None):
     self.openid = openid_
     self.issued = issued
     self.attrs = attrs or {}
     self.sreg = sreg_ or {}
     self.ax = ax_ or {}
     self.is_iname = (xri.identifierScheme(openid_) == 'XRI')
 def __init__(self, openid, issued, attrs=None, sreg=None, pape=None, ax=None):
     self.openid = openid
     self.issued = issued
     self.attrs = attrs or {}
     self.sreg = sreg or {}
     self.pape = pape or {}
     self.ax = ax or {}
     self.is_iname = (xri.identifierScheme(openid) == 'XRI')
Пример #17
0
 def __init__(self, openid, issued, attrs=None, sreg=None, pape=None, ax=None):
     self.openid = openid
     self.issued = issued
     self.attrs = attrs or {}
     self.sreg = sreg or {}
     self.pape = pape or {}
     self.ax = ax or {}
     self.is_iname = xri.identifierScheme(openid) == "XRI"
Пример #18
0
 def clean_openid_url(self):
     """ test if openid is accepted """
     if 'openid_url' in self.cleaned_data:
         openid_url = self.cleaned_data['openid_url']
         if xri.identifierScheme(openid_url) == 'XRI' and getattr(
                 django_settings, 'OPENID_DISALLOW_INAMES', False):
             raise forms.ValidationError(_('i-names are not supported'))
         return self.cleaned_data['openid_url']
Пример #19
0
def ask_openid(request, openid_url, redirect_to, on_failure=None):
    on_failure = on_failure or signin_failure
    sreg_req = None
    ax_req = None
    _openid_url = openid_url
    trust_root = getattr(settings, 'OPENID_TRUST_ROOT',
                         get_url_host(request) + '/')
    if xri.identifierScheme(openid_url) == 'XRI' and getattr(
            settings, 'OPENID_DISALLOW_INAMES', False):
        msg = ("i-names are not supported")
        auth_oidlogin.send(sender=None,
                           openid_url=_openid_url,
                           state='not_supported')
        return on_failure(request, msg)
    consumer = Consumer(request.session, DjangoOpenIDStore())
    try:
        auth_request = consumer.begin(openid_url)
    except DiscoveryFailure:
        msg = ("The OpenID %s was invalid") % openid_url
        auth_oidlogin.send(sender=None,
                           openid_url=_openid_url,
                           state='invalid')
        return on_failure(request, msg)

    # get capabilities
    use_ax, use_sreg = discover_extensions(openid_url)
    if use_sreg:
        # set sreg extension
        # we always ask for nickname and email
        sreg_attrs = getattr(settings, 'OPENID_SREG', {})
        sreg_attrs.update({"optional": ['nickname', 'email']})
        sreg_req = sreg.SRegRequest(**sreg_attrs)
    if use_ax:
        # set ax extension
        # we always ask for nickname and email
        ax_req = ax.FetchRequest()
        ax_req.add(
            ax.AttrInfo('http://schema.openid.net/contact/email',
                        alias='email',
                        required=True))
        ax_req.add(
            ax.AttrInfo('http://schema.openid.net/namePerson/friendly',
                        alias='nickname',
                        required=True))
        # add custom ax attrs
        ax_attrs = getattr(settings, 'OPENID_AX', [])
        for attr in ax_attrs:
            if len(attr) == 2:
                ax_req.add(ax.AttrInfo(attr[0], required=alias[1]))
            else:
                ax_req.add(ax.AttrInfo(attr[0]))

    if sreg_req is not None:
        auth_request.addExtension(sreg_req)
    if ax_req is not None:
        auth_request.addExtension(ax_req)
    redirect_url = auth_request.redirectURL(trust_root, redirect_to)
    return HttpResponseRedirect(redirect_url)
Пример #20
0
 def clean_openid_url(self):
     """ test if openid is accepted """
     if 'openid_url' in self.cleaned_data:
         openid_url = self.cleaned_data['openid_url']
         if xri.identifierScheme(openid_url) == 'XRI' and getattr(
                 django_settings, 'OPENID_DISALLOW_INAMES', False
             ):
             raise forms.ValidationError(_('i-names are not supported'))
         return self.cleaned_data['openid_url']
Пример #21
0
def signin(request, sreg=None, extension_args={}, on_failure=default_on_failure):
    openid_url = None
    if is_valid_next_url(request.GET.get('next')):
        next = request.GET['next']
    elif is_valid_next_url(get_address(request.META.get('HTTP_REFERER'), request)):
        next = get_address(request.META['HTTP_REFERER'], request)
    else:
        next = getattr(settings, 'OPENID_REDIRECT_NEXT', '/')

    def get_with_next(url, next):
        if next:
            return '%s?%s' % (url, urlencode({'next': next}))
        else:
            return url

    if request.user.is_authenticated() and 'force' not in request.GET:
        return HttpResponseRedirect(next)

    request_path = get_with_next(request.path, next)

    if request.method == 'POST':
        form = OpenidSigninForm(request.POST, auto_id='id_%s')
        if form.is_valid():
            # first remove email and nickname from sreg if the are in to prevent dup
            extension_args['sreg.optional'] = 'email,nickname'
            if sreg:
                sreg = ','.join([arg for arg in sreg.split(',') if arg not in extension_args['sreg.optional']])
                extension_args['sreg.optional'] += ',' + sreg

            trust_root = getattr(settings, 'OPENID_TRUST_ROOT', absolutize_uri(request, '/'))

            redirect_to = get_with_next(absolutize_uri(request, reverse('openid_complete')), next)

            if xri.identifierScheme(form.cleaned_data['openid_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(form.cleaned_data['openid_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)
    else:
        form = OpenidSigninForm(auto_id='id_%s')

    return {
        'form': form,
        'action': request_path,
        }
Пример #22
0
def signin(request, sreg=None, extension_args={}, on_failure=default_on_failure):
    openid_url = None
    if is_valid_next_url(request.GET.get("next")):
        next = request.GET["next"]
    elif is_valid_next_url(get_address(request.META.get("HTTP_REFERER"), request)):
        next = get_address(request.META["HTTP_REFERER"], request)
    else:
        next = getattr(settings, "OPENID_REDIRECT_NEXT", "/")

    def get_with_next(url, next):
        if next:
            return "%s?%s" % (url, urlencode({"next": next}))
        else:
            return url

    if request.user.is_authenticated() and "force" not in request.GET:
        return HttpResponseRedirect(next)

    request_path = get_with_next(request.path, next)

    if request.method == "POST":
        form = OpenidSigninForm(request.POST, auto_id="id_%s")
        if form.is_valid():
            # first remove email and nickname from sreg if the are in to prevent dup
            extension_args["sreg.optional"] = "email,nickname"
            if sreg:
                sreg = ",".join([arg for arg in sreg.split(",") if arg not in extension_args["sreg.optional"]])
                extension_args["sreg.optional"] += "," + sreg

            trust_root = getattr(settings, "OPENID_TRUST_ROOT", absolutize_uri(request, "/"))

            redirect_to = get_with_next(absolutize_uri(request, reverse("openid_complete")), next)

            if xri.identifierScheme(form.cleaned_data["openid_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(form.cleaned_data["openid_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)
    else:
        form = OpenidSigninForm(auto_id="id_%s")

    return {"form": form, "action": request_path}
Пример #23
0
 def clean_openid_url(self):
     """
         Проверка введённого OpenID идентификатора
     """
     if 'openid_url' in self.cleaned_data:
         openid_url = self.cleaned_data['openid_url']
         if xri.identifierScheme(openid_url) == 'XRI' and getattr(
             settings, 'OPENID_DISALLOW_INAMES', False
             ):
             raise forms.ValidationError(_('i-names are not supported'))
         return self.cleaned_data['openid_url']
Пример #24
0
def ask_openid(request, openid_url, redirect_to, on_failure=None):
    """ basic function to ask openid and return response """
    on_failure = on_failure or signin_failure
    sreg_req = None
    ax_req = None

    trust_root = getattr(
        settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/'
    )
    if xri.identifierScheme(openid_url) == 'XRI' and getattr(
            settings, 'OPENID_DISALLOW_INAMES', False
    ):
        msg = _("i-names are not supported")
        return on_failure(request, msg)
    consumer = Consumer(request.session, DjangoOpenIDStore())
    try:
        auth_request = consumer.begin(openid_url)
    except DiscoveryFailure:
        msg = _("The OpenID %s was invalid") % openid_url
        return on_failure(request, msg)

    # get capabilities
    use_ax, use_sreg = discover_extensions(openid_url)
    if use_sreg:
        # set sreg extension
        # we always ask for nickname and email
        sreg_attrs = getattr(settings, 'OPENID_SREG', {})
        sreg_attrs.update({"optional": ['nickname', 'email']})
        sreg_req = sreg.SRegRequest(**sreg_attrs)
    if use_ax:
        # set ax extension
        # we always ask for nickname and email
        ax_req = ax.FetchRequest()
        ax_req.add(ax.AttrInfo('http://schema.openid.net/contact/email', 
                                alias='email', required=True))
        ax_req.add(ax.AttrInfo('http://schema.openid.net/namePerson/friendly', 
                                alias='nickname', required=True))

        # add custom ax attrs          
        ax_attrs = getattr(settings, 'OPENID_AX', [])
        for attr in ax_attrs:
            if len(attr) == 2:
                ax_req.add(ax.AttrInfo(attr[0], required=alias[1]))
            else:
                ax_req.add(ax.AttrInfo(attr[0]))

    if sreg_req is not None:
        auth_request.addExtension(sreg_req)
    if ax_req is not None:
        auth_request.addExtension(ax_req)

    redirect_url = auth_request.redirectURL(trust_root, redirect_to)
    return HttpResponseRedirect(redirect_url)
Пример #25
0
def begin(request, sreg=None, extension_args=None, redirect_to=None, on_failure=None, if_not_user_url=None):

    on_failure = on_failure or default_on_failure
    if_not_user_url = if_not_user_url or default_if_not_user_url

    if request.GET.get("logo"):
        # Makes for a better demo
        return logo(request)

    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 + urllib.urlencode({"next": request.GET["next"]})

    user_url = request.REQUEST.get("openid_url", None)
    if not user_url:
        return if_not_user_url(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:
        # basic logging exceptions, may help catch incompatible providers, change file to somefile on HDD
        traceback.print_exc(file=sys.stdout)
        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)
Пример #26
0
    def prepare_authentication_request(self, request, redirect_to):
        if not redirect_to.startswith('http://') or redirect_to.startswith(
                'https://'):
            redirect_to = get_url_host(request) + redirect_to

        user_url = self.get_user_url(request)

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

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

        try:
            auth_request = consumer.begin(user_url)
        except DiscoveryFailure:
            raise InvalidAuthentication(
                _('Sorry, but your input is not a valid OpenId'))

        sreg = getattr(self, 'sreg_attributes', False)

        if sreg:
            s = SRegRequest()

            for k, attr_dic in sreg.items():
                if k == "policy_url":
                    s.policy_url = attr_dic
                    continue

                for attr_name in attr_dic.keys():
                    s.requestField(field_name=attr_name,
                                   required=(k == "required"))

            auth_request.addExtension(s)

        ax_schema = getattr(self, 'dataype2ax_schema', False)

        if ax_schema and request.session.get('force_email_request', True):
            axr = AXFetchRequest()
            for data_type, schema in ax_schema.items():
                if isinstance(schema, tuple):
                    axr.add(AttrInfo(schema[0], required=True,
                                     alias=schema[1]))
                else:
                    axr.add(AttrInfo(schema, required=True, alias=data_type))

            auth_request.addExtension(axr)

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

        return auth_request.redirectURL(trust_root, redirect_to)
Пример #27
0
    def prepare_authentication_request(self, request, redirect_to):
        if not redirect_to.startswith('http://') or redirect_to.startswith('https://'):
		    redirect_to =  get_url_host(request) + redirect_to

        user_url = self.get_user_url(request)

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

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

        try:
            auth_request = consumer.begin(user_url)
        except DiscoveryFailure:
            raise InvalidAuthentication(_('Sorry, but your input is not a valid OpenId'))

        sreg = getattr(self, 'sreg_attributes', False)

        if sreg:
            s = SRegRequest()

            for k, attr_dic in sreg.items():
                if k == "policy_url":
                    s.policy_url = attr_dic
                    continue

                for attr_name in attr_dic.keys():
                    s.requestField(field_name=attr_name, required=(k == "required"))

            auth_request.addExtension(s)

        ax_schema = getattr(self, 'dataype2ax_schema', False)

        if ax_schema and request.session.get('force_email_request', True):
            axr = AXFetchRequest()
            for data_type, schema in ax_schema.items():
                if isinstance(schema, tuple):
                    axr.add(AttrInfo(schema[0], 1, True, schema[1]))
                else:
                    axr.add(AttrInfo(schema, 1, True, data_type))

            auth_request.addExtension(axr)

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

        return auth_request.redirectURL(trust_root, redirect_to)
Пример #28
0
 def clean_openid_url(self):
     openid_error = self.request.session.get(OPENID_ERROR_SESSION_NAME, '')
     if openid_error:
         self.request.session[OPENID_ERROR_SESSION_NAME] = ''
         raise forms.ValidationError(_(openid_error))
     openid_url = self.cleaned_data['openid_url']
     #Determine if we need to and can support openid inames
     disallow_inames = getattr(settings, 'OPENID_DISALLOW_INAMES', False)
     if disallow_inames and xri.identifierScheme(openid_url) == 'XRI':
         raise forms.ValidationError(_('i-names are not allowed'))
     #Set up the openid authorization request
     consumer = Consumer(self.request.session, DjangoOpenIDStore())
     try:
         auth_request = consumer.begin(openid_url)
     except DiscoveryFailure, df:
         raise forms.ValidationError("%s: %s" % (_("OpenID Discovery Failure"), df))
Пример #29
0
    def prepare_authentication_request(self, request, redirect_to):
        if not redirect_to.startswith('http://') or redirect_to.startswith(
                'https://'):
            redirect_to = get_url_host(request) + redirect_to

        user_url = self.get_user_url(request)

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

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

        try:
            auth_request = consumer.begin(user_url)
        except DiscoveryFailure:
            raise InvalidAuthentication(
                _('Sorry, but your input is not a valid OpenId'))

        #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)

        #auth_request.addExtension(SRegRequest(required=['email']))

        if request.session.get('force_email_request', True):
            axr = AXFetchRequest()
            for data_type, schema in self.dataype2ax_schema.items():
                if isinstance(schema, tuple):
                    axr.add(AttrInfo(schema[0], 1, True, schema[1]))
                else:
                    axr.add(AttrInfo(schema, 1, True, data_type))

            auth_request.addExtension(axr)

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

        return auth_request.redirectURL(trust_root, redirect_to)
Пример #30
0
    def prepare_authentication_request(self, request, redirect_to):
        if not redirect_to.startswith('http://') or redirect_to.startswith('https://'):
		    redirect_to =  get_url_host(request) + redirect_to

        user_url = self.get_user_url(request)

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

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

        try:
            auth_request = consumer.begin(user_url)
        except DiscoveryFailure:
            raise InvalidAuthentication(_('Sorry, but your input is not a valid OpenId'))

        #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)

        #auth_request.addExtension(SRegRequest(required=['email']))

        if request.session.get('force_email_request', True):
            axr = AXFetchRequest()
            for data_type, schema in self.dataype2ax_schema.items():
                if isinstance(schema, tuple):
                    axr.add(AttrInfo(schema[0], 1, True, schema[1]))
                else:
                    axr.add(AttrInfo(schema, 1, True, data_type))

            auth_request.addExtension(axr)

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

        return auth_request.redirectURL(trust_root, redirect_to)
Пример #31
0
 def clean_openid_url(self):
     openid_error = self.request.session.get(OPENID_ERROR_SESSION_NAME, '')
     if openid_error:
         self.request.session[OPENID_ERROR_SESSION_NAME] = ''
         raise forms.ValidationError(_(openid_error))
     openid_url = self.cleaned_data['openid_url']
     #Determine if we need to and can support openid inames
     disallow_inames = getattr(settings, 'OPENID_DISALLOW_INAMES', False)
     if disallow_inames and xri.identifierScheme(openid_url) == 'XRI':
         raise forms.ValidationError(_('i-names are not allowed'))
     #Set up the openid authorization request
     consumer = Consumer(self.request.session, DjangoOpenIDStore())
     try:
         auth_request = consumer.begin(openid_url)
     except DiscoveryFailure, df:
         raise forms.ValidationError("%s: %s" %
                                     (_("OpenID Discovery Failure"), df))
Пример #32
0
def ask_openid(request, openid_url, redirect_to, on_failure=None):
    on_failure = on_failure or signin_failure
    sreg_req = None
    ax_req = None
    _openid_url = openid_url
    trust_root = getattr(settings, "OPENID_TRUST_ROOT", get_url_host(request) + "/")
    if xri.identifierScheme(openid_url) == "XRI" and getattr(settings, "OPENID_DISALLOW_INAMES", False):
        msg = "i-names are not supported"
        auth_oidlogin.send(sender=None, openid_url=_openid_url, state="not_supported")
        return on_failure(request, msg)
    consumer = Consumer(request.session, DjangoOpenIDStore())
    try:
        auth_request = consumer.begin(openid_url)
    except DiscoveryFailure:
        msg = ("The OpenID %s was invalid") % openid_url
        auth_oidlogin.send(sender=None, openid_url=_openid_url, state="invalid")
        return on_failure(request, msg)

    # get capabilities
    use_ax, use_sreg = discover_extensions(openid_url)
    if use_sreg:
        # set sreg extension
        # we always ask for nickname and email
        sreg_attrs = getattr(settings, "OPENID_SREG", {})
        sreg_attrs.update({"optional": ["nickname", "email"]})
        sreg_req = sreg.SRegRequest(**sreg_attrs)
    if use_ax:
        # set ax extension
        # we always ask for nickname and email
        ax_req = ax.FetchRequest()
        ax_req.add(ax.AttrInfo("http://schema.openid.net/contact/email", alias="email", required=True))
        ax_req.add(ax.AttrInfo("http://schema.openid.net/namePerson/friendly", alias="nickname", required=True))
        # add custom ax attrs
        ax_attrs = getattr(settings, "OPENID_AX", [])
        for attr in ax_attrs:
            if len(attr) == 2:
                ax_req.add(ax.AttrInfo(attr[0], required=alias[1]))
            else:
                ax_req.add(ax.AttrInfo(attr[0]))

    if sreg_req is not None:
        auth_request.addExtension(sreg_req)
    if ax_req is not None:
        auth_request.addExtension(ax_req)
    redirect_url = auth_request.redirectURL(trust_root, redirect_to)
    return HttpResponseRedirect(redirect_url)
Пример #33
0
 def clean_openid_url(self):
     """ test if openid is accepted """
     if 'openid_url' in self.cleaned_data:
         openid_url = self.cleaned_data['openid_url']
         if xri.identifierScheme(openid_url) == 'XRI' and getattr(
             settings, 'OPENID_DISALLOW_INAMES', False
             ):
             raise forms.ValidationError(_('i-names are not supported'))
         try:
             rel = UserAssociation.objects.get(openid_url__exact=openid_url)
         except UserAssociation.DoesNotExist:
             return self.cleaned_data['openid_url']
         
         if rel.user != self.user:
             raise forms.ValidationError(_("This openid is already \
                 registered in our database by another account. Please choose another."))
                 
         raise forms.ValidationError(_("You already associated this openid to your account."))
Пример #34
0
def ask_openid(request, openid_url):
	""" basic function to ask openid and return response """

	if xri.identifierScheme(openid_url) == 'XRI' and getattr(
			settings, 'OPENID_DISALLOW_INAMES', False
	):
		#msg = _("i-names are not supported")
		raise forms.ValidationError(_("i-names are not supported"))
		#return on_failure(request, msg)
		
	consumer = Consumer(request.session, DjangoOpenIDStore())
	try:
		auth_request = consumer.begin(openid_url)
		return auth_request
	except DiscoveryFailure:
		#msg = _("The password or OpenID was invalid")
		raise forms.ValidationError(_("The password or OpenID is invalid"))
		#return on_failure(request, msg)

	#return HttpResponseRedirect(redirect_url)
	return False
Пример #35
0
    def clean_openid_url(self):
        """ test if openid is accepted """
        if 'openid_url' in self.cleaned_data:
            openid_url = self.cleaned_data['openid_url']
            if xri.identifierScheme(openid_url) == 'XRI' and getattr(
                    settings, 'OPENID_DISALLOW_INAMES', False):
                raise forms.ValidationError(_('i-names are not supported'))

            try:
                rel = UserAssociation.objects.get(openid_url__exact=openid_url)
            except UserAssociation.DoesNotExist:
                return self.cleaned_data['openid_url']

            if rel.user != self.user:
                raise forms.ValidationError(
                    _("This openid is already \
                    registered in our database by another account. Please choose another."
                      ))

            raise forms.ValidationError(
                _("You already associated this openid to your account."))
Пример #36
0
 def is_xri(self, user_url):
     return xri.identifierScheme(user_url) == 'XRI'
Пример #37
0
def signin(request,
           sreg=None,
           extension_args={},
           on_failure=default_on_failure):
    openid_url = None
    if is_valid_next_url(request.GET.get('next')):
        next = request.GET['next']
    elif is_valid_next_url(
            get_address(request.META.get('HTTP_REFERER'), request)):
        next = get_address(request.META['HTTP_REFERER'], request)
    else:
        next = getattr(settings, 'OPENID_REDIRECT_NEXT', '/')

    def get_with_next(url, next):
        if next:
            return '%s?%s' % (url, urlencode({'next': next}))
        else:
            return url

    if request.user.is_authenticated() and 'force' not in request.GET:
        return HttpResponseRedirect(next)

    request_path = get_with_next(request.path, next)

    if request.method == 'POST':
        form = OpenidSigninForm(request.POST, auto_id='id_%s')
        if form.is_valid():
            # first remove email and nickname from sreg if the are in to prevent dup
            extension_args['sreg.optional'] = 'email,nickname'
            if sreg:
                sreg = ','.join([
                    arg for arg in sreg.split(',')
                    if arg not in extension_args['sreg.optional']
                ])
                extension_args['sreg.optional'] += ',' + sreg

            trust_root = getattr(settings, 'OPENID_TRUST_ROOT',
                                 request.build_absolute_uri('/'))

            redirect_to = get_with_next(
                request.build_absolute_uri(reverse('openid_complete')), next)

            if xri.identifierScheme(
                    form.cleaned_data['openid_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(form.cleaned_data['openid_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)
    else:
        form = OpenidSigninForm(auto_id='id_%s')

    return {
        'form': form,
        'action': request_path,
    }
Пример #38
0
 def is_iname(self):
     return xri.identifierScheme(self.openid) == 'XRI'
Пример #39
0
def begin(request, 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 + urllib.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 += "?" + urllib.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)

    OPENID_AX_PROVIDER_MAP = getattr(settings, "OPENID_AX_PROVIDER_MAP", {})

    openid_provider = "Google" if "google" in request.session.get("openid_provider", "") else "Default"
    ax = OPENID_AX_PROVIDER_MAP.get(openid_provider)

    if ax:
        axr = AXFetchRequest()
        for attr_name, attr_url in ax.items():
            # axr.add(AttrInfo(i['type_uri'],
            #    i['count'], i['required'],
            #    i['alias']))

            # setting all as required attrs
            axr.add(AttrInfo(attr_url, required=True))
        auth_request.addExtension(axr)

    redirect_url = auth_request.redirectURL(trust_root, redirect_to)

    return HttpResponseRedirect(redirect_url)
Пример #40
0
 def is_iname(self):
     return xri.identifierScheme(self.openid) == 'XRI'
Пример #41
0
 def openidURI(self):
     from openid.yadis import xri
     if xri.identifierScheme(self.openid) == 'XRI':
         return 'http://xri.net/%s' % self.openid
     return self.openid
Пример #42
0
 def openidURI(self):
   from openid.yadis import xri
   if xri.identifierScheme(self.openid) == "XRI":
     return "http://xri.net/%s" % self.openid
   return self.openid
Пример #43
0
def begin(request, 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 + urllib.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 += '?' + urllib.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)
    
    OPENID_AX_PROVIDER_MAP = getattr(settings, 'OPENID_AX_PROVIDER_MAP', {})
    
    openid_provider = 'Google' if 'Google' == request.session.get('openid_provider', '') else 'Default'
    ax = OPENID_AX_PROVIDER_MAP.get(openid_provider)
    
    if ax:
        axr = AXFetchRequest()
        for attr_name, attr_url in ax.items():
            # axr.add(AttrInfo(i['type_uri'], i['count'], i['required'], i['alias']))
            axr.add(AttrInfo(attr_url, required=True)) # setting all as required attrs
        auth_request.addExtension(axr)
    
    redirect_url = auth_request.redirectURL(trust_root, redirect_to)
    
    return HttpResponseRedirect(redirect_url)
Пример #44
0
def discover(identifier):
    if xri.identifierScheme(identifier) == "XRI":
        return discoverXRI(identifier)
    else:
        return discoverURI(identifier)
Пример #45
0
def begin(request, sreg=None, extension_args=None, redirect_to=None, 
        on_failure=None,**kwards):
    
    on_failure = on_failure or default_on_failure
    
    if request.GET.get('logo'):
        # Makes for a better demo
        return logo(request)
    
    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 + urllib.urlencode({
            'next': request.GET['next']
        })
    
    user_url = request.POST.get('openid_url', None)
    if not user_url:
        request_path = request.path
        if request.GET.get('next'):
            request_path += '?' + urllib.urlencode({
                'next': request.GET['next']
            })
        
        return render('openid_signin.html', {
            'action': request_path,
            'logo': request.path + '?logo=1',
        })
    
    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)
Пример #46
0
 def is_xri(self, user_url):
     return xri.identifierScheme(user_url) == 'XRI'
Пример #47
0
 def openidURI(self):
     from openid.yadis import xri
     if xri.identifierScheme(self.openid) == "XRI":
         return "http://xri.net/%s" % self.openid
     return self.openid
Пример #48
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 logo(request)

    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 + urllib.urlencode({'next': request.GET['next']})

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

        return render(request, 'openid_signin.html', {
            'action': request_path,
            'logo': request.path + '?logo=1',
        })

    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 redirect(redirect_url)
Пример #49
0
def begin(request,
          redirect_to=None,
          on_failure=None,
          template_name='openid_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,
                                                     request.GET['next']):
        if '?' in redirect_to:
            join = '&'
        else:
            join = '?'
        redirect_to += join + urllib.urlencode({'next': request.GET['next']})

    user_url = request.REQUEST.get('openid_url', None)

    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},
                      context_instance=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 = 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)