且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

web2py检查表单中的密码

更新时间:2023-02-19 11:56:37

web2py Auth系统包括一个内置的密码更改操作.如果您在default.py控制器中使用默认的user操作,则可以通过/myapp/default/user/change_password访问此表单.

The web2py Auth system includes a built-in password change action. If you are using the default user action in the default.py controller, you access this form via /myapp/default/user/change_password.

如果您只想为此目的创建一个单独的控制器动作,则只需执行以下操作:

If you prefer to create a separate controller action just for this purpose, you can simply do:

def change_password():
    return dict(form=auth.change_password())

并在关联的视图中:

{{=form}}

关于您的自定义代码,您不能单独使用IS_EQUAL_TO验证器,因为它使用的表达式必须等于用表单提交的值(您不能像这样使用已转换的值来调用验证器,因为将返回一个元组,但是requires属性必须是带有字段和值的可调用对象.

Regarding your custom code, you cannot use the IS_EQUAL_TO validator alone, as it takes an expression that must be equal to the value submitted with the form (you cannot call the validator with a transformed value as you have, as that will return a tuple, but the requires attribute must be a callable object that takes a field and a value).

相反,您可以在列表中使用CRYPT验证器,然后使用IS_EQUAL_TO验证器-第一个验证器会将提交的密码转换为哈希,然后第二个验证器将与存储的密码哈希进行相等性测试

Instead, you could use the CRYPT validator followed by the IS_EQUAL_TO validator in a list -- the first validator will transform the submitted password to a hash, and the second will then test for equality with the stored password hash.

或者,您可以使用:

def check_password(password):
    new_hash = db.auth_user.password.validate(password)[0]
    return new_hash == auth.user.password

form = SQLFORM.factory(Field('current_password', 'password')
                             requires=IS_EXPR(check_password)),
                       ...)

IS_EXPR验证器可以采用将为其传递值的函数,并且该函数应返回TrueFalse(请注意,此用法未记录在册-本书仅显示了替代用法,其中您将Python代码作为字符串提供,该字符串将为exec'ed.

The IS_EXPR validator can take a function that will be passed the value, and the function should return True or False (note, this usage is not documented -- the book only shows the alternative usage, where you provide Python code as a string, which will be exec'ed).