Ejemplo n.º 1
0
def models_fixture(app):
    """Fixture that contains the test data for models tests."""
    from invenio_oauth2server.proxies import current_oauth2server
    with app.app_context():
        # Register a test scope
        current_oauth2server.register_scope(Scope('test:scope1'))
        current_oauth2server.register_scope(Scope('test:scope2',
                                                  internal=True))
        datastore = app.extensions['security'].datastore
        with db.session.begin_nested():
            app.test_user = datastore.create_user(
                email='*****@*****.**', password='******',
            )
            app.resource_owner = datastore.create_user(
                email='*****@*****.**', password='******'
            )
            app.consumer = datastore.create_user(
                email='*****@*****.**', password='******'
            )

            # create resource_owner -> client_1
            app.u1c1 = Client(client_id='client_test_u1c1',
                              client_secret='client_test_u1c1',
                              name='client_test_u1c1',
                              description='',
                              is_confidential=False,
                              user=app.resource_owner,
                              _redirect_uris='',
                              _default_scopes=""
                              )
            # create resource_owner -> client_1 / resource_owner -> token_1
            app.u1c1u1t1 = Token(client=app.u1c1,
                                 user=app.resource_owner,
                                 token_type='u',
                                 access_token='dev_access_1',
                                 refresh_token='dev_refresh_1',
                                 expires=None,
                                 is_personal=False,
                                 is_internal=False,
                                 _scopes='',
                                 )
            # create consumer -> client_1 / resource_owner -> token_2
            app.u1c1u2t2 = Token(client=app.u1c1,
                                 user=app.consumer,
                                 token_type='u',
                                 access_token='dev_access_2',
                                 refresh_token='dev_refresh_2',
                                 expires=None,
                                 is_personal=False,
                                 is_internal=False,
                                 _scopes='',
                                 )
            db.session.add(app.u1c1)
            db.session.add(app.u1c1u1t1)
            db.session.add(app.u1c1u2t2)
    return app
Ejemplo n.º 2
0
def settings_fixture(app):
    """Fixture for testing settings views."""
    from invenio_oauth2server.proxies import current_oauth2server
    with app.app_context():
        with db.session.begin_nested():
            datastore = app.extensions['security'].datastore
            datastore.create_user(email='*****@*****.**',
                                  password='******')
        db.session.commit()
        current_oauth2server.register_scope(Scope('test:scope'))
        current_oauth2server.register_scope(Scope('test:scope2'))
    return app
def setup_app(app, api):
    api.add_resource(
        DepositionListResource,
        '/api/deposit/depositions/',
    )
    api.add_resource(
        DepositionResource,
        '/api/deposit/depositions/<string:resource_id>',
    )
    api.add_resource(
        DepositionFileListResource,
        '/api/deposit/depositions/<string:resource_id>/files/',
    )
    api.add_resource(
        DepositionDraftListResource,
        '/api/deposit/depositions/<string:resource_id>/metadata/',
    )
    api.add_resource(
        DepositionDraftResource,
        '/api/deposit/depositions/<string:resource_id>/metadata/'
        '<string:draft_id>',
    )
    api.add_resource(
        DepositionActionResource,
        '/api/deposit/depositions/<string:resource_id>/actions/'
        '<string:action_id>',
    )
    api.add_resource(
        DepositionFileResource,
        '/api/deposit/depositions/<string:resource_id>/files/<string:file_id>',
    )

    # Register scopes
    with app.app_context():
        from invenio_oauth2server.models import Scope
        from invenio_oauth2server.registry import scopes
        scopes.register(
            Scope(
                'deposit:write',
                group='Deposit',
                help_text='Allow upload (but not publishing).',
            ))
        scopes.register(
            Scope(
                'deposit:actions',
                group='Deposit',
                help_text='Allow publishing of uploads.',
            ))
