Example #1
0
    def _resp(self, request, userdata):
        req = ax.FetchRequest.fromOpenIDRequest(request)
        if req is None:
            return None
        resp = ax.FetchResponse(req)
        for name in req.requested_attributes:
            attr = req.requested_attributes[name]
            try:
                self.debug(name)
                value = None
                if name in AP_MAP:
                    value = userdata[AP_MAP[name]]
                else:
                    value = userdata[name]

                if '\n' in value:
                    raise AuthenticationError('Newline in attribute %s' % name)

                added_vals = 0
                if not isinstance(value, list):
                    value = [value]
                for val in value:
                    val = val.strip()
                    if attr.wantsUnlimitedValues() or added_vals < attr.count:
                        if val != '':
                            added_vals += 1
                            resp.addValue(name, val)
            except Exception:  # pylint: disable=broad-except
                pass
        return resp
Example #2
0
 def test_getExtensionArgs_empty_request(self):
     expected_args = {
         'mode': 'fetch_response',
     }
     req = ax.FetchRequest()
     msg = ax.FetchResponse(request=req)
     self.assertEqual(msg.getExtensionArgs(), expected_args)
Example #3
0
 def test_getExtensionArgs_empty_request(self):
     expected_args = {
         'mode': 'fetch_response',
     }
     req = ax.FetchRequest()
     msg = ax.FetchResponse(request=req)
     self.failUnlessEqual(expected_args, msg.getExtensionArgs())
Example #4
0
def add_user_data(request, openid_response):
    """
    Add user custom data to the request using sreg
    and ax extensions
    """

    openid_request = get_request(request)

    if openid_request == None:
        return

    sreg_data = {
        'fullname': request.user.get_full_name(),
        'nickname': request.user.username,
        'email': request.user.email,
    }

    sreg_req = sreg.SRegRequest.fromOpenIDRequest(openid_request)
    sreg_resp = sreg.SRegResponse.extractResponse(sreg_req, sreg_data)
    openid_response.addExtension(sreg_resp)

    ax_req = ax.FetchRequest.fromOpenIDRequest(openid_request)
    ax_resp = ax.FetchResponse(ax_req)
    ax_resp.addValue('http://openid.net/schema/namePerson/first',
                     request.user.first_name)
    ax_resp.addValue('http://openid.net/schema/namePerson/last',
                     request.user.last_name)
    ax_resp.addValue('http://openid.net/schema/namePerson/friendly',
                     request.user.username)
    ax_resp.addValue('http://openid.net/schema/contact/internet/email',
                     request.user.email)
    ax_resp.addValue('http://id.culturadigital.br/schema/cpf',
                     request.user.get_profile().cpf)
    openid_response.addExtension(ax_resp)
Example #5
0
def addAttributeExchangeResponse(oidrequest, response, request):
    ax_req = ax.FetchRequest.fromOpenIDRequest(oidrequest)
    if ax_req:
        required = ax_req.getRequiredAttrs()
        if len(required
               ) == 1 and 'http://axschema.org/contact/username' in required:
            ax_resp = ax.FetchResponse(request=ax_req)
            ax_resp.addValue('http://axschema.org/contact/username',
                             request.session['username'])
            response.addExtension(ax_resp)
Example #6
0
 def test_getExtensionArgs_some_request(self):
     expected_args = {
         'mode': 'fetch_response',
         'type.' + self.alias_a: self.type_a,
         'value.' + self.alias_a + '.1': self.value_a,
         'count.' + self.alias_a: '1'
     }
     req = ax.FetchRequest()
     req.add(ax.AttrInfo(self.type_a, alias=self.alias_a))
     msg = ax.FetchResponse(request=req)
     msg.addValue(self.type_a, self.value_a)
     self.assertEqual(msg.getExtensionArgs(), expected_args)
