Ejemplo n.º 1
0
    def test_state_token(self, session):
        from invenio_oauthclient.views.client import serializer

        # Mock session id
        session.sid = '1234'

        with self.app.test_client() as c:
            # Ensure remote apps have been loaded (due to before first
            # request)
            c.get(url_for("oauthclient.login", remote_app='test'))
            self.mock_response(app='test')

            # Good state token
            state = serializer.dumps({
                'app': 'test',
                'sid': '1234',
                'next': None,
            })
            resp = c.get(
                url_for("oauthclient.authorized",
                        remote_app='test',
                        code='test',
                        state=state))
            self.assert200(resp)

            outdated_serializer = TimedJSONWebSignatureSerializer(
                cfg['SECRET_KEY'],
                expires_in=0,
            )

            # Bad state - timeout
            state1 = outdated_serializer.dumps({
                'app': 'test',
                'sid': '1234',
                'next': None,
            })
            # Bad state - app
            state2 = serializer.dumps(
                # State for another existing app (test_invalid exists)
                {
                    'app': 'test_invalid',
                    'sid': '1234',
                    'next': None,
                })
            # Bad state - sid
            state3 = serializer.dumps(
                # State for another existing app (test_invalid exists)
                {
                    'app': 'test',
                    'sid': 'bad',
                    'next': None,
                })
            time.sleep(1)
            for s in [state1, state2, state3]:
                resp = c.get(
                    url_for("oauthclient.authorized",
                            remote_app='test',
                            code='test',
                            state=s))
                self.assert403(resp)
def test_state_token(monkeypatch):
    """Test state token."""
    # Mock session id
    monkeypatch.setattr('invenio_oauthclient.views.client.session',
                        {'_id': '1234'})
    app = setup_app()
    with app.test_client() as client:
        # Ensure remote apps have been loaded (due to before first
        # request)
        client.get(url_for("invenio_oauthclient.login", remote_app='test'))
        mock_response(app.extensions['oauthlib.client'], 'test')

        # Good state token
        state = serializer.dumps({
            'app': 'test',
            'sid': '1234',
            'next': None,
        })
        resp = client.get(
            url_for("invenio_oauthclient.authorized",
                    remote_app='test',
                    code='test',
                    state=state))
        assert resp.status_code == 200

        outdated_serializer = TimedJSONWebSignatureSerializer(
            app.config['SECRET_KEY'],
            expires_in=0,
        )

        # Bad state - timeout
        state1 = outdated_serializer.dumps({
            'app': 'test',
            'sid': '1234',
            'next': None,
        })
        # Bad state - app
        state2 = serializer.dumps(
            # State for another existing app (test_invalid exists)
            {
                'app': 'test_invalid',
                'sid': '1234',
                'next': None,
            })
        # Bad state - sid
        state3 = serializer.dumps(
            # State for another existing app (test_invalid exists)
            {
                'app': 'test',
                'sid': 'bad',
                'next': None,
            })
        time.sleep(1)
        for s in [state1, state2, state3]:
            resp = client.get(
                url_for("invenio_oauthclient.authorized",
                        remote_app='test',
                        code='test',
                        state=s))
            assert resp.status_code == 403
Ejemplo n.º 3
0
def test_state_token(app_rest, monkeypatch):
    """Test state token."""
    # Mock session id
    monkeypatch.setattr('invenio_oauthclient._compat._create_identifier',
                        lambda: '1234')
    monkeypatch.setattr(
        'invenio_oauthclient.views.client._create_identifier', lambda: '1234')

    with app_rest.test_client() as client:
        # Ensure remote apps have been loaded (due to before first
        # request)
        client.get(url_for(
            'invenio_oauthclient.rest_login', remote_app='test'))
        mock_response(app_rest.extensions['oauthlib.client'], 'test')

        # Good state token
        state = serializer.dumps(
            {'app': 'test', 'sid': '1234',  'next': None, }
        )
        resp = client.get(
            url_for('invenio_oauthclient.rest_authorized', remote_app='test',
                    code='test', state=state)
        )
        assert resp.status_code == 200

        outdated_serializer = TimedJSONWebSignatureSerializer(
            app_rest.config['SECRET_KEY'],
            expires_in=0,
        )

        # Bad state - timeout
        state1 = outdated_serializer.dumps(
            {'app': 'test', 'sid': '1234',  'next': None, }
        )
        # Bad state - app
        state2 = serializer.dumps(
            # State for another existing app (test_invalid exists)
            {'app': 'test_invalid', 'sid': '1234',  'next': None, }
        )
        # Bad state - sid
        state3 = serializer.dumps(
            # State for another existing app (test_invalid exists)
            {'app': 'test', 'sid': 'bad',  'next': None, }
        )
        time.sleep(1)
        for s in [state1, state2, state3]:
            resp = client.get(
                url_for(
                    'invenio_oauthclient.rest_authorized', remote_app='test',
                    code='test', state=s)
            )
            assert resp.status_code == 302
            assert parse_qs(urlparse(resp.location).query)['code'][0] == '403'
