Loading

Django中Auth认证系统实现注册与登录

Django中Auth认证系统实现注册与登录

(1)创建项目应用user,并将项目应用user,模版文件夹templates和静态资源文件夹static添加到Django的运行环境,如下:

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

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

STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']

(2)执行数据迁移

(3) 在项目应用user中创建urls.py,并分别在项目文件夹的urls.py和user的urls.py定义用户注册,登录,修改密码,注销的路由信息,代码如下:

# 项目默认应用的urls.py
from django.urls import path, include
# from django.contrib import admin
urlpatterns = [
    # path('', admin.site.urls),
    path('', include(('user.urls', 'user'), namespace='user')),
]


# user的urls.py
from django.urls import path
from .views import *
urlpatterns = [
	path('login.html', loginView, name='login'),
	path('register.html', registerView, name='register'),
	path('setps.html', setpsView, name='setps'),
	path('logout.html', logoutView, name='logout'),
]

(4)创建user.html模板,代码如下:

<!DOCTYPE html>
<html>
<head>
    {% load static %}
	<title>{{ title }}</title>
	<link rel="stylesheet" href="{% static "css/reset.css" %}" />
	<link rel="stylesheet" href="{% static "css/user.css" %}" />
    <script src="{% static "js/jquery.min.js" %}"></script>
    <script src="{% static "js/user.js" %}"></script>
</head>
<body>
<div class="page">
	<div class="loginwarrp">
		<div class="logo">{{ pageTitle }}</div>
        <div class="login_form">
			<form id="Login" name="Login" method="post" action="">
                {% csrf_token %}
				<li class="login-item">
					<span>用户名:</span>
					<input type="text" name="username" class="login_input">
                    <span id="count-msg" class="error"></span>
				</li>
				<li class="login-item">
					<span>密 码:</span>
					<input type="password" name="password" class="login_input">
                    <span id="password-msg" class="error"></span>
				</li>
                {% if password2 %}
                    <li class="login-item">
                        <span>新密码:</span>
                        <input type="password" name="password2" class="login_input">
                        <span id="password-msg" class="error"></span>
				    </li>
                {% endif %}
                <div>{{ tips }}</div>
				<li class="login-sub">
					<input type="submit" name="Submit" value="确定">
				</li>				
           </form>
		</div>
	</div>
</div>
<script type="text/javascript">
	window.onload = function() {
		var config = {
			vx : 4,
			vy : 4,
			height : 2,
			width : 2,
			count : 100,
			color : "121, 162, 185",
			stroke : "100, 200, 180",
			dist : 6000,
			e_dist : 20000,
			max_conn : 10
		};
		CanvasParticle(config);
	}
</script>
<script src="{% static "js/canvas-particle.js" %}"></script>
</body>
</html>

注意:模板文件仅为示例,可以更换

(5)在user的views.py中定义视图函数

from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth import login, logout, authenticate

# 用户注册
def registerView(request):
    # 设置模版上下文
    title = '注册'
    pageTitle = '用户注册'
    if request.method == 'POST':
        u = request.POST.get('username', '')
        p = request.POST.get('password', '')
        if User.objects.filter(username=u):
            tips = '用户已存在'
        else:
            d = dict(username=u, password=p, is_staff=1, is_superuser=1)
            user = User.objects.create_user(**d)
            user.save()
            tips = '注册成功,请登录'
    return render(request, 'user.html', locals())

# 用户登录
def loginView(request):
    # 设置模版上下文
    title = '登录'
    pageTitle = '用户登录'
    if request.method == 'POST':
        u = request.POST.get('username', '')
        p = request.POST.get('password', '')
        if User.objects.filter(username=u):
            user = authenticate(username=u, password=p)
            if user:
                if user.is_active:
                    login(request, user)
                return HttpResponse('登录成功')
            else:
                tips = '账号密码错误,请重新输入'
        else:
            tips = '用户不存在,请注册'
    return render(request, 'user.html', locals())

# 修改密码
def setpsView(request):
    # 设置模版上下文
    title = '修改密码'
    pageTitle = '修改密码'
    password2 = True
    if request.method == 'POST':
        u = request.POST.get('username', '')
        p = request.POST.get('password', '')
        p2 = request.POST.get('password2', '')
        if User.objects.filter(username=u):
            user = authenticate(username=u, password=p)
            # 判断用户的账号密码是否正确
            if user:
                user.set_password(p2)
                user.save()
                tips = '密码修改成功'
            else:
                tips = '原始密码不正确'
        else:
            tips = '用户不存在'
    return render(request, 'user.html', locals())

# 用户注销,退出登录
def logoutView(request):
    logout(request)
    return HttpResponse('注销成功')

补充:密码修改主要由函数set_password实现,而函数set_passwor是在内置函数make_password的基础上进行封装而来的,Django默认使用pbkdf2_sha256方式存储和管理用户密码,而内置函数make_password用于实现用户密码的加密处理,并且该函数可以脱离Auth认证系统单独使用,比如对某些特殊数据进行加密处理等,在user的views.py中定义视图函数stepsView2,它使用make_password实现密码修改,代码如下:

from django.contrib.auth.hashers import make_password
def setpsView2(request):
    # 设置模版上下文
    title = '修改密码'
    pageTitle = '修改密码'
    password2 = True
    if request.method == 'POST':
        u = request.POST.get('username', '')
        p = request.POST.get('password', '')
        p2 = request.POST.get('password2', '')
        # 判断用户是否存在
        user = User.objects.filter(username=u)
        if User.objects.filter(username=u):
            user = authenticate(username=u,password=p)
            # 判断用户的账号密码是否正确
            if user:
                # 密码加密处理并保存到数据库
                dj_ps = make_password(p2, None, 'pbkdf2_sha256')
                user.password = dj_ps
                user.save()
            else:
                print('原始密码不正确')
    return render(request, 'user.html', locals())

另外还有一个check_password函数,导入方式与make_password一样,check_password用于判断加密前与加密后的密码是否是同一个密码,返回值是布尔类型。

posted @ 2022-08-06 16:21  minqiliang  阅读(202)  评论(0编辑  收藏  举报
-->