简体   繁体   English

检查密码有效性(Django / Python)

[英]Check Password Validity (Django/Python)

I have a very small Django app, mostly just for learning purposes. 我有一个非常小的Django应用,主要用于学习目的。 I am using the inbuilt User model provided by Django. 我正在使用Django提供的内置用户模型。 To learn the functionality, I've created pages which allow me to create and edit users without having to go to the admin panel. 要学习该功能,我创建了一些页面,这些页面使我可以创建和编辑用户,而无需转到管理面板。

The register page allows me to very easily check for things like password and email validity, as when I POST to a View, I simply use user_form.is_valid() to check the fields are correct (username is less than 30 characters, password less than 128, other conditions...). 注册页面使我可以非常轻松地检查密码和电子邮件的有效性,因为当我发布到视图时,我只需使用user_form.is_valid()来检查字段是否正确(用户名少于30个字符,密码少于128,其他条件...)。

For my edit page, I wanted to make the content more responsive so I have made use of AJAX requests via JQuery, allowing me to perform actions without reloading the page. 对于我的编辑页面,我想使内容更具响应性,因此我通过JQuery使用了AJAX请求,从而使我无需重新加载页面即可执行操作。 This works great, but it does leave me with the problem of checking validity, as I am not sending the form, I am just using Javascript to pick out the queries and send them in an AJAX request as such: 这很好用,但是确实给我带来了检查有效性的问题,因为我没有发送表单,我只是使用Javascript来挑选查询并将它们发送到AJAX请求中,如下所示:

$.get('/dms/edit_user_changeuser/', {inputNameSend : $("#inputname").val(), usernameToSend : $("#usernameID").val(), emailToSend : $("#emailID").val(),passwordToSend : $("#passwordID").val(), disabledToSend : checkedVal}, function(data){
            if(data != "success"){
                $("#errorDisplay").show();
            }else{
                $("#savedDisplay").show();
                $("#user_form").hide();
            }
});

And this is how the associated View handles it: 这是关联的View处理它的方式:

@login_required
def user_edit_changeuser(request):
    # Like before, get the request's context.
    context = RequestContext(request)

    inputname = request.GET['inputNameSend']
    newUsername = request.GET['usernameToSend']
    newEmail = request.GET['emailToSend']
    newPassword = request.GET['passwordToSend']
    if(request.GET['disabledToSend'] == "true"):
        disabledBool = False
    else:
        disabledBool = True
    try:
        user_obj = User.objects.get(username=inputname)
        print("retUser")
        user_obj.username = newUsername
        user_obj.email = newEmail
        user_obj.is_active = disabledBool
        user_obj.set_password(newPassword)
        user_obj.save()
        print(str(disabledBool))
        return HttpResponse("success")
    except Exception, e:
        return HttpResponse(str(e))

This all works assuming input is valid, but is there something like User.checkValidPassword(newPassword) to manually check validity? 假设输入有效,所有这些工作正常,但是是否有类似User.checkValidPassword(newPassword)来手动检查有效性?

User instances have a method check_password which does exactly what you want it to do User实例具有check_password方法,该方法完全可以实现您想要的功能

user = User.object.get(username=inputname)
user.checK_password('a_password')

The above checks to see if the current users password matches what is saved in the db. 上面检查了当前用户密码是否与数据库中保存的密码匹配。 If you were instead asking about validating to make sure the newPassword is valid ie. 如果您要询问有关验证以确保newPassword有效,即。 is the proper length, contains numbers, etc. There is no reason you cannot use a form to validate the user input, just as you would if it were not an AJAX based view 是正确的长度,包含数字,等等。没有理由不能使用表单来验证用户输入,就像它不是基于AJAX的视图一样


as a side note, it is not necessarly the best thing to catch all exceptions in python. 作为附带说明,捕获python中的所有异常不一定是最好的事情。 It can mask all sorts of errors that you want to see fail! 它可以掩盖您想看到的各种错误!

if you are expecting that a user might not exist do it explicitly. 如果您期望某个用户可能不存在,请明确执行此操作。

try:
    user = User.object.get(username=inputname)
except User.DoesNotExist:
    # all other expections will not be caught!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM