예제 #1
0
def includeme(config):
    app = Flask('annotator')  # Create the annotator-store app
    app.register_blueprint(store.store)  # and register the store api.

    # Set up the models
    settings = config.get_settings()
    if 'es.host' in settings:
        app.config['ELASTICSEARCH_HOST'] = settings['es.host']
    if 'es.index' in settings:
        app.config['ELASTICSEARCH_INDEX'] = settings['es.index']
    es.init_app(app)
    with app.test_request_context():
        Annotation.create_all()
        Document.create_all()

    # Configure authentication and authorization
    app.config['AUTHZ_ON'] = True
    app.before_request(before_request)

    # Configure the API views -- version 1 is just an annotator.store proxy
    api_v1 = wsgiapp2(app)

    config.add_view(api_v1, route_name='api')

    if not config.registry.queryUtility(interfaces.IStoreClass):
        config.registry.registerUtility(Store, interfaces.IStoreClass)
예제 #2
0
def main():
    app = Flask(__name__)

    cfg_file = 'annotator.cfg'
    if len(sys.argv) == 2:
        cfg_file = sys.argv[1]

    cfg_path = os.path.join(here, cfg_file)

    try:
        app.config.from_pyfile(cfg_path)
    except IOError:
        print("Could not find config file %s" % cfg_path, file=sys.stderr)
        print(
            "Perhaps you need to copy annotator.cfg.example to annotator.cfg",
            file=sys.stderr)
        sys.exit(1)

    es.init_app(app)

    with app.test_request_context():
        annotation.Annotation.create_all()
        document.Document.create_all()

    @app.before_request
    def before_request():
        # In a real app, the current user and consumer would be determined by
        # a lookup in either the session or the request headers, as described
        # in the Annotator authentication documentation[1].
        #
        # [1]: https://github.com/okfn/annotator/wiki/Authentication
        g.user = MockUser('alice')

        # By default, this test application won't do full-on authentication
        # tests. Set AUTH_ON to True in the config file to enable (limited)
        # authentication testing.
        if current_app.config['AUTH_ON']:
            g.auth = auth.Authenticator(lambda x: MockConsumer('annotateit'))
        else:
            g.auth = MockAuthenticator()

        # Similarly, this test application won't prevent you from modifying
        # annotations you don't own, deleting annotations you're disallowed
        # from deleting, etc. Set AUTHZ_ON to True in the config file to
        # enable authorization testing.
        if current_app.config['AUTHZ_ON']:
            g.authorize = authz.authorize
        else:
            g.authorize = mock_authorizer

    app.register_blueprint(store.store)

    host = os.environ.get('HOST', '127.0.0.1')
    port = int(os.environ.get('PORT', 5000))
    app.run(host=host, port=port)
예제 #3
0
def main():
    app = Flask(__name__)

    cfg_file = 'annotator.cfg'
    if len(sys.argv) == 2:
        cfg_file = sys.argv[1]

    cfg_path = os.path.join(here, cfg_file)

    try:
        app.config.from_pyfile(cfg_path)
    except IOError:
        print("Could not find config file %s" % cfg_path, file=sys.stderr)
        print("Perhaps you need to copy annotator.cfg.example to annotator.cfg", file=sys.stderr)
        sys.exit(1)

    es.init_app(app)

    with app.test_request_context():
        annotation.Annotation.create_all()
        document.Document.create_all()

    @app.before_request
    def before_request():
        # In a real app, the current user and consumer would be determined by
        # a lookup in either the session or the request headers, as described
        # in the Annotator authentication documentation[1].
        #
        # [1]: https://github.com/okfn/annotator/wiki/Authentication
        g.user = MockUser('alice')

        # By default, this test application won't do full-on authentication
        # tests. Set AUTH_ON to True in the config file to enable (limited)
        # authentication testing.
        if current_app.config['AUTH_ON']:
            g.auth = auth.Authenticator(lambda x: MockConsumer('annotateit'))
        else:
            g.auth = MockAuthenticator()

        # Similarly, this test application won't prevent you from modifying
        # annotations you don't own, deleting annotations you're disallowed
        # from deleting, etc. Set AUTHZ_ON to True in the config file to
        # enable authorization testing.
        if current_app.config['AUTHZ_ON']:
            g.authorize = authz.authorize
        else:
            g.authorize = mock_authorizer

    app.register_blueprint(store.store)

    host = os.environ.get('HOST', '127.0.0.1')
    port = int(os.environ.get('PORT', 5000))
    app.run(host=host, port=port)
