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


Python sreg.SRegRequest类代码示例

本文整理汇总了Python中openid.extensions.sreg.SRegRequest的典型用法代码示例。如果您正苦于以下问题:Python SRegRequest类的具体用法?Python SRegRequest怎么用?Python SRegRequest使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: login

def login(request):
    if 'openid' in request.GET or request.method == 'POST':
        form = LoginForm(request.REQUEST)
        if form.is_valid():
            client = _openid_consumer(request)
            try:
                auth_request = client.begin(form.cleaned_data['openid'])
                if QUERY_EMAIL:
                    sreg = SRegRequest()
                    sreg.requestField(field_name=SRegField.EMAIL,
                                      required=True)
                    auth_request.addExtension(sreg)
                    ax = FetchRequest()
                    ax.add(AttrInfo(AXAttribute.CONTACT_EMAIL,
                                    required=True))
                    auth_request.addExtension(ax)
                callback_url = reverse(callback)
                SocialLogin.stash_state(request)
                redirect_url = auth_request.redirectURL(
                    request.build_absolute_uri('/'),
                    request.build_absolute_uri(callback_url))
                return HttpResponseRedirect(redirect_url)
            # UnicodeDecodeError:
            # see https://github.com/necaris/python3-openid/issues/1
            except (UnicodeDecodeError, DiscoveryFailure) as e:
                if request.method == 'POST':
                    form._errors["openid"] = form.error_class([e])
                else:
                    return render_authentication_error(request)
    else:
        form = LoginForm()
    d = dict(form=form)
    return render_to_response('openid/login.html',
                              d, context_instance=RequestContext(request))
开发者ID:aehlke,项目名称:django-allauth,代码行数:34,代码来源:views.py

示例2: __init__

    def __init__(self, status, identity_url):
        self.status = status
        self.identity_url = identity_url
        self.message = message.Message()

        sig_ext = SignatureVerification(consumer_key='CKEY',
                                        secret_key='SKEY',
                                        request_token='token',
                                        hmac=None,
                                        timestamp=None)
        sig_ext.toMessage(self.message)

        sreg_ext = SRegRequest(required = ['nickname','email'],
                               optional = ['fullname'],
                               policy_url = None,
                               sreg_ns_uri = 'http://openid.net/extensions/sreg/1.1')
        sreg_ext.toMessage(self.message)
        self.signed_fields = ['openid.sreg.nickname', 'openid.sreg.email',
                              'openid.sreg.required', 'openid.sreg.optional',
                              'openid.sreg.fullname']



        self.endpoint = OpenIDServiceEndpoint()
        self.endpoint.claimed_id=identity_url
开发者ID:pbs,项目名称:uua-django-consumer2,代码行数:25,代码来源:tests.py

示例3: begin

def begin(request, openid_url):
    request.session['request_referer'] = urlparse.urljoin(request.META.get('HTTP_REFERER', ''), '/')
    
    consumer = Consumer(request.session, DjangoOpenIDStore())
 
    try:
        auth_request = consumer.begin(openid_url)
    except DiscoveryFailure:
        return on_failure(request, _('The OpenID was invalid'))
    
    s = SRegRequest()        
    for sarg in OPENID_SREG:
        if sarg.lower().lstrip() == "policy_url":
            s.policy_url = OPENID_SREG[sarg]
        else:
            for v in OPENID_SREG[sarg].split(','):
                s.requestField(field_name=v.lower().lstrip(), required=(sarg.lower().lstrip() == "required"))
    auth_request.addExtension(s)  
    
    axr = AXFetchRequest()
    for i in OPENID_AX:
        axr.add(AttrInfo(i['type_uri'], i['count'], i['required'], i['alias']))
    auth_request.addExtension(axr)
 
    redirect_url = auth_request.redirectURL(get_trusted_root(request),
                                            request.build_absolute_uri(reverse("openid_complete")))
    
    return HttpResponseRedirect(redirect_url)
开发者ID:Zojax,项目名称:zojax.django.socialauthentication,代码行数:28,代码来源:views.py

示例4: login