Ejemplo n.º 4
0
    def setUp(self):
        super(ProviderTestCase, self).setUp()
        # Set environment variable DEBUG to true, to allow testing without
        # SSL in oauthlib.
        if self.app.config.get('CFG_SITE_SECURE_URL').startswith('http://'):
            self.os_debug = os.environ.get('OAUTHLIB_INSECURE_TRANSPORT', '')
            os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = 'true'

        from invenio_accounts.models import User
        from invenio_oauth2server.models import Client, Scope
        from invenio_oauth2server.registry import scopes as scopes_registry

        # Register a test scope
        scopes_registry.register(Scope('test:scope'))

        self.base_url = self.app.config.get('CFG_SITE_SECURE_URL')

        # Create needed objects
        u = User(email='*****@*****.**', nickname='tester')
        u.password = "******"

        u2 = User(email='*****@*****.**', nickname='tester2')
        u2.password = "******"

        db.session.add(u)
        db.session.add(u2)

        c1 = Client(client_id='dev',
                    client_secret='dev',
                    name='dev',
                    description='',
                    is_confidential=False,
                    user=u,
                    _redirect_uris='%s/oauth2test/authorized' % self.base_url,
                    _default_scopes="test:scope")

        c2 = Client(client_id='confidential',
                    client_secret='confidential',
                    name='confidential',
                    description='',
                    is_confidential=True,
                    user=u,
                    _redirect_uris='%s/oauth2test/authorized' % self.base_url,
                    _default_scopes="test:scope")

        db.session.add(c1)
        db.session.add(c2)

        db.session.commit()

        self.objects = [u, u2, c1, c2]

        # Create a personal access token as well.
        from invenio_oauth2server.models import Token
        self.personal_token = Token.create_personal('test-personal',
                                                    1,
                                                    scopes=[],
                                                    is_internal=True)
Ejemplo n.º 5
0
def provider_fixture(app):
    """Fixture that contains test data for provider tests."""
    from invenio_oauth2server.proxies import current_oauth2server
    # Mock the oauth client calls to prevent them from going online.
    oauth_client = create_oauth_client(app, 'oauth2test')
    oauth_client.http_request = MagicMock(
        side_effect=patch_request(app)
    )
    datastore = app.extensions['security'].datastore
    with app.test_request_context():
        with db.session.begin_nested():
            current_oauth2server.register_scope(Scope('test:scope'))

            app.user1 = datastore.create_user(
                email='*****@*****.**', password='******',
                active=True,
            )
            app.user2 = datastore.create_user(
                email='*****@*****.**', password='******',
                active=True
            )

            app.c1 = Client(client_id='dev',
                            client_secret='dev',
                            name='dev',
                            description='',
                            is_confidential=False,
                            user=app.user1,
                            _redirect_uris=url_for(
                                'oauth2test.authorized', _external=True
                            ),
                            _default_scopes='test:scope'
                            )

            app.c2 = Client(client_id='confidential',
                            client_secret='confidential',
                            name='confidential',
                            description='',
                            is_confidential=True,
                            user=app.user1,
                            _redirect_uris=url_for(
                                'oauth2test.authorized', _external=True
                            ),
                            _default_scopes='test:scope'
                            )
            db.session.add(app.c1)
            db.session.add(app.c2)
        app.personal_token = Token.create_personal('test-personal',
                                                   app.user1.id,
                                                   scopes=[],
                                                   is_internal=True)

    return app
