Exemple #1
0
    def test_token_scopes(self):
        from ..models import Client, Token
        from ..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])
Exemple #2
0
def record_context(recid, app_env, context):
    token = Token.query.filter(Token.user_id == current_user.get_id()).filter(
        Token.is_internal == True).first()
    if not token:
        token = Token.create_personal('analyze',
                                      current_user.get_id(),
                                      is_internal=True)

    user_map = {
        'ssh': 'lw',
        'jupyter-python': 'jupyter',
        'jupyter-r': 'jupyter',
    }

    record_script = b64encode(
        render_template_to_string('analyze/lwget.sh',
                                  token=token,
                                  recid=recid,
                                  lw_user=user_map.get(app_env, 'ubuntu')))
    record_script_path = '/usr/local/bin/lwget.sh'
    context['write_files'].append({
        'encoding': 'b64',
        'content': record_script,
        'permissions': '755',
        'path': record_script_path,
    })
    context['runcmd'].append([record_script_path])
Exemple #3
0
 def create_oauth_token(self, user_id, scopes, is_internal=True):
     """Create an OAuth personal access_token."""
     # Create a personal access token as well.
     from invenio.modules.oauth2server.models import Token
     self.accesstoken[user_id] = Token.create_personal(
         'test-personal-%s' % user_id,
         user_id,
         scopes=scopes,
         is_internal=is_internal).access_token
Exemple #4
0
 def create_oauth_token(self, user_id, scopes, is_internal=True):
     """Create an OAuth personal access_token."""
     # Create a personal access token as well.
     from invenio.modules.oauth2server.models import Token
     self.accesstoken[user_id] = Token.create_personal(
         'test-personal-%s' % user_id,
         user_id,
         scopes=scopes,
         is_internal=is_internal
     ).access_token
Exemple #5
0
def init_provider_tokens(user_id):
    """
    Create local access token used to authenticate GitHub webhook as well as
    the upload using the API.
    """
    webhook_token = ProviderToken.create_personal(
        'github-webhook',
        user_id,
        scopes=['webhooks:event'],
        is_internal=True,
    )

    internal_token = ProviderToken.create_personal(
        'github-upload',
        user_id,
        scopes=['deposit:write', 'deposit:actions'],
        is_internal=True,
    )

    return webhook_token, internal_token
Exemple #6
0
def init_provider_tokens(user_id):
    """
    Create local access token used to authenticate GitHub webhook as well as
    the upload using the API.
    """
    webhook_token = ProviderToken.create_personal(
        'github-webhook',
        user_id,
        scopes=['webhooks:event'],
        is_internal=True,
    )

    internal_token = ProviderToken.create_personal(
        'github-upload',
        user_id,
        scopes=['deposit:write', 'deposit:actions'],
        is_internal=True,
    )

    return webhook_token, internal_token
Exemple #7
0
    def setUp(self):
        from flask_restful import Resource, fields, marshal
        from invenio.modules.accounts.models import User
        from invenio.modules.oauth2server.models import Token

        class TagRepresenation(object):
            """A representation of a tag.

            This class will be only used to return a tag as JSON.
            """

            marshaling_fields = dict(id=fields.Integer,
                                     name=fields.String,
                                     id_user=fields.Integer)

            def __init__(self, retrieved_tag):
                """Initialization.

                Declared the attributes to marshal with a tag.
                :param retrieved_tag: a tag from the database
                """
                # get fields from the given tag
                self.id = retrieved_tag.id
                self.name = retrieved_tag.name
                self.id_user = retrieved_tag.id_user

            def marshal(self):
                """Marshal the Tag."""
                return marshal(self, self.marshaling_fields)

        class TestTagsResource(Resource):

            method_decorators = [require_api_auth()]

            @require_header('Content-Type', 'application/json')
            def get(self):
                import json
                from flask import make_response
                from invenio.ext.restful.errors import (RestfulError,
                                                        InvalidPageError)
                from invenio.ext.restful import pagination

                response = None
                try:
                    endpoint = request.endpoint
                    args = request.args
                    page = int(args.get('page', 1))
                    per_page = int(args.get('per_page', 2))
                    # check values arguments and raise exceptions if any errors
                    if per_page < 0:
                        raise RestfulError(
                            error_msg="Invalid per_page: {}".format(per_page),
                            status_code=400)
                    if page < 0:
                        raise InvalidPageError(
                            error_msg="Invalid page: {}".format(page),
                            status_code=400)

                    # need to sort by id
                    # also assuming only one user so no need to filter
                    # user's id
                    tags_q = WtgTAGPaginationMokup()
                    p = pagination.RestfulSQLAlchemyPagination(
                        query=tags_q, page=page, per_page=per_page)
                    if page > p.pages:
                        raise InvalidPageError(
                            error_msg="Invalid page: {}".format(page),
                            status_code=400)
                    tags_to_return = map(
                        lambda x: TagRepresenation(x).marshal(), p.items)

                    kwargs = {}
                    kwargs['endpoint'] = endpoint
                    kwargs['args'] = request.args
                    link_header = p.link_header(**kwargs)
                    response = make_response(json.dumps(tags_to_return))
                    response.headers[link_header[0]] = link_header[1]
                    response.headers['Content-Type'] = request.headers[
                        'Content-Type']
                except (RestfulError, InvalidPageError) as e:
                    exception = {}
                    exception['message'] = e.error_msg
                    exception['type'] = "{0}".format(type(e))
                    response = make_response(json.dumps(exception))
                return response

        # Register API resources
        api = self.app.extensions['restful']
        api.add_resource(TestTagsResource, '/api/testtags/')

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

        # create token
        self.token = Token.create_personal('test-',
                                           self.user.id,
                                           scopes=[],
                                           is_internal=True)
