Flask管理员在更改用户模型时会覆盖密码

时间:2016-08-27 20:00:10

标签: python flask flask-admin

我目前正潜入烧瓶项目,并尝试首次使用烧瓶管理员。到目前为止,一切都运转正常,但有一件事让我困扰: 每当我编辑用户模型时,用户密码都会被覆盖。我遵循this question第二个答案中给出的建议,以防止烧瓶管理员重新散列我的密码。不幸的是,清空的密码字段仍然被写入数据库。

我试图从User - 模型获取当前密码,该模型作为on_model_change方法的参数给出,但不知何故密码似乎已经被覆盖了(或者它是不是我在这里看到的实际数据库模型 - 我在这里有点困惑。)

以下是我的代码:

用户模型

class User(UserMixin, SurrogatePK, Model):
    """A user of the app."""

    __tablename__ = 'users'
    username = Column(db.String(80), unique=True, nullable=False)
    email = Column(db.String(80), unique=True, nullable=False)
    #: The hashed password
    password = Column(db.String(128), nullable=True)
    created_at = Column(db.DateTime, nullable=False,
                        default=datetime.datetime.utcnow)
    first_name = Column(db.String(30), nullable=True)
    last_name = Column(db.String(30), nullable=True)
    active = Column(db.Boolean(), default=False)
    is_admin = Column(db.Boolean(), default=False)

    def __init__(self, username="", email="", password=None, **kwargs):
        """Create instance."""
        db.Model.__init__(self, username=username, email=email, **kwargs)
        if password:
            self.set_password(password)
        else:
            self.password = None

    def __str__(self):
        """String representation of the user. Shows the users email address."""
        return self.email

    def set_password(self, password):
        """Set password"""
        self.password = bcrypt.generate_password_hash(password)

    def check_password(self, value):
        """Check password."""
        return bcrypt.check_password_hash(self.password, value)

    def get_id(self):
        """Return the email address to satisfy Flask-Login's requirements"""
        return self.id

    @property
    def full_name(self):
        """Full user name."""
        return "{0} {1}".format(self.first_name, self.last_name)

    @property
    def is_active(self):
        """Active or non active user (required by flask-login)"""
        return self.active

    @property
    def is_authenticated(self):
        """Return True if the user is authenticated."""
         if isinstance(self, AnonymousUserMixin):
            return False
        else:
            return True

    @property
    def is_anonymous(self):
        """False, as anonymous users aren't supported."""
        return False

Flask-Admin UserView

class UserView(MyModelView):
    """Flask user model view."""
    create_modal = True
    edit_modal = True

    def on_model_change(self, form, User, is_created):
        if form.password.data is not None:
            User.set_password(form.password.data)
        else:
           del form.password

    def on_form_prefill(self, form, id):
        form.password.data = ''                                              

非常感谢任何帮助。 提前谢谢,

oneiro

2 个答案:

答案 0 :(得分:4)

可能更容易覆盖SIGPIPE方法并完全从编辑表单中删除密码字段。

get_edit_form

另一种方法是从表单中完全删除模型密码字段,然后使用虚拟密码字段,然后可以使用该密码字段填充模型的密码。通过删除真实密码字段,Flask-Admin将不会单击我们的密码数据。示例:

class UserView(MyModelView):
    def get_edit_form(self):
        form_class = super(UserView, self).get_edit_form()
        del form_class.password
        return form_class

答案 1 :(得分:0)

我也遇到过类似的问题。更改密码字段后,我需要生成密码的哈希。我不想添加其他表单来更改密码。在后端,我使用了MongoDB。我的烧瓶管理员解决方案:

class User(db.Document, UserMixin):
    ***
    password = db.StringField(verbose_name='Password')
    roles = db.ListField(db.ReferenceField(Role), default=[] 

    def save(self) -> None:
        if not self.id:
            self.password = hashlib.md5((self.password + Config.SECURITY_PASSWORD_SALT).encode()).hexdigest()
            return super(User, self).save(self)
        else:
            return super(User, self).update(
            ***
            password = self.password,
            )

class UserModelView(ModelView):   
    def on_model_change(self, form, model, is_created):
        user = User.objects(id=model.id)[0]
        if user.password != form.password.data:
            model.password = hashlib.md5((form.password.data + Config.SECURITY_PASSWORD_SALT).encode()).hexdigest()

admin.add_view(UserModelView(User, 'Users'))

对于SQL解决方案,这也是实际的。