Ejemplo n.º 6
0
def resource_fixture(app, api_app):
    """Fixture that contains the test data for models tests."""
    from flask import g, request
    from invenio_oauth2server.proxies import current_oauth2server

    # Setup API resources
    class Test0Resource(MethodView):
        def get(self):
            app.identity = g.identity
            return "success", 200

    class Test1Resource(MethodView):
        # NOTE: Method decorators are applied in reverse order
        decorators = [
            require_oauth_scopes('test:testscope'),
            require_api_auth(),
        ]

        def get(self):
            assert request.oauth.access_token
            app.identity = g.identity
            return "success", 200

        def post(self):
            assert request.oauth.access_token
            return "success", 200

    class Test2Resource(MethodView):
        @require_api_auth()
        @require_oauth_scopes('test:testscope')
        def get(self):
            assert request.oauth.access_token
            return "success", 200

        @require_api_auth()
        @require_oauth_scopes('test:testscope')
        def post(self):
            assert request.oauth.access_token
            return "success", 200

    class Test3Resource(MethodView):
        @require_api_auth()
        def post(self):
            return "success", 200

    class Test4Resource(MethodView):
        @require_api_auth(allow_anonymous=True)
        def get(self):
            from flask_login import current_user
            return str(current_user.get_id()), 200

        def post(self):
            from flask_login import current_user
            return str(current_user.get_id()), 200

    # Register API resources
    api_app.add_url_rule(
        '/test0/identitytestcase/',
        view_func=Test0Resource.as_view('test0resource'),
    )
    api_app.add_url_rule(
        '/test1/decoratorstestcase/',
        view_func=Test1Resource.as_view('test1resource'),
    )
    api_app.add_url_rule(
        '/test2/decoratorstestcase/',
        view_func=Test2Resource.as_view('test2resource'),
    )
    # This one is a UI resource using login_required
    api_app.add_url_rule(
        '/test3/loginrequiredstestcase/',
        view_func=Test3Resource.as_view('test3resource'),
    )
    api_app.add_url_rule(
        '/test4/allowanonymous/',
        view_func=Test4Resource.as_view('test4resource'),
    )

    datastore = app.extensions['security'].datastore
    with app.app_context():
        # Register a test scope
        current_oauth2server.register_scope(
            Scope('test:testscope', group='Test', help_text='Test scope'))
        with db.session.begin_nested():
            app.user = datastore.create_user(
                email='*****@*****.**',
                password='******',
                active=True,
            )

        # Create tokens
        app.user_id = app.user.id
        app.token = Token.create_personal('test-',
                                          app.user.id,
                                          scopes=['test:testscope'],
                                          is_internal=True).access_token
        app.token_noscope = Token.create_personal(
            'test-', app.user.id, scopes=[], is_internal=True).access_token
        db.session.commit()

    with api_app.test_request_context():
        app.url_for_test3resource = url_for('test3resource')

    with api_app.test_request_context():
        app.url_for_test0resource = url_for('test0resource')
        app.url_for_test1resource = url_for('test1resource')
        app.url_for_test2resource = url_for('test2resource')
        app.url_for_test4resource = url_for('test4resource')
        app.url_for_test0resource_token = url_for('test0resource',
                                                  access_token=app.token)
        app.url_for_test1resource_token = url_for('test1resource',
                                                  access_token=app.token)
        app.url_for_test2resource_token = url_for('test2resource',
                                                  access_token=app.token)
        app.url_for_test1resource_token_noscope = url_for(
            'test1resource', access_token=app.token_noscope)
        app.url_for_test2resource_token_noscope = url_for(
            'test2resource', access_token=app.token_noscope)
        app.url_for_test4resource_token = url_for('test4resource',
                                                  access_token=app.token)

    return app
Ejemplo n.º 7
0
def provider_fixture(app):
    """Fixture that contains test data for provider tests."""
    from invenio_oauth2server.proxies import current_oauth2server
    # Mock the oauth client calls to prevent them from going online.
    oauth_client = create_oauth_client(app, 'oauth2test')
    oauth_client.http_request = MagicMock(side_effect=patch_request(app))
    datastore = app.extensions['security'].datastore
    with app.test_request_context():
        with db.session.begin_nested():
            current_oauth2server.register_scope(Scope('test:scope'))

            user1 = datastore.create_user(
                email='*****@*****.**',
                password='******',
                active=True,
            )
            datastore.create_user(email='*****@*****.**',
                                  password='******',
                                  active=True)
            user3 = datastore.create_user(email='*****@*****.**',
                                          password='******',
                                          active=False)

            c1 = Client(client_id='dev',
                        client_secret='dev',
                        name='dev',
                        description='',
                        is_confidential=False,
                        user=user1,
                        _redirect_uris=url_for('oauth2test.authorized',
                                               _external=True),
                        _default_scopes='test:scope')
            c2 = Client(client_id='confidential',
                        client_secret='confidential',
                        name='confidential',
                        description='',
                        is_confidential=True,
                        user=user1,
                        _redirect_uris=url_for('oauth2test.authorized',
                                               _external=True),
                        _default_scopes='test:scope')
            # Same as 'c2' but user belonging to a user that's inactive
            c3 = Client(client_id='confidential-user-inactive',
                        client_secret='confidential-user-inactive',
                        name='confidential-user-inactive',
                        description='',
                        is_confidential=True,
                        user=user3,
                        _redirect_uris=url_for('oauth2test.authorized',
                                               _external=True),
                        _default_scopes='test:scope')
            c4 = Client(client_id='confidential-email',
                        client_secret='confidential-email',
                        name='confidential-email',
                        description='',
                        is_confidential=True,
                        user=user1,
                        _redirect_uris=url_for('oauth2test.authorized',
                                               _external=True),
                        _default_scopes='email')
            db.session.add(c1)
            db.session.add(c2)
            db.session.add(c3)
            db.session.add(c4)
        personal_token = Token.create_personal('test-personal',
                                               user1.id,
                                               scopes=[],
                                               is_internal=True)

        personal_token3 = Token.create_personal('test-personal',
                                                user3.id,
                                                scopes=[],
                                                is_internal=True)
        db.session.commit()

        app.user1_id = user1.id
        app.user3_id = user3.id
        app.personal_token = personal_token.access_token
        app.personal_token3 = personal_token3.access_token
    return app