def login(request):
    if 'openid' in request.GET or request.method == 'POST':
        form = LoginForm(request.REQUEST)
        if form.is_valid():
            client = _openid_consumer(request)
            try:
                auth_request = client.begin(form.cleaned_data['openid'])
                if QUERY_EMAIL:
                    sreg = SRegRequest()
                    sreg.requestField(field_name=SRegField.EMAIL, required=True)
                    auth_request.addExtension(sreg)
                    ax = FetchRequest()
                    ax.add(AttrInfo(AXAttribute.CONTACT_EMAIL,
                                    required=True))
                    auth_request.addExtension(ax)
                callback_url = reverse(callback)
                state = SocialLogin.marshall_state(request)
                callback_url = callback_url + '?' + urlencode(dict(state=state))
                redirect_url = auth_request.redirectURL(
                    request.build_absolute_uri('/'),
                    request.build_absolute_uri(callback_url))
                return HttpResponseRedirect(redirect_url)
            except DiscoveryFailure, e:
                if request.method == 'POST':
                    form._errors["openid"] = form.error_class([e])
                else:
                    return render_authentication_error(request)
开发者ID:CARocha,项目名称:django-allauth,代码行数:27,代码来源:views.py

示例5: login

def login(request):
    if 'openid' in request.GET or request.method == 'POST':
        form = LoginForm(
            dict(list(request.GET.items()) + list(request.POST.items()))
        )
        if form.is_valid():
            client = _openid_consumer(request)
            provider = OpenIDProvider(request)
            realm = provider.get_settings().get(
                'REALM',
                request.build_absolute_uri('/'))
            try:
                auth_request = client.begin(form.cleaned_data['openid'])
                if QUERY_EMAIL:
                    sreg = SRegRequest()
                    for name in SRegFields:
                        sreg.requestField(field_name=name,
                                          required=True)
                    auth_request.addExtension(sreg)
                    ax = FetchRequest()
                    for name in AXAttributes:
                        ax.add(AttrInfo(name,
                                        required=True))
                    provider = OpenIDProvider(request)
                    server_settings = \
                        provider.get_server_settings(request.GET.get('openid'))
                    extra_attributes = \
                        server_settings.get('extra_attributes', [])
                    for _, name, required in extra_attributes:
                        ax.add(AttrInfo(name,
                                        required=required))
                    auth_request.addExtension(ax)
                callback_url = reverse(callback)
                SocialLogin.stash_state(request)
                # Fix for issues 1523 and 2072 (github django-allauth)
                if 'next' in form.cleaned_data and form.cleaned_data['next']:
                    auth_request.return_to_args['next'] = \
                        form.cleaned_data['next']
                redirect_url = auth_request.redirectURL(
                    realm,
                    request.build_absolute_uri(callback_url))
                return HttpResponseRedirect(redirect_url)
            # UnicodeDecodeError:
            # see https://github.com/necaris/python3-openid/issues/1
            except (UnicodeDecodeError, DiscoveryFailure) as e:
                if request.method == 'POST':
                    form._errors["openid"] = form.error_class([e])
                else:
                    return render_authentication_error(
                        request,
                        OpenIDProvider.id,
                        exception=e)
    else:
        form = LoginForm(initial={'next': request.GET.get('next'),
                                  'process': request.GET.get('process')})
    d = dict(form=form)
    return render(request, "openid/login.html", d)
开发者ID:biwin,项目名称:django-allauth,代码行数:57,代码来源:views.py

示例6: prepare_authentication_request

    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)
开发者ID:Granicus,项目名称:civipedia,代码行数:50,代码来源:consumer.py

示例7: _get_approved_data

def _get_approved_data(request, orequest):
    """Given an HTTP request and an OpenID request, return a nested dict of
    values requested in the request and approved by the user.
    """
    if not orequest:
        return None

    approved_data = {}
    rpconfig = utils.get_rpconfig(orequest.trust_root)

    sreg_request = SRegRequest.fromOpenIDRequest(orequest)
    ax_request = ax.FetchRequest.fromOpenIDRequest(orequest)

    user_attribs_form = UserAttribsRequestForm(
        request, sreg_request, ax_request, rpconfig)
    if user_attribs_form.has_data:
        approved_data['user_attribs'] = {
            'requested': user_attribs_form.data.keys(),
            'approved': user_attribs_form.data_approved_for_request.keys()}

    args = orequest.message.getArgs(LAUNCHPAD_TEAMS_NS)
    team_names = args.get('query_membership')
    if team_names:
        team_names = team_names.split(',')
        teams_form = TeamsRequestForm(
            request,
            TeamsRequest.fromOpenIDRequest(orequest),
            rpconfig,
        )
        approved_data['teams'] = {
            'requested': team_names,
            'approved': teams_form.teams_approved_by_user}

    return approved_data
开发者ID:miing,项目名称:mci_migo,代码行数:34,代码来源:server.py

