Exemplo n.º 1
0
def create_access_rights(config):
    """Create access rights"""
    with open('rights.yaml', 'r') as stream:
        roles_rights = yaml.load(stream)

    if not os.path.isfile(config.DB_FILE):
        print('[WARNING] File [{}] doesn\'t exist.'.format(config.DB_FILE))
        sys.exit(1)

    app = create_app(config_object=config)

    with app.app_context():
        DB.init_app(app)

        for group in roles_rights['rights']:
            for rule in roles_rights['rights'][group]:

                rights = Rights(name=get_rights_name(group,
                                                     rule['permission']),
                                group=group,
                                permission=rule['permission'],
                                description=rule['description'])

                DB.session.add(rights)

        DB.session.commit()

    print('[SUCCESS] Rights imported to [{}] file'.format(config.DB_FILE))
    sys.exit(0)
Exemplo n.º 2
0
def flask_app():
    """ Create base flask application for testing. """
    app = create_app('testing')
    app.app_context().push()
    DB.drop_all(app=app)
    DB.create_all(app=app)
    return app
Exemplo n.º 3
0
def rights_check(config, rights_file):
    """Check of rights version"""

    if not os.path.isfile(rights_file):
        print('[Warning] File [{}] doesn\'t exist.'.format(rights_file))
        sys.exit(1)

    with open(rights_file, 'r') as stream:
        roles_rights = yaml.load(stream)

    app = create_app(config_object=config)

    with app.app_context():
        DB.init_app(app)

        internal = Internal.query.order_by(
            Internal.rights_version.desc()).first()

        if internal.rights_version != roles_rights['version']:
            print(
                '[WARNING] Rights version [{}] in file [{}] differs from proper [{}].'
                .format(roles_rights['version'], rights_file,
                        internal.rights_version))
            sys.exit(0)

    print('[SUCCESS] Rights in [{}] file is in correct version [{}].'.format(
        rights_file, internal.rights_version))
Exemplo n.º 4
0
class Internal(DB.Model):
    """Scheme versions"""

    uid = DB.Column(UUID, primary_key=True, default=uuid.uuid4)
    db_version = DB.Column(DB.Integer, nullable=False)
    rights_version = DB.Column(DB.Integer, nullable=False)
    updated_at = DB.Column(DB.DateTime())
Exemplo n.º 5
0
def db_add_user(config, user_email):
    """Adding user"""

    if not os.path.isfile(config.DB_FILE):
        print('[WARNING] File [{}] doesn\'t exist.'.format(config.DB_FILE))
        sys.exit(1)

    app = create_app(config_object=config)

    with app.app_context():
        DB.init_app(app)

        user = User.query.filter_by(email=user_email).first()
        if user:
            print('[WARNING] User [{}] is already added. '.format(user_email))
            sys.exit(0)

        admin = User(email=user_email,
                     password=BCRYPT.generate_password_hash(uuid.uuid4().hex),
                     gdpr_version=config.GDPR_VERSION,
                     is_active=True)

        DB.session.add(admin)
        DB.session.commit()

    print(
        '[SUCCESS] Admin user was set. For activation, you should reset password.'
    )
    sys.exit(0)
Exemplo n.º 6
0
class User(DB.Model):
    """User data model"""

    __tablename__ = 'users'

    id = DB.Column(DB.Integer, primary_key=True)  # pylint: disable=invalid-name
    steam_id = DB.Column(DB.String(50), nullable=False, unique=True)
    created_at = DB.Column(DB.DateTime())
Exemplo n.º 7
0
class User(DB.Model):
    """User data model"""

    uid = DB.Column(UUID, primary_key=True, default=uuid.uuid4)
    email = DB.Column(DB.String(255), nullable=False, unique=True)
    password = DB.Column(DB.String(255), nullable=False, server_default='')
    confirmed_at = DB.Column(DB.DateTime())
    gdpr_version = DB.Column(DB.Integer, nullable=False)
    is_active = DB.Column(DB.Boolean(), nullable=False, server_default='0')
