django Djoser重置密码流到JavaScript前端(Vue)

6l7fqoea  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(125)

我在django中使用djoser完成了大部分密码重置流程。我成功收到了电子邮件。最后一个部分是在用户点击电子邮件中的链接后,我重定向回Vue.js前端,这是我唯一缺少的。为了清楚起见,我希望被重定向到我的Vue前端URL,其中包含uidtoken。从那里我就能完成这一切。我的django文件是:
backend/settings.py(查看DJOSER设置):

"""
Django settings for backend project.

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

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/
"""

from pathlib import Path
from django.urls import reverse

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

# 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 = 'django-insecure-1z1=&mfysp%pklgh@x+^_j3+p5)x+zm@va36wc9eq0z=7r3u7z'

STRIPE_SECRET_KEY = 'sk_test_51NH4LnIIOIhiNEiGlcpsukLE5pi6Me9zYOhTf1uVP4ux7WgCXyR5QG9b6Yzfgm6qB4Agl8ZcQwZ7RN2rKIex04nk00kF97Aeok'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['127.0.0.1']

CORS_ALLOW_CREDENTIALS = True

CSRF_TRUSTED_ORIGINS = [
    'http://127.0.0.1:8080',
]

CORS_ALLOWED_ORIGINS = [
    'http://127.0.0.1:8080',
]

CSRF_COOKIE_HTTPONLY = False

# SESSION_COOKIE_SAMESITE = 'None'
# CORS_ALLOW_CREDENTIALS = True

EMAIL_BACKEND = "django.core.mail.backends.filebased.EmailBackend"
EMAIL_FILE_PATH = BASE_DIR / 'emails'


# Application definition
DJOSER = {
    'PASSWORD_RESET_CONFIRM_URL': 'api/v1/password/reset/confirm/{uid}/{token}', #help me change this please
    
    # 'ACTIVATION_URL': '#/api/v1/activate/{uid}/{token}',
    'SEND_ACTIVATION_EMAIL': True,
    'SERIALIZERS': {},
}

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'rest_framework',
    'rest_framework.authtoken',
    'corsheaders',
    'djoser',

    'product',
    'order',
    'email_app'
]

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

ROOT_URLCONF = 'backend.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'backend.wsgi.application'

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

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/'
MEDIA_URL = 'media/'
MEDIA_ROOT = BASE_DIR / 'media/'

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

字符串
backend/urls.py:

from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/v1/', include('djoser.urls')),
    path('api/v1/', include('djoser.urls.authtoken')),
    path('api/v1/', include('product.urls')),
    path('api/v1/', include('order.urls')),
    path('api/v1/', include('email_app.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


在前端,我有ResetPassword、ResetPasswordDone和ResetPasswordConfirm的路由。
frontend/router/index.js:

import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

import store from '../store'

import ResetPassword from '../views/ResetPassword.vue'
import ResetPasswordConfirm from '../views/ResetPasswordConfirm.vue'
import ResetPasswordDone from '../views/ResetPasswordDone.vue'

const routes = [
  
  
  {
    path: '/reset-password',
    name: 'ResetPassword',
    component: ResetPassword
  },
  {
    path: '/reset-password-done',
    name: 'ResetPasswordDone',
    component: ResetPasswordDone
  },
  {
    path: '/api/v1/password/reset/confirm/:{uid}/:{token}', // this is the path I want DJOSER to redirect to with `uid` and `token`
    name: 'ResetPasswordConfirm',
    component: ResetPasswordConfirm
  },
]


关于DJOSER我采取的步骤:
1.发布到api/v1/reset_password

const config = {
                    headers:{
                        'Content-Type': 'application/json'
                    }
                }
                const email = this.email;
                const body = JSON.stringify({ email })
                
                axios.defaults.withCredentials = true;
                axios.defaults.headers.common = {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRFToken' : this.getCookie('csrftoken')
                };

                axios.post('/api/v1/users/reset_password/', body, config)

  1. djoser用这个链接创建电子邮件,
    后端/电子邮件:
Content-Type: multipart/alternative;
 boundary="===============0720596674918646286=="
MIME-Version: 1.0
Subject: Password reset on 127.0.0.1:8000
From: webmaster@localhost
To: kenneth.shimabukuro@gmail.com
Date: Fri, 21 Jul 2023 11:01:05 -0000
Message-ID: <168993726590.34747.17316762060486301205@2.1.168.192.in-addr.arpa>

--===============0720596674918646286==
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

You're receiving this email because you requested a password reset for your user account at 127.0.0.1:8000.

Please go to the following page and choose a new password:
http://127.0.0.1:8000/api/v1/password/reset/confirm/NQ/brop9t-929c0b1e6031f0d34ca241f1867ba0c1
Your username, in case you've forgotten: ken4

Thanks for using our site!

The 127.0.0.1:8000 team


所有我需要的是djoser发送一封电子邮件重定向到http:127.0.0.1:8080而不是http:127.0.0.1:8000uidtoken存在。我该怎么做呢?

f4t66c6m

f4t66c6m1#

感觉我在这里自言自语,但这是答案(也许我问得不好)。在settings.py中添加DOMAIN。这是基于django docsthis answer,它们指定如果后端和前端位于不同的端口,则需要指定DOMAIN
更新settings.py:

...
DOMAIN = '127.0.0.1:8080'
SITE_NAME = 'd-commerce'
...

DJOSER = {
    'PASSWORD_RESET_CONFIRM_URL': 'api/v1/users/reset_password_confirm/{uid}/{token}',
    'PASSWORD_RESET_CONFIRM_RETYPE' : True,
    'SERIALIZERS': {},
}
...

字符串
你会收到一封电子邮件

Content-Type: multipart/alternative;
 boundary="===============5014392667940436431=="
MIME-Version: 1.0
Subject: Password reset on d-commerce
From: webmaster@localhost
To: a@a.com
Date: Mon, 24 Jul 2023 13:33:30 -0000
Message-ID: <169020561045.43044.9860348640042926888@2.1.168.192.in-addr.arpa>

--===============5014392667940436431==
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

You're receiving this email because you requested a password reset for your user account at d-commerce.

Please go to the following page and choose a new password:
http://127.0.0.1:8080/api/v1/users/reset_password_confirm/MTI/brugbu-c956f64f925f359d044a85c405aff712
Your username, in case you've forgotten: t1

Thanks for using our site!

The d-commerce team
--===============5014392667940436431==
Content-Type: text/html; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit


前端功能很容易从那里弄清楚。希望这对其他人有帮助。

相关问题