Ejemplo n.º 8
0
InvenioOAuth2ServerREST(app)

accounts = InvenioAccountsUI(app)
InvenioAccountsREST(app)
app.register_blueprint(blueprint_account)

InvenioOAuth2Server(app)

# Register blueprints
app.register_blueprint(settings_blueprint)
app.register_blueprint(server_blueprint)
app.register_blueprint(blueprint_admin_ui)

with app.app_context():
    # Register a test scope
    current_oauth2server.register_scope(
        Scope('test:scope', help_text='Access to the homepage', group='test'))

# @app.route('/jwt', methods=['GET'])
# def jwt():
#     """JWT."""
#     return render_template('jwt.html')


@app.route('/', methods=['GET', 'POST'])
@require_api_auth()
@require_oauth_scopes('test:scope')
def index():
    """Protected endpoint."""
    return 'hello world'
Ejemplo n.º 9
0
    def setUp(self):
        from invenio_oauth2server.models import Scope
        from invenio_accounts.models import User
        from invenio_oauth2server.models import Client, Token

        from invenio_oauth2server.registry import scopes as scopes_registry

        # Register a test scope
        scopes_registry.register(Scope('test:scope1'))
        scopes_registry.register(Scope('test:scope2', internal=True))

        self.base_url = self.app.config.get('CFG_SITE_SECURE_URL')

        # Create needed objects
        u = User(email='*****@*****.**', nickname='tester')
        u.password = "******"

        self.create_objects([u])

        # environment
        #
        # resource_owner -- client1 -- token_1
        #                     |
        #                     -------- token_2
        #                               |
        #       consumer ----------------

        # create resource_owner and consumer
        self.resource_owner = User(email='*****@*****.**',
                                   nickname='resource_owner',
                                   password='******')
        self.consumer = User(email='*****@*****.**',
                             nickname='consumer',
                             password='******')

        self.create_objects([self.resource_owner, self.consumer])

        # create resource_owner -> client_1
        self.u1c1 = Client(client_id='client_test_u1c1',
                           client_secret='client_test_u1c1',
                           name='client_test_u1c1',
                           description='',
                           is_confidential=False,
                           user=self.resource_owner,
                           _redirect_uris='',
                           _default_scopes="")

        self.create_objects([self.u1c1])

        # create resource_owner -> client_1 / resource_owner -> token_1
        self.u1c1u1t1 = Token(
            client=self.u1c1,
            user=self.resource_owner,
            token_type='u',
            access_token='dev_access_1',
            refresh_token='dev_refresh_1',
            expires=None,
            is_personal=False,
            is_internal=False,
            _scopes='',
        )
        # create consumer -> client_1 / resource_owner -> token_2
        self.u1c1u2t2 = Token(
            client=self.u1c1,
            user=self.consumer,
            token_type='u',
            access_token='dev_access_2',
            refresh_token='dev_refresh_2',
            expires=None,
            is_personal=False,
            is_internal=False,
            _scopes='',
        )

        # create objects
        self.create_objects([self.u1c1u1t1, self.u1c1u2t2])

        self.objects = [
            u, self.resource_owner, self.consumer, self.u1c1u1t1, self.u1c1u2t2
        ]
Ejemplo n.º 10
0
from flask_babelex import lazy_gettext as _
from invenio_db import db
from invenio_oauth2server import require_api_auth, require_oauth_scopes
from invenio_oauth2server.models import Scope

from .errors import InvalidPayload, ReceiverDoesNotExist, WebhooksError
from .models import Event, Receiver

blueprint = Blueprint('invenio_webhooks', __name__)

#
# Required scope
#
webhooks_event = Scope(
    'webhooks:event',
    group='Notifications',
    help_text=_('Allow notifications from external service.'),
    internal=True,
)


def add_link_header(response, links):
    """Add a Link HTTP header to a REST response.

    :param response: REST response instance.
    :param links: Dictionary of links.
    """
    if links is not None:
        response.headers.extend({
            'Link': ', '.join([
                '<{0}>; rel="{1}"'.format(l, r) for r, l in links.items()])
        })
