Browse Source

完成了用户登录注册重置密码等功能

Shellmiao 3 years ago
parent
commit
82824e5a66

+ 8 - 0
.idea/.gitignore

@@ -0,0 +1,8 @@
+# 默认忽略的文件
+/shelf/
+/workspace.xml
+# 数据源本地存储已忽略文件
+/dataSources/
+/dataSources.local.xml
+# 基于编辑器的 HTTP 客户端请求
+/httpRequests/

+ 8 - 0
.idea/ShellmiaoBlogBackEnd.iml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module type="PYTHON_MODULE" version="4">
+  <component name="NewModuleRootManager">
+    <content url="file://$MODULE_DIR$" />
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+  </component>
+</module>

+ 17 - 0
.idea/inspectionProfiles/Project_Default.xml

@@ -0,0 +1,17 @@
+<component name="InspectionProjectProfileManager">
+  <profile version="1.0">
+    <option name="myName" value="Project Default" />
+    <inspection_tool class="PyCompatibilityInspection" enabled="true" level="WARNING" enabled_by_default="true">
+      <option name="ourVersions">
+        <value>
+          <list size="4">
+            <item index="0" class="java.lang.String" itemvalue="2.7" />
+            <item index="1" class="java.lang.String" itemvalue="3.7" />
+            <item index="2" class="java.lang.String" itemvalue="3.8" />
+            <item index="3" class="java.lang.String" itemvalue="3.9" />
+          </list>
+        </value>
+      </option>
+    </inspection_tool>
+  </profile>
+</component>

+ 6 - 0
.idea/inspectionProfiles/profiles_settings.xml

@@ -0,0 +1,6 @@
+<component name="InspectionProjectProfileManager">
+  <settings>
+    <option name="USE_PROJECT_PROFILE" value="false" />
+    <version value="1.0" />
+  </settings>
+</component>

+ 4 - 0
.idea/misc.xml

@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.8" project-jdk-type="Python SDK" />
+</project>

+ 8 - 0
.idea/modules.xml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectModuleManager">
+    <modules>
+      <module fileurl="file://$PROJECT_DIR$/.idea/ShellmiaoBlogBackEnd.iml" filepath="$PROJECT_DIR$/.idea/ShellmiaoBlogBackEnd.iml" />
+    </modules>
+  </component>
+</project>

+ 6 - 0
.idea/vcs.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="VcsDirectoryMappings">
+    <mapping directory="$PROJECT_DIR$" vcs="Git" />
+  </component>
+</project>

+ 0 - 0
ShellmiaoBlog/Account/__init__.py


+ 10 - 0
ShellmiaoBlog/Account/admin.py

@@ -0,0 +1,10 @@
+from django.contrib import admin
+from .models import Account
+
+
+# Register your models here.
+class AccountAdmin(admin.ModelAdmin):
+    list_display = ["user", "profile"]
+
+
+admin.site.register(Account, AccountAdmin)

+ 6 - 0
ShellmiaoBlog/Account/apps.py

@@ -0,0 +1,6 @@
+from django.apps import AppConfig
+
+
+class AccountConfig(AppConfig):
+    default_auto_field = 'django.db.models.BigAutoField'
+    name = 'Account'

+ 10 - 0
ShellmiaoBlog/Account/form.py

@@ -0,0 +1,10 @@
+from django import forms
+from django.contrib.auth.models import User
+
+
+class UserRegisterForm(forms.ModelForm):
+    password = forms.CharField()
+
+    class Meta:
+        model = User
+        fields = ('username', 'email')

+ 25 - 0
ShellmiaoBlog/Account/migrations/0001_initial.py

@@ -0,0 +1,25 @@
+# Generated by Django 3.2.5 on 2021-09-27 08:56
+
+from django.conf import settings
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+    initial = True
+
+    dependencies = [
+        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+    ]
+
+    operations = [
+        migrations.CreateModel(
+            name='Account',
+            fields=[
+                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+                ('profile', models.CharField(blank=True, max_length=500)),
+                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='account', to=settings.AUTH_USER_MODEL)),
+            ],
+        ),
+    ]

+ 0 - 0
ShellmiaoBlog/Account/migrations/__init__.py


+ 7 - 0
ShellmiaoBlog/Account/models.py

@@ -0,0 +1,7 @@
+from django.db import models
+from django.contrib.auth.models import User
+
+
+class Account(models.Model):
+    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='account')
+    profile = models.CharField(blank=True, max_length=500)

+ 3 - 0
ShellmiaoBlog/Account/tests.py

@@ -0,0 +1,3 @@
+from django.test import TestCase
+
+# Create your tests here.

+ 12 - 0
ShellmiaoBlog/Account/urls.py

@@ -0,0 +1,12 @@
+from django.urls import path
+from . import views
+
+urlpatterns = [
+    path('login/', views.user_login, name='login'),
+    path('islogged/', views.user_is_logged, name='islogged'),
+    path('register/', views.user_register, name='register'),
+    path('logout/', views.user_logout, name='logout'),
+    path('check/', views.user_check, name='check'),
+    path('confirm/', views.user_confirm, name='check'),
+    path('reset/', views.user_reset, name='check'),
+]

