# Path: invenio_oauthclient/_compat.py
# def monkey_patch_werkzeug():
# 
# Path: invenio_oauthclient/errors.py
# class OAuthRemoteNotFound(Exception):
#     """Define exception for remote app not found."""
# 
# Path: invenio_oauthclient/handlers/utils.py
# def set_session_next_url(remote_app, url):
#     """Store redirect url in session for security reasons.
# 
#     :param remote_app: The remote application.
#     :param url: the redirect URL.
#     """
#     session['%s_%s' % (token_session_key(remote_app), 'next_url')] = \
#         url
# 
# Path: invenio_oauthclient/handlers/rest.py
# def response_handler(remote, url, payload=None):
#     """Handle oauthclient rest response."""
#     if not remote:
#         return current_oauthclient.default_response_handler(url, payload)
#     return current_oauthclient.remote_app_response_handler[remote.name](
#         remote, url, payload)
# 
# Path: invenio_oauthclient/utils.py
# def _commit(response=None):
# def _get_external_id(account_info):
# def oauth_get_user(client_id, account_info=None, access_token=None):
# def oauth_authenticate(client_id, user, require_existing_link=False):
# def filter_user_info(user_info, precedence_mask):
# def patch_dictionary(orig_dict, patch_dict):
# def remove_csrf_tokens(user_data):
# def oauth_register(form, user_info=None, precedence_mask=None):
# def oauth_link_external_id(user, external_id=None):
# def oauth_unlink_external_id(external_id):
# def get_safe_redirect_target(arg='next'):
# def obj_or_import_string(value, default=None):
# def load_or_import_from_config(key, app=None, default=None):
# def _create_registrationform(*args, **kwargs):
# def create_registrationform(*args, **kwargs):
# def create_csrf_disabled_registrationform(remote):
# def fill_form(form, data):
# def rebuild_access_tokens(old_key):
# def _get_csrf_disabled_param():
#     class RegistrationForm(_security.confirm_register_form):


from flask import Blueprint, abort, current_app, redirect, request, url_for
from flask_oauthlib.client import OAuthException
from invenio_accounts.views import login as base_login
from invenio_db import db
from itsdangerous import BadData
from .._compat import _create_identifier
from ..errors import OAuthRemoteNotFound
from ..handlers import set_session_next_url
from ..handlers.rest import response_handler
from ..proxies import current_oauthclient
from ..utils import get_safe_redirect_target, serializer


@blueprint.route('/login/<remote_app>/')
def login(remote_app):
    """Send user to remote application for authentication."""
    try:
        return _login(remote_app, '.authorized')
    except OAuthRemoteNotFound:
        return abort(404)


@rest_blueprint.route('/login/<remote_app>/')
def rest_login(remote_app):
    """Send user to remote application for authentication."""
    try:
        return _login(remote_app, '.rest_authorized')
    except OAuthRemoteNotFound:
        abort(404)


def _authorized(remote_app=None):
    """Authorized handler callback."""
    if remote_app not in current_oauthclient.handlers:
        return abort(404)

    state_token = request.args.get('state')

    # Verify state parameter
    assert state_token
    # Checks authenticity and integrity of state and decodes the value.

# Path: invenio_oauthclient/_compat.py
# def monkey_patch_werkzeug():
# 
# Path: invenio_oauthclient/errors.py
# class OAuthRemoteNotFound(Exception):
#     """Define exception for remote app not found."""
# 
# Path: invenio_oauthclient/handlers/utils.py
# def set_session_next_url(remote_app, url):
#     """Store redirect url in session for security reasons.
# 
#     :param remote_app: The remote application.
#     :param url: the redirect URL.
#     """
#     session['%s_%s' % (token_session_key(remote_app), 'next_url')] = \
#         url
# 
# Path: invenio_oauthclient/handlers/rest.py
# def response_handler(remote, url, payload=None):
#     """Handle oauthclient rest response."""
#     if not remote:
#         return current_oauthclient.default_response_handler(url, payload)
#     return current_oauthclient.remote_app_response_handler[remote.name](
#         remote, url, payload)
# 
# Path: invenio_oauthclient/utils.py
# def _commit(response=None):
# def _get_external_id(account_info):
# def oauth_get_user(client_id, account_info=None, access_token=None):
# def oauth_authenticate(client_id, user, require_existing_link=False):
# def filter_user_info(user_info, precedence_mask):
# def patch_dictionary(orig_dict, patch_dict):
# def remove_csrf_tokens(user_data):
# def oauth_register(form, user_info=None, precedence_mask=None):
# def oauth_link_external_id(user, external_id=None):
# def oauth_unlink_external_id(external_id):
# def get_safe_redirect_target(arg='next'):
# def obj_or_import_string(value, default=None):
# def load_or_import_from_config(key, app=None, default=None):
# def _create_registrationform(*args, **kwargs):
# def create_registrationform(*args, **kwargs):
# def create_csrf_disabled_registrationform(remote):
# def fill_form(form, data):
# def rebuild_access_tokens(old_key):
# def _get_csrf_disabled_param():
#     class RegistrationForm(_security.confirm_register_form):


# Path: invenio_oauthclient/views/client.py
from flask import Blueprint, abort, current_app, redirect, request, url_for
from flask_oauthlib.client import OAuthException
from invenio_accounts.views import login as base_login
from invenio_db import db
from itsdangerous import BadData
from .._compat import _create_identifier
from ..errors import OAuthRemoteNotFound
from ..handlers import set_session_next_url
from ..handlers.rest import response_handler
from ..proxies import current_oauthclient
from ..utils import get_safe_redirect_target, serializer



@blueprint.route('/login/<remote_app>/')
def login(remote_app):
    """Send user to remote application for authentication."""
    try:
        return _login(remote_app, '.authorized')
    except OAuthRemoteNotFound:
        return abort(404)


@rest_blueprint.route('/login/<remote_app>/')
def rest_login(remote_app):
    """Send user to remote application for authentication."""
    try:
        return _login(remote_app, '.rest_authorized')
    except OAuthRemoteNotFound:
        abort(404)


def _authorized(remote_app=None):
    """Authorized handler callback."""
    if remote_app not in current_oauthclient.handlers:
        return abort(404)

    state_token = request.args.get('state')

    # Verify state parameter
    assert state_token
    # Checks authenticity and integrity of state and decodes the value.

    state = serializer.loads(state_token)