使用 bcrypt 在烧瓶管理员中更改密码

Posted

技术标签:

【中文标题】使用 bcrypt 在烧瓶管理员中更改密码【英文标题】:Change password in flask admin using bcrypt 【发布时间】:2021-10-20 02:43:51 【问题描述】:

我的应用有小问题。如您所知,flask-admin 使您能够在管理面板中更改用户密码,这很酷

但是我的密码是用 bcrypt 散列的,所以当我去编辑用户密码时,我看到的只有随机字母。我将它们更改为 P@ssword1234 但此密码未经过哈希处理,并且用户被有效地阻止登录

我的数据库模型

class User(db.Model, UserMixin):
    id       = db.Column(db.Integer,    primary_key=True)
    name     = db.Column(db.String(60), unique=False, nullable=False)
    surname  = db.Column(db.String(60), unique=False, nullable=False)
    username = db.Column(db.String(60), unique=True, nullable=False)
    email    = db.Column(db.String(60), unique=True, nullable=False)
    password = db.Column(db.String(60), nullable=False)

我的烧瓶管理设置

class SecureModelView(ModelView):
    column_exclude_list     = ['password']
    column_serchable_list   = ['email']
    column_editable_list    = ['allowed']
    def is_accessible(self):
        if (not current_user.is_authenticated):
            return False
        else:
            return True

class MyAdminIndexView(AdminIndexView):
    def is_accessible(self):
        if (not current_user.is_authenticated):
            return False
        else:
            return True

admin = Admin(app, 'Admin Panel', index_view=MyAdminIndexView())
admin.add_view(SecureModelView(User, db.session))

【问题讨论】:

这能回答你的问题吗? Flask admin overrides password when user model is changed 【参考方案1】:

看看 on_model_change 函数

您可以使用 is_created 来验证是否正在创建用户。

class SecureModelView(ModelView):
    column_exclude_list     = ['password']
    column_serchable_list   = ['email']
    column_editable_list    = ['allowed']

    form_extra_fields = 
       #similar to flask_wtf, write your validation
       'confirm_password' : PasswordField('Confirm Password')
    

    def is_accessible(self):
        if (not current_user.is_authenticated):
            return False
        else:
            return True


    def on_model_change(self,form,model,is_created):
       #where your password hashing here
       # just an example, write your correct pass hashing.
       model.password = bcrypt(form.password.data)

【讨论】:

以上是关于使用 bcrypt 在烧瓶管理员中更改密码的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Laravel 中验证 bcrypt 密码?

spring security 使用 bcrypt 算法对密码进行编码

在 node.js 中使用 passport-local 和 bcrypt 检查和更新密码

通过验证更改用户密码( symfony2 )

Rails 4 - 仅当当前密码正确时才允许更改密码

尝试更新散列密码c#