Ejemplo n.º 4
0
def test_state_token(views_fixture, monkeypatch):
    """Test state token."""
    # Mock session id
    monkeypatch.setattr('invenio_oauthclient._compat._create_identifier',
                        lambda: '1234')
    monkeypatch.setattr(
        'invenio_oauthclient.views.client._create_identifier', lambda: '1234')
    app = views_fixture

    with app.test_client() as client:
        # Ensure remote apps have been loaded (due to before first
        # request)
        client.get(url_for('invenio_oauthclient.login', remote_app='test'))
        mock_response(app.extensions['oauthlib.client'], 'test')

        # Good state token
        state = serializer.dumps(
            {'app': 'test', 'sid': '1234',  'next': None, }
        )
        resp = client.get(
            url_for('invenio_oauthclient.authorized', remote_app='test',
                    code='test', state=state)
        )
        assert resp.status_code == 200

        outdated_serializer = TimedJSONWebSignatureSerializer(
            app.config['SECRET_KEY'],
            expires_in=0,
        )

        # Bad state - timeout
        state1 = outdated_serializer.dumps(
            {'app': 'test', 'sid': '1234',  'next': None, }
        )
        # Bad state - app
        state2 = serializer.dumps(
            # State for another existing app (test_invalid exists)
            {'app': 'test_invalid', 'sid': '1234',  'next': None, }
        )
        # Bad state - sid
        state3 = serializer.dumps(
            # State for another existing app (test_invalid exists)
            {'app': 'test', 'sid': 'bad',  'next': None, }
        )
        time.sleep(1)
        for s in [state1, state2, state3]:
            resp = client.get(
                url_for('invenio_oauthclient.authorized', remote_app='test',
                        code='test', state=s)
            )
            assert resp.status_code == 403
Ejemplo n.º 5
0
    def test_state_token(self, session):
        from invenio_oauthclient.views.client import serializer

        # Mock session id
        session.sid = '1234'

        with self.app.test_client() as c:
            # Ensure remote apps have been loaded (due to before first
            # request)
            c.get(url_for("oauthclient.login", remote_app='test'))
            self.mock_response(app='test')

            # Good state token
            state = serializer.dumps(
                {'app': 'test', 'sid': '1234',  'next': None, }
            )
            resp = c.get(
                url_for("oauthclient.authorized", remote_app='test',
                        code='test', state=state)
            )
            self.assert200(resp)

            outdated_serializer = TimedJSONWebSignatureSerializer(
                cfg['SECRET_KEY'],
                expires_in=0,
            )

            # Bad state - timeout
            state1 = outdated_serializer.dumps(
                {'app': 'test', 'sid': '1234',  'next': None, }
            )
            # Bad state - app
            state2 = serializer.dumps(
                # State for another existing app (test_invalid exists)
                {'app': 'test_invalid', 'sid': '1234',  'next': None, }
            )
            # Bad state - sid
            state3 = serializer.dumps(
                # State for another existing app (test_invalid exists)
                {'app': 'test', 'sid': 'bad',  'next': None, }
            )
            time.sleep(1)
            for s in [state1, state2, state3]:
                resp = c.get(
                    url_for("oauthclient.authorized", remote_app='test',
                            code='test', state=s)
                )
                self.assert403(resp)
