0

我正在尝试创建一个注册表单,用户可以在其中输入用户名/密码组合。

我希望密码 MyPBKDF2用于密码哈希。

我有hashers.py

from django.contrib.auth.hashers import PBKDF2PasswordHasher

    class MyPBKDF2PasswordHasher(PBKDF2PasswordHasher):
        """
        A subclass of PBKDF2PasswordHasher that uses 100 times more iterations.
        """
        iterations = PBKDF2PasswordHasher.iterations * 100

设置.py

PASSWORD_HASHERS = (
    'MyApp.hashers.MyPBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    'django.contrib.auth.hashers.BCryptPasswordHasher',
    'django.contrib.auth.hashers.SHA1PasswordHasher',
    'django.contrib.auth.hashers.MD5PasswordHasher',
    'django.contrib.auth.hashers.CryptPasswordHasher',
)

视图.py

def Registration(request):
    RegForm = RegistrationForm(request.POST or None)
    if request.method == 'POST':
        if RegForm.is_valid():

            clearUserName = RegForm.cleaned_data['userNm']   #set clean username
            hashpass = make_password(RegForm.cleaned_data['userPass'], None, 'pbkdf2_sha256')

            RegForm.save()
            try:
                return HttpResponseRedirect('/Newuser/?userNm=' + clearUserName)
            except:
                raise ValidationError(('Invalid request'), code='300')    ## [ TODO ]: add a custom error page here.
    else:
        RegForm = RegistrationForm()

        return render(request, 'Myapp/reuse/register.html', {
            'RegForm': RegForm 
        })

表格.py c

lass RegistrationForm(ModelForm):
    userPass = forms.CharField(widget=forms.PasswordInput, label='Password')
    class Meta:
        model = Client
        fields = ['userNm','userPass']


def clean_RegForm(self):
    cleanedUserName = self.cleaned_data.get('userNm')
    if Client.objects.filter(userNm=cleanedUserName).exists():
        errorMsg = u"Error occurred."
        raise ValidationError(errorMsg)
    else:
        return cleanedUserName

我正在提交密码,但以纯文本形式提交 - 这不好。

我在这里做错了什么?

4

1 回答 1

2

好吧..您正在创建散列密码,但没有将其保存在任何地方。而且因为您正在保存表单(继承自 ModelForm),所以密码字段直接从密码表单字段保存。

您可以覆盖保存方法并设置hashpass为密码。但我认为这里的最佳做法是使用UserCreationFormwhich 为您处理密码哈希(它将使用您列表中的第一个密码哈希)。

SO上有一些例子,展示了如何自定义UserCreationForm,所以到处搜索。

伪代码:

表格.py

from django.contrib.auth.forms import UserCreationForm


class RegisterForm(UserCreationForm):
    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        # do not require password confirmation
        del self.fields['password2']

视图.py

def home(request):
    form = RegisterForm()

    if request.method == "POST":
        form = RegisterForm(request.POST)

        if form.is_valid():
            user = form.save()
            # redirect!

    return render(request, 'home.html', {
        'form': form
    })
于 2013-09-06T12:48:17.047 回答