def test_init(): """Test extension initialization.""" app = Flask('testapp') FlaskCLI(app) FlaskOAuth(app) ext = InvenioOAuthClient(app) assert 'invenio-oauthclient' in app.extensions app = Flask('testapp') FlaskCLI(app) FlaskOAuth(app) ext = InvenioOAuthClient() assert 'invenio-oauthclient' not in app.extensions ext.init_app(app) assert 'invenio-oauthclient' in app.extensions
def app(request): """Flask application fixture.""" app_ = Flask('testapp') app_.config.update( CELERY_ALWAYS_EAGER=True, CELERY_RESULT_BACKEND="cache", CELERY_CACHE_BACKEND="memory", CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, TESTING=True, SQLALCHEMY_TRACK_MODIFICATIONS=True, SQLALCHEMY_DATABASE_URI=os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///:memory:'), SECURITY_PASSWORD_SALT='TEST', SECRET_KEY='TEST', ) FlaskCeleryExt(app_) InvenioDB(app_) InvenioRecords(app_) InvenioDeposit(app_) InvenioJSONSchemas(app_) InvenioAccounts(app_) InvenioCommunities(app_) InvenioPIDStore(app_) InvenioSIPStore(app_) Babel(app_) InvenioFilesREST(app_) InvenioMigrator(app_) FlaskOAuth(app_) InvenioOAuthClient(app_) with app_.app_context(): yield app_
def app(base_app): """Flask application fixture.""" FlaskOAuth(base_app) InvenioOAuthClient(base_app) base_app.register_blueprint(blueprint_client) base_app.register_blueprint(blueprint_settings) return base_app
def test_response_handler_with_postmessage(remote, app_rest, models_fixture): """Test response handler with postmessage.""" # Force usage of dummy handlers app_rest.config['OAUTHCLIENT_REST_REMOTE_APPS'][ remote.name]['response_handler'] = response_handler_postmessage # Initialize InvenioOAuth FlaskOAuth(app_rest) InvenioOAuthClientREST(app_rest) app_rest.register_blueprint(rest_blueprint) datastore = app_rest.extensions['invenio-accounts'].datastore existing_email = '*****@*****.**' user = datastore.find_user(email=existing_email) # Already authenticated login_user(user) assert current_user.is_authenticated response = signup_handler(remote) expected_message = "Successfully signed up." expected_status = "200" assert expected_message in response assert expected_status in response assert 'window.opener.postMessage' in response
def test_db(request): """Test database backend.""" app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite://') InvenioDB(app) FlaskOAuth(app) InvenioOAuthClient(app) def teardown(): with app.app_context(): db.drop_all() request.addfinalizer(teardown) with app.app_context(): is_sqllite = str(db.engine.url) == 'sqlite://' db_exists = database_exists(str(db.engine.url)) if not is_sqllite and not db_exists: create_database(str(db.engine.url)) db.create_all() tables = list( filter(lambda table: table.startswith('oauthclient'), db.metadata.tables.keys())) assert len(tables) == 2
def create_app(): """REANA Server application factory.""" logging.basicConfig(level=REANA_LOG_LEVEL, format=REANA_LOG_FORMAT) app = Flask(__name__) app.config.from_object('reana_server.config') app.secret_key = "hyper secret key" app.session = Session Babel(app) FlaskMenu(app) InvenioDB(app) InvenioAccounts(app) FlaskOAuth(app) InvenioOAuthClient(app) # Register Invenio OAuth endpoints app.register_blueprint(blueprint_user) app.register_blueprint(blueprint_client) app.register_blueprint(blueprint_settings) # Register API routes from .rest import gitlab, ping, secrets, users, workflows # noqa app.register_blueprint(ping.blueprint, url_prefix='/api') app.register_blueprint(workflows.blueprint, url_prefix='/api') app.register_blueprint(users.blueprint, url_prefix='/api') app.register_blueprint(secrets.blueprint, url_prefix='/api') app.register_blueprint(gitlab.blueprint, url_prefix='/api') return app
def _init_app(app_): """Init OAuth app.""" FlaskOAuth(app_) InvenioOAuthClient(app_) app_.register_blueprint(blueprint_client) app_.register_blueprint(blueprint_settings) return app_
def _init_app(app_): """Init OAuth app.""" app_.config.update(WTF_CSRF_ENABLED=False, ) FlaskOAuth(app_) InvenioOAuthClient(app_) app_.register_blueprint(blueprint_client) app_.register_blueprint(blueprint_settings) return app_
def test_remote_app_factory_global_customization(base_app): """Test remote_app override with global variable.""" base_app.config.update(OAUTHCLIENT_REMOTE_APP=_CustomOAuthRemoteApp, OAUTHCLIENT_REMOTE_APPS=dict(custom_app=REMOTE_APP)) FlaskOAuth(base_app) InvenioOAuthClient(base_app) assert isinstance( base_app.extensions['oauthlib.client'].remote_apps['custom_app'], _CustomOAuthRemoteApp)
def test_standard_remote_app_factory(base_app): """Test standard remote_app class.""" base_app.config.update(OAUTHCLIENT_REMOTE_APPS=dict(custom_app=REMOTE_APP)) FlaskOAuth(base_app) InvenioOAuthClient(base_app) assert isinstance( base_app.extensions['oauthlib.client'].remote_apps['custom_app'], OAuthRemoteApp) assert not isinstance( base_app.extensions['oauthlib.client'].remote_apps['custom_app'], _CustomOAuthRemoteApp)
def test_remote_app_factory_local_customization(base_app): """Test custom remote_app for one app only.""" config_for_one_app = deepcopy(REMOTE_APP) config_for_one_app['remote_app'] = _CustomOAuthRemoteApp base_app.config.update(OAUTHCLIENT_REMOTE_APPS=dict( custom_app=config_for_one_app)) FlaskOAuth(base_app) InvenioOAuthClient(base_app) assert isinstance( base_app.extensions['oauthlib.client'].remote_apps['custom_app'], _CustomOAuthRemoteApp)
def create_app(config_mapping=None): """REANA Server application factory.""" logging.basicConfig(level=REANA_LOG_LEVEL, format=REANA_LOG_FORMAT, force=True) app = Flask(__name__) app.config.from_object("reana_server.config") if config_mapping: app.config.from_mapping(config_mapping) app.secret_key = "hyper secret key" app.session = Session Babel(app) FlaskMenu(app) InvenioDB(app) InvenioAccounts(app) FlaskOAuth(app) InvenioOAuthClient(app) # Register Invenio OAuth endpoints app.register_blueprint(blueprint_user) app.register_blueprint(blueprint_client) app.register_blueprint(blueprint_settings) # Register API routes from .rest import ( config, gitlab, ping, secrets, status, users, workflows, info, ) # noqa app.register_blueprint(ping.blueprint, url_prefix="/api") app.register_blueprint(workflows.blueprint, url_prefix="/api") app.register_blueprint(users.blueprint, url_prefix="/api") app.register_blueprint(secrets.blueprint, url_prefix="/api") app.register_blueprint(gitlab.blueprint, url_prefix="/api") app.register_blueprint(config.blueprint, url_prefix="/api") app.register_blueprint(status.blueprint, url_prefix="/api") app.register_blueprint(info.blueprint, url_prefix="/api") @app.teardown_appcontext def shutdown_session(response_or_exc): """Close session on app teardown.""" current_app.session.remove() return response_or_exc return app
def test_dummy_handler(base_app): """Test dummy handler.""" # Force usage of dummy handlers base_app.config['OAUTHCLIENT_REMOTE_APPS']['cern']['signup_handler'] = {} # Initialize InvenioOAuth FlaskOAuth(base_app) InvenioOAuthClient(base_app) base_app.register_blueprint(blueprint_client) base_app.register_blueprint(blueprint_settings) # Try to sign-up client base_app.test_client().get(url_for('invenio_oauthclient.signup', remote_app='cern', next='/someurl/'))
def views_fixture(base_app, params): """Flask application with example data used to test views.""" with base_app.app_context(): datastore = base_app.extensions['security'].datastore datastore.create_user( email="*****@*****.**", password='******', active=True ) datastore.create_user( email="*****@*****.**", password='******', active=True ) datastore.create_user( email="*****@*****.**", password='******', active=True ) datastore.commit() base_app.config['OAUTHCLIENT_REMOTE_APPS'].update( dict( test=dict( authorized_handler=lambda *args, **kwargs: "TEST", params=params('testid'), title='MyLinkedTestAccount', ), test_invalid=dict( authorized_handler=lambda *args, **kwargs: "TEST", params=params('test_invalidid'), title='Test Invalid', ), full=dict( params=params("fullid"), title='Full', ), ) ) FlaskOAuth(base_app) InvenioOAuthClient(base_app) base_app.register_blueprint(blueprint_client) base_app.register_blueprint(blueprint_settings) return base_app
def test_response_handler(remote_name, app_rest): """Test response handler.""" def mock_response_handler(remote, url, payload): return remote.name # Force usage of dummy handlers app_rest.config['OAUTHCLIENT_REST_REMOTE_APPS'][remote_name][ 'response_handler'] = mock_response_handler # Initialize InvenioOAuth FlaskOAuth(app_rest) InvenioOAuthClientREST(app_rest) app_rest.register_blueprint(rest_blueprint) # Try to sign-up client response = app_rest.test_client().get( url_for('invenio_oauthclient.rest_signup', remote_app=remote_name)) assert remote_name in str(response.data)
def test_dummy_handler(remote_name, base_app): """Test dummy handler.""" signup_handler = base_app.config['OAUTHCLIENT_REST_REMOTE_APPS'][ remote_name]['signup_handler'] # Force usage of dummy handlers base_app.config['OAUTHCLIENT_REST_REMOTE_APPS'][remote_name][ 'signup_handler'] = {} # Initialize InvenioOAuth FlaskOAuth(base_app) InvenioOAuthClientREST(base_app) base_app.register_blueprint(rest_blueprint) # Try to sign-up client base_app.test_client().get( url_for('invenio_oauthclient.rest_signup', remote_app=remote_name, next='/someurl/')) base_app.config['OAUTHCLIENT_REST_REMOTE_APPS'][remote_name][ 'signup_handler'] = signup_handler
def gen_app(config): """Generate a fresh app.""" app = Flask('testapp') app.testing = True app.config.update(**config) FlaskCLI(app) FlaskMenu(app) Babel(app) Mail(app) InvenioDB(app) InvenioAccounts(app) FlaskOAuth(app) InvenioOAuthClient(app) app.register_blueprint(blueprint_client) app.register_blueprint(blueprint_settings) with app.app_context(): db.create_all() app.test_request_context().push() datastore = app.extensions['invenio-accounts'].datastore datastore.create_user(email="*****@*****.**", password='******', active=True) datastore.create_user(email="*****@*****.**", password='******', active=True) datastore.create_user(email="*****@*****.**", password='******', active=True) datastore.commit() return app
def __init__(self, app): """Initialize state.""" self.app = app self.handlers = {} self.disconnect_handlers = {} self.signup_handlers = {} # Connect signal to remove access tokens on logout user_logged_out.connect(oauth_logout_handler) self.oauth = app.extensions.get('oauthlib.client') or FlaskOAuth() # Add remote applications self.oauth.init_app(app) for remote_app, conf in app.config['OAUTHCLIENT_REMOTE_APPS'].items(): # Prevent double creation problems if remote_app not in self.oauth.remote_apps: remote = self.oauth.remote_app(remote_app, **conf['params']) remote = self.oauth.remote_apps[remote_app] # Set token getter for remote remote.tokengetter(make_token_getter(remote)) # Register authorized handler self.handlers[remote_app] = remote.authorized_handler( make_handler( conf.get('authorized_handler', authorized_default_handler), remote, )) # Register disconnect handler self.disconnect_handlers[remote_app] = make_handler( conf.get('disconnect_handler', disconnect_handler), remote, with_response=False, ) # Register sign-up handlers def dummy_handler(remote, *args, **kargs): pass signup_handler = conf.get('signup_handler', dict()) account_info_handler = make_handler(signup_handler.get( 'info', dummy_handler), remote, with_response=False) account_setup_handler = make_handler(signup_handler.get( 'setup', dummy_handler), remote, with_response=False) account_view_handler = make_handler(signup_handler.get( 'view', dummy_handler), remote, with_response=False) self.signup_handlers[remote_app] = dict( info=account_info_handler, setup=account_setup_handler, view=account_view_handler, )
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, ))
DEBUG=True, SECRET_KEY='TEST', SECURITY_PASSWORD_SALT='security-password-salt', SECURITY_LOGIN_WITHOUT_CONFIRMATION=False, USERPROFILES_EXTEND_SECURITY_FORMS=True, SQLALCHEMY_TRACK_MODIFICATIONS=False, APP_THEME=['semantic-ui'], THEME_ICONS={'semantic-ui': dict(link='linkify icon')}) Babel(app) FlaskMenu(app) Mail(app) InvenioDB(app) InvenioAccounts(app) InvenioUserProfiles(app) FlaskOAuth(app) InvenioOAuthClientREST(app) app.register_blueprint(blueprint_user) app.register_blueprint(blueprint_client) app.register_blueprint(blueprint_userprofile_api_init) app.register_blueprint(blueprint_userprofile_ui_init) @app.route('/') def index(): """Homepage.""" return 'Home page (without any restrictions)' @app.route('/orcid')
from jetbridge import app from jetbridge.models import db, User from flask import flash, abort, jsonify, request, redirect, session, url_for, render_template as render from flask_user import current_user, login_required from flask.ext.login import login_user from flask_oauthlib.client import OAuthException, OAuth as FlaskOAuth from flask_wtf.csrf import generate_csrf import requests import json oauth = FlaskOAuth() facebook_oauth = oauth.remote_app('facebook', base_url='https://graph.facebook.com/', request_token_url=None, access_token_url='/oauth/access_token', authorize_url='https://www.facebook.com/dialog/oauth', consumer_key='1286003954758836', consumer_secret=app.config.get('FACEBOOK_SECRET'), request_token_params={'scope': 'email,user_friends'} ) @app.route('/oauth/linkedin/accept_code', methods=['POST', 'OPTIONS']) def oauth_linkedin_accept_code(): if request.method != 'POST': # CORS pre-flight return "ok" # body should be json and contain auth code # this is super lame and ugly. redir_uri = url_for('oauth_linkedin_callback', _external=True) params = { 'client_id': request.json['clientId'],
def __init__(self, app, remote_app_config_key, default_disconnect_handler, default_authorized_handler, default_remote_app_response_handler=None, default_response_handler=None): """Initialize state.""" self.app = app self.handlers = {} self.disconnect_handlers = {} self.signup_handlers = {} self.remote_app_response_handler = {} # Connect signal to remove access tokens on logout user_logged_out.connect(handlers.oauth_logout_handler) self.oauth = app.extensions.get('oauthlib.client') or FlaskOAuth() # Init config self.init_config(app) # Add remote applications self.oauth.init_app(app) remote_app_class = load_or_import_from_config( 'OAUTHCLIENT_REMOTE_APP', app, default=OAuthRemoteApp ) def dummy_handler(remote, *args, **kargs): pass self.default_response_handler = default_response_handler or \ dummy_handler for remote_app, conf in app.config[ remote_app_config_key].items(): # Prevent double creation problems if remote_app not in self.oauth.remote_apps: # use this app's specific remote app class if there is one. current_remote_app_class = obj_or_import_string( conf.get('remote_app'), default=remote_app_class ) # Register the remote app. We are doing this because the # current version of OAuth.remote_app does not allow to specify # the remote app class. Use it once it is fixed. self.oauth.remote_apps[remote_app] = current_remote_app_class( self.oauth, remote_app, **conf['params'] ) remote = self.oauth.remote_apps[remote_app] # Set token getter for remote remote.tokengetter(handlers.make_token_getter(remote)) # Register authorized handler self.handlers[remote_app] = handlers.authorized_handler( handlers.make_handler( conf.get( 'authorized_handler', default_authorized_handler), remote ), remote.authorized_response ) # Register disconnect handler self.disconnect_handlers[remote_app] = handlers.make_handler( conf.get('disconnect_handler', default_disconnect_handler), remote, with_response=False, ) self.remote_app_response_handler[ remote_app] = obj_or_import_string( conf.get( 'response_handler', default_remote_app_response_handler or dummy_handler)) # Register sign-up handlers signup_handler = conf.get('signup_handler', dict()) account_info_handler = handlers.make_handler( signup_handler.get('info', dummy_handler), remote, with_response=False ) account_setup_handler = handlers.make_handler( signup_handler.get('setup', dummy_handler), remote, with_response=False ) account_view_handler = handlers.make_handler( signup_handler.get('view', dummy_handler), remote, with_response=False ) self.signup_handlers[remote_app] = dict( info=account_info_handler, setup=account_setup_handler, view=account_view_handler, ) if 'cern' in self.oauth.remote_apps: warnings.warn( "CERN Remote app is deprecated, use CERN OpenID instead.", DeprecationWarning )
def _init_app_rest(app_): """Init OAuth rest app.""" FlaskOAuth(app_) InvenioOAuthClientREST(app_) app_.register_blueprint(rest_blueprint) return app_