Ejemplo n.º 6
0
    def test_invalid_authorized_response(self):
        from simplejson import JSONDecodeError
        from invenio_oauthclient.client import oauth

        # Fake an authorized request
        with self.app.test_client() as c:
            # Ensure remote apps have been loaded (due to before first
            # request)
            c.get(url_for("oauthclient.login", remote_app='test'))

            oauth.remote_apps['test'].handle_oauth2_response = MagicMock(
                side_effect=JSONDecodeError('Expecting value', '', 0)
            )

            from invenio_oauthclient.views.client import serializer

            state = serializer.dumps({
                'app': 'test',
                'sid': session.sid,
                'next': None,
            })

            self.assertRaises(
                JSONDecodeError,
                c.get,
                url_for(
                    "oauthclient.authorized",
                    remote_app='test',
                    code='test',
                    state=state
                )
            )
Ejemplo n.º 7
0
def get_state(app='test'):
    """Get state."""
    return serializer.dumps({
        'app': app,
        'sid': _create_identifier(),
        'next': None,
    })
Ejemplo n.º 8
0
def test_invalid_authorized_response():
    """Test login."""
    app = setup_app()
    oauth = app.extensions['oauthlib.client']
    with app.test_client() as client:
        # Fake an authorized request
        # Ensure remote apps have been loaded (due to before first
        # request)
        client.get(url_for("invenio_oauthclient.login", remote_app='test'))

        oauth.remote_apps['test'].handle_oauth2_response = MagicMock(
            side_effect=JSONDecodeError('Expecting value', '', 0)
        )

        state = serializer.dumps({
            'app': 'test',
            'sid': _create_identifier(),
            'next': None,
        })

        with pytest.raises(JSONDecodeError):
            client.get(url_for(
                "invenio_oauthclient.authorized",
                remote_app='test',
                code='test',
                state=state
            ))
Ejemplo n.º 9
0
    def test_invalid_authorized_response(self):
        from simplejson import JSONDecodeError
        from invenio_oauthclient.client import oauth

        # Fake an authorized request
        with self.app.test_client() as c:
            # Ensure remote apps have been loaded (due to before first
            # request)
            c.get(url_for("oauthclient.login", remote_app='test'))

            oauth.remote_apps['test'].handle_oauth2_response = MagicMock(
                side_effect=JSONDecodeError('Expecting value', '', 0))

            from invenio_oauthclient.views.client import serializer

            state = serializer.dumps({
                'app': 'test',
                'sid': session.sid,
                'next': None,
            })

            self.assertRaises(
                JSONDecodeError, c.get,
                url_for("oauthclient.authorized",
                        remote_app='test',
                        code='test',
                        state=state))
Ejemplo n.º 10
0
def test_invalid_authorized_response(app_rest):
    """Test login."""
    oauth = app_rest.extensions['oauthlib.client']
    with app_rest.test_client() as client:
        # Fake an authorized request
        # Ensure remote apps have been loaded (due to before first
        # request)
        client.get(url_for(
            'invenio_oauthclient.rest_login', remote_app='test'))

        oauth.remote_apps['test'].handle_oauth2_response = MagicMock(
            side_effect=JSONDecodeError('Expecting value', '', 0)
        )

        state = serializer.dumps({
            'app': 'test',
            'sid': _create_identifier(),
            'next': None,
        })

        with pytest.raises(JSONDecodeError):
            client.get(url_for(
                'invenio_oauthclient.rest_authorized',
                remote_app='test',
                code='test',
                state=state
            ))
Ejemplo n.º 11
0
    def test_authorized(self):
        # Fake an authorized request
        with self.app.test_client() as c:
            # Ensure remote apps have been loaded (due to before first
            # request)
            c.get(url_for("oauthclient.login", remote_app='test'))
            self.mock_response(app='test')
            self.mock_response(app='test_invalid')

            from invenio_oauthclient.views.client import serializer

            state = serializer.dumps({
                'app': 'test',
                'sid': session.sid,
                'next': None,
            })

            resp = c.get(
                url_for(
                    "oauthclient.authorized",
                    remote_app='test',
                    code='test',
                    state=state
                )
            )
            assert resp.data == "TEST"
            assert self.handled_remote.name == 'test'
            assert not self.handled_args
            assert not self.handled_kwargs
            assert self.handled_resp['access_token'] == 'test_access_token'

            state = serializer.dumps({
                'app': 'test_invalid',
                'sid': session.sid,
                'next': None,
            })

            self.assertRaises(
                TypeError,
                c.get,
                url_for(
                    "oauthclient.authorized",
                    remote_app='test_invalid',
                    code='test',
                    state=state,
                )
            )