Example #7
0
    def render_GET(self, request):
        janrain_nonce = request.args.get('janrain_nonce', [None])[0]
        if janrain_nonce is not None:
            cookie = request.getCookie('pc_user')
            if not cookie in globals()['REDIRECTED_USERS']:
                request.redirect('http://buildpc.ru')
                return ""
            consumer = Consumer({}, STORAGE)
            args = dict((k,unicode(v[0], 'utf-8')) for k,v in request.args.items())

            info = consumer.complete(args, RETURN_TO)
            # Если аутентификация не удалась или отменена            
            # Получение данных пользователя при успешной аутентификации
            if info.status != SUCCESS:
                request.redirect('http://buildpc.ru')
                return ""
            
            ax_info = ax.FetchResponse.fromSuccessResponse(info) or ax.FetchResponse()
            user_data = {
                'uid': info.identity_url,
                'first_name': ax_info.getSingle(AXINFO['namePerson']),
                'last_name': '',                
            }
            globals()['PASSED_USERS'].update({cookie:user_data})
            request.redirect(globals()['REDIRECTED_USERS'].pop(cookie).split('?')[0]\
                                 +'?pr=yandex&code='+cookie)
            return ""
            
        # Далее — выборка существующего или регистрация нового пользователя
        else:
            backUrl = request.args.get('backurl', [None])[0]
            globals()['REDIRECTED_USERS'].update({request.getCookie('pc_user'):backUrl})
            # provider = request.get('provider', [None])[0]            
            # url = openid_request.redirectURL(ROOT, ROOT)
            
            # Короткие названия для ключей необходимых данных о пользователе.
            # Список доступных данных см. в разделе Дополнительные данные о пользователе
            
            consumer = Consumer({}, STORAGE)
            openid_request = consumer.begin('http://www.yandex.ru/')

            # Запрос дополнительной информации о пользователе
            # Поля, указанные с ключом required, на сайте Яндекса отображаются как обязательные
            # (незаданные значения подсвечиваются красным цветом)
            ax_request = ax.FetchRequest()
            # ax_request.add(ax.AttrInfo(AXINFO['email'], required=True))
            # ax_request.add(ax.AttrInfo(AXINFO['nickname']))
            ax_request.add(ax.AttrInfo(AXINFO['namePerson'], required=True))
            openid_request.addExtension(ax_request)
            url = openid_request.redirectURL(ROOT, RETURN_TO)
            request.redirect(url)
            return ""            
Example #8
0
    def test_getExtensionArgs_empty_request_some(self):
        uri = 'http://not.found/'
        alias = 'ext0'

        expected_args = {
            'mode': 'fetch_response',
            'type.%s' % (alias, ): uri,
            'count.%s' % (alias, ): '0'
        }
        req = ax.FetchRequest()
        req.add(ax.AttrInfo(uri))
        msg = ax.FetchResponse(request=req)
        self.assertEqual(msg.getExtensionArgs(), expected_args)
Example #9
0
def add_ax_data(request, orequest, oresponse):
    callback = get_ax_callback()
    if callback is None or not callable(callback):
        return
    ax_data = callback(request, orequest)
    ax_req = ax.FetchRequest.fromOpenIDRequest(orequest)
    ax_resp = ax.FetchResponse(ax_req)
    if ax_req is not None:
        for attr in ax_req.getRequiredAttrs():
            value = ax_data.get(attr, None)
            if value is not None:
                ax_resp.addValue(attr, value)
    oresponse.addExtension(ax_resp)
    def decidePage(self, environ, start_response, oidRequest, oidResponse):
        """Handle user interaction required before final submit back to Relying
        Party"""
        self.title = 'Approve OpenID Request?'
        self.heading = 'Approve OpenID Request?'
        self.trust_root = oidRequest.trust_root
        self.oidRequest = oidRequest

        # Get all the content namespaced as AX type
        axArgs = oidResponse.fields.getArgs(ax.AXMessage.ns_uri)
        if len(axArgs) == 0:
            log.debug('No Attribute eXchange (AX) arguments specified')
            axRequestedAttr = {}
            axFetchResponse = None
        else:
            # Add to access object for convenient access based on type URI
            axFetchResponse = ax.FetchResponse()
            axFetchResponse.parseExtensionArgs(axArgs)

            ax_req = ax.FetchRequest.fromOpenIDRequest(oidRequest)
            axRequestedAttr = ax_req.requested_attributes

        self.environ = environ

        if oidRequest.idSelect():
            if 'username' not in self.session:
                log.error("No 'username' key set in session object for "
                          "idselect mode do decide page")
                msg = ('An internal error has occurred.  Please contact '
                       'your system administrator')
                response = self.errorPage(environ, start_response, msg)
                return response

            userIdentifier = self._authN.username2UserIdentifiers(
                environ, self.session['username'])[0]

            # Use the Yadis path because we want to use Yadis only
            # based discovery
            self.identityURI = OpenIDProviderMiddleware.createIdentityURI(
                self.urls['url_yadis'], userIdentifier)
        else:
            self.identityURI = oidRequest.identity

        response = self._render(GenshiRendering.DECIDE_PAGE_TMPL_NAME,
                                axRequestedAttr=axRequestedAttr,
                                axFetchResponse=axFetchResponse)
        self.identityURI = ''

        start_response("200 OK", [('Content-type', 'text/html' + self.charset),
                                  ('Content-length', str(len(response)))])
        return response
