def test_empty_redirect_uri_and_scope(self):
        from invenio_oauth2server.models import Client
        from invenio_oauth2server.errors import ScopeDoesNotExists

        c = Client(
            client_id='dev',
            client_secret='dev',
            name='dev',
            description='',
            is_confidential=False,
            user=self.objects[0],
            _redirect_uris='',
            _default_scopes=""
        )
        self.create_objects([c])
        self.assertIsNone(c.default_redirect_uri)
        self.assertEqual(c.redirect_uris, [])
        self.assertEqual(c.default_scopes, [])

        c.default_scopes = ['test:scope1', 'test:scope2', 'test:scope2', ]

        self.assertEqual(c.default_scopes, ['test:scope1', 'test:scope2'])
        self.assertRaises(ScopeDoesNotExists,
                          c.__setattr__, 'default_scopes', ['invalid', ])
        self.delete_objects([c])
Esempio n. 2
0
    def test_empty_redirect_uri_and_scope(self):
        from invenio_oauth2server.models import Client
        from invenio_oauth2server.errors import ScopeDoesNotExists

        c = Client(client_id='dev',
                   client_secret='dev',
                   name='dev',
                   description='',
                   is_confidential=False,
                   user=self.objects[0],
                   _redirect_uris='',
                   _default_scopes="")
        self.create_objects([c])
        self.assertIsNone(c.default_redirect_uri)
        self.assertEqual(c.redirect_uris, [])
        self.assertEqual(c.default_scopes, [])

        c.default_scopes = [
            'test:scope1',
            'test:scope2',
            'test:scope2',
        ]

        self.assertEqual(c.default_scopes, ['test:scope1', 'test:scope2'])
        self.assertRaises(ScopeDoesNotExists, c.__setattr__, 'default_scopes',
                          [
                              'invalid',
                          ])
        self.delete_objects([c])
def test_empty_redirect_uri_and_scope(models_fixture):
    app = models_fixture
    with app.app_context():

        client = Client(
            client_id='dev2',
            client_secret='dev2',
            name='dev2',
            description='',
            is_confidential=False,
            user=app.test_user,
            _redirect_uris='',
            _default_scopes=""
        )
        with db.session.begin_nested():
            db.session.add(client)

        assert client.default_redirect_uri is None
        assert client.redirect_uris == []
        assert client.default_scopes == []

        client.default_scopes = ['test:scope1', 'test:scope2', 'test:scope2', ]

        assert set(client.default_scopes) == set(
            ['test:scope1', 'test:scope2'])
        with pytest.raises(ScopeDoesNotExists):
            client.default_scopes = ['invalid']

        with db.session.begin_nested():
            db.session.delete(client)
def test_empty_redirect_uri_and_scope(models_fixture):
    app = models_fixture
    with app.app_context():

        client = Client(client_id='dev2',
                        client_secret='dev2',
                        name='dev2',
                        description='',
                        is_confidential=False,
                        user=app.test_user,
                        _redirect_uris='',
                        _default_scopes="")
        with db.session.begin_nested():
            db.session.add(client)

        assert client.default_redirect_uri is None
        assert client.redirect_uris == []
        assert client.default_scopes == []

        client.default_scopes = [
            'test:scope1',
            'test:scope2',
            'test:scope2',
        ]

        assert set(client.default_scopes) == set(
            ['test:scope1', 'test:scope2'])
        with pytest.raises(ScopeDoesNotExists):
            client.default_scopes = ['invalid']

        with db.session.begin_nested():
            db.session.delete(client)
Esempio n. 5
0
def init_oauth_token():
    ds = current_app.extensions["invenio-accounts"].datastore
    user = ds.user_model.query.filter_by(email="*****@*****.**").one()
    with db.session.begin_nested():
        client = Client(
            name="admin",
            user_id=user.id,
            is_internal=True,
            is_confidential=False,
            _default_scopes="",
        )
        client.gen_salt()

        token = Token(
            client_id=client.client_id,
            user_id=user.id,
            access_token=current_app.config["AUTHENTICATION_TOKEN"],
            expires=None,
            _scopes="",
            is_personal=True,
            is_internal=True,
        )

        db.session.add(client)
        db.session.add(token)
    db.session.commit()
    click.secho("Authentication token generated successfully", fg="green")