Ejemplo n.º 12
0
    def test_authorized(self):
        # Fake an authorized request
        with self.app.test_client() as c:
            # Ensure remote apps have been loaded (due to before first
            # request)
            c.get(url_for("oauthclient.login", remote_app='test'))
            self.mock_response(app='test')
            self.mock_response(app='test_invalid')

            from invenio_oauthclient.views.client import serializer

            state = serializer.dumps({
                'app': 'test',
                'sid': session.sid,
                'next': None,
            })

            resp = c.get(
                url_for("oauthclient.authorized",
                        remote_app='test',
                        code='test',
                        state=state))
            assert resp.data == "TEST"
            assert self.handled_remote.name == 'test'
            assert not self.handled_args
            assert not self.handled_kwargs
            assert self.handled_resp['access_token'] == 'test_access_token'

            state = serializer.dumps({
                'app': 'test_invalid',
                'sid': session.sid,
                'next': None,
            })

            self.assertRaises(
                TypeError, c.get,
                url_for(
                    "oauthclient.authorized",
                    remote_app='test_invalid',
                    code='test',
                    state=state,
                ))
Ejemplo n.º 13
0
def test_rejected(views_fixture, monkeypatch):
    """Test rejected."""
    # Mock session id
    monkeypatch.setattr('flask_login._create_identifier', lambda: '1234')
    monkeypatch.setattr('invenio_oauthclient.views.client._create_identifier',
                        lambda: '1234')

    app = views_fixture
    oauth = app.extensions['oauthlib.client']

    # Mock user id
    user = MagicMock()
    user.get_id = MagicMock(return_value=1)
    user.is_authenticated = MagicMock(return_value=True)

    with patch('flask_login._get_user', return_value=user):
        with app.test_client() as c:
            # First call login to be redirected
            res = c.get(url_for("invenio_oauthclient.login",
                                remote_app='full'))
            assert res.status_code == 302
            assert res.location.startswith(
                oauth.remote_apps['full'].authorize_url)

            # Mock response to imitate an invalid response. Here, an
            # example from GitHub when the code is expired.
            mock_response(app.extensions['oauthlib.client'],
                          'full',
                          data=dict(
                              error_uri='http://developer.github.com/v3/oauth/'
                              '#bad-verification-code',
                              error_description='The code passed is '
                              'incorrect or expired.',
                              error='bad_verification_code',
                          ))

            # Imitate that the user authorized our request in the remote
            # application (however, the remote app will son reply with an
            # error)
            state = serializer.dumps({
                'app': 'full',
                'sid': '1234',
                'next': None,
            })

            res = c.get(
                url_for("invenio_oauthclient.authorized",
                        remote_app='full',
                        code='test',
                        state=state))
            assert res.status_code == 302
Ejemplo n.º 14
0
def test_rejected(views_fixture, monkeypatch):
    """Test rejected."""
    # Mock session id
    monkeypatch.setattr('invenio_oauthclient._compat._create_identifier',
                        lambda: '1234')
    monkeypatch.setattr(
        'invenio_oauthclient.views.client._create_identifier', lambda: '1234')

    app = views_fixture
    oauth = app.extensions['oauthlib.client']

    # Mock user id
    user = MagicMock()
    user.get_id = MagicMock(return_value=1)
    user.is_authenticated = MagicMock(return_value=True)

    with app.test_client() as c:
        login_user_via_session(c, user)
        # First call login to be redirected
        res = c.get(url_for('invenio_oauthclient.login',
                            remote_app='full'))
        assert res.status_code == 302
        assert res.location.startswith(
            oauth.remote_apps['full'].authorize_url
        )

        # Mock response to imitate an invalid response. Here, an
        # example from GitHub when the code is expired.
        mock_response(app.extensions['oauthlib.client'], 'full', data=dict(
            error_uri='http://developer.github.com/v3/oauth/'
            '#bad-verification-code',
            error_description='The code passed is '
            'incorrect or expired.',
            error='bad_verification_code',
        ))

        # Imitate that the user authorized our request in the remote
        # application (however, the remote app will son reply with an
        # error)
        state = serializer.dumps({
            'app': 'full', 'sid': '1234',  'next': None,
        })

        res = c.get(url_for(
            'invenio_oauthclient.authorized', remote_app='full',
            code='test', state=state
        ))
        assert res.status_code == 302