Example #11
0
    def test_updateUrlInResponse(self):
        uri = 'http://not.found/'
        alias = 'ext0'

        expected_args = {
            'mode': 'fetch_response',
            'update_url': self.request_update_url,
            'type.%s' % (alias, ): uri,
            'count.%s' % (alias, ): '0'
        }
        req = ax.FetchRequest(update_url=self.request_update_url)
        req.add(ax.AttrInfo(uri))
        msg = ax.FetchResponse(request=req)
        self.assertEqual(msg.getExtensionArgs(), expected_args)
Example #12
0
def approve_id(identity, req, prof):
    res = req.answer(True, identity=identity)
    # Add (if requested) Simple Registration info
    sreg_req = sreg.SRegRequest.fromOpenIDRequest(req)
    if sreg_req:
        sreg_data = {
                'nickname': prof['nickname'],
                'fullname': prof.get('fullName', '')
                }
        sreg_resp = sreg.SRegResponse.extractResponse(sreg_req, sreg_data)
        res.addExtension(sreg_resp)
    # Check for Attribute Exchange
    ax_req = ax.FetchRequest.fromOpenIDRequest(req)
    if ax_req:
        ax_res = ax.FetchResponse(request=ax_req)
        ### Google uses the schema defined at axschema.org.
        fullname_types = ['http://schema.openid.net/namePerson',
                'http://axschema.org/namePerson']
        for t in fullname_types:
            if t in ax_req:
                ax_res.addValue(t, prof.get('fullName', 'anonymous'))
                break
        firstname_types = ['http://axschema.org/namePerson/first',
                'http://openid.net/schema/namePerson/first']
        for t in firstname_types:
            if t in ax_req:
                ax_res.addValue(t, prof.get('givenName', 'anonymous'))
                break
        nickname_types = ['http://schema.openid.net/namePerson/friendly',
                'http://openid.net/schema/namePerson/friendly', 
                'http://axschema.org/namePerson/friendly']
        for t in nickname_types:
            if t in ax_req:
                ax_res.addValue(t, prof['nickname'])
                break
        role_type = 'http://www.w3.org/2006/vcard/ns#role'
        if role_type in ax_req:
            ax_res.setValues(role_type, prof.get('groups',[]))

        res.addExtension(ax_res)
    return res
Example #13
0
def add_openid_attribute_exchange(request, response, data):
    try:
        ax_request = ax.FetchRequest.fromOpenIDRequest(request)
    except ax.AXError:
        #  not using OpenID attribute exchange extension
        pass
    else:
        ax_response = ax.FetchResponse()

        # if consumer requested attribute exchange fields, add them
        if ax_request and ax_request.requested_attributes:
            for type_uri in ax_request.requested_attributes.iterkeys():
                email_schema = 'http://axschema.org/contact/email'
                name_schema = 'http://axschema.org/namePerson'
                if type_uri == email_schema and 'email' in data:
                    ax_response.addValue(email_schema, data['email'])
                elif type_uri == name_schema and 'fullname' in data:
                    ax_response.addValue(name_schema, data['fullname'])

            # construct ax response
            ax_response.toMessage(response.fields)
Example #14
0
def addAX(openid_request, openid_response):
    ax_req = ax.FetchRequest.fromOpenIDRequest(openid_request)
    if ax_req is None:
        return {}
    ax_resp = ax.FetchResponse(ax_req)
    for type_uri, attribute in ax_req.requested_attributes.iteritems():
        lookup = type_uri
        if lookup in AX_WELLKNOWN.keys():
            lookup = AX_WELLKNOWN[type_uri]
        try:
            value = request.auth_module.get_attribute(lookup)
            ax_resp.addValue(type_uri, value)
        except:
            pass
    if openid_response:
        openid_response.addExtension(ax_resp)
    ax_data = {}
    for key in ax_resp.data.keys():
        display = key
        if key in AX_WELLKNOWN.keys():
            display = AX_WELLKNOWN[key].__str__()
        for value in ax_resp.data[key]:
            ax_data[display] = value
    return ax_data
Example #15
0
    def test_login_attribute_exchange(self):
        settings.OPENID_UPDATE_DETAILS_FROM_SREG = True
        user = User.objects.create_user('testuser', '*****@*****.**')
        useropenid = UserOpenID(user=user,
                                claimed_id='http://example.com/identity',
                                display_id='http://example.com/identity')
        useropenid.save()

        # Configure the provider to advertise attribute exchange
        # protocol and start the authentication process:
        self.provider.type_uris.append('http://openid.net/srv/ax/1.0')
        response = self.client.post(
            '/openid/login/', {
                'openid_identifier': 'http://example.com/identity',
                'next': '/getuser/'
            })
        self.assertContains(response, 'OpenID transaction in progress')

        # The resulting OpenID request uses the Attribute Exchange
        # extension rather than the Simple Registration extension.
        openid_request = self.provider.parseFormPost(response.content)
        sreg_request = sreg.SRegRequest.fromOpenIDRequest(openid_request)
        self.assertEqual(sreg_request.required, [])
        self.assertEqual(sreg_request.optional, [])

        fetch_request = ax.FetchRequest.fromOpenIDRequest(openid_request)
        self.assertTrue('http://axschema.org/contact/email' in fetch_request)
        self.assertTrue('http://axschema.org/namePerson' in fetch_request)
        self.assertTrue(
            'http://axschema.org/namePerson/first' in fetch_request)
        self.assertTrue('http://axschema.org/namePerson/last' in fetch_request)
        self.assertTrue(
            'http://axschema.org/namePerson/friendly' in fetch_request)
        # myOpenID compatibilty attributes:
        self.assertTrue(
            'http://schema.openid.net/contact/email' in fetch_request)
        self.assertTrue('http://schema.openid.net/namePerson' in fetch_request)
        self.assertTrue(
            'http://schema.openid.net/namePerson/friendly' in fetch_request)

        # Build up a response including AX data.
        openid_response = openid_request.answer(True)
        fetch_response = ax.FetchResponse(fetch_request)
        fetch_response.addValue('http://axschema.org/contact/email',
                                '*****@*****.**')
        fetch_response.addValue('http://axschema.org/namePerson/first',
                                'Firstname')
        fetch_response.addValue('http://axschema.org/namePerson/last',
                                'Lastname')
        fetch_response.addValue('http://axschema.org/namePerson/friendly',
                                'someuser')
        openid_response.addExtension(fetch_response)
        response = self.complete(openid_response)
        self.assertRedirects(response, 'http://testserver/getuser/')

        # And they are now logged in as testuser (the passed in
        # nickname has not caused the username to change).
        response = self.client.get('/getuser/')
        self.assertEqual(response.content, 'testuser')

        # The user's full name and email have been updated.
        user = User.objects.get(username='******')
        self.assertEqual(user.first_name, 'Firstname')
        self.assertEqual(user.last_name, 'Lastname')
        self.assertEqual(user.email, '*****@*****.**')
Example #16
0
 def test_getExtensionArgs_some_not_request(self):
     req = ax.FetchRequest()
     msg = ax.FetchResponse(request=req)
     msg.addValue(self.type_a, self.value_a)
     self.assertRaises(KeyError, msg.getExtensionArgs)
Example #17
0
 def setUp(self):
     self.msg = ax.FetchResponse()
     self.value_a = 'monkeys'
     self.type_a = 'http://phone.home/'
     self.alias_a = 'robocop'
     self.request_update_url = 'http://update.bogus/'