Exemplo n.º 1
0
class Admin(db.Model):
    __tablename__ = "admin"

    admin_id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(100))
    last_name = db.Column(db.String(100)) 
    username = db.Column(db.String(100), unique=True, nullable=False)
    photo_url = db.Column(db.String(100))
    is_superadmin = db.Column(db.Boolean())

    repetition =  db.relationship("Repetition", back_populates="admin")

    def __init__(self, admin_id, first_name, last_name, username, photo_url, is_superadmin=False):
        self.admin_id = admin_id
        self.first_name = first_name
        self.last_name = last_name
        self.username = username
        self.photo_url = photo_url
        self.is_superadmin = is_superadmin
Exemplo n.º 2
0
class Weekly(db.Model):
    __tablename__ = 'Weekly'

    weekly_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    cont_id = db.Column(db.ForeignKey('WorkContract.cont_id'),
                        nullable=False,
                        index=True)
    target_ym = db.Column(db.String(8), primary_key=True, nullable=False)
    week_num = db.Column(db.Integer)
    total_time = db.Column(db.Time)
    total_pay = db.Column(db.Integer)
    holy_dnum = db.Column(db.Integer)
    weekly_pay = db.Column(db.Integer)
    created_time = db.Column(db.DateTime, server_default=func.now())
    updated_time = db.Column(db.DateTime)

    cont = db.relationship(
        'WorkContract',
        primaryjoin='Weekly.cont_id == WorkContract.cont_id',
        backref='weeklies')
Exemplo n.º 3
0
class UserLabel(BaseModel):

    __tablename__ = "user_labels"

    name = db.Column(db.Text)
    # one to many
    sections = db.relationship("Section", backref="label", lazy="dynamic")
    # foreign key user_id
    user_id = db.Column(db.Integer, db.ForeignKey("users.id"))

    color = db.Column(db.Text)

    def __init__(self, name, user_id, color):
        self.name = name
        self.user_id = user_id
        self.color = color

    def create_user_label(label):
        db.session.add(label)
        db.session.commit()
Exemplo n.º 4
0
class PetModel(db.Model):
    __tablename__ = "pet"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    public_id = db.Column(db.String(100), unique=True, nullable=False)
    status = db.Column(db.Integer, nullable=False)
    name = db.Column(db.String(50), nullable=False)
    bio = db.Column(db.String(100))
    birthday = db.Column(db.DateTime, nullable=True)
    sex = db.Column(db.String(20), nullable=False)
    profile_photo_fn = db.Column(db.String(50), default="pet-default-profile-photo.jpg", nullable=False)
    cover_photo_fn = db.Column(db.String(50), default="pet-default-cover-photo.jpg", nullable=False)
    registered_on = db.Column(db.DateTime, nullable=False)
    owner_user_username = db.Column(db.String, db.ForeignKey("owner.username"), nullable=False)
    group_specie_id = db.Column(db.String, db.ForeignKey("group.public_id"), nullable=False)
    subgroup_breed_id = db.Column(db.String, db.ForeignKey("subgroup.public_id"), nullable=False)
    
    follow_followed_rel = db.relationship("FollowModel", backref="followed", lazy=True)
 
    def __repr__(self):
        return "<pet '{}'>".format(self.name)
Exemplo n.º 5
0
class Post(Content):
    __tablename__ = "post"

    # DATA COLUMNS
    id = db.Column(db.Integer, db.ForeignKey('content.id'), primary_key=True)
    title = db.Column(db.String(1024), nullable=False)

    # FOREIGN KEYS COLUMNS
    posted_to_board_id = db.Column(db.Integer,
                                   db.ForeignKey('board.id'),
                                   nullable=True)

    # RELATIONSHIPS
    posted_to_board = db.relationship('Board',
                                      back_populates='posts',
                                      lazy=True)

    # INHERITANCE
    __mapper_args__ = {
        'polymorphic_identity': 'post',
    }
class Board(db.Model):
    __tablename__ = 'board'

    # DATA COLUMNS
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(255), index=True, nullable=False)

    # RELATIONSHIPS
    posts = db.relationship('Post',
                            back_populates='posted_to_board',
                            lazy='dynamic',
                            cascade="delete")

    # AGGREGATED COLUMNS
    @hybrid_property
    def posts_num(self):
        return self.posts.count()

    # INHERITANCE
    type = db.Column(db.String(255))
    __mapper_args__ = {'polymorphic_identity': 'board', 'polymorphic_on': type}
Exemplo n.º 7
0
class Account(db.Model):
    """ SQLAlchemy model for accounts. """

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    created_at = db.Column(db.DateTime, nullable=False)
    email = db.Column(db.String(255), unique=True, nullable=False)
    username = db.Column(db.String(50), nullable=False)
    password = db.Column(db.String(255), nullable=False)
    brands = db.relationship('Brand', backref='brand', lazy=True)
    """ Hashes and sets a password for the account. """
    def set_password(self, password):
        self.password = flask_bcrypt.generate_password_hash(password).decode(
            'utf-8')

    """ Check if a password matches the hashed password stored for the account. """

    def check_password(self, password):
        return flask_bcrypt.check_password_hash(self.password, password)

    def __repr__(self):
        return f"<Account {self.email}'>"
class GroupChat(Chat):
    __tablename__ = "group_chat"

    # DATA COLUMNS
    id = db.Column(db.Integer,
                   db.ForeignKey('chat.id'),
                   primary_key=True,
                   autoincrement=True)
    of_group_id = db.Column(db.Integer,
                            db.ForeignKey('group.id'),
                            nullable=False)

    # RELATIONSHIPS
    of_group = db.relationship('Group',
                               back_populates='chat',
                               cascade="delete")

    # INHERITANCE
    __mapper_args__ = {
        'polymorphic_identity': 'group_chat',
    }
Exemplo n.º 9
0
class Monthly(db.Model):
    __tablename__ = 'Monthly'

    monthly_id = db.Column(db.String(50), primary_key=True)
    cont_id = db.Column(db.ForeignKey('WorkContract.cont_id'),
                        nullable=False,
                        index=True)
    target_ym = db.Column(db.String(6))
    start_mdate = db.Column(db.String(8))
    end_mdate = db.Column(db.String(8))
    act_work_mtime = db.Column(db.Time)
    cont_work_mtime = db.Column(db.Time)
    act_rest_mtime = db.Column(db.Time)
    cont_rest_mtime = db.Column(db.Time)
    over_mtime = db.Column(db.Time)
    night_mtime = db.Column(db.Time)
    holy_mtime = db.Column(db.Time)
    tardy_mtime = db.Column(db.Time)
    act_work_mpay = db.Column(db.Integer)
    cont_work_mpay = db.Column(db.Integer)
    over_mpay = db.Column(db.Integer)
    night_mpay = db.Column(db.Integer)
    holy_mpay = db.Column(db.Integer)
    tardy_mpay = db.Column(db.Integer)
    weekly_mpay = db.Column(db.Integer)
    total_mpay = db.Column(db.Integer)
    total_days = db.Column(db.Integer)
    nat_pension = db.Column(db.Integer)
    health_ins = db.Column(db.Integer)
    employment_ins = db.Column(db.Integer)
    income_tax = db.Column(db.Integer)
    tax_exempt = db.Column(db.Integer)
    final_pay = db.Column(db.Integer)
    created_time = db.Column(db.DateTime, server_default=func.now())
    updated_time = db.Column(db.DateTime)

    cont = db.relationship(
        'WorkContract',
        primaryjoin='Monthly.cont_id == WorkContract.cont_id',
        backref='monthlies')