예제 #4
0
def main():
    app = Flask(__name__)

    try:
        app.config.from_pyfile(os.path.join(here, 'annotator.cfg'))
    except IOError:
        print("Please copy example config from annotator.cfg.example to annotator.cfg", file=sys.stderr)
        sys.exit(1)

    es.init_app(app)

    with app.test_request_context():
        annotation.Annotation.create_all()

    @app.before_request
    def before_request():
        # In a real app, the current user and consumer would be determined by
        # a lookup in either the session or the request headers, as described
        # in the Annotator authentication documentation[1].
        #
        # [1]: https://github.com/okfn/annotator/wiki/Authentication
        g.user = MockUser('alice')

        # By default, this test application won't do full-on authentication
        # tests. Set AUTH_ON to True in the config file to enable (limited)
        # authentication testing.
        if current_app.config['AUTH_ON']:
#            g.auth = auth.Authenticator(lambda x: MockConsumer('annotateit'))
            consumer_obj = Consumer('yourconsumerkey')
            consumer_obj.secret = '6E1C924B-C03B-4F7F-0000-B72EE2338B39'
            consumer_obj.ttl = auth.DEFAULT_TTL
            g.auth = auth.Authenticator(lambda x: consumer_obj)
        else:
            g.auth = MockAuthenticator()

        # Similarly, this test application won't prevent you from modifying
        # annotations you don't own, deleting annotations you're disallowed
        # from deleting, etc. Set AUTHZ_ON to True in the config file to
        # enable authorization testing.
        if current_app.config['AUTHZ_ON']:
            g.authorize = authz.authorize
            print("[run.py,before_request], AUTHZ_ON")
        else:
            g.authorize = mock_authorizer
            print("[run.py,before_request], AUTHZ_OFF")

    app.register_blueprint(store.store)

    host = os.environ.get('HOST', '127.0.0.1')
    port = int(os.environ.get('PORT', 6000))
    app.run(host=host, port=port)
예제 #5
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile(os.path.join(here, 'test.cfg'))

    es.init_app(app)

    @app.before_request
    def before_request():
        g.auth = auth.Authenticator(MockConsumer)
        g.authorize = authz.authorize

    app.register_blueprint(store.store, url_prefix='/api')

    return app
예제 #6
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile(os.path.join(here, 'test.cfg'))

    es.init_app(app)

    @app.before_request
    def before_request():
        g.auth = auth.Authenticator(MockConsumer)
        g.authorize = authz.authorize

    app.register_blueprint(store.store, url_prefix='/api')

    return app
예제 #7
0
파일: api.py 프로젝트: pablomarti/h
def includeme(config):
    """Include the annotator-store API backend.

    Example INI file:

        [app:h]
        consumer_key: primary_consumer
        consumer_secret: 00000000-0000-0000-0000-000000000000

    """

    settings = config.get_settings()

    if not settings.has_key('h.consumer_key'):
        raise KeyError('h.consumer_key')

    if not settings.has_key('h.consumer_secret'):
        raise KeyError('h.consumer_secret')

    # Create the annotator-store app
    app = Flask(__name__)
    app.register_blueprint(store.store)

    # Set up the models
    es.init_app(app)
    with app.test_request_context():
        try:
            Annotation.create_all()
        except:
            Annotation.update_settings()
            Annotation.create_all()

    # Configure authentication (ours) and authorization (store)
    authenticator = auth.Authenticator(consumer_fetcher)

    def before_request():
        g.auth = authenticator
        g.authorize = authz.authorize

    app.before_request(before_request)

    # Configure the API views
    config.add_view(wsgiapp2(app), route_name='api')
    config.add_view(token, route_name='token', permission='authenticated')
    config.add_view(users,
                    route_name='users',
                    request_method='GET',
                    permission='authenticated',
                    renderer='json')