Esempio n. 6
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)
Esempio n. 7
0
def client_new():
    """Create new client."""
    data, errors = ClientSchema().load(request.get_json())

    if errors:
        return jsonify({"errors": errors}), 400

    c = Client(user_id=current_user.get_id())
    c.gen_salt()
    c.name = data.get("name")
    c.description = data.get("description")
    c.website = data.get("website")
    c._redirect_uris = '\n'.join(data.get("redirect_uris"))
    c.is_confidential = data.get("is_confidential")
    db.session.add(c)
    db.session.commit()

    return jsonify({
        'client_id': c.client_id,
        'client_secret': c.client_secret,
        'client_type': c.client_type,
        'default_redirect_uri': c.default_redirect_uri,
        'default_scopes': c.default_scopes,
        'description': c.description,
        'is_confidential': c.is_confidential,
        'is_internal': c.is_internal,
        'name': c.name,
        'oauth2tokens': c.oauth2tokens,
        'redirect_uris': c.redirect_uris,
        'user_id': c.user_id,
        'website': c.website,
    }), 200
Esempio n. 8
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
def client_new():
    """Create new client."""
    data, errors = ClientSchema().load(request.get_json())

    if errors:
        return jsonify({"errors": errors}), 400

    c = Client(user_id=current_user.get_id())
    c.gen_salt()
    c.name = data.get("name")
    c.description = data.get("description")
    c.website = data.get("website")
    c._redirect_uris = '\n'.join(data.get("redirect_uris"))
    c.is_confidential = data.get("is_confidential")
    db.session.add(c)
    db.session.commit()

    return jsonify(
        {
            'client_id': c.client_id,
            'client_secret': c.client_secret,
            'client_type': c.client_type,
            'default_redirect_uri': c.default_redirect_uri,
            'default_scopes': c.default_scopes,
            'description': c.description,
            'is_confidential': c.is_confidential,
            'is_internal': c.is_internal,
            'name': c.name,
            'oauth2tokens': c.oauth2tokens,
            'redirect_uris': c.redirect_uris,
            'user_id': c.user_id,
            'website': c.website,
        }), 200
def test_client_salt(provider_fixture):
    app = provider_fixture
    with app.app_context():
        with db.session.begin_nested():
            client = Client(name="Test something", is_confidential=True, user_id=1)

            client.gen_salt()
            assert len(client.client_id) == app.config["OAUTH2SERVER_CLIENT_ID_SALT_LEN"]
            assert len(client.client_secret) == app.config["OAUTH2SERVER_CLIENT_SECRET_SALT_LEN"]

            db.session.add(client)

        with db.session.begin_nested():
            db.session.delete(client)
Esempio n. 11
0
    def test_token_scopes(self):
        from invenio_oauth2server.models import Client, Token
        from invenio_oauth2server.errors import ScopeDoesNotExists

        c = Client(client_id='dev2',
                   client_secret='dev2',
                   name='dev2',
                   description='',
                   is_confidential=False,
                   user=self.objects[0],
                   _redirect_uris='',
                   _default_scopes="")
        t = Token(
            client=c,
            user=self.objects[0],
            token_type='bearer',
            access_token='dev_access',
            refresh_token='dev_refresh',
            expires=None,
            is_personal=False,
            is_internal=False,
            _scopes='',
        )
        t.scopes = ['test:scope1', 'test:scope2', 'test:scope2']
        self.create_objects([c, t])
        self.assertEqual(t.scopes, ['test:scope1', 'test:scope2'])
        self.assertRaises(ScopeDoesNotExists, t.__setattr__, 'scopes',
                          ['invalid'])
        self.assertEqual(t.get_visible_scopes(), ['test:scope1'])
        self.delete_objects([c])
Esempio n. 12
0
def developer_app_fixture(settings_fixture):
    """Fixture for testing developer application use cases."""
    settings_app = settings_fixture
    with settings_app.app_context():
        with db.session.begin_nested():
            datastore = settings_app.extensions['security'].datastore
            dev_user = datastore.create_user(email='*****@*****.**',
                                             password='******',
                                             active=True)

            dev_client = Client(client_id='dev',
                                client_secret='dev',
                                name='Test name',
                                description='Test description',
                                is_confidential=False,
                                user=dev_user,
                                website='http://inveniosoftware.org',
                                _redirect_uris='',
                                _default_scopes='test:scope')

            user = datastore.get_user('*****@*****.**')
            user_token = Token(client=dev_client,
                               user=user,
                               token_type='bearer',
                               access_token='dev_access_1',
                               refresh_token='dev_refresh_1',
                               expires=None,
                               is_personal=False,
                               is_internal=False,
                               _scopes='test:scope')

            db.session.add(dev_client)
            db.session.add(user_token)
        db.session.commit()
    return settings_app