示例8: test_login_create_users

    def test_login_create_users(self):
        settings.OPENID_CREATE_USERS = True
        # Create a user with the same name as we'll pass back via sreg.
        User.objects.create_user('someuser', '[email protected]')

        # Posting in an identity URL begins the authentication request:
        response = self.client.post('/openid/login/',
            {'openid_identifier': 'http://example.com/identity',
             'next': '/getuser/'})
        self.assertContains(response, 'OpenID transaction in progress')

        # Complete the request, passing back some simple registration
        # data.  The user is redirected to the next URL.
        openid_request = self.provider.parseFormPost(response.content)
        sreg_request = SRegRequest.fromOpenIDRequest(openid_request)
        openid_response = openid_request.answer(True)
        sreg_response = SRegResponse.extractResponse(
            sreg_request, {'nickname': 'someuser', 'fullname': 'Some User',
                           'email': '[email protected]'})
        openid_response.addExtension(sreg_response)
        response = self.complete(openid_response)
        self.assertRedirects(response, 'http://testserver/getuser/')

        # And they are now logged in as a new user (they haven't taken
        # over the existing "someuser" user).
        response = self.client.get('/getuser/')
        self.assertEquals(response.content, 'someuser2')

        # Check the details of the new user.
        user = User.objects.get(username='someuser2')
        self.assertEquals(user.first_name, 'Some')
        self.assertEquals(user.last_name, 'User')
        self.assertEquals(user.email, '[email protected]')
开发者ID:gcr,项目名称:twg,代码行数:33,代码来源:test_views.py

示例9: Respond

  def Respond(self, oidresponse):
    logging.warning('Respond: oidresponse.request.mode ' + oidresponse.request.mode)

    if oidresponse.request.mode in ['checkid_immediate', 'checkid_setup']:
      user = users.get_current_user()
      if user:
        from openid.extensions.sreg import SRegRequest, SRegResponse
        sreg_req = SRegRequest.fromOpenIDRequest(oidresponse.request)
        if sreg_req.wereFieldsRequested():
          logging.info("sreg_req:%s", sreg_req.allRequestedFields())
          user_data = {'nickname':user.nickname(),
                       'email':user.email()}
          sreg_resp = SRegResponse.extractResponse(sreg_req, user_data)
          sreg_resp.toMessage(oidresponse.fields)        
    logging.info('Using response: %s' % oidresponse)
    encoded_response = oidserver.encodeResponse(oidresponse)

    for header, value in encoded_response.headers.items():
      self.response.headers[header] = str(value)

    if encoded_response.code in (301, 302):
      self.redirect(self.response.headers['location'])
    else:
      self.response.set_status(encoded_response.code)

    if encoded_response.body:
      logging.debug('Sending response body: %s' % encoded_response.body)
      self.response.out.write(encoded_response.body)
    else:
      self.response.out.write('')
开发者ID:DemocracyOS,项目名称:IdentidadEnRed-Prototype,代码行数:30,代码来源:provider.py

示例10: createPositiveResponse

    def createPositiveResponse(self):
        """Create a positive assertion OpenIDResponse.

        This method should be called to create the response to
        successful checkid requests.

        If the trust root for the request is in openid_sreg_trustroots,
        then additional user information is included with the
        response.
        """
        assert self.account is not None, (
            'Must be logged in for positive OpenID response')
        assert self.openid_request is not None, (
            'No OpenID request to respond to.')

        if not self.isIdentityOwner():
            return self.createFailedResponse()

        if self.openid_request.idSelect():
            response = self.openid_request.answer(
                True, identity=self.user_identity_url)
        else:
            response = self.openid_request.answer(True)

        person = IPerson(self.account)
        sreg_fields = dict(
            nickname=person.name,
            email=person.preferredemail.email,
            fullname=self.account.displayname)
        sreg_request = SRegRequest.fromOpenIDRequest(self.openid_request)
        sreg_response = SRegResponse.extractResponse(
            sreg_request, sreg_fields)
        response.addExtension(sreg_response)

        return response
开发者ID:vitaminmoo,项目名称:unnaturalcode,代码行数:35,代码来源:server.py

示例11: decide

