Django REST-Auth 密码重置
Django REST-Auth Password Reset
我对可用的 django 中间件完全困惑:
我只是想获得密码重置(以及后来的密码更改)功能 运行,在后端使用 django
和 rest_auth
,在前端使用 Vue。
第 1 步:通过邮件请求重置-Link
观看次数
到目前为止我做了一个CustomPasswordResetView
:
# project/accounts/views.py
from rest_auth.views import PasswordResetView
class CustomPasswordResetView(PasswordResetView):
pass
序列化程序
和一个CustomPasswordResetSerializer
:
# project/accounts/serializers.py
from rest_auth.serializers import PasswordResetSerializer
class CustomPasswordResetSerializer(PasswordResetSerializer):
email = serializers.EmailField()
password_reset_form_class = ResetPasswordForm
def validate_email(self, value):
# Create PasswordResetForm with the serializer
self.reset_form = self.password_reset_form_class(data=self.initial_data)
if not self.reset_form.is_valid():
raise serializers.ValidationError(self.reset_form.errors)
###### FILTER YOUR USER MODEL ######
if not get_user_model().objects.filter(email=value).exists():
raise serializers.ValidationError(_('Invalid e-mail address'))
return value
def save(self):
request = self.context.get('request')
# Set some values to trigger the send_email method.
opts = {
'use_https': request.is_secure(),
'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
'request': request,
}
opts.update(self.get_email_options())
self.reset_form.save(**opts)
Settings.py
在 settings.py
中,我有这些字段,它们似乎与我的问题相关:
# project/vuedj/settings.py
REST_AUTH_SERIALIZERS = {
"USER_DETAILS_SERIALIZER": "accounts.serializers.CustomUserDetailsSerializer",
"LOGIN_SERIALIZER": "accounts.serializers.CustomUserLoginSerializer",
"PASSWORD_RESET_SERIALIZER": "accounts.serializers.CustomPasswordResetSerializer"
}
(完整的settings.py
附在最下面)
URL 模式
我的网址已经捕捉到我的 API 请求,以便发送密码重置电子邮件:
# project/vuedj/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/', include('api.urls')),
path('accounts/', include('allauth.urls')),
path('', api_views.index, name='home')
]
# project/api/urls.py
urlpatterns = [
path('auth/', include('accounts.urls')),
# other paths...
]
# project/accounts/urls.py
urlpatterns = [
path('', acc_views.UserListView.as_view(), name='user-list'),
path('login/', acc_views.UserLoginView.as_view(), name='login'),
path('logout/', acc_views.UserLogoutView.as_view(), name='logout'),
path('register/', acc_views.CustomRegisterView.as_view(), name='register'),
path('reset-password/', acc_views.CustomPasswordResetView.as_view(), name='reset-password'),
path('reset-password-confirm/', acc_views.CustomPasswordResetConfirmView.as_view(), name='reset-password-confirm'),
path('<int:pk>/', acc_views.UserDetailView.as_view(), name='user-detail')
]
带有 PW-Reset 令牌生成器的电子邮件
CustomPasswordReset 视图最终会生成一封带有漂亮密码重置的漂亮电子邮件 link。 link是有效的,点进去,我可以完美的通过allauth模板重置密码。
rest-auth 使用此代码(间接)生成重置令牌:
# project/.venv/Lib/site-packages/allauth/account/forms.py
def save(self, request, **kwargs):
current_site = get_current_site(request)
email = self.cleaned_data["email"]
token_generator = kwargs.get("token_generator",
default_token_generator)
for user in self.users:
temp_key = token_generator.make_token(user)
# save it to the password reset model
# password_reset = PasswordReset(user=user, temp_key=temp_key)
# password_reset.save()
# send the password reset email
path = reverse("account_reset_password_from_key",
kwargs=dict(uidb36=user_pk_to_url_str(user),
key=temp_key))
url = build_absolute_uri(
request, path)
context = {"current_site": current_site,
"user": user,
"password_reset_url": url,
"request": request}
if app_settings.AUTHENTICATION_METHOD \
!= AuthenticationMethod.EMAIL:
context['username'] = user_username(user)
get_adapter(request).send_mail(
'account/email/password_reset_key',
email,
context)
return self.cleaned_data["email"]
这个PasswordResetTokenGenerator
用在上面的代码中:
# project/.venv/Lib/site-packages/django/contrib/auth/tokens.py
class PasswordResetTokenGenerator:
"""
Strategy object used to generate and check tokens for the password
reset mechanism.
"""
key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator"
secret = settings.SECRET_KEY
def make_token(self, user):
"""
Return a token that can be used once to do a password reset
for the given user.
"""
return self._make_token_with_timestamp(user, self._num_days(self._today()))
def check_token(self, user, token):
"""
Check that a password reset token is correct for a given user.
"""
if not (user and token):
return False
# Parse the token
try:
ts_b36, hash = token.split("-")
except ValueError:
return False
try:
ts = base36_to_int(ts_b36)
except ValueError:
return False
# Check that the timestamp/uid has not been tampered with
if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
return False
# Check the timestamp is within limit. Timestamps are rounded to
# midnight (server time) providing a resolution of only 1 day. If a
# link is generated 5 minutes before midnight and used 6 minutes later,
# that counts as 1 day. Therefore, PASSWORD_RESET_TIMEOUT_DAYS = 1 means
# "at least 1 day, could be up to 2."
if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
return False
return True
上面的 classes 将被 rest_auth
PasswordResetView
:
调用
# project/.venv/Lib/site-packages/rest_auth/views.py
class PasswordResetView(GenericAPIView):
"""
Calls Django Auth PasswordResetForm save method.
Accepts the following POST parameters: email
Returns the success/fail message.
"""
serializer_class = PasswordResetSerializer
permission_classes = (AllowAny,)
def post(self, request, *args, **kwargs):
# Create a serializer with request.data
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save() # <----- Code from above (TokenGenerator) will be called inside this .save() method
# Return the success message with OK HTTP status
return Response(
{"detail": _("Password reset e-mail has been sent.")},
status=status.HTTP_200_OK
)
如您所见,令牌生成器将 return 一个 uidb36
与令牌。
当用户确认密码重置时,它还假定 uidb36
。
生成的令牌(例如生成邮件中的完整 link)将如下所示:
http://localhost:8000/accounts/password/reset/key/16-52h-42b222e6dc30690b2e91/
其中16
是base 36(uidb36
)中的用户id,我还不知道52h
是什么意思,但是我假设,令牌的第三部分是令牌本身 (42b222e6dc30690b2e91
)
第 2 步:将令牌发送到后端(又名 "User clicks link")
我被困在这里了。
API-Endpoints of the Rest-Auth-Framework 说:
/rest-auth/password/reset/confirm/ (POST)
uid
token
new_password1
new_password2
当我发送对象时,例如:
{
uid: '16', // TODO maybe I have to convert it to base10...
token: '42b222e6dc30690b2e91',
new_password1: 'test123A$',
new_password2: 'test123A$'
}
通过我的 api 到 http://localhost:8000/api/v1/auth/reset-password/
上面的对象在 axios
-post 请求的主体中,我的 CustomPasswordResetConfirmView
像预期的那样被触发,它也只是 rest_auth
中 PasswordResetConfirmView
的 Subclass,因此执行此代码:
# project/.venv/Lib/site-packages/rest_auth/views.py
class PasswordResetConfirmView(GenericAPIView):
"""
Password reset e-mail link is confirmed, therefore
this resets the user's password.
Accepts the following POST parameters: token, uid,
new_password1, new_password2
Returns the success/fail message.
"""
serializer_class = PasswordResetConfirmSerializer
permission_classes = (AllowAny,)
@sensitive_post_parameters_m
def dispatch(self, *args, **kwargs):
return super(PasswordResetConfirmView, self).dispatch(*args, **kwargs)
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(
{"detail": _("Password has been reset with the new password.")}
)
行 serializer.is_valid(raise_exception=True)
将调用 rest_framework
的 Serializer(BaseSerializer)
的 run_validation
。
这将进一步使用 rest_auth
的 PasswordResetConfirmSerializer
:
# project/.venv/Lib/site-packages/rest_auth/serializers.py
class PasswordResetConfirmSerializer(serializers.Serializer):
"""
Serializer for requesting a password reset e-mail.
"""
new_password1 = serializers.CharField(max_length=128)
new_password2 = serializers.CharField(max_length=128)
uid = serializers.CharField()
token = serializers.CharField()
set_password_form_class = SetPasswordForm
def custom_validation(self, attrs):
pass
def validate(self, attrs):
self._errors = {}
# Decode the uidb64 to uid to get User object
try:
uid = force_text(uid_decoder(attrs['uid']))
self.user = UserModel._default_manager.get(pk=uid)
except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist):
raise ValidationError({'uid': ['Invalid value']})
self.custom_validation(attrs)
# Construct SetPasswordForm instance
self.set_password_form = self.set_password_form_class(
user=self.user, data=attrs
)
if not self.set_password_form.is_valid():
raise serializers.ValidationError(self.set_password_form.errors)
if not default_token_generator.check_token(self.user, attrs['token']):
raise ValidationError({'token': ['Invalid value']})
return attrs
正如您最终看到的,这个 class 期望用户 ID 是 uidb64 而不是 uidb36,我什至不想知道令牌格式是否与预期相符这里。
我真的找不到关于如何为完整的密码重置过程正确设置 rest_auth
的好文档:我的电子邮件有效,但对我来说似乎 rest_auth
会生成错误token/reset-link 它实际上期望从用户那里得到什么。
总结
我相信,密码重置确认过程以正确的后端代码结束,而 email/token-generation 被搞砸了。
我想要的只是检索一个 uid 和一个 token 我可以将其发送回 django rest-auth 以便让用户重置密码。
目前,这些 uid 和令牌似乎是由一个库创建并由另一个库使用的,这两个库都期望并创建不同格式的令牌和 uid?
提前致谢!
满settings.py
这是我的全部 settings.py
:
# project/vuedj/settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
SECRET_KEY = persisted_settings.SECRET_KEY
DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
CORS_ORIGIN_ALLOW_ALL = True
CORS_URLS_REGEX = r'^/api/.*$'
CORS_ALLOW_CREDENTIALS = True
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.github',
'rest_auth',
'rest_auth.registration',
'sceneries',
'accounts',
'api',
'app',
]
EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = 'app-messages'
SITE_ID = 1
AUTH_USER_MODEL = 'accounts.User'
ACCOUNT_USER_MODEL_USERNAME_FIELD = 'username'
ACCOUNT_AUTHENTICATION_METHOD = 'username_email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = 'none'
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USERNAME_REQUIRED = True
ACCOUNT_USER_EMAIL_FIELD = 'email'
ACCOUNT_LOGOUT_ON_GET = True
ACCOUNT_FORMS = {"login": "accounts.forms.UserLoginForm"}
LOGIN_REDIRECT_URL = 'home'
LOGIN_URL = 'api/v1/accounts/login/'
CSRF_COOKIE_NAME = "csrftoken"
REST_AUTH_SERIALIZERS = {
"USER_DETAILS_SERIALIZER": "accounts.serializers.CustomUserDetailsSerializer",
"LOGIN_SERIALIZER": "accounts.serializers.CustomUserLoginSerializer",
"PASSWORD_RESET_SERIALIZER": "accounts.serializers.CustomPasswordResetSerializer"
}
REST_AUTH_REGISTER_SERIALIZERS = {
"REGISTER_SERIALIZER": "accounts.serializers.CustomRegisterSerializer",
}
# Following is added to enable registration with email instead of username
AUTHENTICATION_BACKENDS = (
# Needed to login by username in Django admin, regardless of `allauth`
"django.contrib.auth.backends.ModelBackend",
# `allauth` specific authentication methods, such as login by e-mail
"allauth.account.auth_backends.AuthenticationBackend",
)
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'vuedj.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
'templates/',
'templates/emails/'
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'vuedj.wsgi.application'
try:
DATABASES = persisted_settings.DATABASES
except AttributeError:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, '../staticfiles/static')
MEDIA_ROOT = os.path.join(BASE_DIR, '../staticfiles/mediafiles')
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
'--with-coverage',
'--cover-package=app', # For multiple apps use '--cover-package=foo, bar'
]
我们有相同的设置,我可以告诉你它有效,但我无法帮助你使用 36 进制,除了 Django documentation 说它是 64 进制!
但是,您已经写到这个理论部分对您来说不是那么重要,让我们找出您遗漏的要点。设置有点混乱,因为您不需要 allauth 的所有内容。我不明白你被困在哪里。因此,我想告诉你我是怎么做到的:
我定义了密码重置 URL 只是为了 Django/allauth 在电子邮件中创建 link 时找到它:
from django.views.generic import TemplateView
PASSWORD_RESET = (
r'^auth/password-reset-confirmation/'
r'(?P<uidb64>[0-9A-Za-z_\-]+)/'
r'(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})$'
)
urlpatterns += [
re_path(
PASSWORD_RESET,
TemplateView.as_view(),
name='password_reset_confirm',
),
]
你不必那样做(因为你include('allauth.urls')
,你实际上don't need these URLs)但我想说明一下,这个URL并不指向后端!就是说,让您的前端使用表单提供此 URL 以输入新密码,然后使用 axios 或其他方式 POST
uid
、token
、new_password1
和 new_password2
到您的端点。
在你的例子中,端点是
path(
'reset-password-confirm/',
acc_views.CustomPasswordResetConfirmView.as_view(),
name='reset-password-confirm'
),
这对你有帮助吗?否则,请告诉我。
幸运的是,我找到了一个不错的图书馆,它让我今天的生活变得如此轻松:
https://github.com/anx-ckreuzberger/django-rest-passwordreset
pip install django-rest-passwordreset
是这样工作的:
- 按照他们网站上的说明进行操作。
我的 accounts/urls.py
现在有以下路径:
# project/accounts/urls.py
from django.urls import path, include
from . import views as acc_views
app_name = 'accounts'
urlpatterns = [
path('', acc_views.UserListView.as_view(), name='user-list'),
path('login/', acc_views.UserLoginView.as_view(), name='login'),
path('logout/', acc_views.UserLogoutView.as_view(), name='logout'),
path('register/', acc_views.CustomRegisterView.as_view(), name='register'),
# NEW: custom verify-token view which is not included in django-rest-passwordreset
path('reset-password/verify-token/', acc_views.CustomPasswordTokenVerificationView.as_view(), name='password_reset_verify_token'),
# NEW: The django-rest-passwordreset urls to request a token and confirm pw-reset
path('reset-password/', include('django_rest_passwordreset.urls', namespace='password_reset')),
path('<int:pk>/', acc_views.UserDetailView.as_view(), name='user-detail')
]
然后我还为我的 CustomTokenVerification 添加了一点 TokenSerializer:
# project/accounts/serializers.py
from rest_framework import serializers
class CustomTokenSerializer(serializers.Serializer):
token = serializers.CharField()
然后我在之前派生的CustomPasswordResetView
中添加了一个Signal Receiver,现在不再派生自rest_auth.views.PasswordResetView
AND 添加了一个新视图 CustomPasswordTokenVerificationView
:
# project/accounts/views.py
from django.dispatch import receiver
from django_rest_passwordreset.signals import reset_password_token_created
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from vuedj.constants import site_url, site_full_name, site_shortcut_name
from rest_framework.views import APIView
from rest_framework import parsers, renderers, status
from rest_framework.response import Response
from .serializers import CustomTokenSerializer
from django_rest_passwordreset.models import ResetPasswordToken
from django_rest_passwordreset.views import get_password_reset_token_expiry_time
from django.utils import timezone
from datetime import timedelta
class CustomPasswordResetView:
@receiver(reset_password_token_created)
def password_reset_token_created(sender, reset_password_token, *args, **kwargs):
"""
Handles password reset tokens
When a token is created, an e-mail needs to be sent to the user
"""
# send an e-mail to the user
context = {
'current_user': reset_password_token.user,
'username': reset_password_token.user.username,
'email': reset_password_token.user.email,
'reset_password_url': "{}/password-reset/{}".format(site_url, reset_password_token.key),
'site_name': site_shortcut_name,
'site_domain': site_url
}
# render email text
email_html_message = render_to_string('email/user_reset_password.html', context)
email_plaintext_message = render_to_string('email/user_reset_password.txt', context)
msg = EmailMultiAlternatives(
# title:
"Password Reset for {}".format(site_full_name),
# message:
email_plaintext_message,
# from:
"noreply@{}".format(site_url),
# to:
[reset_password_token.user.email]
)
msg.attach_alternative(email_html_message, "text/html")
msg.send()
class CustomPasswordTokenVerificationView(APIView):
"""
An Api View which provides a method to verifiy that a given pw-reset token is valid before actually confirming the
reset.
"""
throttle_classes = ()
permission_classes = ()
parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
renderer_classes = (renderers.JSONRenderer,)
serializer_class = CustomTokenSerializer
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
token = serializer.validated_data['token']
# get token validation time
password_reset_token_validation_time = get_password_reset_token_expiry_time()
# find token
reset_password_token = ResetPasswordToken.objects.filter(key=token).first()
if reset_password_token is None:
return Response({'status': 'invalid'}, status=status.HTTP_404_NOT_FOUND)
# check expiry date
expiry_date = reset_password_token.created_at + timedelta(hours=password_reset_token_validation_time)
if timezone.now() > expiry_date:
# delete expired token
reset_password_token.delete()
return Response({'status': 'expired'}, status=status.HTTP_404_NOT_FOUND)
# check if user has password to change
if not reset_password_token.user.has_usable_password():
return Response({'status': 'irrelevant'})
return Response({'status': 'OK'})
现在我的前端将提供一个选项来请求 pw-reset link,因此前端将向 django 发送一个 post 请求,如下所示:
// urls.js
const SERVER_URL = 'http://localhost:8000/' // FIXME: change at production (https and correct IP and port)
const API_URL = 'api/v1/'
const API_AUTH = 'auth/'
API_AUTH_PASSWORD_RESET = API_AUTH + 'reset-password/'
// api.js
import axios from 'axios'
import urls from './urls'
axios.defaults.baseURL = urls.SERVER_URL + urls.API_URL
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'
axios.defaults.xsrfCookieName = 'csrftoken'
const api = {
get,
post,
patch,
put,
head,
delete: _delete
}
function post (url, request) {
return axios.post(url, request)
.then((response) => Promise.resolve(response))
.catch((error) => Promise.reject(error))
}
// user.service.js
import api from '@/_api/api'
import urls from '@/_api/urls'
api.post(`${urls.API_AUTH_PASSWORD_RESET}`, email)
.then( /* handle success */ )
.catch( /* handle error */ )
并且创建的电子邮件将包含这样的 link:
Click the link below to reset your password.
localhost:8000/password-reset/4873759c229f17a94546a63eb7c3d482e73983495fa40c7ec2a3d9ca1adcf017
... 未在 django-urls 中有意定义!
Django 会让每个未知的 url 通过,vue 路由器将决定 url 是否有意义。
然后我让前端发送 token 看看它是否有效,这样用户就可以看到 token 是否已经被使用、过期或其他...
// urls.js
const API_AUTH_PASSWORD_RESET_VERIFY_TOKEN = API_AUTH + 'reset-password/verify-token/'
// users.service.js
api.post(`${urls.API_AUTH_PASSWORD_RESET_VERIFY_TOKEN}`, pwResetToken)
.then( /* handle success */ )
.catch( /* handle error */ )
现在用户将通过 Vue 或密码输入字段收到一条错误消息,他们最终可以在其中重置密码,前端将像这样发送密码:
// urls.js
const API_AUTH_PASSWORD_RESET_CONFIRM = API_AUTH + 'reset-password/confirm/'
// users.service.js
api.post(`${urls.API_AUTH_PASSWORD_RESET_CONFIRM}`, {
token: state[token], // (vuex state)
password: state[password] // (vuex state)
})
.then( /* handle success */ )
.catch( /* handle error */ )
这是主要代码。我使用自定义 vue 路由将 django 剩余端点与前端可见路由分离。剩下的是 api 请求和处理他们的响应。
希望这对以后像我一样挣扎的人有所帮助。
我对可用的 django 中间件完全困惑:
我只是想获得密码重置(以及后来的密码更改)功能 运行,在后端使用 django
和 rest_auth
,在前端使用 Vue。
第 1 步:通过邮件请求重置-Link
观看次数
到目前为止我做了一个CustomPasswordResetView
:
# project/accounts/views.py
from rest_auth.views import PasswordResetView
class CustomPasswordResetView(PasswordResetView):
pass
序列化程序
和一个CustomPasswordResetSerializer
:
# project/accounts/serializers.py
from rest_auth.serializers import PasswordResetSerializer
class CustomPasswordResetSerializer(PasswordResetSerializer):
email = serializers.EmailField()
password_reset_form_class = ResetPasswordForm
def validate_email(self, value):
# Create PasswordResetForm with the serializer
self.reset_form = self.password_reset_form_class(data=self.initial_data)
if not self.reset_form.is_valid():
raise serializers.ValidationError(self.reset_form.errors)
###### FILTER YOUR USER MODEL ######
if not get_user_model().objects.filter(email=value).exists():
raise serializers.ValidationError(_('Invalid e-mail address'))
return value
def save(self):
request = self.context.get('request')
# Set some values to trigger the send_email method.
opts = {
'use_https': request.is_secure(),
'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
'request': request,
}
opts.update(self.get_email_options())
self.reset_form.save(**opts)
Settings.py
在 settings.py
中,我有这些字段,它们似乎与我的问题相关:
# project/vuedj/settings.py
REST_AUTH_SERIALIZERS = {
"USER_DETAILS_SERIALIZER": "accounts.serializers.CustomUserDetailsSerializer",
"LOGIN_SERIALIZER": "accounts.serializers.CustomUserLoginSerializer",
"PASSWORD_RESET_SERIALIZER": "accounts.serializers.CustomPasswordResetSerializer"
}
(完整的settings.py
附在最下面)
URL 模式
我的网址已经捕捉到我的 API 请求,以便发送密码重置电子邮件:
# project/vuedj/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/', include('api.urls')),
path('accounts/', include('allauth.urls')),
path('', api_views.index, name='home')
]
# project/api/urls.py
urlpatterns = [
path('auth/', include('accounts.urls')),
# other paths...
]
# project/accounts/urls.py
urlpatterns = [
path('', acc_views.UserListView.as_view(), name='user-list'),
path('login/', acc_views.UserLoginView.as_view(), name='login'),
path('logout/', acc_views.UserLogoutView.as_view(), name='logout'),
path('register/', acc_views.CustomRegisterView.as_view(), name='register'),
path('reset-password/', acc_views.CustomPasswordResetView.as_view(), name='reset-password'),
path('reset-password-confirm/', acc_views.CustomPasswordResetConfirmView.as_view(), name='reset-password-confirm'),
path('<int:pk>/', acc_views.UserDetailView.as_view(), name='user-detail')
]
带有 PW-Reset 令牌生成器的电子邮件
CustomPasswordReset 视图最终会生成一封带有漂亮密码重置的漂亮电子邮件 link。 link是有效的,点进去,我可以完美的通过allauth模板重置密码。
rest-auth 使用此代码(间接)生成重置令牌:
# project/.venv/Lib/site-packages/allauth/account/forms.py
def save(self, request, **kwargs):
current_site = get_current_site(request)
email = self.cleaned_data["email"]
token_generator = kwargs.get("token_generator",
default_token_generator)
for user in self.users:
temp_key = token_generator.make_token(user)
# save it to the password reset model
# password_reset = PasswordReset(user=user, temp_key=temp_key)
# password_reset.save()
# send the password reset email
path = reverse("account_reset_password_from_key",
kwargs=dict(uidb36=user_pk_to_url_str(user),
key=temp_key))
url = build_absolute_uri(
request, path)
context = {"current_site": current_site,
"user": user,
"password_reset_url": url,
"request": request}
if app_settings.AUTHENTICATION_METHOD \
!= AuthenticationMethod.EMAIL:
context['username'] = user_username(user)
get_adapter(request).send_mail(
'account/email/password_reset_key',
email,
context)
return self.cleaned_data["email"]
这个PasswordResetTokenGenerator
用在上面的代码中:
# project/.venv/Lib/site-packages/django/contrib/auth/tokens.py
class PasswordResetTokenGenerator:
"""
Strategy object used to generate and check tokens for the password
reset mechanism.
"""
key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator"
secret = settings.SECRET_KEY
def make_token(self, user):
"""
Return a token that can be used once to do a password reset
for the given user.
"""
return self._make_token_with_timestamp(user, self._num_days(self._today()))
def check_token(self, user, token):
"""
Check that a password reset token is correct for a given user.
"""
if not (user and token):
return False
# Parse the token
try:
ts_b36, hash = token.split("-")
except ValueError:
return False
try:
ts = base36_to_int(ts_b36)
except ValueError:
return False
# Check that the timestamp/uid has not been tampered with
if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
return False
# Check the timestamp is within limit. Timestamps are rounded to
# midnight (server time) providing a resolution of only 1 day. If a
# link is generated 5 minutes before midnight and used 6 minutes later,
# that counts as 1 day. Therefore, PASSWORD_RESET_TIMEOUT_DAYS = 1 means
# "at least 1 day, could be up to 2."
if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
return False
return True
上面的 classes 将被 rest_auth
PasswordResetView
:
# project/.venv/Lib/site-packages/rest_auth/views.py
class PasswordResetView(GenericAPIView):
"""
Calls Django Auth PasswordResetForm save method.
Accepts the following POST parameters: email
Returns the success/fail message.
"""
serializer_class = PasswordResetSerializer
permission_classes = (AllowAny,)
def post(self, request, *args, **kwargs):
# Create a serializer with request.data
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save() # <----- Code from above (TokenGenerator) will be called inside this .save() method
# Return the success message with OK HTTP status
return Response(
{"detail": _("Password reset e-mail has been sent.")},
status=status.HTTP_200_OK
)
如您所见,令牌生成器将 return 一个 uidb36
与令牌。
当用户确认密码重置时,它还假定 uidb36
。
生成的令牌(例如生成邮件中的完整 link)将如下所示:
http://localhost:8000/accounts/password/reset/key/16-52h-42b222e6dc30690b2e91/
其中16
是base 36(uidb36
)中的用户id,我还不知道52h
是什么意思,但是我假设,令牌的第三部分是令牌本身 (42b222e6dc30690b2e91
)
第 2 步:将令牌发送到后端(又名 "User clicks link")
我被困在这里了。 API-Endpoints of the Rest-Auth-Framework 说:
/rest-auth/password/reset/confirm/ (POST)
uid
token
new_password1
new_password2
当我发送对象时,例如:
{
uid: '16', // TODO maybe I have to convert it to base10...
token: '42b222e6dc30690b2e91',
new_password1: 'test123A$',
new_password2: 'test123A$'
}
通过我的 api 到 http://localhost:8000/api/v1/auth/reset-password/
上面的对象在 axios
-post 请求的主体中,我的 CustomPasswordResetConfirmView
像预期的那样被触发,它也只是 rest_auth
中 PasswordResetConfirmView
的 Subclass,因此执行此代码:
# project/.venv/Lib/site-packages/rest_auth/views.py
class PasswordResetConfirmView(GenericAPIView):
"""
Password reset e-mail link is confirmed, therefore
this resets the user's password.
Accepts the following POST parameters: token, uid,
new_password1, new_password2
Returns the success/fail message.
"""
serializer_class = PasswordResetConfirmSerializer
permission_classes = (AllowAny,)
@sensitive_post_parameters_m
def dispatch(self, *args, **kwargs):
return super(PasswordResetConfirmView, self).dispatch(*args, **kwargs)
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(
{"detail": _("Password has been reset with the new password.")}
)
行 serializer.is_valid(raise_exception=True)
将调用 rest_framework
的 Serializer(BaseSerializer)
的 run_validation
。
这将进一步使用 rest_auth
的 PasswordResetConfirmSerializer
:
# project/.venv/Lib/site-packages/rest_auth/serializers.py
class PasswordResetConfirmSerializer(serializers.Serializer):
"""
Serializer for requesting a password reset e-mail.
"""
new_password1 = serializers.CharField(max_length=128)
new_password2 = serializers.CharField(max_length=128)
uid = serializers.CharField()
token = serializers.CharField()
set_password_form_class = SetPasswordForm
def custom_validation(self, attrs):
pass
def validate(self, attrs):
self._errors = {}
# Decode the uidb64 to uid to get User object
try:
uid = force_text(uid_decoder(attrs['uid']))
self.user = UserModel._default_manager.get(pk=uid)
except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist):
raise ValidationError({'uid': ['Invalid value']})
self.custom_validation(attrs)
# Construct SetPasswordForm instance
self.set_password_form = self.set_password_form_class(
user=self.user, data=attrs
)
if not self.set_password_form.is_valid():
raise serializers.ValidationError(self.set_password_form.errors)
if not default_token_generator.check_token(self.user, attrs['token']):
raise ValidationError({'token': ['Invalid value']})
return attrs
正如您最终看到的,这个 class 期望用户 ID 是 uidb64 而不是 uidb36,我什至不想知道令牌格式是否与预期相符这里。
我真的找不到关于如何为完整的密码重置过程正确设置 rest_auth
的好文档:我的电子邮件有效,但对我来说似乎 rest_auth
会生成错误token/reset-link 它实际上期望从用户那里得到什么。
总结
我相信,密码重置确认过程以正确的后端代码结束,而 email/token-generation 被搞砸了。
我想要的只是检索一个 uid 和一个 token 我可以将其发送回 django rest-auth 以便让用户重置密码。 目前,这些 uid 和令牌似乎是由一个库创建并由另一个库使用的,这两个库都期望并创建不同格式的令牌和 uid?
提前致谢!
满settings.py
这是我的全部 settings.py
:
# project/vuedj/settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
SECRET_KEY = persisted_settings.SECRET_KEY
DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
CORS_ORIGIN_ALLOW_ALL = True
CORS_URLS_REGEX = r'^/api/.*$'
CORS_ALLOW_CREDENTIALS = True
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.github',
'rest_auth',
'rest_auth.registration',
'sceneries',
'accounts',
'api',
'app',
]
EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = 'app-messages'
SITE_ID = 1
AUTH_USER_MODEL = 'accounts.User'
ACCOUNT_USER_MODEL_USERNAME_FIELD = 'username'
ACCOUNT_AUTHENTICATION_METHOD = 'username_email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = 'none'
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USERNAME_REQUIRED = True
ACCOUNT_USER_EMAIL_FIELD = 'email'
ACCOUNT_LOGOUT_ON_GET = True
ACCOUNT_FORMS = {"login": "accounts.forms.UserLoginForm"}
LOGIN_REDIRECT_URL = 'home'
LOGIN_URL = 'api/v1/accounts/login/'
CSRF_COOKIE_NAME = "csrftoken"
REST_AUTH_SERIALIZERS = {
"USER_DETAILS_SERIALIZER": "accounts.serializers.CustomUserDetailsSerializer",
"LOGIN_SERIALIZER": "accounts.serializers.CustomUserLoginSerializer",
"PASSWORD_RESET_SERIALIZER": "accounts.serializers.CustomPasswordResetSerializer"
}
REST_AUTH_REGISTER_SERIALIZERS = {
"REGISTER_SERIALIZER": "accounts.serializers.CustomRegisterSerializer",
}
# Following is added to enable registration with email instead of username
AUTHENTICATION_BACKENDS = (
# Needed to login by username in Django admin, regardless of `allauth`
"django.contrib.auth.backends.ModelBackend",
# `allauth` specific authentication methods, such as login by e-mail
"allauth.account.auth_backends.AuthenticationBackend",
)
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'vuedj.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
'templates/',
'templates/emails/'
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'vuedj.wsgi.application'
try:
DATABASES = persisted_settings.DATABASES
except AttributeError:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, '../staticfiles/static')
MEDIA_ROOT = os.path.join(BASE_DIR, '../staticfiles/mediafiles')
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
'--with-coverage',
'--cover-package=app', # For multiple apps use '--cover-package=foo, bar'
]
我们有相同的设置,我可以告诉你它有效,但我无法帮助你使用 36 进制,除了 Django documentation 说它是 64 进制!
但是,您已经写到这个理论部分对您来说不是那么重要,让我们找出您遗漏的要点。设置有点混乱,因为您不需要 allauth 的所有内容。我不明白你被困在哪里。因此,我想告诉你我是怎么做到的:
我定义了密码重置 URL 只是为了 Django/allauth 在电子邮件中创建 link 时找到它:
from django.views.generic import TemplateView
PASSWORD_RESET = (
r'^auth/password-reset-confirmation/'
r'(?P<uidb64>[0-9A-Za-z_\-]+)/'
r'(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})$'
)
urlpatterns += [
re_path(
PASSWORD_RESET,
TemplateView.as_view(),
name='password_reset_confirm',
),
]
你不必那样做(因为你include('allauth.urls')
,你实际上don't need these URLs)但我想说明一下,这个URL并不指向后端!就是说,让您的前端使用表单提供此 URL 以输入新密码,然后使用 axios 或其他方式 POST
uid
、token
、new_password1
和 new_password2
到您的端点。
在你的例子中,端点是
path(
'reset-password-confirm/',
acc_views.CustomPasswordResetConfirmView.as_view(),
name='reset-password-confirm'
),
这对你有帮助吗?否则,请告诉我。
幸运的是,我找到了一个不错的图书馆,它让我今天的生活变得如此轻松:
https://github.com/anx-ckreuzberger/django-rest-passwordreset
pip install django-rest-passwordreset
是这样工作的:
- 按照他们网站上的说明进行操作。
我的 accounts/urls.py
现在有以下路径:
# project/accounts/urls.py
from django.urls import path, include
from . import views as acc_views
app_name = 'accounts'
urlpatterns = [
path('', acc_views.UserListView.as_view(), name='user-list'),
path('login/', acc_views.UserLoginView.as_view(), name='login'),
path('logout/', acc_views.UserLogoutView.as_view(), name='logout'),
path('register/', acc_views.CustomRegisterView.as_view(), name='register'),
# NEW: custom verify-token view which is not included in django-rest-passwordreset
path('reset-password/verify-token/', acc_views.CustomPasswordTokenVerificationView.as_view(), name='password_reset_verify_token'),
# NEW: The django-rest-passwordreset urls to request a token and confirm pw-reset
path('reset-password/', include('django_rest_passwordreset.urls', namespace='password_reset')),
path('<int:pk>/', acc_views.UserDetailView.as_view(), name='user-detail')
]
然后我还为我的 CustomTokenVerification 添加了一点 TokenSerializer:
# project/accounts/serializers.py
from rest_framework import serializers
class CustomTokenSerializer(serializers.Serializer):
token = serializers.CharField()
然后我在之前派生的CustomPasswordResetView
中添加了一个Signal Receiver,现在不再派生自rest_auth.views.PasswordResetView
AND 添加了一个新视图 CustomPasswordTokenVerificationView
:
# project/accounts/views.py
from django.dispatch import receiver
from django_rest_passwordreset.signals import reset_password_token_created
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from vuedj.constants import site_url, site_full_name, site_shortcut_name
from rest_framework.views import APIView
from rest_framework import parsers, renderers, status
from rest_framework.response import Response
from .serializers import CustomTokenSerializer
from django_rest_passwordreset.models import ResetPasswordToken
from django_rest_passwordreset.views import get_password_reset_token_expiry_time
from django.utils import timezone
from datetime import timedelta
class CustomPasswordResetView:
@receiver(reset_password_token_created)
def password_reset_token_created(sender, reset_password_token, *args, **kwargs):
"""
Handles password reset tokens
When a token is created, an e-mail needs to be sent to the user
"""
# send an e-mail to the user
context = {
'current_user': reset_password_token.user,
'username': reset_password_token.user.username,
'email': reset_password_token.user.email,
'reset_password_url': "{}/password-reset/{}".format(site_url, reset_password_token.key),
'site_name': site_shortcut_name,
'site_domain': site_url
}
# render email text
email_html_message = render_to_string('email/user_reset_password.html', context)
email_plaintext_message = render_to_string('email/user_reset_password.txt', context)
msg = EmailMultiAlternatives(
# title:
"Password Reset for {}".format(site_full_name),
# message:
email_plaintext_message,
# from:
"noreply@{}".format(site_url),
# to:
[reset_password_token.user.email]
)
msg.attach_alternative(email_html_message, "text/html")
msg.send()
class CustomPasswordTokenVerificationView(APIView):
"""
An Api View which provides a method to verifiy that a given pw-reset token is valid before actually confirming the
reset.
"""
throttle_classes = ()
permission_classes = ()
parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
renderer_classes = (renderers.JSONRenderer,)
serializer_class = CustomTokenSerializer
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
token = serializer.validated_data['token']
# get token validation time
password_reset_token_validation_time = get_password_reset_token_expiry_time()
# find token
reset_password_token = ResetPasswordToken.objects.filter(key=token).first()
if reset_password_token is None:
return Response({'status': 'invalid'}, status=status.HTTP_404_NOT_FOUND)
# check expiry date
expiry_date = reset_password_token.created_at + timedelta(hours=password_reset_token_validation_time)
if timezone.now() > expiry_date:
# delete expired token
reset_password_token.delete()
return Response({'status': 'expired'}, status=status.HTTP_404_NOT_FOUND)
# check if user has password to change
if not reset_password_token.user.has_usable_password():
return Response({'status': 'irrelevant'})
return Response({'status': 'OK'})
现在我的前端将提供一个选项来请求 pw-reset link,因此前端将向 django 发送一个 post 请求,如下所示:
// urls.js
const SERVER_URL = 'http://localhost:8000/' // FIXME: change at production (https and correct IP and port)
const API_URL = 'api/v1/'
const API_AUTH = 'auth/'
API_AUTH_PASSWORD_RESET = API_AUTH + 'reset-password/'
// api.js
import axios from 'axios'
import urls from './urls'
axios.defaults.baseURL = urls.SERVER_URL + urls.API_URL
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'
axios.defaults.xsrfCookieName = 'csrftoken'
const api = {
get,
post,
patch,
put,
head,
delete: _delete
}
function post (url, request) {
return axios.post(url, request)
.then((response) => Promise.resolve(response))
.catch((error) => Promise.reject(error))
}
// user.service.js
import api from '@/_api/api'
import urls from '@/_api/urls'
api.post(`${urls.API_AUTH_PASSWORD_RESET}`, email)
.then( /* handle success */ )
.catch( /* handle error */ )
并且创建的电子邮件将包含这样的 link:
Click the link below to reset your password.
localhost:8000/password-reset/4873759c229f17a94546a63eb7c3d482e73983495fa40c7ec2a3d9ca1adcf017
... 未在 django-urls 中有意定义! Django 会让每个未知的 url 通过,vue 路由器将决定 url 是否有意义。 然后我让前端发送 token 看看它是否有效,这样用户就可以看到 token 是否已经被使用、过期或其他...
// urls.js
const API_AUTH_PASSWORD_RESET_VERIFY_TOKEN = API_AUTH + 'reset-password/verify-token/'
// users.service.js
api.post(`${urls.API_AUTH_PASSWORD_RESET_VERIFY_TOKEN}`, pwResetToken)
.then( /* handle success */ )
.catch( /* handle error */ )
现在用户将通过 Vue 或密码输入字段收到一条错误消息,他们最终可以在其中重置密码,前端将像这样发送密码:
// urls.js
const API_AUTH_PASSWORD_RESET_CONFIRM = API_AUTH + 'reset-password/confirm/'
// users.service.js
api.post(`${urls.API_AUTH_PASSWORD_RESET_CONFIRM}`, {
token: state[token], // (vuex state)
password: state[password] // (vuex state)
})
.then( /* handle success */ )
.catch( /* handle error */ )
这是主要代码。我使用自定义 vue 路由将 django 剩余端点与前端可见路由分离。剩下的是 api 请求和处理他们的响应。
希望这对以后像我一样挣扎的人有所帮助。