Ejemplo n.º 11
0
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2017-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.

"""OAuth2 scopes."""

from __future__ import absolute_import, print_function

from flask_babelex import lazy_gettext as _

from invenio_oauth2server.models import Scope

email_scope = Scope(
    id_='user:email',
    group='user',
    help_text=_('Allow access to email address (read-only).'),
)
"""Scope to protect the user's email address."""
Ejemplo n.º 12
0
InvenioAdmin(app)
OAuth2Provider(app)
InvenioOAuth2ServerREST(app)

accounts = InvenioAccounts(app)
app.register_blueprint(accounts_blueprint)

InvenioOAuth2Server(app)

# register blueprints
app.register_blueprint(settings_blueprint)
app.register_blueprint(server_blueprint)

with app.app_context():
    # Register a test scope
    current_oauth2server.register_scope(Scope('test:scope'))


@app.route('/', methods=['GET'])
@require_api_auth()
@require_oauth_scopes('test:scope')
def example():
    """Index."""
    return 'hello world'


@app.cli.group()
def fixtures():
    """Command for working with test data."""

Ejemplo n.º 13
0
    def setUp(self):
        from invenio_accounts.models import User
        from invenio_oauth2server.registry import scopes
        from invenio_oauth2server.models import Token, Scope

        # Setup variables:
        self.called = dict()

        # Setup test scopes
        with self.app.app_context():
            scopes.register(
                Scope(
                    'test:testscope',
                    group='Test',
                    help_text='Test scope',
                ))

        # Setup API resources
        class Test1Resource(Resource):
            # NOTE: Method decorators are applied in reverse order
            method_decorators = [
                require_oauth_scopes('test:testscope'),
                require_api_auth(),
            ]

            def get(self):
                assert request.oauth.access_token
                return "success", 200

            def post(self):
                assert request.oauth.access_token
                return "success", 200

            @require_header('Content-Type', 'application/json')
            def put(self):
                return "success", 200

        class Test2Resource(Resource):
            @require_api_auth()
            @require_oauth_scopes('test:testscope')
            def get(self):
                assert request.oauth.access_token
                return "success", 200

            @require_api_auth()
            @require_oauth_scopes('test:testscope')
            def post(self):
                assert request.oauth.access_token
                return "success", 200

            @require_header('Content-Type', 'text/html')
            def put(self):
                return "success", 200

        # Register API resources
        api = self.app.extensions['restful']
        api.add_resource(Test1Resource, '/api/test1/decoratorstestcase/')
        api.add_resource(Test2Resource, '/api/test2/decoratorstestcase/')

        # Create a user
        self.user = User(email='*****@*****.**', nickname='tester')
        self.user.password = "******"
        db.session.add(self.user)
        db.session.commit()

        # Create tokens
        self.token = Token.create_personal('test-',
                                           self.user.id,
                                           scopes=['test:testscope'],
                                           is_internal=True)
        self.token_noscope = Token.create_personal('test-',
                                                   self.user.id,
                                                   scopes=[],
                                                   is_internal=True)
Ejemplo n.º 14
0
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.

"""OAuth2 tokens scopes."""

from __future__ import absolute_import, print_function

from flask_babelex import lazy_gettext as _
from invenio_oauth2server.models import Scope

tokens_generate_scope = Scope(
    id_='generate', group='tokens',
    help_text=_('Allow generation of granular access JWT tokens.'),
    internal=True,
)
"""Allow generation of granular access JWT tokens."""
Ejemplo n.º 15
0
# -*- coding: utf-8 -*-
#
# RERO ILS
# Copyright (C) 2021 RERO
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""OAuth server scopes."""

from invenio_oauth2server.models import Scope

fullname = Scope('fullname', help_text='Full name', group='User')
birthdate = Scope('birthdate', help_text='Birthdate', group='User')
institution = Scope('institution', help_text='Institution', group='User')
expiration_date = Scope('expiration_date',
                        help_text='Expiration date',
                        group='User')
patron_type = Scope('patron_type', help_text='Patron type', group='User')
patron_types = Scope('patron_types', help_text='Patron types', group='User')
Ejemplo n.º 16
0
from invenio_oauth2server.models import Scope

harvesting_read = Scope('harvesting:read',
                        help_text='Access to the haresting',
                        group='test')