コード例 #1
0
class Transaction(db.Model):
    __tablename__ = 'transaction'
    user_id = db.Column(db.Integer, db.ForeignKey(User.id))
    user = db.relationship('User')
    id = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(200))
    occurrence_date = db.Column(db.DateTime())
    booking_date = db.Column(db.DateTime())
    amount = db.Column(db.Numeric(precision=10, scale=4))
    is_credit = db.Column(db.Boolean())
    category_id = db.Column(db.Integer, db.ForeignKey(TransactionCategory.id))
    category = db.relationship('TransactionCategory')
    account_id = db.Column(db.Integer, db.ForeignKey(Account.id))
    account = db.relationship('Account')
コード例 #2
0
class Emotion(db.Model):
    __tablename__ = "emotion"
    id = Column(Integer, primary_key=True)
    name = Column(String)
    value = Column(Numeric(12, 8))

    entry_id = Column(Integer, ForeignKey('entry.id'), nullable=False)
    entry = db.relationship("Entry", backref="entry", foreign_keys=[entry_id])
コード例 #3
0
class Entry(Base):
    __tablename__ = "entry"
    id = Column(Integer, primary_key=True)
    title = Column(String)
    body = Column(String)

    journal_id = Column(Integer, ForeignKey('journal.id'), nullable=False)
    journal = db.relationship("Journal", backref="journal", foreign_keys=[journal_id])

    def get_emotions(self):
        emotion = Emotion.query.filter_by(entry_id=self.id).all()
        return emotion

    def add_emotion(self, name, value):
        emotion = Emotion(name=name, value=value, entry_id=self.id)
        db.session.add(emotion)
        db.session.commit()
コード例 #4
0
class Journal(Base):
    __tablename__ = "journal"
    id = Column(Integer, primary_key=True)
    title = Column(String, nullable=False)
    description = Column(String, nullable=True)

    user_id = Column(Integer, ForeignKey('user.id'), nullable=False)
    user = db.relationship("User", backref="user", foreign_keys=[user_id])

    def get_entries(self):
        entry = Entry.query.filter_by(journal_id=self.id).all()
        return entry

    def add_entry(self, title, body):
        entry = Entry(title=title, body=body, journal_id=self.id)
        db.session.add(entry)
        db.session.commit()
コード例 #5
0
class User(UserMixin, db_sec.Model):
    __tablename__ = 'user'

    id = db_sec.Column(db_sec.Integer, primary_key=True)
    email = db_sec.Column(db_sec.String(255), unique=True)
    password = db_sec.Column(db_sec.String(120))
    active = db_sec.Column(db_sec.Boolean())
    confirmed_at = db_sec.Column(db_sec.DateTime())
    last_login_at = db_sec.Column(db_sec.DateTime())
    current_login_at = db_sec.Column(db_sec.DateTime())
    last_login_ip = db_sec.Column(db_sec.String(100))
    current_login_ip = db_sec.Column(db_sec.String(100))
    login_count = db_sec.Column(db_sec.Integer)
    registered_at = db_sec.Column(db_sec.DateTime())
    roles = db_sec.relationship('Role',
                                secondary=roles_users,
                                backref=db_sec.backref('user', lazy='dynamic'))

    def has_role(self, role):
        return role in self.roles