예제 #8
0
파일: api.py 프로젝트: nlholdem/h
def store_from_settings(settings):
    app = flask.Flask('annotator')  # Create the annotator-store app
    app.register_blueprint(store.store)  # and register the store api.

    if 'es.host' in settings:
        app.config['ELASTICSEARCH_HOST'] = settings['es.host']

    if 'es.index' in settings:
        app.config['ELASTICSEARCH_INDEX'] = settings['es.index']

    if 'es.compatibility' in settings:
        compat = settings['es.compatibility']
        app.config['ELASTICSEARCH_COMPATIBILITY_MODE'] = compat

    es.init_app(app)
    return app
예제 #9
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile(os.path.join(here, 'test.cfg'))

    es.init_app(app)

    @app.before_request
    def before_request():
        g.user = MockUser(request.headers.get(auth.HEADER_PREFIX + 'user-id'))
        g.consumer = MockConsumer(request.headers.get(auth.HEADER_PREFIX + 'consumer-key'))

        g.auth = auth.Authenticator(MockConsumer)
        g.authorize = authz.authorize

    app.register_blueprint(store.store, url_prefix='/api')

    return app
예제 #10
0
파일: api.py 프로젝트: hyperstudio/h
def includeme(config):
    """Include the annotator-store API backend.

    Example INI file:

        [app:h]
        consumer_key: primary_consumer
        consumer_secret: 00000000-0000-0000-0000-000000000000

    """

    settings = config.get_settings()

    if not settings.has_key('h.consumer_key'):
        raise KeyError('h.consumer_key')

    if not settings.has_key('h.consumer_secret'):
        raise KeyError('h.consumer_secret')

    # Create the annotator-store app
    app = Flask(__name__)
    app.register_blueprint(store.store)

    # Set up the models
    es.init_app(app)
    with app.test_request_context():
        try:
            Annotation.create_all()
        except:
            Annotation.update_settings()
            Annotation.create_all()

    # Configure authentication (ours) and authorization (store)
    authenticator = auth.Authenticator(consumer_fetcher)
    def before_request():
        g.auth = authenticator
        g.authorize = authz.authorize
    app.before_request(before_request)

    # Configure the API views
    config.add_view(wsgiapp2(app), route_name='api')
    config.add_view(token, route_name='token', permission='authenticated')
    config.add_view(users, route_name='users', request_method='GET',
                    permission='authenticated',
                    renderer='json')
예제 #11
0
def main():
    app = Flask(__name__)

    try:
        app.config.from_pyfile(os.path.join(here, 'annotator.cfg'))
    except IOError:
        print("Please copy example config from annotator.cfg.example to annotator.cfg", file=sys.stderr)
        sys.exit(1)

    es.init_app(app)

    with app.test_request_context():
        annotation.Annotation.create_all()

    @app.before_request
    def before_request():
        # In a real app, the current user and consumer would be determined by
        # a lookup in either the session or the request headers, as described
        # in the Annotator authentication documentation[1].
        #
        # [1]: https://github.com/okfn/annotator/wiki/Authentication
        g.user = MockUser('alice')
        g.session_user = MockUser('alice')
        g.consumer = MockConsumer('annotateit')

        # By default, this test application won't do full-on authentication
        # tests. Set AUTH_ON to True in the config file to enable (limited)
        # authentication testing.
        if current_app.config['AUTH_ON']:
            g.auth = auth.Authenticator(lambda x: MockConsumer('annotateit'))
        else:
            g.auth = MockAuthenticator()

        # Similarly, this test application won't prevent you from modifying
        # annotations you don't own, deleting annotations you're disallowed
        # from deleting, etc. Set AUTHZ_ON to True in the config file to
        # enable authorization testing.
        if current_app.config['AUTHZ_ON']:
            g.authorize = authz.authorize
        else:
            g.authorize = mock_authorizer

    app.register_blueprint(store.store)
    app.run()