def decide(request, token):
    try:
        orequest = _get_orequest(request, token)
        rpconfig = utils.get_rpconfig(orequest.trust_root)
    except:
        return HttpResponse("Invalid OpenID transaction")

    if not request.user.is_authenticated():
        # XXX: need to remove this circular dep to the webui app
        from webui.views import ui
        return ui.LoginView.as_view()(request, token, rpconfig=rpconfig)

    if not _user_is_verified_for_rp(request.user, rpconfig):
        name = rpconfig.displayname if rpconfig else orequest.trust_root
        messages.warning(
            request,
            SITE_REQUIRES_VERIFIED.format(rp_name=name)
        )
        return HttpResponseRedirect(reverse('account-emails'))

    site_requires_twofactor = twofactor.site_requires_twofactor_auth(
        request, token, rpconfig)
    if (not twofactor.is_authenticated(request) or
            (site_requires_twofactor and not twofactor.is_upgraded(request))):
        if is_twofactor_enabled(request):
            return HttpResponseRedirect(reverse('twofactor', args=[token]))
        else:
            return _process_decide(request, orequest, decision=False)

    if ('ok' in request.POST or
            (rpconfig is not None and rpconfig.auto_authorize)):
        return _process_decide(request, orequest, decision=True)

    sreg_request = SRegRequest.fromOpenIDRequest(orequest)
    ax_request = ax.FetchRequest.fromOpenIDRequest(orequest)
    teams_request = TeamsRequest.fromOpenIDRequest(orequest)
    try:
        summary = OpenIDRPSummary.objects.get(
            account=request.user, trust_root=orequest.trust_root,
            openid_identifier=request.user.openid_identity_url)
        approved_data = summary.get_approved_data()
    except OpenIDRPSummary.DoesNotExist:
        approved_data = {}

    user_attribs_form = UserAttribsRequestForm(
        request, sreg_request, ax_request, rpconfig,
        approved_data=approved_data.get('user_attribs'))
    teams_form = TeamsRequestForm(request, teams_request, rpconfig,
                                  approved_data=approved_data.get('teams'))
    context = RequestContext(request, {
        'account': request.user,
        'trust_root': orequest.trust_root,
        'rpconfig': rpconfig,
        'user_attribs_form': user_attribs_form,
        'teams_form': teams_form,
        'token': token,
        'sane_trust_root': _request_has_sane_trust_root(orequest)
    })
    return render_to_response('server/decide.html', context)
开发者ID:miing,项目名称:mci_migo,代码行数:59,代码来源:server.py

示例12: openid_decide

def openid_decide(request):
    """
    The page that asks the user if they really want to sign in to the site, and
    lets them add the consumer to their trusted whitelist.
    # If user is logged in, ask if they want to trust this trust_root
    # If they are NOT logged in, show the landing page
    """
    orequest = request.session.get('OPENID_REQUEST')
    # No request ? Failure..
    if not orequest:
        logger.warning('OpenID decide view failed, \
because no OpenID request is saved')
        return HttpResponseRedirect('/')
    sreg_request = SRegRequest.fromOpenIDRequest(orequest)
    logger.debug('SREG request: %s' % sreg_request.__dict__)
    if not request.user.is_authenticated():
        # Not authenticated ? Authenticate and go back to the server endpoint
        return redirect_to_login(request, next=reverse(openid_server),
                nonce='1')

    if request.method == 'POST':
        if 'cancel' in request.POST:
            # User refused
            logger.info('OpenID decide canceled')
            return HttpResponseRedirect('%s?cancel' % reverse(openid_server))
        else:
            form = DecideForm(sreg_request=sreg_request, data=request.POST)
            if form.is_valid():
                data = form.cleaned_data
                # Remember the choice
                t, created = models.TrustedRoot.objects.get_or_create(
                        user=request.user.id, trust_root=orequest.trust_root)
		t.choices = sreg_request.required \
                    + [ field for field in data if data[field] ]
                t.save()
                logger.debug('OpenID decide, user choice:%s' % data)
                return HttpResponseRedirect(reverse('openid-provider-root'))
    else:
        form = DecideForm(sreg_request=sreg_request)
    logger.info('OpenID device view, orequest:%s' % orequest)

    # verify return_to of trust_root
    try:
        trust_root_valid = verifyReturnTo(orequest.trust_root,
                orequest.return_to) and "Valid" or "Invalid"
    except HTTPFetchingError:
        trust_root_valid = "Unreachable"
    except DiscoveryFailure:
        trust_root_valid = "DISCOVERY_FAILED"

    return render_to_response('idp/openid/decide.html', {
        'title': _('Trust this site?'),
        'required': sreg_request.required,
        'optional': sreg_request.optional,
        'trust_root_valid': trust_root_valid,
        'form': form,
    }, context_instance=RequestContext(request))