コード例 #6
0
class Dashboard(db.Model):
    __tablename__ = 'dashboards'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    dashboard_data = db.Column(JSON, nullable=False)
    account_id = db.Column(db.Integer,
                           db.ForeignKey('accounts.id'),
                           primary_key=True)
    active = db.Column(db.Boolean, nullable=False, default=False)
    name = db.Column(db.String, nullable=False, default="")
    created_at = db.Column(db.DateTime,
                           nullable=False,
                           default=db.func.current_timestamp())
    modified_at = db.Column(db.DateTime,
                            nullable=False,
                            default=db.func.current_timestamp(),
                            onupdate=db.func.current_timestamp())

    widgets = db.relationship("DashboardWidget",
                              cascade="save-update, merge, delete")

    def __init__(self, account_id, dashboard_data, name):
        self.account_id = account_id
        self.dashboard_data = dashboard_data
        self.name = name

    def save(self):
        """
        Stores this dashboard to database
        This may raise errors
        """
        db.session.add(self)
        db.session.commit()

    def delete(self):
        """
        Deletes this dashboard from database
        """
        db.session.delete(self)
        db.session.commit()

    @staticmethod
    def exists_with_any_of(**kwargs):
        """
        Checks if dashboard with any of the given arguments exists
        """
        for key, value in kwargs.items():
            args = {key: value}
            if Dashboard.query.filter_by(**args).first():
                return True
        return False

    @staticmethod
    def exists(**kwargs):
        """
        Checks if dashboard with all of the given arguments exists
        """
        if Dashboard.query.filter_by(**kwargs).first():
            return True
        return False

    @staticmethod
    def get_all():
        """
        Get all stored dashboards
        """
        return Dashboard.query.all()

    @staticmethod
    def get_many(**kwargs):
        """
        Get dashboards with given filters

        Available filters:
         * id
         * account_id
        """
        return Dashboard.query.filter_by(**kwargs).all()

    @staticmethod
    def get_many_filtered(account_id, active):
        """
        Get many dashboard with given filters

        Available filters:
         * active
        """
        query = Dashboard.query.filter(Dashboard.account_id == account_id)
        if active is not None:
            query = query.filter(Dashboard.active == active)
        return query.all()

    @staticmethod
    def deactivate_all_for_user(account_id):
        """
        Deactivates all dashboards for this user
        """
        db.session.query(Dashboard).filter(account_id == account_id) \
                                   .update({'active': False})
        db.session.commit()

    @staticmethod
    def get(**kwargs):
        """
        Get dashboard with given filters

        Available filters:
         * id
         * account_id
        """
        return Dashboard.query.filter_by(**kwargs).first_or_404()

    def __repr__(self):
        return '<Dashboard (dashboard_data=%s, account_id=%s)>' % (
            self.dashboard_data, self.account_id)
コード例 #7
0
class DashboardWidget(db.Model):
    __tablename__ = 'dashboard_widgets'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    dashboard_id = db.Column(db.Integer,
                             db.ForeignKey('dashboards.id'),
                             nullable=False)
    device_id = db.Column(db.Integer,
                          db.ForeignKey('devices.id'),
                          nullable=False)
    name = db.Column(db.String, nullable=False)
    height = db.Column(db.Integer, nullable=False)
    width = db.Column(db.Integer, nullable=False)
    x = db.Column(db.Integer, nullable=False)
    y = db.Column(db.Integer, nullable=False)
    chart_type = db.Column(db.String, nullable=False)
    filters = db.Column(JSON, nullable=False)
    created_at = db.Column(db.DateTime,
                           nullable=False,
                           default=db.func.current_timestamp())
    modified_at = db.Column(db.DateTime,
                            nullable=False,
                            default=db.func.current_timestamp(),
                            onupdate=db.func.current_timestamp())

    dashboard = db.relationship("Dashboard", foreign_keys=[dashboard_id])

    def __init__(self, dashboard_id, device_id, name, height, width, x, y,
                 chart_type, filters):
        self.dashboard_id = dashboard_id
        self.device_id = device_id
        self.name = name
        self.height = height
        self.width = width
        self.x = x
        self.y = y
        self.chart_type = chart_type
        self.filters = filters

    def save(self):
        """
        Stores this widget to database
        This may raise errors
        """
        db.session.add(self)
        db.session.commit()

    def delete(self):
        """
        Deletes this widget from database
        """
        db.session.delete(self)
        db.session.commit()

    @staticmethod
    def exists_with_any_of(**kwargs):
        """
        Checks if widget with any of the given arguments exists
        """
        for key, value in kwargs.items():
            args = {key: value}
            if DashboardWidget.query.filter_by(**args).first():
                return True
        return False

    @staticmethod
    def exists(**kwargs):
        """
        Checks if widget with all of the given arguments exists
        """
        if DashboardWidget.query.filter_by(**kwargs).first():
            return True
        return False

    @staticmethod
    def get_all():
        """
        Get all stored widgets
        """
        return DashboardWidget.query.paginate(None, None, False).items

    @staticmethod
    def get_many(**kwargs):
        """
        Get widgets with given filters

        Available filters:
         * id
         * dashboard_id
         * device_id
         * dimensions and positions, but useless
         * chart_type
         * filters, but useless
        """
        return DashboardWidget.query.filter_by(**kwargs).paginate(
            None, None, False).items

    @staticmethod
    def get_many_for_dashboard(dashboard_id):
        """
        Get widgets for given dashboard
        """
        query = DashboardWidget.query.filter(
            DashboardWidget.dashboard_id == dashboard_id)
        return query.paginate(None, None, False).items

    @staticmethod
    def get(**kwargs):
        """
        Get widget with given filters

        Available filters:
         * id
         * dashboard_id
         * device_id
         * dimensions and positions, but useless
         * chart_type
         * filters, but useless
        """
        return DashboardWidget.query.filter_by(**kwargs).first_or_404()

    def __repr__(self):
        return '<DashboardWidget (id=%s, dashboard_id=%s)>' % (
            self.dashboard_data, self.account_id)
