gpt4 book ai didi

dj_rest_auth password reset serializer is not working(DJ_REST_AUTH密码重置串行化程序不工作)

转载 作者:bug小助手 更新时间:2023-10-25 11:27:24 26 4
gpt4 key购买 nike



I have followed this guide and also tried this stackoverflow post but for some reason none of them seem to pick up anything from my custom serializer for password reset. I have implemented the custom serializer like this:

我遵循了这个指南,也尝试了这个堆栈溢出帖子,但出于某种原因,他们似乎都没有从我的定制序列化程序中获得任何密码重置。我实现了定制的序列化程序,如下所示:


accounts/urls.py

帐户/urls.py


from django.urls import include, path
from .views import check_user_email
from dj_rest_auth.views import PasswordResetConfirmView, PasswordResetView
from django.views.generic import TemplateView

urlpatterns = [
path(
"password/reset/confirm/<slug:uidb64>/<slug:token>/",
PasswordResetConfirmView.as_view(),
name="password_reset_confirm",
),
path("", include("dj_rest_auth.urls")),
# path("registration/", include("dj_rest_auth.registration.urls")),
path("check-user-email/", check_user_email),
]

accounts/serializer.py

Account/Serializer.py


from allauth.account.utils import (
filter_users_by_email,
user_pk_to_url_str,
user_username,
)
from allauth.utils import build_absolute_uri
from django.contrib.sites.shortcuts import get_current_site
from allauth.account.adapter import get_adapter
from allauth.account.forms import default_token_generator
from allauth.account import app_settings
from dj_rest_auth.forms import AllAuthPasswordResetForm
from dj_rest_auth.serializers import PasswordResetSerializer
from rest_framework import serializers


class CustomAllAuthPasswordResetForm(AllAuthPasswordResetForm):
def clean_email(self):
"""
Invalid email should not raise error, as this would leak users
for unit test: test_password_reset_with_invalid_email
"""
email = self.cleaned_data["email"]
email = get_adapter().clean_email(email)
self.users = filter_users_by_email(email, is_active=True)
return self.cleaned_data["email"]

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)

path = f"I basically want to add frontend url here/{user_pk_to_url_str(user)}/{temp_key}/"
url = build_absolute_uri(request, path)
# Values which are passed to password_reset_key_message.txt
context = {
"current_site": current_site,
"user": user,
"password_reset_url": url,
"request": request,
"path": path,
}

if (
app_settings.AUTHENTICATION_METHOD
!= app_settings.AuthenticationMethod.EMAIL
):
context["username"] = user_username(user)
get_adapter(request).send_mail(
"account/email/password_reset_key", email, context
)

return self.cleaned_data["email"]


class MyPasswordResetSerializer(PasswordResetSerializer):
def validate_email(self, value):
# use the custom reset form
self.reset_form = CustomAllAuthPasswordResetForm(data=self.initial_data)
if not self.reset_form.is_valid():
raise serializers.ValidationError(self.reset_form.errors)

return value

This is settings.py file:

这是settings.py文件:


"""
Django settings for server project.

Generated by 'django-admin startproject' using Django 4.2.3.

For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

import os
from datetime import timedelta
from pathlib import Path

from decouple import config

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config("SECRET_KEY")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config("DEBUG", cast=bool)
isProd = (
config("ENVIRONMENT") != "local"
) # true of isProd == "production" or isProd == "staged"

ALLOWED_HOSTS = config("HOSTS", cast=lambda v: [s.strip() for s in v.split(",")])
ORIGINS = config("ORIGINS", cast=lambda v: [s.strip() for s in v.split(",")])
CORS_ALLOWED_ORIGINS = ORIGINS
CSRF_TRUSTED_ORIGINS = ORIGINS

# 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",
"accounts",
"api",
"rest_framework",
"rest_framework.authtoken",
"dj_rest_auth",
"corsheaders",
"allauth",
"allauth.account",
"dj_rest_auth.registration",
]

MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"accounts.middleware.VerifyTokenByHttpOnlyCookie",
]

ROOT_URLCONF = "server.urls"

TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [os.path.join(BASE_DIR, "templates")],
"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 = "server.wsgi.application"


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

# Database
if isProd:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": config("DB_NAME"),
"USER": config("DB_USER"),
"PASSWORD": config("DB_PASS"),
"HOST": "localhost",
"PORT": "",
}
}
else:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}


# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

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",
},
]


# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = "static/"
STATIC_ROOT = os.path.join(BASE_DIR, "static/")

MEDIA_URL = "media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media/")

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

SITE_ID = 1

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

ACCOUNT_AUTHENTICATION_METHOD = "email"
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_EMAIL_VERIFICATION = config("EMAIL_VERIFICATION")

EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = config("APP_EMAIL_USER")
EMAIL_HOST_PASSWORD = config("APP_EMAIL_PASS")

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",
]

REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"dj_rest_auth.jwt_auth.JWTCookieAuthentication",
),
"DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
"EXCEPTION_HANDLER": "rest_framework.views.exception_handler",
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
"PAGE_SIZE": 25,
}

REST_AUTH_SERIALIZERS = {
"PASSWORD_RESET_SERIALIZER": "accounts.serializers.MyPasswordResetSerializer",
}

CORS_ALLOW_CREDENTIALS = True
CONN_MAX_AGE = None if isProd else 0 # persistent database connections in prod/stage

CSRF_COOKIE_SECURE = isProd
SESSION_COOKIE_SECURE = isProd
SECURE_SSL_REDIRECT = isProd

REST_AUTH = {
"USE_JWT": True,
"JWT_AUTH_COOKIE": "jwt-auth",
"JWT_AUTH_REFRESH_COOKIE": "jwt-refresh",
"JWT_AUTH_SECURE": isProd,
}

SIMPLE_JWT = {
"ACCESS_TOKEN_LIFETIME": timedelta(days=1),
"REFRESH_TOKEN_LIFETIME": timedelta(days=15),
}

I am using dj-rest-auth==4.0.1, django-allauth==0.54.0 what am I doing wrong! Did they changed some settings!!!!

我正在使用dj-rest-auth==4.0.1,django-allauth==0.54.0我做错了什么!他们是否更改了某些设置!


更多回答
优秀答案推荐

The problem was how I was using the serializers in the settings.py! All the articles online refers that the serializer should be imported like this:

问题是我是如何使用settings.py中的序列化程序的!网上的所有文章都提到,序列化程序应该像这样导入:


REST_AUTH_SERIALIZERS = {
"PASSWORD_RESET_SERIALIZER": "accounts.serializers.MyPasswordResetSerializer",
}

But nope you have to do it like this:

但不,你必须这样做:


REST_AUTH = {
"PASSWORD_RESET_SERIALIZER": "accounts.serializers.MyPasswordResetSerializer",
}

Change REST_AUTH_SERIALIZERS to REST_AUTH and it should work. I think dj_rest_auth package changed recently how you should use the variables! And instantly every other article became obsolete. It would be so much easier if they detailly documented this exact setting on how to use custom serializer for password-reset/account-confirm-email in their own doc. Then I didn't have to waste my 8h time debugging different things! May be they did, comment it if anyone can find this.

将REST_AUTH_SERIALIZERS更改为REST_AUTH,它应该可以工作。我认为dj_rest_auth包最近改变了您应该如何使用变量!很快,所有其他文章都变得过时了。如果他们在自己的文档中详细记录了如何对密码重置/帐户确认电子邮件使用定制序列化程序的准确设置,就会容易得多。这样我就不必浪费8小时的时间来调试不同的东西了!也许他们做到了,如果有人能发现这一点,请评论一下。


更多回答

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com