Esempio n. 1
0
 def test_set_factories(self):
     some_func = lambda: None
     some_other_func = lambda: None
     plugin = FlaskPlugin(current_user_id_factory=some_func,
                          remote_addr_factory=some_other_func)
     assert plugin.current_user_id_factory is some_func
     assert plugin.remote_addr_factory is some_other_func
Esempio n. 2
0
    def init_versioning(self, app, database, versioning_manager=None):
        """Initialize the versioning support using SQLAlchemy-Continuum."""
        try:
            pkg_resources.get_distribution('sqlalchemy_continuum')
        except pkg_resources.DistributionNotFound:  # pragma: no cover
            default_versioning = False
        else:
            default_versioning = True

        app.config.setdefault('DB_VERSIONING', default_versioning)

        if not app.config['DB_VERSIONING']:
            return

        if not default_versioning:  # pragma: no cover
            raise RuntimeError(
                'Please install extra versioning support first by running '
                'pip install invenio-db[versioning].'
            )

        # Now we can import SQLAlchemy-Continuum.
        from sqlalchemy_continuum import make_versioned
        from sqlalchemy_continuum import versioning_manager as default_vm
        from sqlalchemy_continuum.plugins import FlaskPlugin

        # Try to guess user model class:
        if 'DB_VERSIONING_USER_MODEL' not in app.config:  # pragma: no cover
            try:
                pkg_resources.get_distribution('invenio_accounts')
            except pkg_resources.DistributionNotFound:
                user_cls = None
            else:
                user_cls = 'User'
        else:
            user_cls = app.config.get('DB_VERSIONING_USER_MODEL')

        plugins = [FlaskPlugin()] if user_cls else []

        extra_plugins = app.config.get('DB_EXTRA_PLUGINS', [])
        plugins.extend(import_string(obj)() for obj in extra_plugins)

        # Call make_versioned() before your models are defined.
        self.versioning_manager = versioning_manager or default_vm
        make_versioned(
            user_cls=user_cls,
            manager=self.versioning_manager,
            plugins=plugins,
        )

        # Register models that have been loaded beforehand.
        builder = self.versioning_manager.builder

        for tbl in database.metadata.tables.values():
            builder.instrument_versioned_classes(
                database.mapper, get_class_by_table(database.Model, tbl)
            )
Esempio n. 3
0
    def init_versioning(self, app, database, versioning_manager=None):
        """Initialize the versioning support using SQLAlchemy-Continuum."""
        try:
            importlib_metadata.version("sqlalchemy_continuum")
        except importlib_metadata.PackageNotFoundError:  # pragma: no cover
            default_versioning = False
        else:
            default_versioning = True

        app.config.setdefault("DB_VERSIONING", default_versioning)

        if not app.config["DB_VERSIONING"]:
            return

        if not default_versioning:  # pragma: no cover
            raise RuntimeError(
                "Please install extra versioning support first by running "
                "pip install invenio-db[versioning].")

        # Now we can import SQLAlchemy-Continuum.
        from sqlalchemy_continuum import make_versioned
        from sqlalchemy_continuum import versioning_manager as default_vm
        from sqlalchemy_continuum.plugins import FlaskPlugin

        # Try to guess user model class:
        if "DB_VERSIONING_USER_MODEL" not in app.config:  # pragma: no cover
            try:
                importlib_metadata.version("invenio_accounts")
            except importlib_metadata.PackageNotFoundError:
                user_cls = None
            else:
                user_cls = "User"
        else:
            user_cls = app.config.get("DB_VERSIONING_USER_MODEL")

        plugins = [FlaskPlugin()] if user_cls else []

        # Call make_versioned() before your models are defined.
        self.versioning_manager = versioning_manager or default_vm
        make_versioned(
            user_cls=user_cls,
            manager=self.versioning_manager,
            plugins=plugins,
        )

        # Register models that have been loaded beforehand.
        builder = self.versioning_manager.builder

        for tbl in database.metadata.tables.values():
            builder.instrument_versioned_classes(
                database.mapper, get_class_by_table(database.Model, tbl))