コード例 #8
0
class Lab(db.Model):
    __tablename__ = 'labs'
    uuid = db.Column(UUIDType(binary=False),
                     primary_key=True,
                     default=uuid.uuid4())
    code = db.Column(db.String(64), unique=True, nullable=False)
    description = db.Column(db.Text, nullable=False)
    start_ip_range = db.Column(IPAddressType, unique=True, nullable=False)
    end_ip_range = db.Column(IPAddressType, unique=True, nullable=False)
    hosts_vcpus = db.Column(db.Integer, nullable=False)
    hosts_memory = db.Column(db.Integer, nullable=False)
    hosts_disk = db.Column(db.Integer, nullable=False)
    hosts = db.relationship('Host',
                            backref='lab',
                            lazy=True,
                            cascade="all, delete-orphan")

    def __init__(self, data):
        self.uuid = uuid.uuid4()
        self.code = data['code'].upper()
        self.description = data['description']
        self.start_ip_range = ipaddress.ip_address(data['start_ip_range'])
        self.end_ip_range = ipaddress.ip_address(data['end_ip_range'])
        self.hosts_vcpus = data['hosts']['vcpus']
        self.hosts_memory = data['hosts']['memory']
        self.hosts_disk = data['hosts']['disk']

    def save(self):
        """Adds into database an existent laboratory

        :return: None
        """
        try:
            db.session.add(self)
            db.session.commit()
        except KeyError or IntegrityError as e:
            db.session.rollback()
            raise e

    def remove(self):
        """Deletes from database an existent laboratory

        :return: None
        """
        try:
            db.session.delete(self)
            db.session.commit()
        except UnmappedInstanceError as e:
            db.session.rollback()
            raise e

    def add_host(self, host):
        """Appends into the laboratory a new host

        :param host:
        :return: None
        """
        if not self.has_host(host):
            self.hosts.append(host)

    def remove_host(self, host):
        """Removes from database an existent host

        :param host:
        :return: None
        """
        if self.has_host(host):
            self.hosts.remove(host)

    def has_host(self, host):
        """Checks if the host is appended in the laboratory

        :param host:
        :return: True or False
        """
        return True if host in self.hosts else False

    @staticmethod
    def get(lab_uuid=None):
        """Gets a list with all laboratories if None lab_uuid is passed. If lab_uuid is present, it returns the
        laboratory defined by lab_uuid

        :param lab_uuid: UUID of the laboratory
        :return:
        """
        try:
            return Lab.query.get(lab_uuid) if lab_uuid else Lab.query.all()
        except Exception as e:
            raise e

    def update(self, data):
        if 'code' in data and data['code'] != "":
            self.code = data['code'].upper()
        if 'description' in data and data['description'] != "":
            self.description = data['description']
        if 'start_ip_range' in data and data['start_ip_range'] != "":
            self.start_ip_range = data['start_ip_range']
        if 'end_ip_range' in data and data['end_ip_range'] != "":
            self.end_ip_range = data['end_ip_range']
        if 'hosts' in data:
            if 'vcpus' in data['hosts'] and data['hosts']['vcpus'] != "":
                self.hosts_vcpus = data['hosts']['vcpus']
            if 'memory' in data['hosts'] and data['hosts']['memory'] != "":
                self.hosts_memory = data['hosts']['memory']
            if 'disk' in data['hosts'] and data['hosts']['disk'] != "":
                self.hosts_disk = data['hosts']['disk']
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            raise e

    @staticmethod
    def delete(lab):
        try:
            db.session.delete(lab)
            db.session.commit()
        except UnmappedInstanceError as e:
            db.session.rollback()
            raise e

    def to_dict(self):
        return dict(uuid=str(self.uuid),
                    code=self.code,
                    description=self.description,
                    start_ip_range=self.start_ip_range.compressed,
                    end_ip_range=self.end_ip_range.compressed,
                    hosts=dict(total=self.hosts.__len__(),
                               vcpus=self.hosts_vcpus,
                               memory=self.hosts_memory,
                               disk=self.hosts_disk))