예제 #12
0
파일: api.py 프로젝트: martinq/h
def includeme(config):
    """Include the annotator-store API backend.

    Example INI file:

        [app:h]
        api.key: 00000000-0000-0000-0000-000000000000

    """

    app = Flask('annotator')  # Create the annotator-store app
    app.register_blueprint(store.store)  # and register the store api.

    # Set up the models
    settings = config.get_settings()
    if 'es.host' in settings:
        app.config['ELASTICSEARCH_HOST'] = settings['es.host']
    if 'es.index' in settings:
        app.config['ELASTICSEARCH_INDEX'] = settings['es.index']
    es.init_app(app)
    with app.test_request_context():
        try:
            Annotation.create_all()
        except:
            Annotation.update_settings()
            Annotation.create_all()

    # Configure authentication (ours) and authorization (store)
    authenticator = auth.Authenticator(models.Consumer.get_by_key)

    def before_request():
        g.auth = authenticator
        g.authorize = authz.authorize

    app.before_request(before_request)

    # Configure the API view -- version 1 is just an annotator.store proxy
    config.add_view(wsgiapp2(app), context='h.resources.APIFactory', name='v1')
    config.add_view(wsgiapp2(app), context='h.resources.APIFactory',
                    name='current')

    # And pick up the token view
    config.scan(__name__)
예제 #13
0
def store_from_settings(settings):
    app = flask.Flask('annotator')  # Create the annotator-store app
    app.register_blueprint(store.store)  # and register the store api.

    if 'ELASTICSEARCH_PORT' in os.environ:
        app.config['ELASTICSEARCH_HOST'] = 'http%s' % (
            os.environ['ELASTICSEARCH_PORT'][3:], )
    elif 'es.host' in settings:
        app.config['ELASTICSEARCH_HOST'] = settings['es.host']

    if 'es.index' in settings:
        app.config['ELASTICSEARCH_INDEX'] = settings['es.index']

    if 'es.compatibility' in settings:
        compat = settings['es.compatibility']
        app.config['ELASTICSEARCH_COMPATIBILITY_MODE'] = compat

    es.init_app(app)
    return app
예제 #14
0
def create_app():
    log.debug("Creating %s application", __name__)
    app = Flask(__name__)

    configure(app)

    # Configure database
    db.init_app(app)

    # Configure mailer
    mail.init_app(app)
    app.extensions['mail'] = mail

    # Configure ES
    es.init_app(app)

    # Add regex converter
    from annotateit.util import RegexConverter
    app.url_map.converters['regex'] = RegexConverter

    # Add filters
    from annotateit.util import filters
    for name, func in vars(filters).iteritems():
        if not name.startswith('_'):
            app.template_filter()(func)

    # Mount views
    from annotator import store
    from annotateit import user, main
    app.register_blueprint(store.store, url_prefix='/api')
    app.register_blueprint(user.user, url_prefix='/user')
    app.register_blueprint(main.main)

    app.before_request(main.before_request)
    app.errorhandler(404)(main.page_not_found)
    app.errorhandler(401)(main.not_authorized)

    log.debug("Successfully created %s application", __name__)
    return app
예제 #15
0
def create_app():
    log.debug("Creating %s application", __name__)
    app = Flask(__name__)

    configure(app)

    # Configure database
    db.init_app(app)

    # Configure mailer
    mail.init_app(app)
    app.extensions['mail'] = mail

    # Configure ES
    es.init_app(app)

    # Add regex converter
    from annotateit.util import RegexConverter
    app.url_map.converters['regex'] = RegexConverter

    # Add filters
    from annotateit.util import filters
    for name, func in vars(filters).iteritems():
        if not name.startswith('_'):
            app.template_filter()(func)

    # Mount views
    from annotator import store
    from annotateit import user, main
    app.register_blueprint(store.store, url_prefix='/api')
    app.register_blueprint(user.user, url_prefix='/user')
    app.register_blueprint(main.main)

    app.before_request(main.before_request)
    app.errorhandler(404)(main.page_not_found)
    app.errorhandler(401)(main.not_authorized)

    log.debug("Successfully created %s application", __name__)
    return app