Exemplo n.º 10
0
class RoomEvent(db.Model):
    __tablename__ = 'scheduler_room_reservations'
    id = db.Column('id', db.Integer(), primary_key=True, autoincrement=True)
    room_id = db.Column('room_id',
                        db.ForeignKey('scheduler_room_resources.id'),
                        nullable=False)
    category_id = db.Column('category_id',
                            db.ForeignKey('scheduler_event_categories.id'))
    category = db.relationship('EventCategory', backref=db.backref('events'))
    title = db.Column('title', db.String(255), nullable=False)
    start = db.Column('start', db.DateTime(timezone=True), nullable=False)
    end = db.Column('end', db.DateTime(timezone=True), nullable=False)
    iocode_id = db.Column('iocode_id', db.ForeignKey('iocodes.id'))
    occupancy = db.Column('occupancy', db.Integer())
    # number of sets of food/refreshment requested
    refreshment = db.Column('refreshment', db.Integer(), default=0)
    request = db.Column('request', db.Text())  # comma separated list of things
    approved = db.Column('approved', db.Boolean(), default=True)
    created_at = db.Column('created_at',
                           db.DateTime(timezone=True),
                           server_default=func.now())
    created_by = db.Column('created_by', db.ForeignKey('staff_account.id'))
    updated_at = db.Column('updated_at',
                           db.DateTime(timezone=True),
                           server_default=None)
    updated_by = db.Column('updated_by', db.ForeignKey('staff_account.id'))
    cancelled_at = db.Column('cancelled_at',
                             db.DateTime(timezone=True),
                             server_default=None)
    cancelled_by = db.Column('cancelled_by', db.ForeignKey('staff_account.id'))
    approved_by = db.Column('approved_by', db.ForeignKey('staff_account.id'))
    approved_at = db.Column('approved_at',
                            db.DateTime(timezone=True),
                            server_default=None)
    extra_items = db.Column('extra_items', db.JSON)
    note = db.Column('note', db.Text())
    google_event_id = db.Column('google_event_id', db.String(64))
    google_calendar_id = db.Column('google_calendar_id', db.String(255))
Exemplo n.º 11
0
class Alumni(db.Model):
    __tablename__ = "alumni"

    alumni_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    alumni_uuid = db.Column(db.String(50), unique=True)
    odoo_contact_id = db.Column(db.String(50), unique=True, nullable=False)
    email = db.Column(db.String(100), unique=True)
    password = db.Column(db.String(100))
    user_confirmed = db.Column(db.Boolean())
    allow_show_contacts = db.Column(db.Boolean())

    update_form = db.relationship("UpdateForm", back_populates="alumni")

    def __init__(self, odoo_contact_id, email, password, allow_show_contacts):
        self.alumni_uuid = str(uuid.uuid4())
        self.odoo_contact_id = odoo_contact_id
        self.email = email
        self.password = flask_bcrypt.generate_password_hash(password).decode()
        self.user_confirmed = False
        self.allow_show_contacts = allow_show_contacts

    def check_password(self, password):
        return flask_bcrypt.check_password_hash(self.password, password)
Exemplo n.º 12
0
class Section(BaseModel):

    __tablename__ = "sections"

    name = db.Column(db.Text)
    # One to many with Tasks
    tasks = db.relationship("Task", backref="section", lazy="dynamic")
    # Foreign key user_label_id
    user_label_id = db.Column(db.Integer, db.ForeignKey("user_labels.id"))

    def __init__(self, name, user_label_id):
        self.name = name
        self.user_label_id = user_label_id

    def create_section(section):
        db.session.add(section)
        db.session.commit()

    def __repr__(self) -> str:
        if self.tasks:
            return "Section with name ::: {} and tasks ::: {}".format(
                self.name, self.tasks)
        else:
            return "Section with name ::: {}".format(self.name)
Exemplo n.º 13
0
class User(db.Model, UserMixin):
    __tablename__ = 'sys_user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(80), unique=True, nullable=False, comment=u'用户名')
    password_hash = db.Column(db.String(128), comment="加密密码")
    email = db.Column(db.String(120), unique=True, comment=u'email')
    phone = db.Column(db.String(20), unique=True, comment=u'手机号码')
    avatar = db.Column(db.String(200), comment=u'头像')
    status = db.Column(db.Integer, default=1, comment=u'状态')
    lastLoginTime = db.Column(db.DATETIME, server_default=func.now(), comment=u'最后登录时间')
    createTime = db.Column(db.DATETIME, server_default=func.now(), comment=u'创建时间')
    createBy = db.Column(db.String(50), comment=u'创建人')
    updateTime = db.Column(db.DATETIME, server_default=func.now(), comment=u'修改时间')
    updateBy = db.Column(db.String(50), comment=u'修改人')

    roles = db.relationship(
        'Role',
        secondary=sys_user_role,
        backref=db.backref('users', lazy='dynamic')
    )

    @property
    def role_names(self):
        strs = ''
        for i in range(len(self.roles)):
            strs = strs + self.roles[i].name + ','
        return strs

    # @property
    # def permissions(self):
    #     permissions = Permission.query.join(sys_role_permission).join(Role).join(sys_user_role).join(User). \
    #         filter(
    #         User.id == self.id
    #     )
    #     return permissions

    @property
    def menus(self):
        menus = Menu.query.join(sys_role_menu).join(Role).join(sys_user_role).join(User). \
            filter(
            User.id == self.id
        ).order_by(Menu.type, Menu.order).all()
        return menus

    def check(self, action):
        permission = self.permissions.filter(Permission.action == action).first()
        return bool(permission)

    def __init__(self, username, password):
        self.username = username
        self.password = password

    def __init__(self, username, phone):
        self.username = username
        self.password = phone

    @property
    def password(self):
        return self.password_hash
        # raise AttributeError('不能直接获取明文密码!')

    @property
    def create_time(self):
        return self.createTime.strftime('%Y-%m-%d')

    # def auth(method):
    #     @functools.wraps(method)
    #     def wrapper(*args, **kwargs):
    #         user_id = session.get('user_id')
    #         if not user_id:
    #             return abort(403)
    #         return method(*args, **kwargs)
    #
    #     return wrapper

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

    def get_id(self):
        return self.username

    def update(self):
        globals.db.commit()

    def delete(self):
        globals.db.delete(self)
        globals.db.commit()

    def save(self):
        globals.db.add(self)
        globals.db.commit()