コード例 #9
0
class Account(db.Model):
    __tablename__ = 'accounts'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String, index=True, unique=True)
    password = db.Column(db.String)
    email = db.Column(db.String, index=True, unique=True)
    role_id = db.Column(db.Integer, db.ForeignKey("roles.id"))
    role = db.relationship("Role", foreign_keys=[role_id])
    confirmed = db.Column(db.Boolean, default=False, nullable=False)
    confirmed_at = db.Column(db.DateTime, nullable=True)
    created_at = db.Column(db.DateTime,
                           nullable=False,
                           default=db.func.current_timestamp())
    modified_at = db.Column(db.DateTime,
                            nullable=False,
                            default=db.func.current_timestamp(),
                            onupdate=db.func.current_timestamp())

    dashboards = db.relationship("Dashboard",
                                 cascade="save-update, merge, delete")

    def __init__(self, username, password, email, role=2):
        self.username = str(username)
        self.password = str(password)
        self.email = str(email)
        if isinstance(role, Role):
            self.role_id = role.id
        else:
            self.role_id = int(role)

    def save(self):
        """
        Stores this user to database
        This may raise errors
        """
        db.session.add(self)
        db.session.commit()

    @staticmethod
    def exists_with_any_of(**kwargs):
        """
        Checks if user with any of the given arguments exists
        """
        for key, value in kwargs.items():
            args = {key: value}
            if Account.query.filter_by(**args).first():
                return True
        return False

    @staticmethod
    def exists(**kwargs):
        """
        Checks if user with all of the given arguments exists
        """
        if Account.query.filter_by(**kwargs).first():
            return True
        return False

    @staticmethod
    def get_all():
        """
        Get all stored accounts
        """
        return Account.query.all()

    @staticmethod
    def get(**kwargs):
        """
        Get account with given filters

        Available filters:
         * username
         * email
         * role_id
         * id
         * password (useless, but not forbidden)

        """
        return Account.query.filter_by(**kwargs).first()

    def create_auth_token(self):
        """
        Generates the Auth Token
        :return: string
        """
        current_time = datetime.datetime.utcnow()
        payload = {
            'exp': current_time + datetime.timedelta(days=0, hours=1),
            'iat': current_time,
            'sub': self.id
        }
        return jwt.encode(payload,
                          app.config.get('SECRET_KEY'),
                          algorithm='HS256').decode('utf-8')

    @staticmethod
    def validate_token(token):
        """
        Validates given Auth token
        :rtype: Account
        :return: Account associated with token
        """
        payload = jwt.decode(token,
                             app.config.get('SECRET_KEY'),
                             algorithms=['HS256'])
        current_time = timegm(datetime.datetime.utcnow().utctimetuple())
        if current_time > payload['exp']:
            raise ValueError("Expired token")
        return Account.get(id=payload['sub'])

    def __repr__(self):
        return '<Account (name=%s, role=%s)>' % (self.username, self.role)