+ 180 - 0
ShellmiaoBlog/Account/views.py

@@ -0,0 +1,180 @@
+from django.core.mail import send_mail
+from django.http import JsonResponse
+from django.contrib.auth import authenticate, login, logout
+from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie
+
+from .form import UserRegisterForm
+from .models import Account
+from django.contrib.auth.models import User
+
+
+@ensure_csrf_cookie
+def user_login(request):
+    if request.method == 'POST':
+        data = request.POST
+        # 检测账号密码是否匹配数据库中的一个用户
+        # 如果均匹配,则返回此User对象
+        user = authenticate(username=data['username'], password=data['password'])
+        if user:
+            login(request, user)
+            res = {
+                'code': '402',
+                'message': 'Login Successfully'
+            }
+            return JsonResponse(res)
+        else:
+            res = {
+                'code': '403',
+                'message': 'The Username Or Password Is Incorrect'
+            }
+            return JsonResponse(res)
+    else:
+        # 请求方法错误,请使用POST
+        res = {
+            'code': '401',
+            'message': 'Please Use POST'
+        }
+        return JsonResponse(res)
+
+
+def user_is_logged(request):
+    if request.user.is_authenticated:
+        res = {
+            'code': '402',
+            'message': 'You\'ve Logged In'
+        }
+        return JsonResponse(res)
+    else:
+        res = {
+            'code': '401',
+            'message': 'You\'re Not Logged in'
+        }
+        return JsonResponse(res)
+
+
+@ensure_csrf_cookie
+def user_register(request):
+    if request.method == 'POST':
+        user_register_form = UserRegisterForm(data=request.POST)
+        if user_register_form.is_valid():
+            # 新建一个user,但是不提交
+            new_user = user_register_form.save(commit=False)
+            new_user.set_password(request.POST['password'])
+            # 保存
+            new_user.save()
+            account = Account()
+            account.user = new_user
+            account.profile = '这个人很懒,没有写个人简介'
+            account.save()
+            res = {
+                'code': '402',
+                'message': 'Registered Successfully'
+            }
+            return JsonResponse(res)
+        else:
+            res = {
+                'code': '403',
+                'message': 'Data Formatting Error'
+            }
+            return JsonResponse(res)
+    else:
+        # 请求方法错误,请使用POST
+        res = {
+            'code': '401',
+            'message': 'Please Use POST'
+        }
+        return JsonResponse(res)
+
+
+@ensure_csrf_cookie
+def user_logout(request):
+    logout(request)
+    res = {
+        'code': '402',
+        'message': 'Logout Successfully'
+    }
+    return JsonResponse(res)
+
+
+@csrf_exempt
+def user_check(request):
+    if request.method == 'POST':
+        user = User.objects.filter(username=request.POST['username'], email=request.POST['email']).get()
+        if user:
+            print('233ok1')
+            send = send_mail('Shellmiao的博客——重置账号密码',
+                             user.password,
+                             'shellmiao@shellmiao.com',
+                             [user.email])
+            print('233ok2')
+            if send == 1:
+                res = {
+                    'code': '402',
+                    'message': 'Email Sent Successfully'
+                }
+                return JsonResponse(res)
+            else:
+                res = {
+                    'code': '403',
+                    'message': 'Failed To Send Mail'
+                }
+                return JsonResponse(res)
+    else:
+        # 请求方法错误,请使用POST
+        res = {
+            'code': '401',
+            'message': 'Please Use POST'
+        }
+        return JsonResponse(res)
+
+
+@csrf_exempt
+def user_confirm(request):
+    if request.method == 'POST':
+        user = User.objects.filter(password=request.POST['code']).get()
+        if user:
+            res = {
+                'code': '402',
+                'message': 'Confirm Successfully'
+            }
+            return JsonResponse(res)
+        else:
+            res = {
+                'code': '403',
+                'message': 'Failed To Confirm'
+            }
+            return JsonResponse(res)
+    else:
+        # 请求方法错误,请使用POST
+        res = {
+            'code': '401',
+            'message': 'Please Use POST'
+        }
+        return JsonResponse(res)
+
+
+@csrf_exempt
+def user_reset(request):
+    if request.method == 'POST':
+        user = User.objects.filter(password=request.POST['code']).get()
+        if user:
+            user.set_password(request.POST['password'])
+            user.save()
+            res = {
+                'code': '402',
+                'message': 'Reset Successfully'
+            }
+            return JsonResponse(res)
+        else:
+            res = {
+                'code': '403',
+                'message': 'Failed To Reset'
+            }
+            return JsonResponse(res)
+    else:
+        # 请求方法错误,请使用POST
+        res = {
+            'code': '401',
+            'message': 'Please Use POST'
+        }
+        return JsonResponse(res)

+ 0 - 0
ShellmiaoBlog/ShellmiaoBlog/__init__.py


+ 164 - 0
ShellmiaoBlog/ShellmiaoBlog/settings.py