Exemplo n.º 14
0
class NodeModel(db.Model):
    __tablename__ = 'nodes'

    id = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String(200), nullable = False)
    address = db.Column(db.String(400), nullable = False)
    lat = db.Column(db.Float, nullable = False)
    long = db.Column(db.Float, nullable = False)
    manager = db.Column(db.String(200), nullable = False)
    key = db.Column(db.String(30), nullable = False)
    datas = db.relationship('DataNodesModel', backref='nodes')

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    @classmethod
    def return_all_public(cls):
        # fractal datas of node
        def to_json_data(data):
            return {
                'aqi': data.aqi,
                'pm25': data.pm25,
                'pm10': data.pm10,
                'created_at': data.created_at.strftime("%m/%d/%Y, %H:%M:%S")
            }
        # fractal nodes
        def to_json(x):
            return {
                'name': x.name,
                'address': x.address,
                'lat': x.lat,
                'long': x.long,
                'datas': list(map(lambda y: to_json_data(y), DataNodesModel.query.filter_by(node_id = x.id).limit(10).all()))
            }
        return {'nodes': list(map(lambda x: to_json(x), NodeModel.query.all()))}

    @classmethod
    def return_all_public_current(cls):
        # status air 1,2,3,4,5,6
        def air_status(data):
            if data <= 50:
                return {
                    "type": 1,
                    "info": "Tốt",
                    "infoEng": "Good"
                }
            elif data <= 100:
                return {
                    "type": 2,
                    "info": "Vừa phải",
                    "infoEng": "Moderate"
                }
            elif data <= 150:
                return {
                    "type": 3,
                    "info": "Không tốt cho sức khỏe với nhóm người nhạy cảm",
                    "infoEng": "Unhealthy for Sensitive Groups"
                }
            elif data <= 200:
                return {
                    "type": 4,
                    "info": "Ô nhiễm",
                    "infoEng": "Unhealthy"
                }
            elif data <= 300:
                return {
                    "type": 5,
                    "info": "Rất ô nhiễm",
                    "infoEng": "Very Unhealthy"
                }
            else:
                return {
                    "type": 6,
                    "info": "Nguy hiểm",
                    "infoEng": "Hazardous"
                }
        # fractal datas of node
        def to_json_data(data):
            return {
                'aqi': data.aqi,
                'pm25': data.pm25,
                'pm10': data.pm10,
                'status': air_status(data.aqi),
                'created_at': data.created_at.strftime("%m/%d/%Y, %H:%M:%S")
            }
        # fractal nodes
        def to_json(x):
            # time 24 hours ago
            data24h = db.session.execute('SELECT AVG(aqi) as aqi, AVG(pm25) as pm25, AVG(pm10) as pm10, \
                        HOUR(created_at) as created_at FROM datas \
                        WHERE node_id = :node_id AND DATE_SUB(`created_at`,INTERVAL 1 HOUR) And \
                        created_at > DATE_SUB(NOW(), INTERVAL 1 DAY) \
                        GROUP BY HOUR(created_at) ORDER BY id', {'node_id': x.id})
            if data24h.returns_rows == False:
                response_24h = []
            # Convert the response to a plain list of dicts
            else:
                response_24h = [dict(row.items()) for row in data24h]
            
            # time 7 days ago
            data7day = db.session.execute("SELECT AVG(aqi) as aqi, AVG(pm25) as pm25, AVG(pm10) as pm10, \
                        DATE_FORMAT(created_at, '%d/%m') as created_at FROM datas \
                        WHERE node_id = :node_id AND DATE_SUB(`created_at`, INTERVAL 7 DAY) And \
                        created_at > DATE_SUB(NOW(), INTERVAL 7 DAY) \
                        GROUP BY DATE_FORMAT(created_at, '%d/%m') ORDER BY id", {'node_id': x.id})
            if data7day.returns_rows == False:
                response_7day = []
            # Convert the response to a plain list of dicts
            else:
                response_7day = [dict(row.items()) for row in data7day]

            try:
                data = to_json_data(DataNodesModel.query.filter_by(node_id = x.id).order_by(DataNodesModel.created_at.desc()).first())
            except:
                data = ''
            return {
                'id': x.id,
                'name': x.name,
                'address': x.address,
                'lat': x.lat,
                'long': x.long,
                'data':  data,
                '_24h': json.loads(json.dumps(response_24h, default=defaultencode)),
                '_7day': json.loads(json.dumps(response_7day, default=defaultencode))
            }
        return {'nodes': list(map(lambda x: to_json(x), NodeModel.query.all()))}
    
    @classmethod
    def return_all_private(cls):
        def to_json(x):
            return {
                'id': x.id,
                'name': x.name,
                'address': x.address,
                'lat': x.lat,
                'long': x.long,
                'manager': x.manager,
                'key': x.key
            }
        return {'nodes': list(map(lambda x: to_json(x), NodeModel.query.all()))}

    @classmethod
    def find_by_key(cls, key):
        return cls.query.filter_by(key = key).first()

    @classmethod
    def find_by_id(cls, id):
        return cls.query.filter_by(id = id).first()
    
    @classmethod
    def get_json_node_by_id(cls, id):
        def to_json(x):
            return {
                'id': x.id,
                'name': x.name,
                'address': x.address,
                'lat': x.lat,
                'long': x.long,
                'manager': x.manager,
                'key': x.key
            }
        return {'data': to_json(cls.query.filter_by(id = id).first())}

    @classmethod
    def delete_by_id(cls, id):
        cls.query.filter_by(id = id).delete()
        db.session.commit()

    @staticmethod
    def randomString(stringLength):
        letters = string.ascii_letters
        return ''.join(random.choice(letters) for i in range(stringLength))
Exemplo n.º 15
0
class Content(db.Model):
    __tablename__ = 'content'

    # DATA COLUMNS
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    body = db.Column(db.Text(4294000000), nullable=False)
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)

    # FOREIGN KEYS COLUMNS
    author_id = db.Column(db.String(255),
                          db.ForeignKey('user.id'),
                          nullable=False)

    # RELATIONSHIPS
    author = db.relationship('User',
                             back_populates='published_content',
                             lazy=True)
    comments = db.relationship('Comment',
                               back_populates='commented_content',
                               lazy='dynamic',
                               foreign_keys='Comment.commented_content_id',
                               cascade="delete")
    likes = db.relationship('Likes',
                            back_populates='content',
                            lazy='dynamic',
                            cascade="delete")
    dislikes = db.relationship('Dislikes',
                               back_populates='content',
                               lazy='dynamic',
                               cascade="delete")

    @hybrid_property
    def comments_num(self):
        sum = self.comments.count()
        if sum > 0:
            for content in self.comments.all():
                sum += content.comments_num
        return sum

    @hybrid_property
    def likes_num(self):
        return self.likes.count()

    @hybrid_property
    def dislikes_num(self):
        return self.dislikes.count()

    @hybrid_method
    def liked(self, user):
        return db.session.query(
            Content.query.filter(Content.id == self.id).join(Likes).filter(
                Likes.user_id == user.id).exists()).scalar()

    @hybrid_method
    def disliked(self, user):
        return db.session.query(
            Content.query.filter(Content.id == self.id).join(Dislikes).filter(
                Dislikes.user_id == user.id).exists()).scalar()

    @staticmethod
    def get_content_with_user_data(content_query, user):
        return content_query.outerjoin(Likes).filter(
            or_(Likes.user_id == user.id,
                Likes.user_id == None)).outerjoin(Dislikes).filter(
                    or_(Dislikes.user_id == user.id,
                        Dislikes.user_id == None)).with_entities(
                            Content,
                            cast(func.count(Likes.user_id),
                                 sqlalchemy.Boolean).label('liked'),
                            cast(func.count(Dislikes.user_id),
                                 sqlalchemy.Boolean).label(
                                     'disliked')).group_by(Content.id)

    # INHERITANCE
    type = db.Column(db.String(255))
    __mapper_args__ = {
        'polymorphic_identity': 'content',
        'polymorphic_on': type
    }