开发者ID:pu239ppy,项目名称:authentic2,代码行数:57,代码来源:views.py

示例13: post

  def post(self):

    parsed = urlparse.urlparse(self.request.uri)
    request_url_without_path = parsed[0] + '://' + parsed[1]
    request_url_without_params = request_url_without_path + parsed[2]

    token = self.request.get('token') or urlparse.urlparse(self.request.uri)[2].rsplit('/',2)[2]
    oid_args = False
    query = datastore.Query('Verification')
    query['token ='] = token
    v = query.Get(1)
    if v:
      v = v[0]
      if v['expires'] > time.time():
        self.user = v['email']
        self.oid_args = pickle.loads(str(v['oidrequest']))
      else:
        error = 'That token has expired.  Please try again.'
      datastore.Delete(v)
    else:
      error = 'No such token found.'

    if not self.CheckUser():
      self.ShowFrontPage(error)
      return

    args = self.ArgsToDict()

    try:
      oidrequest = OpenIDServer.CheckIDRequest.fromMessage(OpenIDMessage.fromPostArgs(args), '')
    except:
      trace = ''.join(traceback.format_exception(*sys.exc_info()))
      self.ReportError('Error decoding login request:\n%s' % trace)
      return

    if True: #args.has_key('yes'):
      logging.debug('Confirming identity to %s' % oidrequest.trust_root)
      if args.get('remember', '') == 'yes':
        logging.info('Setting cookie to remember openid login for two weeks')

        expires = datetime.datetime.now() + datetime.timedelta(weeks=2)
        expires_rfc822 = expires.strftime('%a, %d %b %Y %H:%M:%S +0000')
        self.response.headers.add_header(
          'Set-Cookie', 'openid_remembered=yes; expires=%s' % expires_rfc822)

      self.store_login(oidrequest, 'confirmed')
      sreg_req = SRegRequest.fromOpenIDRequest(oidrequest)
      self.Respond(oidrequest.answer(True, request_url_without_path + '/id/' + urllib.quote(self.user)), sreg_req)

    elif args.has_key('no'):
      logging.debug('Login denied, sending cancel to %s' %
                    oidrequest.trust_root)
      self.store_login(oidrequest, 'declined')
      return self.Respond(oidrequest.answer(False))

    else:
      self.ReportError('Bad login request.')
开发者ID:singpolyma,项目名称:Email-Verify,代码行数:57,代码来源:provider.py

示例14: handle_sreg

def handle_sreg(request, response):
    """Handle any sreg data requests"""
    sreg_req = SRegRequest.fromOpenIDRequest(request)
    # Extract information if required
    if sreg_req.wereFieldsRequested():
        fields = config.sreg_fields()
        if not fields:
            return
        sreg_resp = SRegResponse.extractResponse(sreg_req, config.sreg_fields())
        sreg_resp.toMessage(response.fields)
开发者ID:kgaughan,项目名称:poit-wsgi,代码行数:10,代码来源:poit.py

示例15: perform_openid_auth

    def perform_openid_auth(self, form):
        if not form.is_valid():
            return form

        request = self.request
        client = self.get_client()
        provider = self.provider(request)
        realm = self.get_realm(provider)

        auth_request = client.begin(form.cleaned_data['openid'])
        if QUERY_EMAIL:
            sreg = SRegRequest()
            for name in SRegFields:
                sreg.requestField(
                    field_name=name, required=True
                )
            auth_request.addExtension(sreg)
            ax = FetchRequest()
            for name in AXAttributes:
                ax.add(AttrInfo(name,
                                required=True))
            provider = OpenIDProvider(request)
            server_settings = \
                provider.get_server_settings(request.GET.get('openid'))
            extra_attributes = \
                server_settings.get('extra_attributes', [])
            for _, name, required in extra_attributes:
                ax.add(AttrInfo(name,
                                required=required))
            auth_request.addExtension(ax)

        SocialLogin.stash_state(request)

        # Fix for issues 1523 and 2072 (github django-allauth)
        if "next" in form.cleaned_data and form.cleaned_data["next"]:
            auth_request.return_to_args['next'] = \
                form.cleaned_data['next']
        redirect_url = auth_request.redirectURL(
            realm,
            request.build_absolute_uri(self.get_callback_url()))
        return HttpResponseRedirect(redirect_url)
开发者ID:jleclanche,项目名称:django-allauth,代码行数:41,代码来源:views.py


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