的POST部分要重置密碼,用戶應該去鏈接包含令牌:驗證令牌GET和Django的觀點
example.com/password-change/?token=8125b6da86694a19b5d76f30a04c9db8
鑑於我有下面的代碼:
def _get_and_check_password_recovery_token(request, token_hex):
try:
token = tokens.get_token(token_hex)
except Token.DoesNotExist:
raise Http404
if token.is_expired():
token.delete()
messages.warning(request,
'Link you use for password recovery became obsolete. Please, request another one.')
return redirect(reverse('password_recovery') + '?email=%s' % token.user.email)
return token
def password_change(request):
if request.method == 'POST':
form = forms.PasswordChangeForm(request.POST)
if form.is_valid():
token_hex = form.cleaned_data.get('token')
new_password = form.cleaned_data['new_password']
if token_hex:
token_or_response = _get_and_check_password_recovery_token(request, token_hex)
if isinstance(token_or_response, Token):
user = token_or_response.user
else:
return token_or_response
else:
...
...
else:
token_hex = request.GET.get('token')
if token_hex:
token_or_response = _get_and_check_password_recovery_token(request, token_hex)
if isinstance(token_or_response, Token):
token_hex = token_or_response.hex
else:
return token_or_response
form = forms.PasswordChangeForm(initial={'token': token_hex})
else:
form = forms.PasswordChangeForm() # TODO Authenticated user changes his password.
return render_template(request, 'accounts/password_change.html', {'password_change_form': form})
正如你所看到的,令牌之前必須更改密碼的形式來檢查將被渲染,它會被我們提交後呃。所以我打電話給方法_get_and_check_password_recovery_token(request, token_hex)
2次。它返回響應對象(是未找到或不正確的令牌)或令牌。我對此感到不舒服 - 這是完全不同的對象。
你們看到更好的方式來寫這段代碼嗎? Python中返回邏輯上不同的對象嗎?
這更適合於http://codereview.stackexchange.com/。 – orlp 2012-07-17 09:07:06
謝謝,@nightcracker,我不知道這個資源。將來會發布類似的問題。 – Marboni 2012-07-17 09:10:42