Exemplo n.º 16
0
class User(db.Model, UserMixin):
    """
    Description of User model.
    Columns
    -----------
    :id: int [pk]
    :username: varchar(128) [not NULL]
    :password: varchar(128) [not NULL]
    :first_name: varchar(255) [not NULL]
    :last_name: varchar(255)
    :dob: date
    :email: varchar(255) [not NULL]
    :fb_handle: varchar(255)
    :g_handle: varchar(255)
    :medium_handle: varchar(255)
    :twitter_handle: varchar(255)
    :linkedin_handle: varchar(255)
    :bio: text
    :occupation: varchar(255)
    :profile_picture: int
    :last_login: timestamp
    :creation_time: timestamp
    :is_verified: boolean
    """

    # Columns
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(128), unique=True, nullable=False)
    password = db.Column(db.String(128), nullable=False)
    first_name = db.Column(db.String(255), default="")
    last_name = db.Column(db.String(255), default="")
    dob = db.Column(db.DateTime)
    email = db.Column(db.String(255), nullable=False)
    fb_handle = db.Column(db.String(255))
    g_handle = db.Column(db.String(255))
    medium_handle = db.Column(db.String(255))
    twitter_handle = db.Column(db.String(255))
    linkedin_handle = db.Column(db.String(255))
    profile_picture = db.Column(db.Integer)
    bio = db.Column(db.Text)
    occupation = db.Column(db.String(255))
    last_login = db.Column(db.DateTime)
    creation_time = db.Column(db.DateTime)
    is_verified = db.Column(db.Boolean, default=False)

    # Relationships
    tags = db.relationship('Tag', secondary=userTagJunction, lazy='subquery',
                           backref=db.backref("users", lazy=True))

    saves = db.relationship('Post', secondary=userPostInteraction, lazy=True,
                            backref=db.backref("savers", lazy=True))

    payments = db.relationship('Payment', backref='user', lazy=True)

    def __init__(self, username, password, email):
        self.username = username
        self.password = generate_password_hash(password)
        self.email = email
        self.is_verified = False
        self.profile_picture = 1

        db.session.add(self)
        db.session.commit()

    @staticmethod
    @login_manager.user_loader
    def load_user(id):
        return User.query.filter_by(id=id).first()

    def update_col(self, key, value):
        self.__dict__[key] = value
        db.session.commit()

    def check_password(self, password):
        return check_password_hash(self.password, password)

    def resetPassword(self, newPassword):
        # Pass in a hashed password
        self.password = generate_password_hash(newPassword)
        db.session.commit()

    def addPayment(self, data):
        pay = Payment(self, data.get("amount"), data.get("api_response"))
        self.payments.append(pay)
        db.session.commit()

    def get_id(self):
        return self.id

    # We do not need to implement update metadata.
    # Actually, it can be updated ad hoc by assignment without calling commit.
    def isVerified(self):
        return self.is_verified

    def setVerified(self):
        self.is_verified = True
        db.session.commit()

    def setNewTag(self, tag):
        self.tags.append(tag)
        db.session.commit()

    def setTagPriority(self, tag, priority):
        result = self.getTagPriority(tag)

        if result is None:
            self.setNewTag(tag)

        s = userTagJunction.update().\
            values(priority=PriorityType(priority)).\
            where(and_(
                userTagJunction.c.user_id == self.id,
                userTagJunction.c.keyword_id == tag.id))

        db.session.execute(s)
        db.session.commit()

    def getTagPriority(self, tag):
        s = select([userTagJunction]).where(and_(
            userTagJunction.c.user_id == self.id,
            userTagJunction.c.keyword_id == tag.id))
        result = list(db.session.execute(s))
        try:
            return result[0]["priority"]
        except IndexError:
            return None

    def savePost(self, post):
        if post not in self.saves:
            self.saves.append(post)
        else:
            self.saves.remove(post)
        db.session.commit()

    def ratePost(self, post, rating):
        try:
            s = userPostInteraction.update().\
                where(user_id=self.id, post_id=post.post_id).\
                values(rating=rating)
            db.session.execute(s)
        except BaseException:
            # User has not yet saved the post so there is no entry here
            s = userPostInteraction.insert().\
                values(save=False, rating=rating,
                       user_id=self.id, post_id=post.post_id)
            db.session.execute(s)
        finally:
            db.session.commit()
Exemplo n.º 17
0
class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))
    posts = db.relationship("Post", backref="author", lazy="dynamic")
    comments = db.relationship("Comment", backref="author", lazy="dynamic")
    about_me = db.Column(db.String(140))
    last_seen = db.Column(db.DateTime, default=datetime.utcnow)
    followed = db.relationship(
        "User",
        secondary=followers,
        primaryjoin=(followers.c.follower_id == id),
        secondaryjoin=(followers.c.followed_id == id),
        backref=db.backref("followers", lazy="dynamic"),
        lazy="dynamic",
    )
    posts_liked = db.relationship(
        "Post",
        secondary=likes,
        primaryjoin=(likes.c.user_id == id),
        secondaryjoin=(likes.c.post_id == id),
        backref=db.backref("likes", lazy="dynamic"),
        lazy="dynamic",
    )
    messages_sent = db.relationship('Message', foreign_keys='Message.sender_id', backref='author', lazy='dynamic')
    messages_received = db.relationship('Message', foreign_keys='Message.recipient_id', backref='recipient', lazy='dynamic')
    last_message_read_time = db.Column(db.DateTime)
    notifications = db.relationship('Notification', backref='user', lazy='dynamic')

    def __repr__(self):
        return f"<User: {self.username}>"

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def avatar(self, size):
        digest = md5(self.email.lower().encode("utf-8")).hexdigest()
        return f"https://www.gravatar.com/avatar/{digest}?d=identicon&s={size}"

    def follow(self, user):
        if not self.is_following(user):
            self.followed.append(user)

    def unfollow(self, user):
        if self.is_following(user):
            self.followed.remove(user)

    def is_following(self, user):
        return self.followed.filter(followers.c.followed_id == user.id).count() > 0

    def followed_posts(self):
        followed = Post.query.join(
            followers, (followers.c.followed_id == Post.user_id)
        ).filter(followers.c.follower_id == self.id)
        return followed.union(self.posts).order_by(Post.timestamp.desc())
    
    def like_post(self, post):
        if not self.like_post.liked(post):
            self.posts_liked.append(post)
    
    def unlike_post(self, post):
        if self.liked(post):
            self.like_post.remove(post)
    
    def liked(self, post):
        return self.posts_liked.filter(likes.c.post_id==post.id).count() > 0

    def get_reset_password_token(self, expires_in=600):
        return jwt.encode(
            {"reset_password": self.id, "exp": time() + expires_in},
            current_app.config["SECRET_KEY"],
            algorithm="HS256",
        )

    @staticmethod
    def verify_reset_password_token(token):
        try:
            id = jwt.decode(
                token, current_app.config["SECRET_KEY"], algorithms=["HS256"]
            )["reset_password"]
        except:
            return
        return User.query.get(id)

    def new_messages(self):
        last_read_time = self.last_message_read_time or datetime(1900, 1, 1)
        return Message.query.filter_by(recipient=self).filter(
            Message.timestamp > last_read_time
        ).count()
    
    def add_notification(self, name, data):
        self.notifications.filter_by(name=name).delete()
        n = Notification(name=name, payload_json=json.dumps(data), user=self)
        db.session.add(n)
        return n
    
    def notify_followers(self, name, data):
        for follower in self.followers:
            follower.notifications.filter_by(name=name).delete()
            follower.add_notification(name, data)
