# Path: invenio_oauthclient/ext.py
# class InvenioOAuthClientREST(object):
#     """Invenio Oauthclient extension."""
# 
#     def __init__(self, app=None):
#         """Extension initialization."""
#         if app:
#             self._state = self.init_app(app)
# 
#     def init_app(self, app):
#         """Flask application initialization."""
#         _default_response_handler = obj_or_import_string(
#             app.config.get("OAUTHCLIENT_REST_DEFAULT_RESPONSE_HANDLER"),
#             handlers.rest.default_response_handler
#         )
#         _default_remote_handler = handlers.rest.default_remote_response_handler
#         state = _OAuthClientState(
#             app, 'OAUTHCLIENT_REST_REMOTE_APPS',
#             handlers.rest.disconnect_handler,
#             handlers.rest.authorized_default_handler,
#             default_remote_app_response_handler=_default_remote_handler,
#             default_response_handler=_default_response_handler
#         )
# 
#         app.extensions['invenio-oauthclient'] = state
#         return state
# 
# Path: invenio_oauthclient/_compat.py
# def monkey_patch_werkzeug():
# 
# Path: invenio_oauthclient/handlers/utils.py
# def token_getter(remote, token=''):
#     """Retrieve OAuth access token.
# 
#     Used by flask-oauthlib to get the access token when making requests.
# 
#     :param remote: The remote application.
#     :param token: Type of token to get. Data passed from ``oauth.request()`` to
#         identify which token to retrieve. (Default: ``''``)
#     :returns: The token.
#     """
#     session_key = token_session_key(remote.name)
# 
#     if session_key not in session and current_user.is_authenticated:
#         # Fetch key from token store if user is authenticated, and the key
#         # isn't already cached in the session.
#         remote_token = RemoteToken.get(
#             current_user.get_id(),
#             remote.consumer_key,
#             token_type=token,
#         )
# 
#         if remote_token is None:
#             return None
# 
#         # Store token and secret in session
#         session[session_key] = remote_token.token()
# 
#     return session.get(session_key, None)
# 
# Path: invenio_oauthclient/views/client.py
# def post_ext_init(state):
# def auto_redirect_login(*args, **kwargs):
# def _login(remote_app, authorized_view_name):
# def login(remote_app):
# def rest_login(remote_app):
# def _authorized(remote_app=None):
# def authorized(remote_app=None):
# def rest_authorized(remote_app=None):
# def _signup(remote_app):
# def signup(remote_app):
# def rest_signup(remote_app):
# def _disconnect(remote_app):
# def disconnect(remote_app):
# def rest_disconnect(remote_app):


import time
import pytest
from flask import url_for
from flask_oauthlib.client import OAuth as FlaskOAuth
from helpers import check_response_redirect_url, \
    check_response_redirect_url_args
from invenio_accounts.testutils import login_user_via_session
from invenio_db import db
from itsdangerous import TimedJSONWebSignatureSerializer
from mock import MagicMock
from simplejson import JSONDecodeError
from six.moves.urllib_parse import parse_qs, urlparse
from invenio_oauthclient import InvenioOAuthClientREST
from invenio_oauthclient._compat import _create_identifier
from invenio_oauthclient.handlers import token_getter
from invenio_oauthclient.models import RemoteToken
from invenio_oauthclient.views.client import rest_blueprint, serializer
        from invenio_oauthclient.views.client import serializer
        from flask import session as flask_session
            '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 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',

# Path: invenio_oauthclient/ext.py
# class InvenioOAuthClientREST(object):
#     """Invenio Oauthclient extension."""
# 
#     def __init__(self, app=None):
#         """Extension initialization."""
#         if app:
#             self._state = self.init_app(app)
# 
#     def init_app(self, app):
#         """Flask application initialization."""
#         _default_response_handler = obj_or_import_string(
#             app.config.get("OAUTHCLIENT_REST_DEFAULT_RESPONSE_HANDLER"),
#             handlers.rest.default_response_handler
#         )
#         _default_remote_handler = handlers.rest.default_remote_response_handler
#         state = _OAuthClientState(
#             app, 'OAUTHCLIENT_REST_REMOTE_APPS',
#             handlers.rest.disconnect_handler,
#             handlers.rest.authorized_default_handler,
#             default_remote_app_response_handler=_default_remote_handler,
#             default_response_handler=_default_response_handler
#         )
# 
#         app.extensions['invenio-oauthclient'] = state
#         return state
# 
# Path: invenio_oauthclient/_compat.py
# def monkey_patch_werkzeug():
# 
# Path: invenio_oauthclient/handlers/utils.py
# def token_getter(remote, token=''):
#     """Retrieve OAuth access token.
# 
#     Used by flask-oauthlib to get the access token when making requests.
# 
#     :param remote: The remote application.
#     :param token: Type of token to get. Data passed from ``oauth.request()`` to
#         identify which token to retrieve. (Default: ``''``)
#     :returns: The token.
#     """
#     session_key = token_session_key(remote.name)
# 
#     if session_key not in session and current_user.is_authenticated:
#         # Fetch key from token store if user is authenticated, and the key
#         # isn't already cached in the session.
#         remote_token = RemoteToken.get(
#             current_user.get_id(),
#             remote.consumer_key,
#             token_type=token,
#         )
# 
#         if remote_token is None:
#             return None
# 
#         # Store token and secret in session
#         session[session_key] = remote_token.token()
# 
#     return session.get(session_key, None)
# 
# Path: invenio_oauthclient/views/client.py
# def post_ext_init(state):
# def auto_redirect_login(*args, **kwargs):
# def _login(remote_app, authorized_view_name):
# def login(remote_app):
# def rest_login(remote_app):
# def _authorized(remote_app=None):
# def authorized(remote_app=None):
# def rest_authorized(remote_app=None):
# def _signup(remote_app):
# def signup(remote_app):
# def rest_signup(remote_app):
# def _disconnect(remote_app):
# def disconnect(remote_app):
# def rest_disconnect(remote_app):


# Path: tests/test_views_rest.py
import time
import pytest
from flask import url_for
from flask_oauthlib.client import OAuth as FlaskOAuth
from helpers import check_response_redirect_url, \
    check_response_redirect_url_args
from invenio_accounts.testutils import login_user_via_session
from invenio_db import db
from itsdangerous import TimedJSONWebSignatureSerializer
from mock import MagicMock
from simplejson import JSONDecodeError
from six.moves.urllib_parse import parse_qs, urlparse
from invenio_oauthclient import InvenioOAuthClientREST
from invenio_oauthclient._compat import _create_identifier
from invenio_oauthclient.handlers import token_getter
from invenio_oauthclient.models import RemoteToken
from invenio_oauthclient.views.client import rest_blueprint, serializer
        from invenio_oauthclient.views.client import serializer
        from flask import session as flask_session

            '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 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(),