Esempio n. 4
0
class TestFlaskPluginWithoutRequestContext(TestCase):
    plugins = [FlaskPlugin()]
    user_cls = 'User'

    def create_models(self):
        class User(self.Model):
            __tablename__ = 'user'
            __versioned__ = {'base_classes': (self.Model, )}

            id = sa.Column(sa.Integer, autoincrement=True, primary_key=True)
            name = sa.Column(sa.Unicode(255), nullable=False)

        self.User = User

        TestCase.create_models(self)

    def test_versioning_outside_request(self):
        user = self.User(name=u'Rambo')
        self.session.add(user)
        self.session.commit()
Esempio n. 5
0
    def __init__(self,
                 app=None,
                 db=None,
                 migrate=None,
                 user_cls=None,
                 engine=None,
                 current_user=fetch_current_user_id,
                 plugins=[]):
        self.db = None
        self.migrate = None
        self.app = None
        self.engine = engine
        self.user_cls = user_cls
        self.current_user = current_user

        # arg mismatch
        if app is not None and \
           db is None and \
           not isinstance(app, Flask):
            self.init_db(app)
            app = None

        # proper spec
        if db is not None:
            self.init_db(db)
        if migrate is not None:
            self.init_migrate(migrate)

        # app is specified properly
        if app is not None:
            self.init_app(app)

        # configure versioning support
        make_versioned(
            user_cls=self.user_cls,
            plugins=[FlaskPlugin(current_user_id_factory=self.current_user)] +
            list(plugins))
        return
Esempio n. 6
0
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import func
from sqlalchemy_continuum import make_versioned, versioning_manager
from sqlalchemy_continuum.plugins import FlaskPlugin, PropertyModTrackerPlugin

db = SQLAlchemy()

make_versioned(plugins=[FlaskPlugin()])
versioning_manager.plugins.append(PropertyModTrackerPlugin())


class TimeTrackedModel(db.Model):
    __abstract__ = True

    created_at = db.Column(db.DateTime(timezone=True), server_default=func.now())
    updated_at = db.Column(db.DateTime(timezone=True),
                                                 server_default=func.now(), onupdate=func.now())
    return oauth.idp.authorize_redirect(redirect_url)


csp = {
    'default-src': '\'self\'',
    'style-src': '\'self\'',
    'font-src': '\'self\'',
    'form-action': '\'self\''
}

db = SQLAlchemy()
db.get = MethodType(db_get, db)
db.create = MethodType(db_create, db)
db.get_or_create = MethodType(db_get_or_create, db)

make_versioned(plugins=[FlaskPlugin(), PropertyModTrackerPlugin()])
migrate = Migrate(db=db, directory=SQLALCHEMY_MIGRATE_REPO)
talisman = Talisman()
login_manager = LoginManager()
oauth = OAuth()
tracker = Blueprint('tracker', __name__)


def create_app(script_info=None):
    app = Flask(__name__)
    app.config.from_object('config')

    db.init_app(app)
    migrate.init_app(app)
    orm.configure_mappers()
Esempio n. 8
0
class TestFlaskPlugin(TestCase):
    plugins = [FlaskPlugin()]
    transaction_cls = TransactionFactory()
    user_cls = 'User'

    def setup_method(self, method):
        TestCase.setup_method(self, method)
        self.app = Flask(__name__)
        self.app.secret_key = 'secret'
        self.app.debug = True
        self.setup_views()
        login_manager = LoginManager()
        login_manager.init_app(self.app)
        self.client = self.app.test_client()
        self.context = self.app.test_request_context()
        self.context.push()

        @login_manager.user_loader
        def load_user(id):
            return self.session.query(self.User).get(id)

    def teardown_method(self, method):
        TestCase.teardown_method(self, method)
        self.context.pop()
        self.context = None
        self.client = None
        self.app = None

    def login(self, user):
        """
        Log in the user returned by :meth:`create_user`.

        :returns: the logged in user
        """
        with self.client.session_transaction() as s:
            s['_user_id'] = user.id
        return user

    def logout(self, user=None):
        with self.client.session_transaction() as s:
            s['_user_id'] = None

    def create_models(self):
        TestCase.create_models(self)

        class User(self.Model):
            __tablename__ = 'user'
            __versioned__ = {'base_classes': (self.Model, )}

            id = sa.Column(sa.Integer, autoincrement=True, primary_key=True)
            name = sa.Column(sa.Unicode(255), nullable=False)

        self.User = User

    def setup_views(self):
        @self.app.route('/simple-flush')
        def test_simple_flush():
            article = self.Article()
            article.name = u'Some article'
            self.session.add(article)
            self.session.commit()
            return ''

        @self.app.route('/raw-sql-and-flush')
        def test_raw_sql_and_flush():
            self.session.execute(
                "INSERT INTO article (name) VALUES ('some article')")
            article = self.Article()
            article.name = u'Some article'
            self.session.add(article)
            self.session.flush()
            self.session.execute(
                "INSERT INTO article (name) VALUES ('some article')")
            self.session.commit()
            return ''

    def test_versioning_inside_request(self):
        user = self.User(name=u'Rambo')
        self.session.add(user)
        self.session.commit()
        self.login(user)
        self.client.get(url_for('.test_simple_flush'))

        article = self.session.query(self.Article).first()
        tx = article.versions[-1].transaction
        assert tx.user.id == user.id

    def test_raw_sql_and_flush(self):
        user = self.User(name=u'Rambo')
        self.session.add(user)
        self.session.commit()
        self.login(user)
        self.client.get(url_for('.test_raw_sql_and_flush'))
        assert (self.session.query(
            versioning_manager.transaction_cls).count() == 2)
