Ejemplo n.º 1
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])
Ejemplo n.º 2
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
Ejemplo n.º 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
Ejemplo n.º 4
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
Ejemplo n.º 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
Ejemplo n.º 6
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)
Ejemplo n.º 7
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)
Ejemplo n.º 8
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)
Ejemplo n.º 9
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)
Ejemplo n.º 10
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)
Ejemplo n.º 11
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)