Exemple #8
0
    def setUp(self):
        from invenio.modules.accounts.models import User
        from invenio.modules.oauth2server.registry import scopes
        from invenio.modules.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)
Exemple #9
0
    def setUp(self):
        """Set up some dummy data and a resource."""
        from invenio.modules.accounts.models import User
        from invenio.modules.oauth2server.models import Token

        self.data = range(25)

        # setup test api resources

        class TestDataResource(Resource):

            method_decorators = [require_api_auth()]

            @require_header('Content-Type', 'application/json')
            def get(self):
                import json
                from flask import make_response
                from invenio.ext.restful.errors import (InvalidPageError)
                from invenio.ext.restful import pagination
                # Test to see that the exceptions are raised correctly
                # In restful.py it is not needed because the error_hanler
                # takes care of exceptions
                response = None
                try:
                    # test data
                    testdata = range(25)
                    endpoint = request.endpoint
                    args = request.args
                    page = int(args.get('page', 1))
                    per_page = int(args.get('per_page', 10))
                    p = pagination.RestfulPagination(page=page,
                                                     per_page=per_page,
                                                     total_count=len(testdata))
                    data_to_return = p.slice(testdata)
                    kwargs = {}
                    kwargs['endpoint'] = endpoint
                    kwargs['args'] = request.args
                    link_header = p.link_header(**kwargs)
                    response = make_response(json.dumps(data_to_return))
                    response.headers[link_header[0]] = link_header[1]
                    response.headers['Content-Type'] = request.headers[
                        'Content-Type']
                except InvalidPageError as e:
                    exception = {}
                    exception['message'] = e.error_msg
                    exception['type'] = "{0}".format(type(e))
                    response = make_response(json.dumps(exception))
                return response

        # Register API resources
        api = self.app.extensions['restful']
        api.add_resource(TestDataResource, '/api/testdata/')

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

        # create token
        self.token = Token.create_personal('test-',
                                           self.user.id,
                                           scopes=[],
                                           is_internal=True)
Exemple #10
0
    def setUp(self):
        from ..models import Scope
        from invenio.modules.accounts.models import User
        from invenio.modules.oauth2server.models import Client, Token

        from ..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]