Exemplo n.º 18
0
class sdLed(db.Model):
    __tablename__ = "sd32_leds"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(20), comment="Name")
    display_name = db.Column(db.String(50), comment="Display name")
    comment = db.Column(db.Text, comment="Comment")
    create_time = db.Column(db.DateTime,
                            server_default=func.now(),
                            comment="Create time")
    update_time = db.Column(db.DateTime,
                            server_default=func.now(),
                            comment="Update time")
    cust_id = db.Column(db.Integer,
                        db.ForeignKey(sdCustomer.id),
                        comment="Customer id")
    status = db.Column(
        db.Integer,
        server_default="0",
        comment="Device status flag. bit 0: warning, bit 1: error")
    model_id = db.Column(db.Integer,
                         db.ForeignKey(sdDeviceModel.id),
                         server_default="0",
                         comment="Traffic Light model/part no")
    serial_no = db.Column(db.String(50), nullable=False, comment="Serial No")
    device = db.relationship("sdDevice", uselist=False, backref="led")

    __table_args__ = (db.UniqueConstraint("serial_no"),
                      db.UniqueConstraint("cust_id", "name"))

    def __repr__(self):
        return f"<sdLed id={self.id}/name={self.name}/display_name={self.display_name}/sn={self.serial_no}>"

    @staticmethod
    def add(cust_id, led):
        model = db.session.query(sdDeviceModel) \
            .filter(sdDeviceModel.name == led.get("model_name")).first()
        obj = sdLed()
        obj.cust_id = cust_id
        obj.name = led.get("name")
        obj.display_name = led.get("display_name")
        obj.comment = led.get("comment")
        obj.model = model
        obj.serial_no = led.get("serial_no")
        return obj

    @staticmethod
    def update(cust_id, led):
        model = db.session.query(sdDeviceModel) \
            .filter(sdDeviceModel.name == led.get("model_name")).first()
        sdn = led["serial_no"]
        obj = db.session.query(sdLed).filter(sdLed.serial_no == sdn).first()
        if obj:
            obj.cust_id = cust_id
            obj.name = led.get("name")
            obj.display_name = led.get("display_name")
            obj.comment = led.get("comment")
            obj.model = model
            obj.serial_no = led.get("serial_no")
        else:
            obj = sdLed.add(cust_id, led)
        return obj
Exemplo n.º 19
0
class Category(db.Model):
    __tablename__ = 'categories'

    id = db.Column(db.Integer, primary_key=True)
    type = db.Column(db.String, nullable=False)
    questions = db.relationship('Question', backref='cat', lazy=True)
Exemplo n.º 20
0
class sdCustomer(db.Model):
    __tablename__ = "sd10_customers"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(20),
                     unique=True,
                     nullable=False,
                     index=True,
                     comment="Name")
    display_name = db.Column(db.String(50),
                             nullable=False,
                             comment="Display name")
    comment = db.Column(db.Text, comment="Comment")
    status = db.Column(db.Integer,
                       nullable=False,
                       server_default="0",
                       comment="Status")
    create_time = db.Column(db.DateTime,
                            nullable=False,
                            server_default=func.now(),
                            comment="Create time")
    update_time = db.Column(db.DateTime,
                            nullable=False,
                            server_default=func.now(),
                            comment="Update time")
    cust_id = db.Column(db.Integer,
                        db.ForeignKey("sd10_customers.id"),
                        comment="Vendor of customer")

    vendors = db.relationship("sdCustomer", lazy="dynamic")
    users = db.relationship("sdUser", backref="cust", lazy="dynamic")
    controllers = db.relationship("sdController",
                                  backref="cust",
                                  lazy="dynamic")
    leds = db.relationship("sdLed", backref="cust", lazy="dynamic")
    device_groups = db.relationship("sdDeviceGroup",
                                    backref="cust",
                                    lazy="dynamic")
    schedules = db.relationship("sdSchedule", backref="cust", lazy="dynamic")
    codes = db.relationship("sdCode", backref="cust", lazy="dynamic")
    user_groups = db.relationship("sdUserGroup",
                                  backref="cust",
                                  lazy="dynamic")
    status_privilege = db.relationship("sdStatusPrivilege",
                                       backref="cust",
                                       lazy="dynamic")
    device_info = db.relationship("sdDeviceInfo",
                                  backref="cust",
                                  lazy="dynamic")

    cust_devices = db.relationship("sdDevice",
                                   foreign_keys="sdDevice.cust_id",
                                   backref="cust",
                                   lazy="dynamic")
    vendor_devices = db.relationship("sdDevice",
                                     foreign_keys="sdDevice.vendor_id",
                                     backref="vendor",
                                     lazy="dynamic")

    def __repr__(self):
        return f"<sdCustomer id={self.id}/name={self.name}/display_name={self.display_name}>"

    @staticmethod
    def search(cust_id):
        customer = db.session.query(
            sdCustomer.id).filter(sdCustomer.id == cust_id).first()
        return customer

    @staticmethod
    def search_by_name(cust_name):
        customer = sdCustomer.query.filter_by(name=cust_name).first()
        return customer

    @staticmethod
    def search_cust(cust_id):
        customer = db.session.query(sdCustomer).filter(
            sdCustomer.id == cust_id, sdCustomer.cust_id.is_(None)).all()
        return customer

    @staticmethod
    def get_vendors(cust_id):
        vendors = db.session.query(sdCustomer).filter(
            sdCustomer.cust_id == cust_id).all()
        return vendors

    @staticmethod
    def search_cust_obj(cust_id):
        customer = db.session.query(sdCustomer).filter(
            sdCustomer.id == cust_id).first()
        return customer
Exemplo n.º 21
0
class Post(Base, SearchableMixin):
    """
    Description of User model.
    Columns
    -----------
    :id: int [pk]
    :title: Text [not NULL]
    :author_id: int [Foreign Key]
    :creation_time: DateTime [not NULL]
    :last_edit_time: DateTime [not NULL]
    :post_body: Text

    # Relationships
    :comments: Relationship -> Comments (one to many)
    """
    # Columns
    id = db.Column(db.Integer, db.ForeignKey("base.id"), primary_key=True)
    post_id = db.Column(db.Integer,
                        autoincrement=True,
                        primary_key=True,
                        unique=True)
    title = db.Column(db.Text, nullable=False)

    post_movie = db.Column(db.String(20))

    tags = db.Column(db.JSON)

    __searchable__ = ['title', 'body', 'tags']

    __mapper_args__ = {
        'polymorphic_identity': 'post',
        'inherit_condition': (id == Base.id)
    }

    comments = db.relationship(
        'Comment',
        primaryjoin="(Post.post_id == Comment.parent_post_id)",
        backref=db.backref('post'),
        lazy='dynamic')

    def __init__(self, author_id, post_movie, title, post_body, tags):
        super().__init__(author_id, post_body, "post")
        self.title = title
        self.post_movie = post_movie
        self.tags = tags
        db.session.add(self)
        db.session.commit()

    def add_comment(self, author_id, comment_body):
        parent_post_id = self.id
        comment = Comment(author_id, parent_post_id, comment_body)
        self.comments.append(comment)
        db.session.commit()

        return comment.id

    def update_col(self, key, value):
        setattr(self, key, value)
        db.session.commit()

    def delete_post(self, post_id):
        post = Post.query.filter_by(id=post_id).delete()
        db.session.commit()