Ejemplo n.º 15
0
    def test_rejected(self, session, save_session):
        from invenio_oauthclient.client import oauth

        # Mock user id
        user = MagicMock()
        user.get_id = MagicMock(return_value=1)
        user.is_authenticated = MagicMock(return_value=True)

        # Mock session id
        session.sid = '1234'

        with patch('flask_login._get_user', return_value=user):
            with self.app.test_client() as c:
                # First call login to be redirected
                res = c.get(url_for("oauthclient.login", remote_app='full'))
                assert res.status_code == 302
                assert res.location.startswith(
                    oauth.remote_apps['full'].authorize_url)

                # Mock response to imitate an invalid response. Here, an
                # example from GitHub when the code is expired.
                self.mock_response(
                    app='full',
                    data=dict(
                        error_uri='http://developer.github.com/v3/oauth/'
                        '#bad-verification-code',
                        error_description='The code passed is '
                        'incorrect or expired.',
                        error='bad_verification_code',
                    ))

                # Imitate that the user authorized our request in the remote
                # application (however, the remote app will son reply with an
                # error)
                from invenio_oauthclient.views.client import serializer
                state = serializer.dumps({
                    'app': 'full',
                    'sid': '1234',
                    'next': None,
                })

                res = c.get(
                    url_for("oauthclient.authorized",
                            remote_app='full',
                            code='test',
                            state=state))
                assert res.status_code == 302
Ejemplo n.º 16
0
    def test_rejected(self, session, save_session):
        from invenio_oauthclient.client import oauth

        # Mock user id
        user = MagicMock()
        user.get_id = MagicMock(return_value=1)
        user.is_authenticated = MagicMock(return_value=True)

        # Mock session id
        session.sid = '1234'

        with patch('flask_login._get_user', return_value=user):
            with self.app.test_client() as c:
                # First call login to be redirected
                res = c.get(url_for("oauthclient.login", remote_app='full'))
                assert res.status_code == 302
                assert res.location.startswith(
                    oauth.remote_apps['full'].authorize_url
                )

                # Mock response to imitate an invalid response. Here, an
                # example from GitHub when the code is expired.
                self.mock_response(app='full', data=dict(
                    error_uri='http://developer.github.com/v3/oauth/'
                              '#bad-verification-code',
                    error_description='The code passed is '
                                      'incorrect or expired.',
                    error='bad_verification_code',
                ))

                # Imitate that the user authorized our request in the remote
                # application (however, the remote app will son reply with an
                # error)
                from invenio_oauthclient.views.client import serializer
                state = serializer.dumps({
                    'app': 'full', 'sid': '1234',  'next': None,
                })

                res = c.get(url_for(
                    "oauthclient.authorized", remote_app='full', code='test',
                    state=state
                ))
                assert res.status_code == 302
def test_authorized():
    """Test login."""
    handled = {}

    def test_authorized_handler(resp, remote, *args, **kwargs):
        """Save configuration."""
        handled['resp'] = resp
        handled['remote'] = remote
        handled['args'] = args
        handled['kwargs'] = kwargs
        return "TEST"

    def test_invalid_authorized_handler(resp, remote, *args, **kwargs):
        """Set wrong configuration."""
        handled['resp'] = 1
        handled['remote'] = 1
        handled['args'] = 1
        handled['kwargs'] = 1

    app = setup_app(test_authorized_handler, test_invalid_authorized_handler)
    with app.test_client() as client:
        # Ensure remote apps have been loaded (due to before first
        # request)
        client.get(url_for("invenio_oauthclient.login", remote_app='test'))
        mock_response(app.extensions['oauthlib.client'], 'test')
        mock_response(app.extensions['oauthlib.client'], 'test_invalid')

        from invenio_oauthclient.views.client import serializer

        state = serializer.dumps({
            'app': 'test',
            'sid': session['_id'],
            'next': None,
        })

        resp = client.get(
            url_for("invenio_oauthclient.authorized",
                    remote_app='test',
                    code='test',
                    state=state))
        assert resp.data == b"TEST"
        assert handled['remote'].name == 'test'
        assert not handled['args']
        assert not handled['kwargs']
        assert handled['resp']['access_token'] == 'test_access_token'

        state = serializer.dumps({
            'app': 'test_invalid',
            'sid': session['_id'],
            'next': None,
        })

        # handler should be return something
        with pytest.raises(ValueError):
            client.get(
                url_for(
                    "invenio_oauthclient.authorized",
                    remote_app='test_invalid',
                    code='test',
                    state=state,
                ))
