Пример #1
0
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    admin = db.Column(db.Boolean)
    image_file = db.Column(db.String(20),
                           nullable=False,
                           default='default.jpg')
    password = db.Column(db.String(60), nullable=False)
    posts = db.relationship('Post', backref='author', lazy=True)
    offers = db.relationship('Offer', backref='author', lazy=True)
    wishlists = db.relationship('Wishlist', backref='author', lazy=True)

    def get_reset_token(self, expires_sec=1800):
        s = Serializer(current_app.config['SECRET_KEY'], expires_sec)
        return s.dumps({'user_id': self.id}).decode('utf-8')

    @staticmethod
    def verify_reset_token(token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            user_id = s.loads(token)['user_id']
        except:
            return None
        return User.query.get(user_id)

    def __repr__(self):
        return f"User('{self.username}', '{self.email}', '{self.image_file}')"
Пример #2
0
class Wishlist(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    price = db.Column(db.Integer, nullable=False)
    image_file = db.Column(db.String(20),
                           nullable=False,
                           default='default.jpg')
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    def __repr__(self):
        return f"User('{self.title}', '{self.description}', '{self.image_file}', '{self.price}')"
Пример #3
0
class Offer(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    date = db.Column(db.DateTime, nullable=False)
    content = db.Column(db.Text, nullable=False)
    image_file = db.Column(db.String(20),
                           nullable=False,
                           default='default.jpg')
    price = db.Column(db.Integer)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    def __repr__(self):
        return f"User('{self.title}', '{self.date}','{self.content}','{self.image_file}','{self.price}')"
Пример #4
0
class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=True)

    def __repr__(self):
        return '<User %r>' % self.username

    def to_json(self):
        return {
            'id': self.id,
            'name': self.name,
            'email': self.email,
        }
Пример #5
0
class Permission(db.Model):
    __tablename__ = "permissions"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    description = db.Column(db.Text)
    users = db.relationship('User', secondary='user_permission_links')
    roles = db.relationship('Role', secondary='role_permission_links')

    def __repr__(self):
        return '<Permission %r>' % self.name
Пример #6
0
class Post(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    date_posted = db.Column(db.DateTime,
                            default=datetime.utcnow,
                            nullable=False)
    content = db.Column(db.Text, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    def __repr__(self):
        return f"User('{self.title}', '{self.date_posted}')"
Пример #7
0
class User(UserMixin, pm.UserMixinP, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(64), unique=True, index=True)

    def __repr__(self):
        return '<User %r>' % self.email
Пример #8
0
class Role(db.Model):
    __tablename__ = "roles"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    description = db.Column(db.Text)
    users = db.relationship('User', secondary='user_role_links')
    permissions = db.relationship('Permission',
                                  secondary='role_permission_links')
    parents = db.relationship('Role',
                              secondary='role_links',
                              primaryjoin=RoleLink.role_id == id,
                              secondaryjoin=RoleLink.parent_id == id,
                              backref="children")

    def __repr__(self):
        return '<Role %r>' % self.name

    def inheritRole(self, role=None, roleName=None, roleId=None):
        """
        Add a role from which permissions will be inherited.  Checks to make sure not trying to inherit itself, and
        itself is not inherited down the line.  Priority to arguments goes role, roleName, then roleId.
        :param role:
        :param roleName:
        :param roleId:
        :return:
        """
        if role:
            try:
                if self.name == role.name:
                    return False, f'Role cannot inherit itself.'
            except AttributeError:
                return False, f'{role} is not a valid Role.'
            inheritedRole = role
        elif roleName:
            if self.name == str(roleName):
                return False, f'Role cannot inherit itself.'
            inheritedRole = Role.query.filter_by(name=roleName).first()
            if not inheritedRole:
                return False, f'{roleName} is not a valid Role name.'
        elif roleId:
            if self.id == int(roleId):
                return False, f'Role cannot inherit itself.'
            inheritedRole = Role.query.filter_by(id=roleId).first()
            if not inheritedRole:
                return False, f'{roleName} is not a valid Role name.'
        else:
            return False, 'One of arguments role, roleName, or roleId must be specified.'

        currentInheritedRoles = inheritedRoles(self)

        if inheritedRole.name in currentInheritedRoles:
            return False, f"<Role '{self.name}'> already inherits from <Role '{inheritedRole.name}'>."

        self.parents.append(inheritedRole)
        db.session.add(self)
        db.session.commit()

        return True, f"<Role '{self.name}'> now inherits from <Role '{inheritedRole.name}'>."

    def removeInheritedRole(self, role=None, roleName=None, roleId=None):
        """
        Remove a role from which permissions were inherited.  Checks to make sure not trying to inherit itself, and
        itself is not inherited down the line.  Priority to arguments goes role, roleName, then roleId.
        :param role:
        :param roleName:
        :param roleId:
        :return:
        """
        if role:
            try:
                if self.name == role.name:
                    return False, f'Role cannot remove itself.'
            except AttributeError:
                return False, f'{role} is not a valid Role.'
            inheritedRole = role
        elif roleName:
            if self.name == str(roleName):
                return False, f'Role cannot remove itself.'
            inheritedRole = Role.query.filter_by(name=roleName).first()
            if not inheritedRole:
                return False, f'{roleName} is not a valid Role name.'
        elif roleId:
            if self.id == int(roleId):
                return False, f'Role cannot remove itself.'
            inheritedRole = Role.query.filter_by(id=roleId).first()
            if not inheritedRole:
                return False, f'{roleName} is not a valid Role name.'
        else:
            return False, 'One of arguments role, roleName, or roleId must be specified.'

        currentInheritedRoles = inheritedRoles(self)

        if inheritedRole.name not in currentInheritedRoles:
            return False, f"<Role '{self.name}'> does not directly inherit from <Role '{inheritedRole.name}'>."

        self.parents.remove(inheritedRole)
        db.session.add(self)
        db.session.commit()

        return True, f"<Role '{self.name}'> no longer inherits directly from <Role '{inheritedRole.name}'>. " \
            f"NOTE it may still inherit the Role (or the Role's permissions) " \
            f"through another inherited Role's inherited Roles."

    def addPermission(self, permission=None, permName=None):
        if permission:
            try:
                tempName = permission.name
                addedPerm = permission
            except AttributeError:
                return False, f'{permission} is not a valid Permission.'
        elif permName:
            addedPerm = Permission.query.filter_by(name=permName).first()
            if not addedPerm:
                return False, f'{permName} is not a valid Permission name.'

        if addedPerm in self.permissions:
            return False, f'{self} already has {addedPerm}.'

        self.permissions.append(addedPerm)
        db.session.add(self)
        db.session.commit()

        return True, f'{addedPerm} added to {self}.'

    def removePermission(self, permission=None, permName=None):
        if permission:
            try:
                tempName = permission.name
                removedPerm = permission
            except AttributeError:
                return False, f'{permission} is not a valid Permission.'
        elif permName:
            removedPerm = Permission.query.filter_by(name=permName).first()
            if not removedPerm:
                return False, f'{permName} is not a valid Permission name.'

        if removedPerm not in self.permissions:
            return False, f'{self} does not directly have {removedPerm}.'

        self.permissions.remove(removedPerm)
        db.session.add(self)
        db.session.commit()

        return True, f'{removedPerm} removed from {self}. NOTE it may still be present in an inherited Role.'

    def allPermissionsRoles(self, previousRoleNames=None):

        rolePermsSet = set()
        if not previousRoleNames:
            previousRoleNames = set()

        # if role has already been counted, end recursion
        if self.id in previousRoleNames:
            return set(), set()

        previousRoleNames.add(self.name)

        for perm in self.permissions:
            rolePermsSet.add(perm.name)

        for subRole in self.parents:
            if subRole.name in previousRoleNames:
                continue
            tempRolePermSet, tempRoleNames = subRole.allPermissionsRoles(
                previousRoleNames=previousRoleNames)
            rolePermsSet = rolePermsSet | tempRolePermSet
            previousRoleNames = previousRoleNames | tempRoleNames

        return rolePermsSet, previousRoleNames