Esempio n. 9
0
import flask_bcrypt
from flask_sqlalchemy import SQLAlchemy
from p2k16.core import P2k16TechnicalException, P2k16UserException
from sqlalchemy import Column, DateTime, Integer, String, ForeignKey, Numeric, Boolean, Sequence, event, func
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import relationship

logger = logging.getLogger(__name__)

db = SQLAlchemy()

from sqlalchemy_continuum.plugins import FlaskPlugin
from sqlalchemy_continuum import make_versioned

make_versioned(plugins=[FlaskPlugin()], user_cls=None)


class ModelSupport(object):
    def __init__(self):
        self.stack = []

    def push(self, account: "Account"):
        if not account:
            raise P2k16TechnicalException("account is None")

        db.session.flush(
        )  # Make sure all callbacks are executed before modifying the stack
        self.stack.append(account)

    def pop(self):
Esempio n. 10
0
from flask import _app_ctx_stack, _request_ctx_stack, g
from sqlalchemy.orm import configure_mappers
from sqlalchemy_continuum import make_versioned
from sqlalchemy_continuum.plugins import FlaskPlugin, PropertyModTrackerPlugin


def fetch_current_user_id():
    """Fetch the current user id value for version logging and auditing"""
    try:
        return g.current_user.id
    except AttributeError:
        return


make_versioned(plugins=[FlaskPlugin(current_user_id_factory=fetch_current_user_id), PropertyModTrackerPlugin()])

from . import user, role, app_permission, app_group, source_data
from .fhir import address, codesets, email_address, organization, patient, phone_number

configure_mappers()
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy_continuum import make_versioned
from sqlalchemy_continuum.plugins import FlaskPlugin

make_versioned(plugins=[FlaskPlugin()], options={'strategy': 'subquery'})

db = SQLAlchemy()
Esempio n. 12
0
from flask import _request_ctx_stack
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy_continuum import make_versioned
from sqlalchemy_continuum.plugins import FlaskPlugin
from sqlalchemy_utils import force_auto_coercion

from momedict.user import get_user


def fetch_current_user_id():
    # Return None if we are outside of request context.
    if _request_ctx_stack.top is None:
        return
    return getattr(get_user(), 'id', None)


db = SQLAlchemy()

force_auto_coercion()
make_versioned(
    plugins=[FlaskPlugin(current_user_id_factory=fetch_current_user_id)])
Esempio n. 13
0
"""Copyright 2015 Rafal Kowalski"""
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy_continuum import make_versioned
from sqlalchemy_continuum.plugins import FlaskPlugin

make_versioned(plugins=[FlaskPlugin()], options={
    'strategy': 'subquery'
})

db = SQLAlchemy()
Esempio n. 14
0
import hashlib
import math
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from werkzeug.security import generate_password_hash, check_password_hash
from markdown import markdown
import bleach
from flask import current_app, request, url_for
from flask.ext.login import UserMixin, AnonymousUserMixin, current_user
from . import db, login_manager
from .exceptions import ValidationError
import sqlalchemy as sa
from sqlalchemy_continuum import make_versioned
from sqlalchemy_continuum.plugins import ActivityPlugin, FlaskPlugin