@@ -0,0 +1,164 @@
+"""
+Django settings for ShellmiaoBlog project.
+
+Generated by 'django-admin startproject' using Django 2.0.13.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/2.0/topics/settings/
+
+For the full list of settings and their values, see
+https://docs.djangoproject.com/en/2.0/ref/settings/
+"""
+
+import os
+
+# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
+BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+# Quick-start development settings - unsuitable for production
+# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
+
+# SECURITY WARNING: keep the secret key used in production secret!
+SECRET_KEY = '_rk^igb%3fwf6lh%ifu(9qdw)b%$xt!if!r$8w1=%e0+4(4&tz'
+
+# SECURITY WARNING: don't run with debug turned on in production!
+DEBUG = True
+
+ALLOWED_HOSTS = ['*']
+
+# Application definition
+
+INSTALLED_APPS = [
+    'django.contrib.admin',
+    'django.contrib.auth',
+    'django.contrib.contenttypes',
+    'django.contrib.sessions',
+    'django.contrib.messages',
+    'django.contrib.staticfiles',
+    'Account',
+    'corsheaders',
+]
+
+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',
+]
+
+ROOT_URLCONF = 'ShellmiaoBlog.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 = 'ShellmiaoBlog.wsgi.application'
+
+# Database
+# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
+
+DATABASES = {
+    'default': {
+        'ENGINE': 'django.db.backends.sqlite3',
+        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
+    }
+}
+
+# Password validation
+# https://docs.djangoproject.com/en/2.0/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/2.0/topics/i18n/
+
+LANGUAGE_CODE = 'en-us'
+
+TIME_ZONE = 'UTC'
+
+USE_I18N = True
+
+USE_L10N = True
+
+USE_TZ = True
+
+# Static files (CSS, JavaScript, Images)
+# https://docs.djangoproject.com/en/2.0/howto/static-files/
+
+STATIC_URL = '/static/'
+
+CORS_ALLOW_CREDENTIALS = True
+
+CORS_ORIGIN_ALLOW_ALL = True
+
+CORS_ALLOW_METHODS = (
+    'DELETE',
+    'GET',
+    'OPTIONS',
+    'PATCH',
+    'POST',
+    'PUT',
+    'VIEW',
+)
+
+CORS_ALLOW_HEADERS = (
+    'XMLHttpRequest',
+    'X_FILENAME',
+    'accept-encoding',
+    'authorization',
+    'content-type',
+    'dnt',
+    'origin',
+    'user-agent',
+    'x-csrftoken',
+    'x-requested-with',
+    'Pragma',
+)
+EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
+# 设置邮件域名
+EMAIL_HOST = 'smtp.exmail.qq.com'
+# 设置端口号,为数字
+EMAIL_PORT = 25
+# 设置发件人邮箱
+EMAIL_HOST_USER = 'shellmiao@shellmiao.com'
+# 设置发件人 授权码
+EMAIL_HOST_PASSWORD = 'T9HsJo96DSq5wsh2'
+# 设置是否启用安全链接
+EMAIL_USER_SSL = True
+
+DEFAULT_FROM_EMAIL = 'shellmiao@shellmiao.com'
+# 以上这个配置信息,Django会自动读取,
+# 使用账号以及授权码进行登录,
+# 如果登录成功,可以发送邮件
+
+
+SESSION_COOKIE_SAMESITE = None

+ 22 - 0
ShellmiaoBlog/ShellmiaoBlog/urls.py

@@ -0,0 +1,22 @@
+"""ShellmiaoBlog URL Configuration
+
+The `urlpatterns` list routes URLs to views. For more information please see:
+    https://docs.djangoproject.com/en/2.0/topics/http/urls/
+Examples:
+Function views
+    1. Add an import:  from my_app import views
+    2. Add a URL to urlpatterns:  path('', views.home, name='home')
+Class-based views
+    1. Add an import:  from other_app.views import Home
+    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
+Including another URLconf
+    1. Import the include() function: from django.urls import include, path
+    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
+"""
+from django.contrib import admin
+from django.urls import path, include
+
+urlpatterns = [
+    path('admin/', admin.site.urls),
+    path('account/', include(('Account.urls', 'Account'), namespace='Account'))
+]

+ 16 - 0
ShellmiaoBlog/ShellmiaoBlog/wsgi.py

@@ -0,0 +1,16 @@
+"""
+WSGI config for ShellmiaoBlog project.
+
+It exposes the WSGI callable as a module-level variable named ``application``.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
+"""
+
+import os
+
+from django.core.wsgi import get_wsgi_application
+
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ShellmiaoBlog.settings")
+
+application = get_wsgi_application()

BIN
ShellmiaoBlog/db.sqlite3


+ 15 - 0
ShellmiaoBlog/manage.py

@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+import os
+import sys
+
+if __name__ == "__main__":
+    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ShellmiaoBlog.settings")
+    try:
+        from django.core.management import execute_from_command_line
+    except ImportError as exc:
+        raise ImportError(
+            "Couldn't import Django. Are you sure it's installed and "
+            "available on your PYTHONPATH environment variable? Did you "
+            "forget to activate a virtual environment?"
+        ) from exc
+    execute_from_command_line(sys.argv)