예제 #16
0
파일: store.py 프로젝트: shepazu/h
def includeme(config):
    """Include the annotator-store API backend via http or route embedding.

    Example INI file:
    .. code-block:: ini
        [app:h]
        api.key: 00000000-0000-0000-0000-000000000000
        api.endpoint: https://example.com/api

    or use a relative path for the endpoint to embed the annotation store
    directly in the application.
    .. code-block:: ini
        [app:h]
        api.endpoint: /api

    The default is to embed the store as a route bound to "/api".
    """

    app = flask.Flask('annotator')  # Create the annotator-store app
    app.register_blueprint(store.store)  # and register the store api.
    settings = config.get_settings()

    if 'es.host' in settings:
        app.config['ELASTICSEARCH_HOST'] = settings['es.host']
    if 'es.index' in settings:
        app.config['ELASTICSEARCH_INDEX'] = settings['es.index']
    es.init_app(app)
    try:
        with app.test_request_context():
            Annotation.create_all()
            Document.create_all()
    except socket.error:
        raise Exception(
            "Can not access ElasticSearch at %s! Are you sure it's running?" %
            (app.config["ELASTICSEARCH_HOST"], ))
    except:
        with app.test_request_context():
            Annotation.update_settings()
            Annotation.create_all()
            Document.create_all()

    # Configure authentication and authorization
    app.config['AUTHZ_ON'] = True
    app.before_request(before_request)
    app.after_request(after_request)

    # Configure the API routes
    api_config = {'static': True}
    api_endpoint = config.registry.settings.get('api.endpoint', None)
    api_url = config.registry.settings.get('api.url', api_endpoint)

    if api_endpoint is not None:
        api_path = api_endpoint.rstrip('/')
        api_pattern = '/'.join([api_path, '*subpath'])

        # Configure the API views -- version 1 is just an annotator.store proxy
        api_v1 = wsgiapp2(app)

        config.add_route('api_real', api_pattern)
        config.add_view(api_v1, route_name='api_real')
        config.add_view(api_v1, name='api_virtual')

    if api_url is not None:
        api_url = api_url.strip('/')
        if urlparse.urlparse(api_url).scheme:

            def set_app_url(request, elements, kw):
                kw.setdefault('_app_url', api_url)
                return (elements, kw)

            api_config['pregenerator'] = set_app_url
            config.add_route('api', '/*subpath', **api_config)
        else:
            config.add_route('api', api_url + '/*subpath', **api_config)

    if not config.registry.queryUtility(interfaces.IStoreClass):
        config.registry.registerUtility(Store, interfaces.IStoreClass)
예제 #17
0
파일: store.py 프로젝트: mrienstra/h
def includeme(config):
    """Include the annotator-store API backend via http or route embedding.

    Example INI file:
    .. code-block:: ini
        [app:h]
        api.key: 00000000-0000-0000-0000-000000000000
        api.endpoint: https://example.com/api

    or use a relative path for the endpoint to embed the annotation store
    directly in the application.
    .. code-block:: ini
        [app:h]
        api.endpoint: /api

    The default is to embed the store as a route bound to "/api".
    """

    app = flask.Flask('annotator')  # Create the annotator-store app
    app.register_blueprint(store.store)  # and register the store api.
    settings = config.get_settings()

    if 'es.host' in settings:
        app.config['ELASTICSEARCH_HOST'] = settings['es.host']
    if 'es.index' in settings:
        app.config['ELASTICSEARCH_INDEX'] = settings['es.index']
    es.init_app(app)
    try:
        with app.test_request_context():
            Annotation.create_all()
            Document.create_all()
    except socket.error:
        raise Exception(
            "Can not access ElasticSearch at %s! Are you sure it's running?" %
            (app.config["ELASTICSEARCH_HOST"],)
        )

    # Configure authentication and authorization
    app.config['AUTHZ_ON'] = True
    app.before_request(before_request)
    app.after_request(after_request)

    # Configure the API routes
    api_config = {'static': True}
    api_endpoint = config.registry.settings.get('api.endpoint', None)
    api_url = config.registry.settings.get('api.url', api_endpoint)

    if api_endpoint is not None:
        api_path = api_endpoint.rstrip('/')
        api_pattern = '/'.join([api_path, '*subpath'])

        # Configure the API views -- version 1 is just an annotator.store proxy
        api_v1 = wsgiapp2(app)

        config.add_route('api_real', api_pattern)
        config.add_view(api_v1, route_name='api_real')
        config.add_view(api_v1, name='api_virtual')

    if api_url is not None:
        api_url = api_url.strip('/')
        if urlparse.urlparse(api_url).scheme:
            def set_app_url(request, elements, kw):
                kw.setdefault('_app_url', api_url)
                return (elements, kw)
            api_config['pregenerator'] = set_app_url
            config.add_route('api', '/*subpath', **api_config)
        else:
            config.add_route('api', api_url + '/*subpath', **api_config)

    if not config.registry.queryUtility(interfaces.IStoreClass):
        config.registry.registerUtility(Store, interfaces.IStoreClass)
