当前位置: 首页>>代码示例>>Python>>正文


Python Consumer.complete方法代码示例

本文整理汇总了Python中openid.consumer.consumer.Consumer.complete方法的典型用法代码示例。如果您正苦于以下问题:Python Consumer.complete方法的具体用法?Python Consumer.complete怎么用?Python Consumer.complete使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在openid.consumer.consumer.Consumer的用法示例。


在下文中一共展示了Consumer.complete方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: callback

# 需要导入模块: from openid.consumer.consumer import Consumer [as 别名]
# 或者: from openid.consumer.consumer.Consumer import complete [as 别名]
def callback(request):
    consumer = Consumer(request.session, FileOpenIDStore("/tmp/gtugdemo"))

    openid_response = consumer.complete(request.REQUEST, "http://%s/login/callback" % request.get_host())

    if openid_response.status == SUCCESS:
        ax_response = ax.FetchResponse.fromSuccessResponse(openid_response)
        if ax_response:
            ax_items = {
                "firstname": ax_response.get("http://axschema.org/namePerson/first"),
                "lastname": ax_response.get("http://axschema.org/namePerson/last"),
                "email": ax_response.get("http://schema.openid.net/contact/email"),
            }

            username = "".join(ax_items["email"])
            firstname = "".join(ax_items["firstname"])
            lastname = "".join(ax_items["lastname"])
            email = "".join(ax_items["email"])
            register_user(username, firstname, lastname, email)
            user = User.objects.get(username=username)
            user.backend = "django.contrib.auth.backends.ModelBackend"
            login(request, user)
            return redirect(to="http://%s/" % request.get_host())
        else:
            message = openid_response.message

    return render_to_response("login.html", locals(), context_instance=RequestContext(request))
开发者ID:jagbolanos,项目名称:gtugdemo,代码行数:29,代码来源:views.py

示例2: process_request

# 需要导入模块: from openid.consumer.consumer import Consumer [as 别名]
# 或者: from openid.consumer.consumer.Consumer import complete [as 别名]
    def process_request(self, request):
        if request.path_info[0:7] != '/admin/':
            return None

        if 'openid_username' not in request.session:
            request.session['openid_session'] = {}
            consumer = Consumer(request.session['openid_session'], None)

            # auth request to google has not been made yet
            if 'openid.mode' not in request.REQUEST:
                ax_request = ax.FetchRequest()
                ax_request.add(ax.AttrInfo('http://axschema.org/contact/email', required = True))

                auth_request = consumer.begin('https://www.google.com/accounts/o8/id')
                auth_request.addExtension(ax_request)

                url = auth_request.redirectURL(
                    request.build_absolute_uri('/'),
                    return_to=request.build_absolute_uri())
                return redirect(url)
            # auth request has been made, thus analyse google response
            else:
                info = consumer.complete(request.REQUEST, request.build_absolute_uri())
                if info.status == SUCCESS:
                    ax_response = ax.FetchResponse.fromSuccessResponse(info)
                    username = ax_response.get('http://axschema.org/contact/email')[0]
                    request.session['openid_username'] = username

        username = request.session.get('openid_username', None)
        if username not in AUTHORIZED_EMAILS:
            if username: del request.session['openid_username']
            return HttpResponse('403 Forbidden', status=403)
开发者ID:veloce,项目名称:parole2,代码行数:34,代码来源:middleware.py

示例3: complete_openid