def configure_extensions(app):
    """
    This function configures all extensions used in app.
    """

    DB.init_app(app)

    with app.app_context():
        DB.create_all()
        DB.session.commit()
Exemplo n.º 9
0
class Rights(DB.Model):
    """Access rights"""

    uid = DB.Column(UUID, primary_key=True, default=uuid.uuid4)
    name = DB.Column(DB.String(50), nullable=False, unique=True)
    group = DB.Column(DB.String(50), nullable=False)
    permission = DB.Column(DB.String(50), nullable=False)
    description = DB.Column(DB.String(255), nullable=False)
Exemplo n.º 10
0
def import_rights(config, rights_file):
    """Import rights to database

    :param config: Configuration object
    :param rights_file: File with rights and roles definitions
    :return:
    """

    with open(rights_file, 'r') as stream:
        roles_rights = yaml.load(stream)

    if not os.path.isfile(config.DB_FILE):
        print('[WARNING] File [{}] doesn\'t exist.'.format(config.DB_FILE))
        sys.exit(1)

    app = create_app(config_object=config)

    with app.app_context():
        DB.init_app(app)

        rr_scheme = {'rights': [], 'roles': [], 'role_rights': []}

        for role in roles_rights['roles']:
            rr_scheme['roles'].append(Role(name=get_role_name(role)))

        for group in roles_rights['rights']:
            for rule in roles_rights['rights'][group]:
                rr_scheme['rights'].append(
                    Rights(name=get_rights_name(group, rule['permission']),
                           group=group,
                           permission=rule['permission'],
                           description=rule['description']))

                for role in rule['roles']:
                    rr_scheme['role_rights'].append(
                        RoleRights(role=get_role_name(role),
                                   rights=get_rights_name(
                                       group, rule['permission'])))

        for rights in rr_scheme['rights']:
            DB.session.add(rights)

        for roles in rr_scheme['roles']:
            DB.session.add(roles)

        for role_rights in rr_scheme['role_rights']:
            DB.session.add(role_rights)

        DB.session.commit()

    print('[SUCCESS] Rights imported to [{}] file'.format(config.DB_FILE))
Exemplo n.º 11
0
class Rights(DB.Model):
    """Access rights"""

    name = DB.Column(DB.String(50), primary_key=True)
    group = DB.Column(DB.String(50), nullable=False)
    permission = DB.Column(DB.String(50), nullable=False)
    description = DB.Column(DB.String(255), nullable=False)
Exemplo n.º 12
0
class BaseModel:
    """ This class is BaseModel and used by all model object in our app"""
    id = sa.Column(sa.Integer, primary_key=True)
    create_at = sa.Column(sa.DateTime, server_default=sql.func.now())
    update_at = sa.Column(sa.DateTime, onupdate=sql.func.now())
    deleted = sa.Column(sa.Boolean, default=False)
    delete_at = sa.Column(sa.DateTime)

    def __init__(self, *args, **kwargs):
        super(BaseModel, self).__init__(*args, **kwargs)
        for data in args:
            for key in data:
                if isinstance(data[key], dict):
                    setattr(self, key, data[key])

    def from_request(self, *args):
        """Parsing data from request json
            """
        for data in args:
            for key in data:
                if isinstance(data[key], dict):
                    setattr(self, key, data[key])

    def save(self):
        """Method to save object to database"""
        sa.session.add(self)
        sa.session.commit()

    def delete(self):
        """Method to delete object
        In this method just add flag deleted to data.
        Not remove data from database
        """
        self.deleted = True
        self.delete_at = datetime.now()
        self.save()

    def restore(self):
        """Method to restore object
        In this method just set flag deleted to false to restore object.
        """
        self.deleted = False
        self.delete_at = None
        self.save()

    def remove(self):
        """Method to remove object permanently from database"""
        sa.session.delete(self)
        sa.session.commit()