예제 #18
0
파일: run.py 프로젝트: WSULib/textAnalysis
def main():
	app = Flask(__name__)

	cfg_file = 'annotator.cfg'
	if len(sys.argv) == 2:
		cfg_file = sys.argv[1]

	cfg_path = os.path.join(here, cfg_file)

	try:
		app.config.from_pyfile(cfg_path)
	except IOError:
		print("Could not find config file %s" % cfg_path, file=sys.stderr)
		print("Perhaps you need to copy annotator.cfg.example to annotator.cfg", file=sys.stderr)
		sys.exit(1)

	es.init_app(app)

	with app.test_request_context():
		annotation.Annotation.create_all()
		document.Document.create_all()

	@app.before_request
	def before_request():
		# In a real app, the current user and consumer would be determined by
		# a lookup in either the session or the request headers, as described
		# in the Annotator authentication documentation[1].
		#
		# [1]: https://github.com/okfn/annotator/wiki/Authentication
		# g.user = MockUser('alice')        

		# By default, this test application won't do full-on authentication
		# tests. Set AUTH_ON to True in the config file to enable (limited)
		# authentication testing.
		if current_app.config['AUTH_ON']:
			g.auth = auth.Authenticator(lambda x: MockConsumer('annotateit'))
			# print("passed validation")
		else:
			# print("did NOT pass validation")
			g.auth = MockAuthenticator()

		# Similarly, this test application won't prevent you from modifying
		# annotations you don't own, deleting annotations you're disallowed
		# from deleting, etc. Set AUTHZ_ON to True in the config file to
		# enable authorization testing.
		if current_app.config['AUTHZ_ON']:
			g.authorize = authz.authorize
			# print("authorized")
		else:
			g.authorize = mock_authorizer
			# print("something authorized fail?")

	
	@app.route('/authToken')
	def authToken():
		def generate_token(user_id):
			return jwt.encode({
			  'consumerKey': CONSUMER_KEY,
			  'userId': user_id,
			  'issuedAt': _now().isoformat() + 'Z',
			  'ttl': CONSUMER_TTL
			}, CONSUMER_SECRET)

		def _now():
			return datetime.datetime.now(iso8601.iso8601.UTC).replace(microsecond=0)

		WSUDORcookie = request.cookies.get('WSUDOR')
		unescapedWSUDORcoookie = urllib.unquote(WSUDORcookie)	
		unescapedWSUDORcoookie = unescapedWSUDORcoookie.replace('true','"true"')			
		WSUDORdict = ast.literal_eval(unescapedWSUDORcoookie)
		username = WSUDORdict['username_WSUDOR']
		displayName = WSUDORdict['displayName']
		annotation_signature = displayName+" / "+username

		return generate_token(annotation_signature)

	app.register_blueprint(store.store)

	host = os.environ.get('HOST', '127.0.0.1')
	port = int(os.environ.get('PORT', 5000))
	app.run(host=host, port=port)