コード例 #10
0
class DeviceAssociation(db.Model):
    __tablename__ = 'device_associations'

    device_id = db.Column(db.Integer,
                          db.ForeignKey('devices.id'),
                          primary_key=True)
    account_id = db.Column(db.Integer,
                           db.ForeignKey('accounts.id'),
                           primary_key=True)
    access_level = db.Column(db.Integer,
                             db.ForeignKey('access_levels.id'),
                             nullable=False)
    created_at = db.Column(db.DateTime,
                           nullable=False,
                           default=db.func.current_timestamp())
    modified_at = db.Column(db.DateTime,
                            nullable=False,
                            default=db.func.current_timestamp(),
                            onupdate=db.func.current_timestamp())

    access_level_data = db.relationship("AccessLevel",
                                        foreign_keys=[access_level])

    def __init__(self, device_id, account_id, access_level=1):
        self.device_id = device_id
        self.account_id = account_id
        self.access_level = access_level

    def save(self):
        """
        Stores this device association to database
        This may raise errors
        """
        db.session.add(self)
        db.session.commit()

    @staticmethod
    def get_many(**kwargs):
        """
        Get many device associations with given filters as a list

        Available filters:
         * device_id
         * account_id
        """
        return DeviceAssociation.query.filter_by(**kwargs).all()

    @staticmethod
    def get_for_user(account_id):
        """
        Get many device associations for user with account id passed in
        parameter
        """
        return DeviceAssociation.get_many(account_id=account_id)

    @staticmethod
    def get_for_device(device_id):
        """
        Get many device associations for device with account id passed in
        parameter
        """
        return DeviceAssociation.get_many(device_id=device_id)

    def __repr__(self):
        return '<DeviceAssociation (device_id=%s, accoount_id=%s)>' % (
            self.device_id, self.account_id)
コード例 #11
0
class Device(db.Model):
    __tablename__ = 'devices'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    created_at = db.Column(db.DateTime,
                           nullable=False,
                           default=db.func.current_timestamp())
    modified_at = db.Column(db.DateTime,
                            nullable=False,
                            default=db.func.current_timestamp(),
                            onupdate=db.func.current_timestamp())
    name = db.Column(db.String, nullable=False)
    device_type_id = db.Column(db.Integer, db.ForeignKey('device_types.id'))
    device_type = db.relationship("DeviceType", foreign_keys=[device_type_id])
    device_secret = db.Column(db.String, nullable=False)
    secret_algorithm = db.Column(db.String, nullable=False)
    configuration = db.Column(JSON, nullable=True)

    users = db.relationship("DeviceAssociation",
                            cascade="save-update, merge, delete")
    recordings = db.relationship("Recording",
                                 cascade="save-update, merge, delete")
    widgets = db.relationship("DashboardWidget",
                              cascade="save-update, merge, delete")
    documentations = db.relationship("DeviceDocumentation",
                                     cascade="save-update, merge, delete")

    def __init__(self, name, configuration=None, device_type=1):
        self.name = name
        self.configuration = configuration
        self.device_type_id = device_type
        self.secret_algorithm = 'sha256'
        self.device_secret = token_urlsafe(32)

    def save(self):
        """
        Stores this device to database
        This may raise errors
        """
        db.session.add(self)
        db.session.commit()

    def delete(self):
        """
        Deletes this recording from database
        """
        db.session.delete(self)
        db.session.commit()

    @staticmethod
    def get_many(**kwargs):
        """
        Get many devices with given filters as a list

        Available filters:
         * id
         * name
         * device_type_id
         * created_at
         * modified_at
         * configuration (useless)

        """
        return Device.query.filter_by(**kwargs).paginate(None, None,
                                                         False).items

    @staticmethod
    def get_many_for_user(account_id):
        """
        Get many devices which are associated to account
        """
        return Device.query.filter(Device.users.any(
            account_id=account_id)).paginate(None, None, False).items

    @staticmethod
    def get(**kwargs):
        """
        Get device with given filters

        Available filters:
         * id
         * name
         * device_type_id
         * created_at
         * modified_at
         * configuration (useless)

        """
        return Device.query.filter_by(**kwargs).first_or_404()

    @staticmethod
    def exists(**kwargs):
        """
        Checks if device with all of the given arguments exists
        """
        if Device.query.filter_by(**kwargs).first():
            return True
        return False

    def __repr__(self):
        return '<Device (name=%s, type=%s)>' % (self.name, self.device_type_id)