Ejemplo n.º 18
0
def _get_state():
    return serializer.dumps({
        'app': 'orcid',
        'sid': session['_id'],
        'next': None,
    })
Ejemplo n.º 19
0
def test_authorized(base_app, params):
    """Test login."""
    handled = {}

    def test_authorized_handler(resp, remote, *args, **kwargs):
        """Save configuration."""
        handled['resp'] = resp
        handled['remote'] = remote
        handled['args'] = args
        handled['kwargs'] = kwargs
        return 'TEST'

    def test_invalid_authorized_handler(resp, remote, *args, **kwargs):
        """Set wrong configuration."""
        handled['resp'] = 1
        handled['remote'] = 1
        handled['args'] = 1
        handled['kwargs'] = 1

    base_app.config['OAUTHCLIENT_REST_REMOTE_APPS'].update(
        dict(
            test=dict(
                authorized_handler=test_authorized_handler,
                params=params('testid'),
                title='MyLinkedTestAccount',
            ),
            test_invalid=dict(
                authorized_handler=test_invalid_authorized_handler,
                params=params('test_invalidid'),
                title='Test Invalid',
            ),
            full=dict(
                params=params('fullid'),
                title='Full',
            ),
        ))

    FlaskOAuth(base_app)
    InvenioOAuthClientREST(base_app)
    base_app.register_blueprint(rest_blueprint)

    with base_app.test_client() as client:
        # Ensure remote apps have been loaded (due to before first
        # request)
        client.get(url_for(
            'invenio_oauthclient.rest_login', remote_app='test'))
        mock_response(base_app.extensions['oauthlib.client'], 'test')
        mock_response(base_app.extensions['oauthlib.client'], 'test_invalid')

        from invenio_oauthclient.views.client import serializer

        state = serializer.dumps({
            'app': 'test',
            'sid': _create_identifier(),
            'next': None,
        })

        resp = client.get(
            url_for(
                'invenio_oauthclient.rest_authorized',
                remote_app='test',
                code='test',
                state=state
            )
        )
        assert resp.data == b'TEST'
        assert handled['remote'].name == 'test'
        assert not handled['args']
        assert not handled['kwargs']
        assert handled['resp']['access_token'] == 'test_access_token'

        state = serializer.dumps({
            'app': 'test_invalid',
            'sid': _create_identifier(),
            'next': None,
        })

        # handler should return something
        # Flask>1.0 is throwing TypeError and Flask<1.0 ValueError
        with pytest.raises((ValueError, TypeError)):
            client.get(url_for(
                'invenio_oauthclient.rest_authorized',
                remote_app='test_invalid',
                code='test',
                state=state,
            ))
def _get_state():
    return serializer.dumps({'app': 'orcid', 'sid': _create_identifier(),
                             'next': None, })
