# Path: invenio_oauthclient/ext.py
# class InvenioOAuthClient(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."""
#         self.init_config(app)
#         state = _OAuthClientState(
#             app, 'OAUTHCLIENT_REMOTE_APPS',
#             handlers.disconnect_handler,
#             handlers.authorized_default_handler)
#         app.extensions['invenio-oauthclient'] = state
#         return state
# 
#     def init_config(self, app):
#         """Initialize configuration."""
#         @app.before_first_request
#         def override_template_configuration():
#             """Override template configuration."""
#             template_key = app.config.get(
#                 'OAUTHCLIENT_TEMPLATE_KEY',
#                 'SECURITY_LOGIN_USER_TEMPLATE'  # default template key
#             )
#             if template_key is not None:
#                 template = app.config[template_key]  # keep the old value
#                 app.config['OAUTHCLIENT_LOGIN_USER_TEMPLATE_PARENT'] = template
#                 app.config[template_key] = app.config.get(
#                     'OAUTHCLIENT_LOGIN_USER_TEMPLATE',
#                     'invenio_oauthclient/login_user.html'
#                 )
# 
# 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: 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: invenio_oauthclient/views/settings.py
# def index():


import time
import pytest
from flask import url_for
from flask_oauthlib.client import OAuth as FlaskOAuth
from flask_security import login_user
from helpers import check_response_redirect_url
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 InvenioOAuthClient
from invenio_oauthclient._compat import _create_identifier
from invenio_oauthclient.handlers import token_getter
from invenio_oauthclient.models import RemoteAccount, RemoteToken
from invenio_oauthclient.views.client import blueprint as blueprint_client
from invenio_oauthclient.views.client import serializer
from invenio_oauthclient.views.settings import blueprint as blueprint_settings
        from invenio_oauthclient.views.client import serializer
        from flask import session as flask_session
        # 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

# Path: invenio_oauthclient/ext.py
# class InvenioOAuthClient(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."""
#         self.init_config(app)
#         state = _OAuthClientState(
#             app, 'OAUTHCLIENT_REMOTE_APPS',
#             handlers.disconnect_handler,
#             handlers.authorized_default_handler)
#         app.extensions['invenio-oauthclient'] = state
#         return state
# 
#     def init_config(self, app):
#         """Initialize configuration."""
#         @app.before_first_request
#         def override_template_configuration():
#             """Override template configuration."""
#             template_key = app.config.get(
#                 'OAUTHCLIENT_TEMPLATE_KEY',
#                 'SECURITY_LOGIN_USER_TEMPLATE'  # default template key
#             )
#             if template_key is not None:
#                 template = app.config[template_key]  # keep the old value
#                 app.config['OAUTHCLIENT_LOGIN_USER_TEMPLATE_PARENT'] = template
#                 app.config[template_key] = app.config.get(
#                     'OAUTHCLIENT_LOGIN_USER_TEMPLATE',
#                     'invenio_oauthclient/login_user.html'
#                 )
# 
# 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: 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: invenio_oauthclient/views/settings.py
# def index():


# Path: tests/test_views.py
import time
import pytest
from flask import url_for
from flask_oauthlib.client import OAuth as FlaskOAuth
from flask_security import login_user
from helpers import check_response_redirect_url
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 InvenioOAuthClient
from invenio_oauthclient._compat import _create_identifier
from invenio_oauthclient.handlers import token_getter
from invenio_oauthclient.models import RemoteAccount, RemoteToken
from invenio_oauthclient.views.client import blueprint as blueprint_client
from invenio_oauthclient.views.client import serializer
from invenio_oauthclient.views.settings import blueprint as blueprint_settings
        from invenio_oauthclient.views.client import serializer
        from flask import session as flask_session

        # 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(