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
Esempio n. 2
0
def _init_app(app_):
    """Init OAuth app."""
    FlaskOAuth(app_)
    InvenioOAuthClient(app_)
    app_.register_blueprint(blueprint_client)
    app_.register_blueprint(blueprint_settings)
    return app_
Esempio n. 3
0
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
Esempio n. 4
0
def test_admin(app):
    """Test flask-admin interace."""
    InvenioOAuthClient(app)

    assert isinstance(remote_account_adminview, dict)
    assert isinstance(remote_token_adminview, dict)
    assert isinstance(user_identity_adminview, dict)

    assert 'model' in remote_account_adminview
    assert 'modelview' in remote_account_adminview
    assert 'model' in remote_token_adminview
    assert 'modelview' in remote_token_adminview
    assert 'model' in user_identity_adminview
    assert 'modelview' in user_identity_adminview

    admin = Admin(app, name='Test')

    user_model = remote_account_adminview.pop('model')
    user_view = remote_account_adminview.pop('modelview')
    admin.add_view(
        user_view(user_model, db.session, **remote_account_adminview))

    with app.app_context():
        # create user and save url for testing
        request_url = url_for('remoteaccount.index_view')

    with app.app_context():
        with app.test_client() as client:
            res = client.get(request_url, follow_redirects=True)
            assert res.status_code == 200
            assert 'Extra Data' in str(res.get_data())
            assert 'Tokens' in str(res.get_data())
Esempio n. 5
0
def app(request):
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    app = Flask('testapp', instance_path=instance_path)
    app.config.update(
        # HTTPretty doesn't play well with Redis.
        # See gabrielfalcao/HTTPretty#110
        CACHE_TYPE='simple',
        CELERY_ALWAYS_EAGER=True,
        CELERY_CACHE_BACKEND='memory',
        CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
        CELERY_RESULT_BACKEND='cache',
        GITHUB_SHIELDSIO_BASE_URL='http://example.org/badge/',
        GITHUB_APP_CREDENTIALS=dict(
            consumer_key='changeme',
            consumer_secret='changeme',
        ),
        LOGIN_DISABLED=False,
        OAUTHLIB_INSECURE_TRANSPORT=True,
        OAUTH2_CACHE_TYPE='simple',
        OAUTHCLIENT_REMOTE_APPS=dict(
            github=REMOTE_APP,
        ),
        SECRET_KEY='test_key',
        SQLALCHEMY_TRACK_MODIFICATIONS=True,
        SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI',
                                          'sqlite:///test.db'),
        SECURITY_PASSWORD_HASH='plaintext',
        SECURITY_PASSWORD_SCHEMES=['plaintext'],
        TESTING=True,
        WTF_CSRF_ENABLED=False,
    )
    app.url_map.converters['pid'] = PIDConverter

    FlaskCLI(app)
    celeryext = FlaskCeleryExt(app)
    celeryext.celery.flask_app = app  # Make sure both apps are the same!
    Babel(app)
    Mail(app)
    Menu(app)
    Breadcrumbs(app)
    InvenioDB(app)
    InvenioAccounts(app)
    app.register_blueprint(accounts_blueprint)
    InvenioOAuthClient(app)
    app.register_blueprint(oauthclient_blueprint)
    InvenioOAuth2Server(app)
    app.register_blueprint(server_blueprint)
    app.register_blueprint(settings_blueprint)
    InvenioPIDStore(app)
    InvenioRecordsREST(app)
    InvenioDepositREST(app)
    InvenioWebhooks(app)
    app.register_blueprint(webhooks_blueprint)
    InvenioGitHub(app)

    with app.app_context():
        yield app

    shutil.rmtree(instance_path)
Esempio n. 6
0
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_
Esempio n. 7
0
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
Esempio n. 8
0
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
Esempio n. 9
0
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_
Esempio n. 10
0
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)
Esempio n. 11
0
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)
Esempio n. 12
0
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)
Esempio n. 13
0
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
Esempio n. 14
0
def test_init():
    """Test extension initialization."""
    app = Flask('testapp')
    FlaskOAuth(app)
    ext = InvenioOAuthClient(app)
    assert 'invenio-oauthclient' in app.extensions

    app = Flask('testapp')
    ext = InvenioOAuthClient(app)
    assert 'invenio-oauthclient' in app.extensions

    app = Flask('testapp')
    FlaskOAuth(app)
    ext = InvenioOAuthClient()
    assert 'invenio-oauthclient' not in app.extensions
    ext.init_app(app)
    assert 'invenio-oauthclient' in app.extensions
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/'))
Esempio n. 16
0
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
Esempio n. 17
0
def app(env_config, zenodo_config, config, instance_path):
    """Flask application fixture."""
    app_ = Flask(__name__, instance_path=instance_path)
    app_.config.update(zenodo_config)
    app_.config.update(config)

    FlaskCeleryExt(app_)
    InvenioDB(app_)
    InvenioAccounts(app_)
    InvenioOAuthClient(app_)
    InvenioOAuth2Server(app_)
    InvenioRecords(app_)
    InvenioIndexer(app_)
    InvenioJSONSchemas(app_)
    InvenioSearch(app_)
    InvenioPIDStore(app_)
    ZenodoMigrator(app_)

    with app_.app_context():
        yield app_