Exemple #11
0
    def setUp(self):
        from flask_restful import Resource, fields, marshal
        from invenio.modules.accounts.models import User
        from invenio.modules.oauth2server.models import Token

        class TagRepresenation(object):

            """A representation of a tag.

            This class will be only used to return a tag as JSON.
            """

            marshaling_fields = dict(
                id=fields.Integer,
                name=fields.String,
                id_user=fields.Integer
            )

            def __init__(self, retrieved_tag):
                """Initialization.

                Declared the attributes to marshal with a tag.
                :param retrieved_tag: a tag from the database
                """
                #get fields from the given tag
                self.id = retrieved_tag.id
                self.name = retrieved_tag.name
                self.id_user = retrieved_tag.id_user

            def marshal(self):
                """Marshal the Tag."""
                return marshal(self, self.marshaling_fields)

        class TestTagsResource(Resource):

            method_decorators = [
                require_api_auth()
            ]

            @require_header('Content-Type', 'application/json')
            def get(self):
                import json
                from flask import make_response
                from invenio.modules.tags.models import WtgTAG
                from invenio.ext.restful.errors import(
                    RestfulError, InvalidPageError
                )
                from invenio.ext.restful import pagination

                response = None
                try:
                    endpoint = request.endpoint
                    args = request.args
                    page = int(args.get('page', 1))
                    per_page = int(args.get('per_page', 2))
                    # check values arguments and raise exceptions if any errors
                    if per_page < 0:
                        raise RestfulError(
                            error_msg="Invalid per_page: {}".format(per_page),
                            status_code=400
                        )
                    if page < 0:
                        raise InvalidPageError(
                            error_msg="Invalid page: {}".format(page),
                            status_code=400
                        )

                    # need to sort by id
                    # also assuming only one user so no need to filter
                    # user's id
                    tags_q = WtgTAG.query.order_by(WtgTAG.id)
                    p = pagination.RestfulSQLAlchemyPagination(
                        query=tags_q, page=page, per_page=per_page
                    )
                    if page > p.pages:
                        raise InvalidPageError(
                            error_msg="Invalid page: {}".format(page),
                            status_code=400
                        )
                    tags_to_return = map(
                        lambda x: TagRepresenation(x).marshal(),
                        p.items
                    )

                    kwargs = {}
                    kwargs['endpoint'] = endpoint
                    kwargs['args'] = request.args
                    link_header = p.link_header(**kwargs)
                    response = make_response(json.dumps(tags_to_return))
                    response.headers[link_header[0]] = link_header[1]
                    response.headers['Content-Type'] = request.headers['Content-Type']
                except (RestfulError, InvalidPageError) as e:
                    exception = {}
                    exception['message'] = e.error_msg
                    exception['type'] = "{0}".format(type(e))
                    response = make_response(json.dumps(exception))
                return response

        # Register API resources
        api = self.app.extensions['restful']
        api.add_resource(
            TestTagsResource,
            '/api/testtags/'
        )

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

        # create token
        self.token = Token.create_personal(
            'test-', self.user.id, scopes=[], is_internal=True)
Exemple #12
0
    def setUp(self):
        from invenio.modules.accounts.models import User
        from invenio.modules.oauth2server.registry import scopes
        from invenio.modules.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)
Exemple #13
0
    def setUp(self):
        """Set up some dummy data and a resource."""
        from invenio.modules.accounts.models import User
        from invenio.modules.oauth2server.models import Token

        self.data = range(25)

        # setup test api resources

        class TestDataResource(Resource):

            method_decorators = [
                require_api_auth()
            ]

            @require_header('Content-Type', 'application/json')
            def get(self):
                import json
                from flask import make_response
                from invenio.ext.restful.errors import(
                    InvalidPageError
                )
                from invenio.ext.restful import pagination
                # Test to see that the exceptions are raised correctly
                # In restful.py it is not needed because the error_hanler
                # takes care of exceptions
                response = None
                try:
                    # test data
                    testdata = range(25)
                    endpoint = request.endpoint
                    args = request.args
                    page = int(args.get('page', 1))
                    per_page = int(args.get('per_page', 10))
                    p = pagination.RestfulPagination(
                        page=page, per_page=per_page, total_count=len(testdata)
                    )
                    data_to_return = p.slice(testdata)
                    kwargs = {}
                    kwargs['endpoint'] = endpoint
                    kwargs['args'] = request.args
                    link_header = p.link_header(**kwargs)
                    response = make_response(json.dumps(data_to_return))
                    response.headers[link_header[0]] = link_header[1]
                    response.headers['Content-Type'] = request.headers['Content-Type']
                except InvalidPageError as e:
                    exception = {}
                    exception['message'] = e.error_msg
                    exception['type'] = "{0}".format(type(e))
                    response = make_response(json.dumps(exception))
                return response

        # Register API resources
        api = self.app.extensions['restful']
        api.add_resource(
            TestDataResource,
            '/api/testdata/'
        )

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

        # create token
        self.token = Token.create_personal(
            'test-', self.user.id, scopes=[], is_internal=True)