Ejemplo n.º 21
0
def test_authorized():
    """Test login."""
    handled = {}

    def test_authorized_handler(resp, remote, *args, **kwargs):
        """Save configuration."""
        handled['resp'] = resp
        handled['remote'] = remote
        handled['args'] = args
        handled['kwargs'] = kwargs
        return "TEST"

    def test_invalid_authorized_handler(resp, remote, *args, **kwargs):
        """Set wrong configuration."""
        handled['resp'] = 1
        handled['remote'] = 1
        handled['args'] = 1
        handled['kwargs'] = 1

    app = setup_app(test_authorized_handler, test_invalid_authorized_handler)
    with app.test_client() as client:
        # Ensure remote apps have been loaded (due to before first
        # request)
        client.get(url_for("invenio_oauthclient.login", remote_app='test'))
        mock_response(app.extensions['oauthlib.client'], 'test')
        mock_response(app.extensions['oauthlib.client'], 'test_invalid')

        from invenio_oauthclient.views.client import serializer

        state = serializer.dumps({
            'app': 'test',
            'sid': _create_identifier(),
            'next': None,
        })

        resp = client.get(
            url_for(
                "invenio_oauthclient.authorized",
                remote_app='test',
                code='test',
                state=state
            )
        )
        assert resp.data == b"TEST"
        assert handled['remote'].name == 'test'
        assert not handled['args']
        assert not handled['kwargs']
        assert handled['resp']['access_token'] == 'test_access_token'

        state = serializer.dumps({
            'app': 'test_invalid',
            'sid': _create_identifier(),
            'next': None,
        })

        # handler should be return something
        with pytest.raises(ValueError):
            client.get(url_for(
                "invenio_oauthclient.authorized",
                remote_app='test_invalid',
                code='test',
                state=state,
            ))
 def _get_state(self):
     from invenio_oauthclient.views.client import serializer
     return serializer.dumps({'app': 'orcid', 'sid': session.sid,
                              'next': None, })
Ejemplo n.º 23
0
def test_authorized(base_app, params):
    """Test login."""
    app = base_app

    handled = {}

    def test_authorized_handler(resp, remote, *args, **kwargs):
        """Save configuration."""
        handled['resp'] = resp
        handled['remote'] = remote
        handled['args'] = args
        handled['kwargs'] = kwargs
        return 'TEST'

    def test_invalid_authorized_handler(resp, remote, *args, **kwargs):
        """Set wrong configuration."""
        handled['resp'] = 1
        handled['remote'] = 1
        handled['args'] = 1
        handled['kwargs'] = 1

    base_app.config['OAUTHCLIENT_REMOTE_APPS'].update(
        dict(
            test=dict(
                authorized_handler=test_authorized_handler,
                params=params('testid'),
                title='MyLinkedTestAccount',
            ),
            test_invalid=dict(
                authorized_handler=test_invalid_authorized_handler,
                params=params('test_invalidid'),
                title='Test Invalid',
            ),
            full=dict(
                params=params('fullid'),
                title='Full',
            ),
        )
    )

    FlaskOAuth(app)
    InvenioOAuthClient(app)
    base_app.register_blueprint(blueprint_client)
    base_app.register_blueprint(blueprint_settings)

    with app.test_client() as client:
        # Ensure remote apps have been loaded (due to before first
        # request)
        client.get(url_for('invenio_oauthclient.login', remote_app='test'))
        mock_response(app.extensions['oauthlib.client'], 'test')
        mock_response(app.extensions['oauthlib.client'], 'test_invalid')

        from invenio_oauthclient.views.client import serializer

        state = serializer.dumps({
            'app': 'test',
            'sid': _create_identifier(),
            'next': None,
        })

        resp = client.get(
            url_for(
                'invenio_oauthclient.authorized',
                remote_app='test',
                code='test',
                state=state
            )
        )
        assert resp.data == b'TEST'
        assert handled['remote'].name == 'test'
        assert not handled['args']
        assert not handled['kwargs']
        assert handled['resp']['access_token'] == 'test_access_token'

        state = serializer.dumps({
            'app': 'test_invalid',
            'sid': _create_identifier(),
            'next': None,
        })

        # handler should be return something
        with pytest.raises(ValueError):
            client.get(url_for(
                'invenio_oauthclient.authorized',
                remote_app='test_invalid',
                code='test',
                state=state,
            ))
Ejemplo n.º 24
0
def _get_state():
    return serializer.dumps({
        'app': 'github',
        'sid': _create_identifier(),
        'next': None,
    })
def _get_state():
    return serializer.dumps({'app': 'orcid', 'sid': session['_id'],
                             'next': None, })
Ejemplo n.º 26
0
def get_state(app="test"):
    """Get state."""
    return serializer.dumps({"app": app, "sid": _create_identifier(), "next": None})
Ejemplo n.º 27
0
def get_state(app='test'):
    return serializer.dumps({'app': app, 'sid': _create_identifier(),
                             'next': None, })
 def _get_state(self):
     from invenio_oauthclient.views.client import serializer
     return serializer.dumps({'app': 'orcid', 'sid': session.sid,
                              'next': None, })