Esempio n. 13
0
def test_token_scopes(models_fixture):
    app = models_fixture
    with app.app_context():
        client = Client(client_id='dev2',
                        client_secret='dev2',
                        name='dev2',
                        description='',
                        is_confidential=False,
                        user=app.test_user,
                        _redirect_uris='',
                        _default_scopes="")
        token = Token(
            client=client,
            user=app.test_user,
            token_type='bearer',
            access_token='dev_access',
            refresh_token='dev_refresh',
            expires=None,
            is_personal=False,
            is_internal=False,
            _scopes='',
        )
        token.scopes = ['test:scope1', 'test:scope2', 'test:scope2']
        with db.session.begin_nested():
            db.session.add(client)
            db.session.add(token)

        assert set(token.scopes) == set(['test:scope1', 'test:scope2'])
        with pytest.raises(ScopeDoesNotExists):
            token.scopes = ['invalid']
        assert token.get_visible_scopes() == ['test:scope1']

        with db.session.begin_nested():
            db.session.delete(client)
Esempio n. 14
0
def create_personal(name,
                    user_id,
                    scopes=None,
                    is_internal=False,
                    access_token=None):
    """Create a personal access token.

    A token that is bound to a specific user and which doesn't expire, i.e.
    similar to the concept of an API key.

    :param name: Client name.
    :param user_id: User ID.
    :param scopes: The list of permitted scopes. (Default: ``None``)
    :param is_internal: If ``True`` it's a internal access token.
            (Default: ``False``)
    :param access_token: personalized access_token.
    :returns: A new access token.
    """
    with db.session.begin_nested():
        scopes = " ".join(scopes) if scopes else ""

        client = Client(name=name,
                        user_id=user_id,
                        is_internal=True,
                        is_confidential=False,
                        _default_scopes=scopes)
        client.gen_salt()

        if not access_token:
            access_token = gen_salt(
                current_app.config.get('OAUTH2SERVER_TOKEN_PERSONAL_SALT_LEN'))
        token = Token(
            client_id=client.client_id,
            user_id=user_id,
            access_token=access_token,
            expires=None,
            _scopes=scopes,
            is_personal=True,
            is_internal=is_internal,
        )

        db.session.add(client)
        db.session.add(token)

    return token
Esempio n. 15
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
Esempio n. 16
0
    def test_client_salt(self):
        from invenio_oauth2server.models import Client

        c = Client(
            name='Test something',
            is_confidential=True,
            user_id=1,
        )

        c.gen_salt()
        assert len(c.client_id) == \
            self.app.config.get('OAUTH2_CLIENT_ID_SALT_LEN')
        assert len(c.client_secret) == \
            self.app.config.get('OAUTH2_CLIENT_SECRET_SALT_LEN')

        db.session.add(c)
        db.session.commit()

        self.delete_objects([c])
    def test_client_salt(self):
        from invenio_oauth2server.models import Client

        c = Client(
            name='Test something',
            is_confidential=True,
            user_id=1,
        )

        c.gen_salt()
        assert len(c.client_id) == \
            self.app.config.get('OAUTH2_CLIENT_ID_SALT_LEN')
        assert len(c.client_secret) == \
            self.app.config.get('OAUTH2_CLIENT_SECRET_SALT_LEN')

        db.session.add(c)
        db.session.commit()

        self.delete_objects([c])
Esempio n. 18
0
def create_user_token(client_name, user, access_token):
    """Create a token for the given user."""
    # Create token for user
    with db.session.begin_nested():
        client = Client(name=client_name,
                        user_id=user.id,
                        is_internal=True,
                        is_confidential=False,
                        _default_scopes='')
        client.gen_salt()
        token = Token(client_id=client.client_id,
                      user_id=user.id,
                      access_token=access_token,
                      expires=None,
                      is_personal=True,
                      is_internal=True,
                      _scopes='')
        db.session.add(client)
        db.session.add(token)
    return token
Esempio n. 19
0
def test_client_salt(provider_fixture):
    app = provider_fixture
    with app.app_context():
        with db.session.begin_nested():
            client = Client(
                name='Test something',
                is_confidential=True,
                user_id=1,
            )

            client.gen_salt()
            assert len(client.client_id) == \
                app.config['OAUTH2SERVER_CLIENT_ID_SALT_LEN']
            assert len(client.client_secret) == \
                app.config['OAUTH2SERVER_CLIENT_SECRET_SALT_LEN']

            db.session.add(client)

        with db.session.begin_nested():
            db.session.delete(client)
Esempio n. 20
0
def init_authentication_token():
    with db.session.begin_nested():
        client = Client(name='admin',
                        user_id=1,
                        is_internal=True,
                        is_confidential=False,
                        _default_scopes="")
        client.gen_salt()

        token = Token(
            client_id=client.client_id,
            user_id=1,
            access_token=current_app.config["AUTHENTICATION_TOKEN"],
            expires=None,
            _scopes="",
            is_personal=True,
            is_internal=True,
        )

        db.session.add(client)
        db.session.add(token)
    db.session.commit()
