Exemple #1
0
class User(db.Model):
    """
    用户信息表
    """
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(16))
    password = db.Column(db.String(100))
    create_time = db.Column(db.DateTime, default=datetime.datetime.now)

    # 多对多的双向关联,用于跨表查询
    roles = db.relationship('Role', secondary=user_role, passive_deletes=True)

    def check_password(self, password):
        from werkzeug.security import check_password_hash
        return check_password_hash(self.password, password)

    def __str__(self):
        return '<User %s>' % self.username
Exemple #2
0
class UsersRoles(BaseModel, db.Model):
    """
    desc:   用户角色关联表

    """
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey("user.id"))
    user = db.relationship("User",
                           backref=db.backref("user_roles",
                                              lazy="dynamic",
                                              cascade="all, delete-orphan"))
    role_id = db.Column(db.Integer, db.ForeignKey("role.id"))
    role = db.relationship("Role",
                           backref=db.backref("role_users",
                                              lazy="dynamic",
                                              cascade="all, delete-orphan"))

    def __init__(self, user, role):
        self.user = user
        self.role = role
Exemple #3
0
class Students(BaseModel, db.Model):
    """
    desc:   学生表模型

    """
    name = db.Column(db.String(20))

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

    def to_dict(self):
        return self._to_dict(name=self.name)
Exemple #4
0
class Actor(db.Model):
    __tablename__ = 'actor'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    sex = db.Column(db.Integer)  # 0 is male, 1 is female.
    country = db.Column(db.String(50))
    description = db.Column(db.Text)
    thumb = db.Column(db.Integer)  # the record id in photo table.
    type = db.Column(db.String(100))  # the mediatype list for the actor.

    def __repr__(self):
        return '<Actor %r>' % self.name
Exemple #5
0
class Role(BaseModel, db.Model):
    """
    desc:   角色表

    """
    name = db.Column(db.String(20))
    comment = db.Column(db.String(100))

    def __init__(self, name, comment):
        self.name = name
        self.create_date = datetime.datetime.now()
        self.modify_date = datetime.datetime.now()
        self.comment = comment

    def to_dict(self):
        return self._to_dict(name=self.name, comment=self.comment)

    def update(self, **kwargs):
        """
        desc:   更新角色信息

        """
        self.name = kwargs['name']
        self.comment = kwargs['comment']
Exemple #6
0
class Contact(db.Model):
    __tablename__ = "contacts"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    email = db.Column(db.String(100), nullable=False)
    phone = db.Column(db.String(20), nullable=False)
    content = db.Column(db.Text(), nullable=False)
    date = db.Column(db.DateTime, default=datetime.utcnow())

    def __str__(self):
        return self.name
Exemple #7
0
class Photo(db.Model):
    __tablename__ = 'photo'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    ext = db.Column(db.String(10))
    content = db.Column(db.LargeBinary)  # store the image into db
    path = db.Column(db.String(255))  # image url or file path for the image.
    type = db.Column(db.String(100))  # list of type, split with comma

    def __repr__(self):
        return '<Photo %r>' % self.name
Exemple #8
0
class User(TimeStamp, db.Model):
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255), unique=True, nullable=False)
    first_name = db.Column(db.String(255), unique=False, nullable=True)
    last_name = db.Column(db.String(255), unique=False, nullable=True)
    password = db.Column(db.Text, unique=False, nullable=False)
    user_type = db.Column(db.SmallInteger, default=1)
    access_token = db.Column(db.Text, nullable=True)

    roles = db.relationship("Role",
                            secondary="user_roles",
                            back_populates="users")

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

    def to_json(self):
        return {
            'first_name': self.first_name,
            'last_name': self.last_name,
            'email': self.email,
            'id': self.id,
            'access_token': self.access_token,
            'user_type': self.user_type
        }

    @classmethod
    def find_by_email(cls, email):
        return cls.query.filter_by(email=email).first()

    @classmethod
    def find_by_id(cls, id):
        return cls.query.filter_by(id=id).first()

    @staticmethod
    def generate_hash(password):
        return sha256.hash(password)

    @staticmethod
    def verify_hash(password, hash):
        return sha256.verify(password, hash)

    def __repr__(self):
        return '<User %r>' % (self.first_name)
Exemple #9
0
class EBook(db.Model):
    __tablename__ = 'ebook'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    mediatype = db.Column(
        db.String(100))  # with the media type id, split with comma
    storage = db.Column(db.Integer)
    file_path = db.Column(db.String(500))
    actors = db.Column(db.String(100))  # The list of author.

    def __repr__(self):
        return '<EBook %r>' % self.name
Exemple #10
0
class Permission(db.Model):
    """
    权限表
    """
    __tablename__ = 'permission'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(10))
    url = db.Column(db.String(64))
    menu_ref = db.Column(db.Integer, db.ForeignKey('permission.id'))  # 自关联
    code = db.Column(db.String(10))
    group_id = db.Column(db.Integer, db.ForeignKey('permissiongroup.id'))

    # 自关联声明
    self_ref = db.relationship('Permission', remote_side=[id])

    # 多对多的双向关联,用于跨表查询
    roles = db.relationship('Role', secondary=permission_role, passive_deletes=True)

    def __str__(self):
        return '<Permission> %s' % self.title