activity_plugin = ActivityPlugin()
make_versioned(plugins=[activity_plugin, FlaskPlugin()])


class Permission:
    FOLLOW = 0x01
    COMMENT = 0x02
    ASK = 0x04
    ANSWER = 0x08
    MODERATE_COMMENTS = 0x10
    ADMINISTER = 0x80


class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
Esempio n. 15
0
    install_logging = False

naming_convention = {
    "ix": 'ix_%(column_0_label)s',
    "uq": "uq_%(table_name)s_%(column_0_name)s",
    "ck": "ck_%(table_name)s_%(column_0_name)s",
    "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
    "pk": "pk_%(table_name)s"
}
db = SQLAlchemy(metadata=MetaData(naming_convention=naming_convention))

cache = Cache()
csrf = CsrfProtect()
migrate = Migrate()
manager = VersioningManager(options={'strategy': 'subquery'})
make_versioned(manager=manager, plugins=[FlaskPlugin()])
mail = Mail()
cdn = CDN()
login_manager = LoginManager()
assets = Environment()
toolbar = DebugToolbarExtension()

assets.register(
    'css_main',
    Bundle('css/main.scss',
           output='gen/main-packed.css',
           depends='css/*.scss',
           filters='pyscss,cssmin'))
assets.register(
    'css_admin',
    Bundle('css/admin.scss',
Esempio n. 16
0
make_versioned(
    user_cls=None,
    manager=ConditionalVersioningManager(
        # Conditionally Disable the versioning based on each
        # project's privacy preferences
        tracking_predicate=version_privacy_predicate,
        # Patch in a fix to a SQLAchemy-Continuum Bug.
        # See patch_sqlalchemy_continuum.py
        builder=PatchedBuilder(),
    ),
    plugins=[
        FlaskPlugin(
            # Redirect to our own function, which respects user preferences
            # on IP address collection
            remote_addr_factory=get_ip_if_allowed,
            # Suppress the plugin's attempt to grab a user id,
            # which imports the flask_login module (causing an error)
            current_user_id_factory=lambda: None,
        )
    ],
)

db = SQLAlchemy()


class Project(db.Model):
    class ProjectQuery(BaseQuery):
        def get_by_name(self, name):
            return Project.query.filter(Project.name == name).one()

    # Direct SQLAlchemy-Continuum to track changes to this model
Esempio n. 17
0
from sqlalchemy_continuum.plugins import FlaskPlugin
from sqlalchemy_continuum import make_versioned, version_class
from flask.globals import _app_ctx_stack, _request_ctx_stack


def fetch_current_user_id():
    from flask.ext.login import current_user

    # Return None if we are outside of request context.
    if _app_ctx_stack.top is None or _request_ctx_stack.top is None:
        return
    try:
        return current_user.user_id
    except AttributeError:
        return


flask_plugin = FlaskPlugin(current_user_id_factory=fetch_current_user_id)
make_versioned(plugins=[flask_plugin])

from .permission import Permission
from .role import Role
from .user import User

from .gtfs import *

orm.configure_mappers()

from .tag import Tag
from .tag import AgencyTag
Esempio n. 18
0
from sqlalchemy import Column, Integer, String, ForeignKey, Sequence, UniqueConstraint, Unicode
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, validates, configure_mappers
from sqlalchemy_continuum import make_versioned
from sqlalchemy_continuum.plugins import FlaskPlugin, PropertyModTrackerPlugin, TransactionChangesPlugin

make_versioned(plugins=[
    FlaskPlugin(),
    PropertyModTrackerPlugin(),
    TransactionChangesPlugin()
],
               user_cls=None)
Schema = declarative_base()


class Pack(Schema):
    """
    :type id: int
    :type name: str
    :type instances: List[Instance]
    :type parent_id: int
    :type parent: Pack|None
    """

    __tablename__ = 'packs'
    __versioned__ = {}

    id = Column(Integer, Sequence('pack_id_seq'), primary_key=True)
    name = Column(String(255), unique=True, nullable=False)

    instances = relationship('Instance',