Exemplo n.º 22
0
class sdUserGroup(db.Model):
    __tablename__ = "sd13_user_groups"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(20), comment="Name", nullable=False)
    display_name = db.Column(db.String(50), comment="Display name")
    comment = db.Column(db.Text, comment="Comment")
    create_time = db.Column(db.DateTime, server_default=func.now(), comment="Create time")
    update_time = db.Column(db.DateTime, server_default=func.now(), comment="Update time")
    cust_id = db.Column(db.Integer, db.ForeignKey("sd10_customers.id"), comment="Customer id")

    rel_dg_ug = db.relationship('sdDeviceGroup', secondary=rel_dg_ug, backref='user_groups')
    rel_u_ug = db.relationship('sdUser', secondary=rel_u_ug, backref='user_groups')
    rel_role_ug = db.relationship('sdRole', secondary=rel_role_ug, backref='user_groups')

    __table_args__ = (db.UniqueConstraint("cust_id", "name"),)

    def __repr__(self):
        return f"<sdUserGroup id={self.id}/name={self.name}/display_name={self.display_name}/cust_id={self.cust_id}"

    @staticmethod
    def getall(cust_id):
        usergroups = db.session.query(sdUserGroup).filter(sdUserGroup.cust_id == cust_id).all()
        return usergroups

    @staticmethod
    def add(cust_id, name, display_name, comment):
        obj = sdUserGroup()
        obj.cust_id = cust_id
        obj.name = name
        obj.display_name = display_name
        obj.comment = comment
        return obj

    # delete_all_users: delete all users, device groups record corresponding to the user group from m2m table
    @staticmethod
    def delete_all_users(cust_id, user_list):
        user_groups = db.session.query(sdUserGroup).filter(sdUserGroup.cust_id == cust_id,
                                                           sdUserGroup.id.in_(user_list)).all()
        # TAG clear() attribute is active only without lazy = dynamic
        for user_group in user_groups:
            dg_rels = user_group.rel_dg_ug
            dg_rels.clear()
            u_rels = user_group.rel_u_ug
            u_rels.clear()
            role_rels = user_group.rel_role_ug
            role_rels.clear()

    @staticmethod
    def delete(cust_id, user_list):
        sdUserGroup.query.filter(sdUserGroup.cust_id == cust_id,
                                 sdUserGroup.id.in_(user_list)).delete(synchronize_session=False)

    @staticmethod
    def update(cust_id, group_id, new_name, new_display_name, new_comment):
        obj = db.session.query(sdUserGroup).filter(sdUserGroup.cust_id == cust_id, sdUserGroup.id == group_id).first()
        obj.name = new_name if new_name else obj.name
        obj.display_name = new_display_name if new_display_name else obj.display_name
        obj.comment = new_comment if new_comment else obj.comment
        return obj

    # user join user group
    @staticmethod
    def join_users(cust_id, user_group_id, user_list):
        selected_user_group = db.session.query(sdUserGroup).filter(
            sdUserGroup.id == user_group_id, sdUserGroup.cust_id == cust_id).first()
        query_obj = db.session.query(sdUser).filter(sdUser.id.in_(user_list), sdUser.cust_id == cust_id).all()
        selected_user_group.rel_u_ug.extend(query_obj)

    # user leave user group
    @staticmethod
    def leave_users(user_group_id, user_list):
        db.session.query(rel_u_ug).filter(rel_u_ug.c.user_group_id == user_group_id).\
            filter(rel_u_ug.c.user_id.in_(user_list)).\
            delete(synchronize_session=False)

    @staticmethod
    def get_status_privilege(usergroup_obj, cust_id, flag, priv_set):
        # status_privilege = []
        for ug_obj in usergroup_obj:
            # get roles of user group
            role_ug = ug_obj.rel_role_ug
            for role in role_ug:
                # get status privilege of role, filter cust_id
                status_privilege = sdStatusPrivilege.get_privilege(role.id, cust_id)
                if flag == 2:
                    for priv_obj in status_privilege:
                        # get status tuple
                        priv_set.add(priv_obj.status_to)
                else:
                    for priv_obj in status_privilege:
                        # get status tuple
                        priv_set.add((str(priv_obj.status_from), str(priv_obj.status_to)))

        return priv_set

    @staticmethod
    def give_user_id_get_roles(user_id):
        user_obj = db.session.query(sdUser).filter(sdUser.id == user_id).first()
        # get user groups of users
        usergroup_obj = user_obj.user_groups
        role_set = set()

        # Gathering data from models using relationship
        for ug_obj in usergroup_obj:
            # get roles of user group
            role_ug = ug_obj.rel_role_ug
            for role in role_ug:
                # get privilege of role
                role_set.add(role.id)
        return role_set

    @staticmethod
    def give_user_id_get_auths(user_id, flag, cust_id=None):
        user_obj = db.session.query(sdUser).filter(sdUser.id == user_id).first()
        # get user groups of users
        usergroup_obj = user_obj.user_groups
        priv_set = set()

        # Gathering data from models using relationship
        if flag == 0:
            for ug_obj in usergroup_obj:
                # get roles of user group
                role_ug = ug_obj.rel_role_ug
                for role in role_ug:
                    # get privilege of role
                    priv = role.privileges
                    for route in priv:
                        # get api route
                        priv_set.add(route.api_route)
        else:
            priv_set = sdUserGroup.get_status_privilege(usergroup_obj, cust_id, flag, priv_set)
        return priv_set
Exemplo n.º 23
0
class LogEntity(db.Model, CRUDMixin):
    """ Keep track of important user actions """
    __tablename__ = 'Log'

    id = db.Column('logID', db.Integer, primary_key=True)
    type_id = db.Column('logtID',
                        db.Integer,
                        db.ForeignKey('LogType.logtID'),
                        nullable=False)
    web_session_id = db.Column('webID',
                               db.Integer,
                               db.ForeignKey('WebSession.webID'),
                               nullable=False)
    date_time = db.Column('logDateTime',
                          db.DateTime,
                          nullable=False,
                          server_default='0000-00-00 00:00:00')
    details = db.Column('logDetails', db.Text, nullable=False)

    # @OneToOne
    log_type = db.relationship(LogTypeEntity, uselist=False, lazy='joined')
    web_session = db.relationship(WebSessionEntity,
                                  uselist=False,
                                  lazy='joined')

    @staticmethod
    def get_logs(per_page=25, page_num=1):
        """
        Helper for formating the event details
        """
        def item_from_entity(entity):
            return {
                'id':
                entity.id,
                'user_email':
                entity.web_session.user.email
                if entity.web_session.user is not None else '',
                'type':
                entity.log_type.type,
                'details':
                entity.details,
                'web_session_ip':
                entity.web_session.ip,
                'date_time':
                utils.localize_est_datetime(entity.date_time),
            }

        pagination = LogEntity.query.paginate(page_num, per_page, False)
        items = map(item_from_entity, pagination.items)
        return items, pagination.pages

    @staticmethod
    def _log(log_type, session_id, details=''):
        """ Helper for logging """
        logt = LogTypeEntity.query.filter_by(type=log_type).first()
        if logt is None:
            app.logger.error(
                "Developer error. Invalid log type: {}".format(log_type))
            return

        web_session = WebSessionEntity.get_by_session_id(session_id)
        if web_session is None:
            app.logger.error(
                "Developer error. Invalid session id: {}".format(session_id))
            return

        LogEntity.create(log_type=logt,
                         date_time=datetime.datetime.now(),
                         details=details,
                         web_session=web_session)

    @staticmethod
    def account_created(session_id, details=''):
        """ Log account creation """
        LogEntity._log(LOG_TYPE_ACCOUNT_CREATED, session_id, details)

    @staticmethod
    def login(session_id, details=''):
        """ Log successful login """
        LogEntity._log(LOG_TYPE_LOGIN, session_id, details)

    @staticmethod
    def logout(session_id, details=''):
        """ Log logout click """
        LogEntity._log(LOG_TYPE_LOGOUT, session_id, details)

    @staticmethod
    def login_error(session_id, details=''):
        """ Log failed login """
        LogEntity._log(LOG_TYPE_LOGIN_ERROR, session_id, details)

    @staticmethod
    def account_modified(session_id, details=''):
        """ Log account changes """
        LogEntity._log(LOG_TYPE_ACCOUNT_MODIFIED, session_id, details)

    def __repr__(self):
        """ Return a friendly object representation """
        return "<LogEntity(logID: {0.id}, "\
            "logtID: {0.type_id}" \
            "webID: {0.web_session_id}, "\
            "date_time: {0.date_time})>".format(self)