Exemple #11
0
from sqlalchemy_serializer import SerializerMixin


class TimeStamp(object):
    created_at = db.Column(db.DateTime,
                           nullable=False,
                           default=datetime.utcnow)
    updated_at = db.Column(db.DateTime,
                           nullable=True,
                           onupdate=datetime.utcnow)
    deleted_at = db.Column(db.DateTime, nullable=True)


user_roles = db.Table(
    'user_roles', db.Model.metadata,
    db.Column('id', db.Integer, primary_key=True),
    db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('role_id', db.Integer, db.ForeignKey('role.id')))


class User(TimeStamp, db.Model):
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255), unique=True, nullable=False)
    first_name = db.Column(db.String(255), unique=False, nullable=True)
    last_name = db.Column(db.String(255), unique=False, nullable=True)
    password = db.Column(db.Text, unique=False, nullable=False)
    user_type = db.Column(db.SmallInteger, default=1)
    access_token = db.Column(db.Text, nullable=True)
Exemple #12
0
    __tablename__ = 'permissiongroup'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(10))
    menu_id = db.Column(db.Integer, db.ForeignKey('menu.id'))

    # 双向关联,用于跨表查询
    permissions = db.relationship('Permission', backref='perm_group')

    def __str__(self):
        return '<PermissionGroup %s>' % self.title


# 权限—角色关联表
permission_role = db.Table('permission_role', db.metadata,
                           db.Column('permission_id', db.Integer,
                                     db.ForeignKey('permission.id', ondelete='CASCADE', onupdate='CASCADE')),
                           db.Column('role_id', db.Integer,
                                     db.ForeignKey('role.id', ondelete='CASCADE', onupdate='CASCADE'))
                           )


class Permission(db.Model):
    """
    权限表
    """
    __tablename__ = 'permission'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(10))
    url = db.Column(db.String(64))
    menu_ref = db.Column(db.Integer, db.ForeignKey('permission.id'))  # 自关联
class Todos(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    task = db.Column(db.String(30), unique=True)
    complete = db.Column(db.Boolean, default=False)
Exemple #14
0
class User(BaseModel, db.Model):
    username = db.Column(db.String(20), unique=True)
    nickname = db.Column(db.String(30))
    password = db.Column(db.String(32))
    email = db.Column(db.String(255), default="")
    is_superuser = db.Column(db.Boolean, default=False)

    def __init__(self,
                 username,
                 nickname,
                 password,
                 email,
                 create_date=None,
                 modify_date=None,
                 is_superuser=False):
        self.username = username
        self.nickname = nickname if nickname else username
        self.create_date = create_date if create_date else datetime.datetime.now(
        )
        self.modify_date = modify_date if modify_date else datetime.datetime.now(
        )
        self.password = self._hash_password(password)
        self.email = email
        self.is_superuser = is_superuser

    def _hash_password(self, password):
        key = "%s%s" % (password, 'SECRET')
        return hashlib.md5(key).hexdigest()

    def verify_password(self, password):
        return self.password == self._hash_password(password)

    def update_password(self, password):
        self.password = self._hash_password(password)

    def update(self, **kwargs):
        self.username = kwargs['username']
        if kwargs.get("email"):
            self.email = kwargs["email"]
        if kwargs.get("nickname"):
            self.nickname = kwargs["nickname"]

    def to_dict(self):
        return self._to_dict(username=self.username,
                             nickname=self.nickname,
                             email=self.email)

    def generate_auth_token(self):
        """
        desc:   生成登录用户的token
        params: user_id     用户唯一标识号
        return: token
        date:   2016-10-28

        """
        s = TimedJSONWebSignatureSerializer(
            current_app.config.get("SECRET_KEY", "No secret key"),
            current_app.config.get("USER_TOKEN_EXPIRATION", 3600))

        return s.dumps({"user_id": self.id})

    @classmethod
    def verify_auth_token(cls, token):
        s = TimedJSONWebSignatureSerializer(
            current_app.config.get("SECRET_KEY", "No secret key"))
        try:
            data = s.loads(token)
        except SignatureExpired:
            raise TokenExpired(
                http_responses.HTTP_400_BAD_REQUEST(
                    msg={"error": u"Token过期了,请重新登录"}))
        except BadSignature:
            raise BadToken(
                http_responses.HTTP_400_BAD_REQUEST(
                    msg={"error": u"Token无效,请重新登录"}))

        try:
            user = User.get_object(id=data["user_id"])
        except ObjectNotExists:
            raise BadToken(
                http_responses.HTTP_400_BAD_REQUEST(
                    msg={"error": u"Token无效,请重新登录"}))
        return user