Esempio n. 18
0
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
Esempio n. 19
0
def app(request):
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    app_ = Flask('testapp', instance_path=instance_path)
    app_.config.update(
        # HTTPretty doesn't play well with Redis.
        # See gabrielfalcao/HTTPretty#110
        CACHE_TYPE='simple',
        CELERY_ALWAYS_EAGER=True,
        CELERY_CACHE_BACKEND='memory',
        CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
        CELERY_RESULT_BACKEND='cache',
        GITHUB_APP_CREDENTIALS=dict(
            consumer_key='changeme',
            consumer_secret='changeme',
        ),
        GITHUB_PID_FETCHER='doi_fetcher',
        LOGIN_DISABLED=False,
        OAUTHLIB_INSECURE_TRANSPORT=True,
        OAUTH2_CACHE_TYPE='simple',
        OAUTHCLIENT_REMOTE_APPS=dict(github=REMOTE_APP, ),
        SECRET_KEY='test_key',
        SERVER_NAME='testserver',
        SQLALCHEMY_TRACK_MODIFICATIONS=True,
        SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI',
                                          'sqlite:///test.db'),
        SECURITY_PASSWORD_HASH='plaintext',
        SECURITY_PASSWORD_SCHEMES=['plaintext'],
        SECURITY_DEPRECATED_PASSWORD_SCHEMES=[],
        TESTING=True,
        WTF_CSRF_ENABLED=False,
    )
    app_.config['OAUTHCLIENT_REMOTE_APPS']['github']['params'][
        'request_token_params'][
            'scope'] = 'user:email,admin:repo_hook,read:org'
    app_.url_map.converters['pid'] = PIDConverter

    celeryext = FlaskCeleryExt(app_)
    Babel(app_)
    Mail(app_)
    Menu(app_)
    Breadcrumbs(app_)
    InvenioAssets(app_)
    InvenioDB(app_)
    InvenioAccounts(app_)
    app_.register_blueprint(accounts_blueprint)
    InvenioOAuthClient(app_)
    app_.register_blueprint(oauthclient_blueprint)
    InvenioOAuth2Server(app_)
    app_.register_blueprint(server_blueprint)
    app_.register_blueprint(settings_blueprint)
    InvenioFormatter(app_)

    from .helpers import doi_fetcher
    pidstore = InvenioPIDStore(app_)
    pidstore.register_fetcher('doi_fetcher', doi_fetcher)

    InvenioJSONSchemas(app_)
    InvenioRecords(app_)
    InvenioSearch(app_)
    InvenioIndexer(app_)
    InvenioFilesREST(app_)
    InvenioRecordsREST(app_)
    InvenioDepositREST(app_)
    InvenioWebhooks(app_)
    celeryext.celery.flask_app = app_  # Make sure both apps are the same!
    app_.register_blueprint(webhooks_blueprint)
    InvenioGitHub(app_)
    app_.register_blueprint(github_blueprint)
    app_.register_blueprint(github_badge_blueprint)

    with app_.app_context():
        yield app_

    shutil.rmtree(instance_path)
Esempio n. 20
0
    DEBUG=True,
    SECRET_KEY='TEST',
    SQLALCHEMY_ECHO=False,
    SECURITY_PASSWORD_SALT='security-password-salt',
    MAIL_SUPPRESS_SEND=True,
    TESTING=True,
    USERPROFILES_EXTEND_SECURITY_FORMS=True,
)

Babel(app)
FlaskMenu(app)
InvenioDB(app)
InvenioAccounts(app)
InvenioUserProfiles(app)
FlaskOAuth(app)
InvenioOAuthClient(app)
InvenioMail(app)

app.register_blueprint(blueprint_user)
app.register_blueprint(blueprint_client)
app.register_blueprint(blueprint_settings)
app.register_blueprint(blueprint_userprofile_init)


@app.route('/')
def index():
    """Homepage."""
    return 'Home page (without any restrictions)'


@app.route('/globus')
Esempio n. 21
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,
                ))