Exemplo n.º 24
0
class Recipe(db.Model):
    __tablename__ = "recipes"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text(), nullable=False)
    description = db.Column(db.Text(), nullable=False)
    steps = db.Column(db.Text(), nullable=False)
    account_id = db.Column(db.Integer, db.ForeignKey(
        "accounts.id",
        ondelete="CASCADE",
    ), nullable=False, index=True)

    ingredient_amounts = db.relationship(
        "RecipeIngredient", backref="recipe", lazy=True,
        passive_deletes=True)

    def __init__(self, name, description, steps):
        self.name = name
        self.description = description
        self.steps = steps

    def get_ingredients(self):
        stmt = text("""
SELECT
    ri.amount AS amount,
    ri.amount_unit AS amount_unit,
    ri.group_name AS group_name,
    i.id AS id,
    i.name AS name
FROM ingredients i, recipe_ingredient ri
WHERE
    ri.recipe_id = :recipe_id
    AND i.account_id = :account_id
    AND ri.ingredient_id = i.id
ORDER BY ri.id
""").bindparams(recipe_id=self.id, account_id=self.account_id)
        return db.session().execute(stmt)

    def get_shopping_list_amounts(self):
        stmt = text("""
SELECT
    i.id AS id,
    SUM(sli.amount) AS amount,
    sli.amount_unit AS unit
FROM (
    SELECT DISTINCT
        i.id AS id,
        i.name AS name
    FROM ingredients i, recipe_ingredient ri
    WHERE
        i.account_id = :account_id
        AND i.id = ri.ingredient_id
        AND ri.recipe_id = :recipe_id
) i
LEFT JOIN shopping_list_items sli
ON sli.ingredient_id = i.id
WHERE sli.account_id = :account_id
GROUP BY i.id, sli.amount_unit
""").bindparams(recipe_id=self.id, account_id=self.account_id)
        return db.session().execute(stmt)

    def insert_ingredients_from_form(self, form):
        ingredients = []
        missing_ingredients = []
        ingredients_by_name = {}
        for recipe_ingredient_form in form.ingredient_amounts:
            name = recipe_ingredient_form.data["name"].strip()
            lower_name = name.lower()
            existing_ingredient = ingredients_by_name.get(lower_name)
            if not existing_ingredient:
                existing_ingredient = Ingredient.query.filter(
                    Ingredient.account_id == self.account_id,
                    func.lower(Ingredient.name) == lower_name,
                ).first()
                if not existing_ingredient:
                    existing_ingredient = Ingredient(name)
                    existing_ingredient.account_id = self.account_id
                    missing_ingredients.append(existing_ingredient)
                ingredients_by_name[lower_name] = existing_ingredient
            ingredients.append(existing_ingredient)
        db.session().bulk_save_objects(missing_ingredients, return_defaults=True)
        db.session().flush()

        recipe_ingredients = []
        for index, recipe_ingredient_form in enumerate(form.ingredient_amounts):
            amount, unit = recipe_ingredient_form.parse_amount()
            recipe_ingredients.append(RecipeIngredient(
                amount=amount,
                amount_unit=unit,
                ingredient_id=ingredients[index].id,
                recipe_id=self.id,
                group_name=recipe_ingredient_form.group.data,
            ))
        db.session().bulk_save_objects(recipe_ingredients)
        db.session().flush()
class User(db.Model):
    __tablename__ = 'user'

    # DATA COLUMNS
    id = db.Column(db.String(255), primary_key=True, autoincrement=False)
    display_name = db.Column(db.String(255), unique=True, nullable=True)
    registered_on = db.Column(db.DateTime, default=datetime.utcnow)

    # RELATIONSHIPS
    published_content = db.relationship('Content',
                                        back_populates='author',
                                        lazy='dynamic')
    liked_content = db.relationship('Likes',
                                    back_populates='user',
                                    lazy='dynamic')
    disliked_content = db.relationship('Dislikes',
                                       back_populates='user',
                                       lazy='dynamic')
    followed_courses = db.relationship('Course',
                                       secondary=user_follows_course,
                                       back_populates='followers',
                                       lazy='dynamic')
    groups = db.relationship('GroupMember',
                             back_populates='user',
                             lazy='dynamic')
    sent_messages = db.relationship('Message',
                                    back_populates='sender_user',
                                    lazy='dynamic')
    chats_with_users = db.relationship('UsersChat',
                                       back_populates='of_user',
                                       foreign_keys='UsersChat.of_user_id',
                                       lazy='dynamic')
    group_invites = db.relationship('GroupInvite',
                                    foreign_keys='GroupInvite.invited_id',
                                    back_populates='invited',
                                    lazy='dynamic')
    devices_tokens = db.relationship('DeviceToken',
                                     back_populates='user',
                                     lazy='dynamic')

    @hybrid_property
    def joined_groups(self):
        return self.groups.join(Group).with_entities(Group)

    @hybrid_property
    def published_posts(self):
        return self.published_content.filter(Content.type == 'post')

    @hybrid_property
    def published_reviews(self):
        return self.published_content.filter(Content.type == 'review')

    @hybrid_property
    def published_comments(self):
        return self.published_content.filter(Content.type == 'comment')

    @hybrid_property
    def get_posts_feed(self):
        joined_groups_sq = self.joined_groups.subquery('joined_groups', True)
        followed_courses_sq = self.followed_courses.subquery(
            'followed_courses', True)

        return Post.query.join(
            joined_groups_sq,
            Post.posted_to_board_id == joined_groups_sq.c.group_id).union(
                Post.query.join(
                    followed_courses_sq, Post.posted_to_board_id ==
                    followed_courses_sq.c.course_id)).union(
                        Post.query.filter(Post.posted_to_board_id == None))

    @hybrid_method
    def chat_with_user(self, other_user):
        other_user_chats = other_user.chats_with_users.subquery(
            'other_user_chats', True)

        return self.chats_with_users.join(
            other_user_chats, UsersChat.other_user_chat_id ==
            other_user_chats.c.users_chat_id).with_entities(UsersChat)
class Synonym(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    synonym = db.Column(db.String(255), unique=True, nullable=False)
    snapshots = db.relationship("Snapshot", back_populates="synonym")
Exemplo n.º 27
0
class Account(db.Model):
    __tablename__ = "accounts"

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.Text, nullable=False, unique=True)
    password_hash = db.Column(db.Text, nullable=False)
    role = db.Column(db.Text, nullable=False)

    valid_roles = {"user", "admin"}

    recipes = db.relationship("Recipe",
                              backref="account",
                              lazy=True,
                              passive_deletes=True)
    ingredients = db.relationship("Ingredient",
                                  backref="account",
                                  lazy=True,
                                  passive_deletes=True)
    shopping_list_items = db.relationship("ShoppingListItem",
                                          backref="account",
                                          lazy=True,
                                          passive_deletes=True)

    def is_admin(self):
        return self.role == "admin"

    def get_id(self):
        return str(self.id)

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def is_authenticated(self):
        return True

    def fullfills_role(self, role):
        """
        Checks if this Account fullfills `role`.

        The role "user" is fullfilled by roles "user" and "admin". The role
        "admin" is fullfilled by role "admin".
        """
        if self.role == role:
            return True
        return self.role == "admin" and role == "user"

    @staticmethod
    def get_top_recipe_collectors(count):
        stmt = text("""
SELECT accounts.username username, COUNT(recipes.id) recipe_count
FROM accounts
LEFT JOIN recipes ON recipes.account_id = accounts.id
GROUP BY accounts.username
ORDER BY COUNT(recipes.id) DESC, accounts.username
LIMIT :count
""").params(count=count)
        rows = db.session().execute(stmt)
        try:
            return rows.fetchall()
        finally:
            rows.close()

    @staticmethod
    def is_username_taken(username):
        return db.session().query(
            exists().where(Account.username == username)).scalar()