Esempio n. 21
0
def init_authentication_token():
    with db.session.begin_nested():
        client = Client(
            name='admin',
            user_id=1,
            is_internal=True,
            is_confidential=False,
            _default_scopes=""
        )
        client.gen_salt()

        token = Token(
            client_id=client.client_id,
            user_id=1,
            access_token=current_app.config["AUTHENTICATION_TOKEN"],
            expires=None,
            _scopes="",
            is_personal=True,
            is_internal=True,
        )

        db.session.add(client)
        db.session.add(token)
    db.session.commit()
Esempio n. 22
0
def client(app, users):
    """Create client."""
    with db.session.begin_nested():
        # create resource_owner -> client_1
        client_ = Client(
            client_id="client_test_u1c1",
            client_secret="client_test_u1c1",
            name="client_test_u1c1",
            description="",
            is_confidential=False,
            user_id=users[0]["id"],
            _redirect_uris="",
            _default_scopes="",
        )
        db.session.add(client_)
    db.session.commit()
    return client_
Esempio n. 23
0
def oauth2_client(app, db, users):
    """Create client."""
    with db.session.begin_nested():
        # create resource_owner -> client_1
        client_ = Client(
            client_id='client_test_u1c1',
            client_secret='client_test_u1c1',
            name='client_test_u1c1',
            description='',
            is_confidential=False,
            user_id=users[0]['id'],
            _redirect_uris='',
            _default_scopes='',
        )
        db.session.add(client_)
    db.session.commit()
    return client_.client_id
Esempio n. 24
0
    def _write_token(user):
        """Return json headers with write oauth token for given user."""
        client_ = Client.query.filter_by(
            user_id=user.id
        ).first()

        if not client_:
            client_ = Client(
                client_id=user.id,
                client_secret='client_secret_{}'.format(user.id),
                name='client_test_{}'.format(user.id),
                description='',
                is_confidential=False,
                user_id=user.id,
                _redirect_uris='',
                _default_scopes='',
            )
            db.session.add(client_)

        token_ = Token.query.filter_by(
            user_id=user.id
        ).first()

        if not token_:
            token_ = Token(
                client_id=client_.client_id,
                user_id=user.id,
                access_token='dev_access_{}'.format(user.id),
                refresh_token='dev_refresh_{}'.format(user.id),
                expires=datetime.utcnow() + timedelta(hours=10),
                is_personal=False,
                is_internal=True,
                _scopes=write_scope.id,
            )
            db.session.add(token_)
        db.session.commit()

        return bearer_auth(dict(
            token=token_,
            auth_header=[
                ('Authorization', 'Bearer {0}'.format(token_.access_token)),
            ]
        ))
Esempio n. 25
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
        ]
Esempio n. 26
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
Esempio n. 27
0
def test_patron_info(app, client, patron_martigny, librarian_martigny):
    """Test patron info."""

    # All scopes
    scopes = [
        'fullname', 'birthdate', 'institution', 'expiration_date',
        'patron_type', 'patron_types'
    ]

    # create a oauth client liked to the librarian account
    oauth_client = Client(client_id='dev',
                          client_secret='dev',
                          name='Test name',
                          description='Test description',
                          is_confidential=False,
                          user=librarian_martigny.user,
                          website='http://foo.org',
                          _redirect_uris='')

    # token with all scopes
    token = Token(client=oauth_client,
                  user=patron_martigny.user,
                  token_type='bearer',
                  access_token='test_access_1',
                  expires=None,
                  is_personal=False,
                  is_internal=False,
                  _scopes=' '.join(scopes))

    # token without scope
    no_scope_token = Token(client=oauth_client,
                           user=patron_martigny.user,
                           token_type='bearer',
                           access_token='test_access_2',
                           expires=None,
                           is_personal=False,
                           is_internal=False)

    db.session.add(oauth_client)
    db.session.add(token)
    db.session.commit()

    # denied with a wrong token
    res = client.get(url_for('api_patrons.info', access_token='wrong'))
    assert res.status_code == 401

    # denied without token
    res = client.get(url_for('api_patrons.info'))
    assert res.status_code == 401

    # minimal information without scope
    res = client.get(
        url_for('api_patrons.info', access_token=no_scope_token.access_token))
    assert res.status_code == 200
    assert res.json == {'barcode': patron_martigny['patron']['barcode'].pop()}

    # full information with all scopes
    res = client.get(
        url_for('api_patrons.info', access_token=token.access_token))
    assert res.status_code == 200
    assert res.json == {
        'barcode':
        '4098124352',
        'birthdate':
        '1947-06-07',
        'fullname':
        'Roduit, Louis',
        'patron_types': [{
            'expiration_date': '2023-10-07T00:00:00',
            'institution': 'org1',
            'patron_type': 'patron-code'
        }]
    }