Exemplo n.º 13
0
def flask_app_user_in_db():
    """ Create flask application for testing with a user in the DB. """
    app = create_app('testing')
    DB.drop_all(app=app)
    DB.create_all(app=app)
    app.app_context().push()

    user_id = {'user_id': "1"}

    schema = UserSchema().load(user_id)
    new_user = UserModel(**schema.data)
    DB.session.begin()
    DB.session.add(new_user)
    DB.session.commit()
    return app
Exemplo n.º 14
0
def create_app(config_name='development'):
    """ Create the application with the relevant configuration. """
    app = Flask(__name__)
    app.config.from_object(CONFIG_MAPPER[config_name])
    app.wsgi_app = ProxyFix(app.wsgi_app)

    from . import extensions
    from . import modules
    for content in (
            extensions,
            modules,
    ):
        content.init_app(app)

    DB.create_all(app=app)

    return app
Exemplo n.º 15
0
def db_init(config):
    """Creation of database"""

    if os.path.isfile(config.DB_FILE):
        print('[WARNING] File [{}] already exists.'.format(config.DB_FILE))
        sys.exit(0)

    if not os.path.exists(os.path.dirname(config.DB_FILE)):
        os.makedirs(os.path.dirname(config.DB_FILE))

    app = create_app(config_object=config)

    with app.app_context():
        DB.init_app(app)
        DB.create_all()
        DB.session.commit()

    print('[SUCCESS] File [{}] created.'.format(config.DB_FILE))
    sys.exit(0)
Exemplo n.º 16
0
def register_extensions(app):
    """Register Flask extensions."""

    BCRYPT.init_app(app)

    DB.init_app(app)

    MAIL.init_app(app)

    BOOTSTRAP.init_app(app)
    bootstrapcdn = WebCDN(
        "https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/")
    bootswatchcdn = WebCDN(
        "https://stackpath.bootstrapcdn.com/bootswatch/3.3.7/")
    app.extensions['bootstrap']['cdns'].update({
        'bootstrapcdn': bootstrapcdn,
        'bootswatchcdn': bootswatchcdn
    })

    CSRF.init_app(app)
Exemplo n.º 17
0
def db_check(config):
    """Check of database"""

    if not os.path.isfile(config.DB_FILE):
        print('[WARNING] File [{}] doesn\'t exist.'.format(config.DB_FILE))
        sys.exit(1)

    app = create_app(config_object=config)

    with app.app_context():
        DB.init_app(app)

        internal = Internal.query.order_by(Internal.db_version.desc()).first()

        if internal.db_version != config.DB_VERSION:
            print(
                '[WARNING] Schema version [{}] in file [{}] differs from proper [{}].'
                .format(internal.db_version, config.DB_FILE,
                        config.DB_VERSION))
            sys.exit(0)

    print('[SUCCESS] Schema in [{}] file is in correct version [{}].'.format(
        config.DB_FILE, config.DB_VERSION))
Exemplo n.º 18
0
def db_init(config):
    """Creation of database"""

    if os.path.isfile(config.DB_FILE):
        print('[WARNING] File [{}] already exists.'.format(config.DB_FILE))
        sys.exit(0)

    if not os.path.exists(os.path.dirname(config.DB_FILE)):
        os.makedirs(os.path.dirname(config.DB_FILE))

    app = create_app(config_object=config)

    with app.app_context():
        DB.init_app(app)
        DB.create_all()

        internal = Internal(db_version=config.DB_VERSION,
                            rights_version=0,
                            updated_at=datetime.now())

        DB.session.add(internal)
        DB.session.commit()

    print('[SUCCESS] File [{}] created.'.format(config.DB_FILE))
