Ejemplo n.º 1
0
def test_get_default_values_for_api() -> None:
    """Check if default values saved in unit test configuration is properly defined."""
    config = AppConfiguration()

    assert config.get('api', 'host') == 'localhost'
    assert config.getint('api', 'rest_port') == 51000
    assert config.getint('api', 'websocket_port') == 51001
    assert not config.getboolean('api', 'debug')
    assert config.get('api', 'secret_key') == 'SECRET_KEY'
    assert config.get('db', 'database_uri') == 'sqlite:///:memory:'
Ejemplo n.º 2
0
def generate_auth_token(user: User,
                        expiration: int = TOKEN_EXPIRE_TIME) -> str:
    """Generate token that will be then used for User's authorization.

    :param user: User's database object
    :param expiration: expiration time (in minutes) after such token should expire
    :return: authorization token as a string
    """
    serializer = Serializer(AppConfiguration.get('api', 'secret_key'),
                            expires_in=expiration)
    token_bytes = cast(bytes, serializer.dumps({'id': user.id}))
    return token_bytes.decode('ascii')
Ejemplo n.º 3
0
def get_user_by_token(token: str) -> Optional[User]:
    """Return User using passed token.

    :param token: authorization token
    :return: User if found or None
    """
    serializer = Serializer(AppConfiguration.get('api', 'secret_key'))
    try:
        data = serializer.loads(token)
    except SignatureExpired:
        return None  # Valid token, but expired
    except BadSignature:
        return None  # Invalid token
    return User.query.get(data['id'])
Ejemplo n.º 4
0
    _created = Column(DateTime, nullable=False, server_default=func.now(), default=datetime.utcnow)
    _modified = Column(DateTime, nullable=False, server_default=func.now(), default=datetime.utcnow,
                       onupdate=datetime.utcnow)

    def __repr__(self) -> str:
        """Return string representation."""
        return '<{}: {}>'.format(self.__class__.__name__, getattr(self, 'id', '-'))

    def save(self) -> None:
        """Save the model into the database after changes."""
        with db_session() as _session:
            _session.add(self)


configuration = AppConfiguration()
db_uri = configuration.get('db', 'database_uri')
db_pool_size = configuration.getint('db', 'connection_pool_size')
engine = create_engine(db_uri, pool_size=db_pool_size, convert_unicode=True)
session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))

convention = {
    "ix": 'ix_%(column_0_label)s',
    "uq": "uq_%(table_name)s_%(column_0_name)s",
    "ck": "ck_%(table_name)s_%(constraint_name)s",
    "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
    "pk": "pk_%(table_name)s",
}

metadata = MetaData(naming_convention=convention)
Ejemplo n.º 5
0
    :return: list of all modules with tasks
    """
    module_prefix = 'medtagger.workers.'
    tasks_directory = 'medtagger/workers'
    python_files = filter(lambda filename: filename.endswith('.py'),
                          os.listdir(tasks_directory))
    return [
        module_prefix + os.path.splitext(filename)[0]
        for filename in python_files
    ]


@setup_logging.connect
def setup_logging_handler(*args: List[Any], **kwargs: List[Any]) -> None:  # pylint: disable=unused-argument
    """Set up logger for Celery tasks."""
    logging.config.fileConfig('logging.conf')


@worker_process_init.connect
def process_initialization(*args: List[Any], **kwargs: List[Any]) -> None:  # pylint: disable=unused-argument
    """Initialize given Celery process."""
    create_connection()
    engine.dispose()  # Recreate SQL Pool


configuration = AppConfiguration()
broker_url = configuration.get('celery',
                               'broker',
                               fallback='pyamqp://*****:*****@localhost//')
imports = get_all_modules_with_tasks()
Ejemplo n.º 6
0
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)

# add your model's MetaData object here
# for 'autogenerate' support
from medtagger.database.models import *
target_metadata = Base.metadata

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
configuration = AppConfiguration()
url = configuration.get('db', 'database_uri')


def run_migrations_offline():
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.

    """
Ejemplo n.º 7
0
from medtagger.database import session  # noqa
from medtagger.database.models import User, Role  # noqa
from medtagger.storage import create_connection  # noqa

# Import all REST services
from medtagger.api.core.service import core_ns as core_rest_ns  # noqa
from medtagger.api.labels.service import labels_ns  # noqa
from medtagger.api.scans.service_rest import scans_ns as scans_rest_ns  # noqa
from medtagger.api.users.service import users_ns  # noqa
from medtagger.api.auth.service import auth_ns  # noqa

logger = logging.getLogger(__name__)

# Load configuration
logger.info('Loading configuration file...')
configuration = AppConfiguration()
host = configuration.get('api', 'host', fallback='localhost')
port = configuration.getint('api', 'rest_port', fallback=51000)
debug = configuration.getboolean('api', 'debug', fallback=True)

# Definition of application
app = Flask(__name__)
CORS(app)
app.secret_key = configuration.get('api', 'secret_key', fallback='')
app.register_blueprint(blueprint)

# Application config
app.config['RESTPLUS_MASK_SWAGGER'] = False
app.config['SWAGGER_UI_DOC_EXPANSION'] = 'list'
app.config['RESTPLUS_VALIDATE'] = True
Ejemplo n.º 8
0
"""Definition of storage for MedTagger."""
from cassandra.cluster import Cluster, Session, NoHostAvailable  # pylint: disable=no-name-in-module
from cassandra.policies import RoundRobinPolicy
from cassandra.cqlengine import connection
from cassandra.io.asyncorereactor import AsyncoreConnection
from cassandra.io.geventreactor import GeventConnection

from medtagger.config import AppConfiguration

MEDTAGGER_KEYSPACE = 'medtagger'

configuration = AppConfiguration()
addresses = configuration.get('cassandra', 'addresses', 'localhost').split(',')
port = configuration.getint('cassandra', 'port', 9042)
default_timeout = configuration.getint('cassandra', 'default_timeout', 20)
connect_timeout = configuration.getint('cassandra', 'connect_timeout', 20)


def create_session(use_gevent: bool = False) -> Session:
    """Create a Session object for above Cluster."""
    connection_class = GeventConnection if use_gevent else AsyncoreConnection
    cluster = Cluster(addresses,
                      port=port,
                      load_balancing_policy=RoundRobinPolicy(),
                      connection_class=connection_class,
                      connect_timeout=connect_timeout)
    session = cluster.connect()
    session.default_timeout = default_timeout
    return session