Exemplo n.º 28
0
class Content(db.Model):
    __tablename__ = "CONTENT"
    id = db.Column(db.String(32), primary_key=True)
    companies = db.relationship("Company",
                                secondary=association_table,
                                back_populates="contents")
Exemplo n.º 29
0
class Apartment(db.Model):
    __tablename__ = 'apartment'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column('title', db.String)
    created_at = db.Column('created_at', db.DateTime)
    price_usd = db.Column('price_usd', db.Integer)
    price_uah = db.Column('price_uah', db.Integer)
    description = db.Column('description', db.Text)
    street_name = db.Column('street_name', db.String, nullable=True)
    state_name = db.Column('state_name', db.String, nullable=True)
    city_name = db.Column('city_name', db.String, nullable=True)
    total_square_meters = db.Column('total_square_meters',
                                    db.Float,
                                    nullable=True)
    living_square_meters = db.Column('living_square_meters',
                                     db.Float,
                                     nullable=True)
    kitchen_square_meters = db.Column('kitchen_square_meters',
                                      db.Float,
                                      nullable=True)
    rooms_count = db.Column('rooms_count', db.Integer, nullable=True)
    floor = db.Column('floor', db.String, nullable=True)
    floors_count = db.Column('floors_count', db.String, nullable=True)
    wall_type = db.Column('wall_type', db.String, nullable=True)
    inspected = db.Column('inspected', db.String, nullable=True)
    verified_price = db.Column('verified_price', db.String, nullable=True)
    latitude = db.Column('latitude', db.Float, nullable=True)
    longitude = db.Column('longitude', db.Float, nullable=True)
    construction_year = db.Column('construction_year',
                                  db.String,
                                  nullable=True)
    heating = db.Column('heating', db.String, nullable=True)
    seller = db.Column('seller', db.String, nullable=True)
    water = db.Column('water', db.String, nullable=True)
    building_condition = db.Column('building_condition',
                                   db.String,
                                   nullable=True)
    dist_to_center = db.Column('dist_to_center', db.String, nullable=True)
    dist_to_railway_station = db.Column('dist_to_railway_station',
                                        db.String,
                                        nullable=True)
    dist_to_airport = db.Column('dist_to_airport', db.String, nullable=True)
    images = db.relationship("ApartmentImage")
    seller_info = db.relationship("SellerInfo", uselist=False)

    def __init__(self,
                 title,
                 created_at,
                 price_usd,
                 price_uah,
                 description,
                 street_name=None,
                 state_name=None,
                 city_name=None,
                 total_square_meters=None,
                 living_square_meters=None,
                 kitchen_square_meters=None,
                 rooms_count=None,
                 floor=None,
                 floors_count=None,
                 wall_type=None,
                 inspected=None,
                 verified_price=None,
                 latitude=None,
                 longitude=None,
                 construction_year=None,
                 heating=None,
                 seller=None,
                 water=None,
                 building_condition=None,
                 dist_to_center=None,
                 dist_to_railway_station=None,
                 dist_to_airport=None):
        self.title = title
        self.created_at = created_at
        self.price_usd = price_usd
        self.price_uah = price_uah
        self.description = description
        self.street_name = street_name
        self.state_name = state_name
        self.city_name = city_name
        self.total_square_meters = total_square_meters
        self.living_square_meters = living_square_meters
        self.kitchen_square_meters = kitchen_square_meters
        self.rooms_count = rooms_count
        self.floor = floor
        self.floors_count = floors_count
        self.wall_type = wall_type
        self.inspected = inspected
        self.verified_price = verified_price
        self.latitude = latitude
        self.longitude = longitude
        self.construction_year = construction_year
        self.heating = heating
        self.seller = seller
        self.water = water
        self.building_condition = building_condition
        self.dist_to_airport = dist_to_airport
        self.dist_to_center = dist_to_center
        self.dist_to_railway_station = dist_to_railway_station

    @property
    def serialize(self):
        return {
            'title': self.title,
            'created_at': self.created_at,
            'price_usd': self.price_usd,
            'price_uah': self.price_uah,
            'description': self.description,
            'street_name': self.street_name,
            'state_name': self.state_name,
            'city_name': self.city_name,
            'total_square_meters': self.total_square_meters,
            'living_square_meters': self.living_square_meters,
            'kitchen_square_meters': self.kitchen_square_meters,
            'rooms_count': self.rooms_count,
            'floor': self.floor,
            'floors_count': self.floors_count,
            'wall_type': self.wall_type,
            'inspected': self.inspected,
            'verified_price': self.verified_price,
            'latitude': self.latitude,
            'longitude': self.longitude,
            'construction_year': self.construction_year,
            'heating': self.heating,
            'seller': self.seller,
            'water': self.water,
            'building_condition': self.building_condition,
            'dist_to_airport': self.dist_to_airport,
            'dist_to_center': self.dist_to_center,
            'dist_to_railway_station': self.dist_to_railway_station,
            'images':
            [i.serialize for i in self.images] if self.images else [],
            'seller_info':
            self.seller_info.serialize if self.seller_info else None
        }
Exemplo n.º 30
0
class UserModel(db.Model):
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String(255), unique=True, nullable=False)
    username = db.Column(db.String(50), unique=True)
    password_hash = db.Column(db.String(100))

    role_id = db.Column(db.Integer, db.ForeignKey('role.id'), nullable=False)

    card_lists = db.relationship('CardListModel',
                                 secondary=user_card_list,
                                 backref=db.backref('users', lazy='dynamic'))
    cards = db.relationship('CardModel', backref='user', lazy='dynamic')
    comments = db.relationship('CommentModel', backref='user', lazy='dynamic')

    @property
    def password(self):
        raise AttributeError('password: write-only field')

    @password.setter
    def password(self, password):
        self.password_hash = flask_bcrypt.generate_password_hash(
            password).decode('utf-8')

    def check_password(self, password):
        return flask_bcrypt.check_password_hash(self.password_hash, password)

    def json(self):
        return {'id': self.id, 'email': self.email, 'username': self.username}

    @staticmethod
    def encode_auth_token(user_id):
        """
        Generates the Auth Token
        :return: string
        """
        try:
            payload = {
                'exp':
                datetime.datetime.utcnow() +
                datetime.timedelta(days=1, seconds=5),
                'iat':
                datetime.datetime.utcnow(),
                'sub':
                user_id
            }
            return jwt.encode(payload, key, algorithm='HS256')
        except Exception as e:
            return e

    @staticmethod
    def decode_auth_token(auth_token):
        """
        Decodes the auth token
        :param auth_token:
        :return: integer|string
        """
        try:
            payload = jwt.decode(auth_token, key, algorithms='HS256')
            is_blacklisted_token = BlacklistToken.check_blacklist(auth_token)
            if is_blacklisted_token:
                return 'Token blacklisted. Please log in again.'
            else:
                return payload['sub']
        except jwt.ExpiredSignatureError:
            return 'Signature expired. Please log in again.'
        except jwt.InvalidTokenError:
            return 'Invalid token. Please log in again.'

    def __repr__(self):
        return f"<User name:'{self.username}', id:'{self.id}', role: {self.role}>"