# 需要导入模块: from openid.consumer.consumer import Consumer [as 别名]
# 或者: from openid.consumer.consumer.Consumer import complete [as 别名]
def complete_openid(request, success_view, failure_view, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    The openid callback utility view.
    
    ``redirect_field_name`` must be set to the same value as that passed into
    the ``begin_openid`` view that initiates the openid call.
    """
    success_view = get_view(success_view)
    failure_view = get_view(failure_view)
    #Get the openid response
    consumer = Consumer(request.session, DjangoOpenIDStore())
    openid_response = consumer.complete(dict(request.GET.items()))
    #Deal with the response based on status
    if openid_response.status == SUCCESS:
        return success_view(request, openid_response, redirect_field_name=redirect_field_name)
    else:
        if openid_response.status == CANCEL:
            error_message = _("The request was cancelled.")
        elif openid_response.status == FAILURE:
            error_message = _(openid_response.message)
        elif openid_response.status == SETUP_NEEDED:
            error_message = _("Setup needed.  Please check your OpenID provider and try again.")
        else:
            error_message = "%s: %s" % (_("Bad openid status"), openid_response.status)
        return failure_view(request, openid_response, error_message, redirect_field_name=redirect_field_name)
开发者ID:ejconlon,项目名称:Wecolage_Django,代码行数:27,代码来源:auth_controller.py

示例4: login_openid_callback

# 需要导入模块: from openid.consumer.consumer import Consumer [as 别名]
# 或者: from openid.consumer.consumer.Consumer import complete [as 别名]
def login_openid_callback(request):
    consumer = Consumer(request.session, DjangoOpenIDStore())
    #trust_root = 'http://'+settings.SEYMOUR_DOMAIN + '/'
    redirect_to = 'http://'+settings.SEYMOUR_DOMAIN+'/login/openid/'                
    #redirect_url = auth_request.redirectURL(trust_root, redirect_to)
    openid_response = consumer.complete(dict(request.GET.items()), redirect_to)
    
    if openid_response.status == SUCCESS:        
        try:
            account = Account.objects.get(openid=openid_response.identity_url)
        except Account.DoesNotExist:
            error_msg = "No account using that OpenID found."
        else:
            request.session['account_id'] = account.id
            account.last_login = datetime.datetime.now()
            account.save()
        
            return HttpResponseRedirect('/feeds/unread/')
        
    elif openid_response.status == CANCEL:
        error_msg = "The request was cancelled"
    elif openid_response.status == FAILURE:
        error_msg = openid_response.message
    elif openid_response.status == SETUP_NEEDED:
        error_msg = "Setup needed"
    else:
        error_msg = "Bad openid status: %s" % openid_response.status
    
    return render_to_response('accounts/login_error.html', {
        'error_msg': error_msg,
        'section': 'login',
    }, context_instance=RequestContext(request))        
开发者ID:lerouxb,项目名称:seymour,代码行数:34,代码来源:views.py

示例5: get

# 需要导入模块: from openid.consumer.consumer import Consumer [as 别名]
# 或者: from openid.consumer.consumer.Consumer import complete [as 别名]
    def get(self, request, *args, **kwargs):
        consumer = Consumer(request.session, DjangoOpenIDStore())
        query = dict((k, smart_unicode(v)) for k, v in request.GET.items())
        openid_response = consumer.complete(query, self.get_return_url())
        self.openid_response = openid_response

        if openid_response.status == SUCCESS:
            if 'openids' not in request.session.keys():
                request.session['openids'] = []
            request.session['openids'] = filter(
                lambda o: o.openid != openid_response.identity_url,
                request.session['openids'],
            )
            request.session['openids'].append(
                from_openid_response(openid_response),
            )
            OpenIDMiddleware().process_request(request)
            return self.success()
        elif openid_response.status == CANCEL:
            return self.failure(_('The request was cancelled'))
        elif openid_response.status == FAILURE:
            return self.failure(openid_response.message)
        elif openid_response.status == SETUP_NEEDED:
            return self.failure(_('Setup needed'))
        else:
            raise BadOpenIDStatus(openid_response.status)
开发者ID:idan,项目名称:django-le-social,代码行数:28,代码来源:views.py

示例6: signup_openid_callback

# 需要导入模块: from openid.consumer.consumer import Consumer [as 别名]
# 或者: from openid.consumer.consumer.Consumer import complete [as 别名]
def signup_openid_callback(request):
    consumer = Consumer(request.session, DjangoOpenIDStore())    
    redirect_to = 'http://'+settings.SEYMOUR_DOMAIN+'/signup/openid/'
    openid_response = consumer.complete(dict(request.GET.items()), redirect_to)
    
    if openid_response.status == SUCCESS:
        try:
            account = Account.objects.get(openid=openid_response.identity_url)
        except Account.DoesNotExist:
            account = Account(openid=openid_response.identity_url, last_login=datetime.datetime.now(), is_active=True)
            account.save()
            request.session['account_id'] = account.id
            return HttpResponseRedirect('/feeds/unread/')
        else:
            error_msg = "An account for that openid already exists."        
    elif openid_response.status == CANCEL:
        error_msg = "The request was cancelled"
    elif openid_response.status == FAILURE:
        error_msg = openid_response.message
    elif openid_response.status == SETUP_NEEDED:
        error_msg = "Setup needed"
    else:
        error_msg = "Bad openid status: %s" % openid_response.status
    
    return render_to_response('accounts/signup_error.html', {
        'error_msg': error_msg,
        'section': 'signup',
    }, context_instance=RequestContext(request))
开发者ID:lerouxb,项目名称:seymour,代码行数:30,代码来源:views.py

示例7: OpenIDFinish

# 需要导入模块: from openid.consumer.consumer import Consumer [as 别名]
# 或者: from openid.consumer.consumer.Consumer import complete [as 别名]
def OpenIDFinish(request, default_success_url='/', success_handler=None):
  if request.method not in ('GET', 'POST'):
    return django.http.HttpResponseNotAllowed(['GET', 'POST'])
  else:
    args = args_to_dict(request.GET)
    assert type(args) is dict
    if request.method == 'POST':
      args.update(args_to_dict(request.POST))
    url = 'http://'+request.META['HTTP_HOST']+django.core.urlresolvers.reverse(OpenIDFinish)

    s = {}
    sess_key = request.COOKIES.get(COOKIE_NAME, None)
    if sess_key:
      s = store.restoreConsumerSession(sess_key)

    c = Consumer(s, store.DatastoreStore())
    auth_response = c.complete(args, url)

    if auth_response.status == auth_SUCCESS:

      openid_url = auth_response.getDisplayIdentifier()
      continueUrl = get_continue_url(request, default_success_url)
      response = django.http.HttpResponseRedirect(continueUrl)

      if success_handler:
        success_handler(request, response, openid_url)

      return response

    else:
      return err_page("verification_failed")
开发者ID:algby,项目名称:gae-openid,代码行数:33,代码来源:views.py

示例8: complete

# 需要导入模块: from openid.consumer.consumer import Consumer [as 别名]
# 或者: from openid.consumer.consumer.Consumer import complete [as 别名]
def complete(request, on_success=None, on_failure=None, return_to=None):
    """ complete openid signin """
    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()),
            return_to)

    try:
        rel = UserAssociation.objects.get(openid_url__exact = openid_response.identity_url)  
        try:
            rel.user
        except User.DoesNotExist:
            rel.delete()
            return register(request)
    except UserAssociation.DoesNotExist:
        pass

    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
开发者ID:dekom,项目名称:threepress-bookworm-read-only,代码行数:32,代码来源:views.py

示例9: complete

# 需要导入模块: from openid.consumer.consumer import Consumer [as 别名]
# 或者: from openid.consumer.consumer.Consumer import complete [as 别名]
def complete(request, 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.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, _('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
开发者ID:aduston,项目名称:Django-Socialauth,代码行数:29,代码来源:views.py

示例10: callback

# 需要导入模块: from openid.consumer.consumer import Consumer [as 别名]
# 或者: from openid.consumer.consumer.Consumer import complete [as 别名]
def callback(request):
    consumer = Consumer(request.session, FileOpenIDStore('/tmp/gtugdemo'))
    
    openid_response = consumer.complete(request.REQUEST, 'http://%s/login/callback' % request.get_host())
    
    if openid_response.status == SUCCESS:
        print "SUCCESS"
        ax_response = ax.FetchResponse.fromSuccessResponse(openid_response)
        if ax_response:
            ax_items = {
                    'firstname': ax_response.get(
                        'http://axschema.org/namePerson/first'),
                    'lastname': ax_response.get(
                        'http://axschema.org/namePerson/last'),
                    'email': ax_response.get(
                        'http://axschema.org/contact/email'),
                    }
            
            username = ''.join(ax_items['email'])
            firstname = ''.join(ax_items['firstname'])
            lastname = ''.join(ax_items['lastname'])
            email = ''.join(ax_items['email'])
            register_user(username, firstname , lastname , email)
            print "%s %s %s" % (firstname, lastname, email)
            user = User.objects.get(username=username)
            user.backend='django.contrib.auth.backends.ModelBackend'
            login(request, user)
            return redirect(to='http://%s/' % request.get_host())
                
    if openid_response.status == FAILURE:
        print "NOOOOOOOOOOO: %s" % openid_response.message
    
    return render_to_response('login.html', locals(), context_instance=RequestContext(request))
开发者ID:lfborjas,项目名称:gtugdemo,代码行数:35,代码来源:views.py

示例11: complete

# 需要导入模块: from openid.consumer.consumer import Consumer [as 别名]
# 或者: from openid.consumer.consumer.Consumer import complete [as 别名]
def complete(request, on_success=None, on_failure=None, return_to=None):
    """ complete openid signin """
    on_success = on_success or default_on_success
    on_failure = on_failure or default_on_failure
    
    logging.debug('in django_authopenid.complete')
    
    consumer = Consumer(request.session, DjangoOpenIDStore())
    # make sure params are encoded in utf8
    params = dict((k,smart_unicode(v)) for k, v in request.GET.items())
    openid_response = consumer.complete(params, return_to)
    
    if openid_response.status == SUCCESS:
        logging.debug('SUCCESS')
        return on_success(request, openid_response.identity_url,
                openid_response)
    elif openid_response.status == CANCEL:
        logging.debug('CANCEL')
        return on_failure(request, 'The request was canceled')
    elif openid_response.status == FAILURE:
        logging.debug('FAILURE')
        return on_failure(request, openid_response.message)
    elif openid_response.status == SETUP_NEEDED:
        logging.debug('SETUP NEEDED')
        return on_failure(request, 'Setup needed')
    else:
        logging.debug('BAD OPENID STATUS')
        assert False, "Bad openid status: %s" % openid_response.status
开发者ID:evgenyfadeev,项目名称:askbot-devel,代码行数:30,代码来源:views.py

示例12: get

# 需要导入模块: from openid.consumer.consumer import Consumer [as 别名]
# 或者: from openid.consumer.consumer.Consumer import complete [as 别名]
 def get(self, ctx):
     pprint(ctx.args, sys.stderr)
     consumer = Consumer(self.app.session, self.app.store)
     info = consumer.complete(ctx.args, 'http://localhost/profile')
     self.app.session = {}
     if info.status == SUCCESS:
         return Response(200, content="OK")
     return Response(401, 'Unauthorized')
开发者ID:rivan,项目名称:w3fu,代码行数:10,代码来源:_openid.py

示例13: authenticateCredentials

# 需要导入模块: from openid.consumer.consumer import Consumer [as 别名]
# 或者: from openid.consumer.consumer.Consumer import complete [as 别名]
    def authenticateCredentials(self, credentials):
        """Authenticates credentials.

        If the credentials can be authenticated, return an object that provides
        IPrincipalInfo. If the plugin cannot authenticate the credentials,
        returns None.
        """
        if not IOpenIdCredentials.providedBy(credentials):
            return None

        if credentials.failed:
            return None

        if credentials.principalInfo is not None \
                and credentials.principalInfo.internalId in self:
            return credentials.principalInfo

        request = credentials.request

        consumer = Consumer(ISession(request)[SESSION_KEY], self.store)

        returnto = credentials.parameters.get(
            'openid.return_to', getReturnToURL(request))
        response = consumer.complete(
            credentials.parameters, returnto.split('?')[0])

        if isinstance(response, SuccessResponse):
            identifier = normalizeIdentifier(response.identity_url)
            principalId = self.getPrincipalByOpenIdIdentifier(identifier)
            if principalId is None:
                # Principal does not exist
                principal = OpenIdPrincipal()
                principal.identifier = identifier

                sregResponse = SRegResponse.fromSuccessResponse(response)

                name = INameChooser(self).chooseName('', principal)
                self[name] = principal
                principalId = self.getPrincipalByOpenIdIdentifier(identifier)

                # register principal in portal registration tool
                auth = getUtility(IAuthentication)
                pid = auth.prefix + self.prefix + name
                try:
                    principal = auth.getPrincipal(pid)
                    getUtility(IPortalRegistration).registerPrincipal(principal)
                except PrincipalLookupError:
                    pass

            principalInfo = self.principalInfo(self.prefix + principalId)
            credentials.principalInfo = principalInfo
            return principalInfo

        else:
            raise PrincipalInitializationFailed(response.message)

        return None
开发者ID:Zojax,项目名称:zojax.principal.openid,代码行数:59,代码来源:plugin.py

示例14: openid_return

# 需要导入模块: from openid.consumer.consumer import Consumer [as 别名]
# 或者: from openid.consumer.consumer.Consumer import complete [as 别名]
def openid_return(request):
    oidutil.log = dummyOpenIdLoggingFunction

    if request.method != 'GET':
        return HttpResponseServerError("Invalid Input")

    get_dict = request.GET
    base_url = request.build_absolute_uri(request.path)

    openid_consumer = Consumer(request.session, CassandraStore())
    response = openid_consumer.complete(get_dict, base_url)

    if response.status != 'success':
        messages.error(request, 'Failed response from OpenID Provider')
        return redirect('users.views.login')

    if login_with_openid_identity(request, response.identity_url):
        return redirect('content.views.browse')

    ax_resp = ax.FetchResponse.fromSuccessResponse(response)

    if ax_resp:
        try:
            email = ax_resp.get('http://axschema.org/contact/email')[0]
        except KeyError:
            email = ''
    
        try:
            first_name = ax_resp.get('http://axschema.org/namePerson/first')[0]
        except KeyError:
            first_name = None
    
        try:
            last_name = ax_resp.get('http://axschema.org/namePerson/last')[0]
        except KeyError:
            last_name = None

    else:
        first_name = None
        last_name = None
        email = ''

    if first_name == None and last_name == None:
        name = ''
    elif first_name == None:
        name = last_name
    elif last_name == None:
        name = first_name
    else:
        name = "%s %s" % (first_name, last_name)

    request.session['openid_identity'] = response.identity_url
    request.session['openid_email'] = email
    request.session['openid_name'] = name

    return redirect('users.views.openid_link')
开发者ID:hnkien,项目名称:sirikata-cdn,代码行数:58,代码来源:views.py

示例15: login_complete

# 需要导入模块: from openid.consumer.consumer import Consumer [as 别名]
# 或者: from openid.consumer.consumer.Consumer import complete [as 别名]
    def login_complete(self):
        """This function is called once a user has succesfully logged in to
        his/her OpenID account. The user is then prompted to choose a
        preferred alias to be known as if a default one is not provided.
        """
        consumer = Consumer(session=session, store=self.openid_store)
        host = request.headers['host']
        return_url = url(host=host, controller='account',
            action='login_complete')
        result = consumer.complete(request.params, return_url)
        if result.status != 'success':
            return _('An error ocurred with login.')
        try:
            user = model.User.by_identifier(result.identity_url).one()
            session['userid'] = user.id
        except (AttributeError, NoResultFound):
            # No previous login record for the user.
            sreg_res = SRegResponse.fromSuccessResponse(result)
            try:
                email = sreg_res['email']
            except (TypeError, KeyError):
                email = ''

            try:
                name = sreg_res['nickname']
            except (TypeError, KeyError):
                name = result.identity_url
            user = model.User(
                name=name,
                identifier=result.identity_url,
                email=email
            )
            try:
                model.User.all()
            except NoResultFound:
                # Since you're going to be the only user, might as well grant
                # you administrator privileges.
                user.admin = True
            model.session.add(user)
            model.session.commit()
            session['userid'] = user.id
        session.save()
        if user.name == result.identity_url:
            h.flash(
                _('Login was successful, but now you need to set a name.'),
                'warning'
            )
            redirect(
                url(
                    controller='account',
                    action='profile',
                    id=user.id,
                    edit='true'
                )
            )
        redirect(url(controller='blog', action='index'))
开发者ID:chrisrsantiago,项目名称:muse,代码行数:58,代码来源:account.py


注:本文中的openid.consumer.consumer.Consumer.complete方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。