Exemplo n.º 19
0
class Token(DB.Model):
    """Token data model"""

    uid = DB.Column(UUID, primary_key=True, default=uuid.uuid4)
    token_type = DB.Column(DB.Integer, nullable=False)
    created_at = DB.Column(DB.DateTime(), nullable=False)
    valid_until = DB.Column(DB.DateTime(), nullable=False)
    is_active = DB.Column(DB.Boolean(), nullable=False, server_default='1')
    user_uid = DB.Column(UUID, DB.ForeignKey('user.uid'), nullable=False)
    note = DB.Column(DB.String(20), nullable=False, server_default='')

    user = DB.relationship('User', back_populates='tokens', lazy='select')
Exemplo n.º 20
0
class Player(DB.Model):
    """User data model"""

    uid = DB.Column(UUID, primary_key=True, default=uuid.uuid4)
    user_uid = DB.Column(UUID, DB.ForeignKey('user.uid'), nullable=False)
    steam_id = DB.Column(DB.Integer, nullable=False)
    name = DB.Column(DB.String(50), nullable=False, unique=True)
    avatar = DB.Column(DB.String(300), nullable=False, unique=True)
    avatar_medium = DB.Column(DB.String(300), nullable=False, unique=True)
    avatar_full = DB.Column(DB.String(300), nullable=False, unique=True)

    user = DB.relationship('User', back_populates='players', lazy='select')
Exemplo n.º 21
0
class UserRole(DB.Model):
    """User Roles"""

    uid = DB.Column(UUID, primary_key=True, default=uuid.uuid4)
    name = DB.Column(DB.String(50), nullable=False, unique=True)
Exemplo n.º 22
0
class RoleRights(DB.Model):
    """Connection roles <--> rights"""

    uid = DB.Column(UUID, primary_key=True, default=uuid.uuid4)
    role = DB.Column(DB.String(50), nullable=False)
    rights = DB.Column(DB.String(50), nullable=False)
Exemplo n.º 23
0
class RoleRight(DB.Model):
    """Connection roles <--> rights"""

    uid = DB.Column(UUID, primary_key=True, default=uuid.uuid4)
    role_uid = DB.Column(UUID, nullable=False, unique=True)
    right_uid = DB.Column(UUID, nullable=False, unique=True)
Exemplo n.º 24
0
class Role(DB.Model):
    """User Roles"""

    name = DB.Column(DB.String(50), primary_key=True)
Exemplo n.º 25
0
def register_extensions(flask_app: Flask) -> None:
    DB.init_app(flask_app)
Exemplo n.º 26
0
class Player(DB.Model):
    """User data model"""

    uid = DB.Column(UUID, primary_key=True, default=uuid.uuid4)
    user_uid = DB.Column(UUID, DB.ForeignKey('user.uid'), nullable=False)
    steam_id = DB.Column(DB.Integer, nullable=False)
    name = DB.Column(DB.String(50), nullable=False, unique=True)
    avatar = DB.Column(DB.String(300), nullable=False, unique=True)
    avatar_medium = DB.Column(DB.String(300), nullable=False, unique=True)
    avatar_full = DB.Column(DB.String(300), nullable=False, unique=True)

    user = DB.relationship('User', back_populates='players', lazy='select')


User.players = DB.relationship('Player',
                               order_by=Player.name,
                               back_populates='user',
                               lazy='select')


@unique
class TokenType(Enum):
    """Type of tokens"""

    INVITATION = 1
    RESET_PASSWORD = 2
    ACCESS = 3
    RENEW_ACCESS = 4


class Token(DB.Model):
    """Token data model"""
Exemplo n.º 27
0
class User(DB.Model):
    user_id = DB.Column(DB.String(40), primary_key=True)
    first_name = DB.Column(DB.String(100))
    last_name = DB.Column(DB.String(100))
Exemplo n.º 28
0
def register_extensions(app):
    """Register Flask extensions."""

    DB.init_app(app)
    API.init_app(app)