Implementation of Registration Mailbox Verification and Login Verification Code

Keywords: Web Development Django JQuery Session pip

Django Sends Mail

Modules need to be used
from django.core.mail import send_mail,send_mass_mail

SMTP is a mail server, each kind of mailbox SMTP server address is different, Baidu itself
 For example, mailbox 163 is smtp.163.com

1. Adding configuration to settings

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',

        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        # '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',
            ],
        },
    },
]

#Mail configuration
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True #Whether to use TLS secure transport protocol (used to provide confidentiality and data integrity between two communication applications).
EMAIL_USE_SSL = False #qq Enterprise Mailbox Requires Use of SSL Encryption
EMAIL_HOST = 'smtp.163.com' #SMTP server for mailboxes, which uses 163 mailboxes
EMAIL_PORT = 25 #SMTP Server Port of Outbox
EMAIL_HOST_USER = '######@163.com' #Mailbox address for sending mail
EMAIL_HOST_PASSWORD = 'pwd'
DEFAULT_FROM_EMAIL = 'zjw <#####@163.com>'

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

# The following options indicate that session objects are handed over to redis management
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"

Add configuration in middle urls

from django.contrib import admin

from django.conf.urls import include, url

urlpatterns = [

    url('admin/', admin.site.urls),
    url(r'Voting_items/', include('news.urls',namespace='voting')),

]
    The above configuration enables sending mail using \\\\\\\\\\

2. How to Send

Write template files

from django.db import models
from django.contrib.auth.models import User
#Create your models here.

class MyUser(User):
        #Inherit and override the USer model class that comes with Django
    url = models.URLField(blank=True, null=True, default="http://www.baidu.com")
    class Meta():
        verbose_name = "user"
        verbose_name_plural = verbose_name

Register in admin
from django.contrib import admin
from .models import *
#Register your models here.

admin.site.register(MyUser)

Generate migration files and create tables in the database
python manage.py makemigrations
python manage.py migrate

Write routing

from django.conf.urls import url
from . import views

app_name= 'voting'

urlpatterns = [

    # Verification Code
    url(r'^verify/$', views.verify, name='verify'),
    # register
    url(r'^regist/$',views.regist,name='regist'),
    # Send emails
    url(r'^active/(.*?)/$',views.active,name='active'),

]

Compiling views
The view function is as follows
1. Install itsdangerous
pip install itsdangerous
2. Serialization
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,SignatureExpired

#Send emails
from django.core.mail import send_mail, send_mass_mail, EmailMultiAlternatives
from django.conf import settings
import random,io

#Introducing serialized encryption and expiration date information
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,SignatureExpired

from django.shortcuts import render
from django.http import HttpResponse
from .models import MyUser
def regist(request):

    if request.method == 'GET':
        return render(request, 'Voting_items/regist.html')
    if request.method == "POST":
        username = request.POST.get("username_regi")
        pwd = request.POST.get("password_regi")
        pwd2 = request.POST.get("password_regi_2")

        res = None
        try:
            MyUser.objects.get()
            users = MyUser.objects.get_by_natural_key(username=username)
            if username == str(users):
                res = "The user is registered"
                return render(request, 'Voting_items/login.html', {"res": res})
        except Exception as q:
            print(q)

        if pwd != pwd2:
            res = "Inconsistent passwords"
            return render(request, 'Voting_items/login.html', {"res": res})
        else:

            res = "login was successful,Please activate within 2 hours."
            user = MyUser.objects.create_user(username= username, password=pwd, url = 'http://www.baidu.com')
            print(user.id,user.username,user.is_active)
            # Registered users default to inactive status
            user.is_active = False
            user.save()

            # To prevent unauthorized activation, the activation address needs to be encrypted
            # Serialization with validity
            # 1 Get the serialization tool
            serutil = Serializer(settings.SECRET_KEY,expires_in=7200)
            # 2 Use tools to serialize dictionary objects
            result =  serutil.dumps({"userid": user.id }).decode("utf-8")
            # print(result, type(result))

            mail = EmailMultiAlternatives("Click Activate User","Please click:<a href = 'http://127.0.0.1:8000/Voting_items/active/%s/'> Click Activate </a>"(result,), settings.DEFAULT_FROM_EMAIL, ['zjw505104341@163.com'])
            mail.content_subtype = "html"
            mail.send()

            return render(request, 'Voting_items/login.html', {"res": res})

# Encrypted data coexists in serutive

def active(request,info):
    serutil = Serializer(settings.SECRET_KEY,expires_in=7200)
    try:
        obj = serutil.loads(info)
        print(obj["userid"])
        id = obj["userid"]
        user = get_object_or_404(MyUser, pk=id)
        user.is_active = True
        user.save()
        return redirect(reverse('voting:login'), {"res": "The activation was successful."})
    except SignatureExpired as e:
        return HttpResponse("Out of date")

Verification code

def verify(request):
    # try:
    #with open('1.png', 'wb') as f:
    #return HttpResponse(f.readable())
    #except Exception as e:
    #print(e)
    #return HttpResponse("Error")

    #Every time a verification code is requested, an image needs to be constructed using pillow and returned.
    #Define variables for background, width and height of the picture
    bgcolor = (random.randrange(20, 100),
               random.randrange(20, 100),
               random.randrange(20, 100))
    width = 100
    heigth = 35
    #Create screen objects
    im = Image.new('RGB', (width, heigth), bgcolor)
    #Create Brush Objects
    draw = ImageDraw.Draw(im)
    #Drawing Noise Points by Calling the point() Function of the Brush
    for i in range(0, 100):
        # Random location
        xy = (random.randrange(0, width), random.randrange(0, heigth))
        #Random color acquisition
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        #Fill
        draw.point(xy, fill=fill)
    #Define alternative values for validation codes
    str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0qwertyuiopasdfghjklzxcvbnm'
    #Random selection of four values as verification codes
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    print(rand_str)
    #Constructing font objects
    font = ImageFont.truetype('cambriab.ttf', 23)
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))

    #Draw four words
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)

    #Releasing brushes
    del draw
    request.session['verifycode'] = rand_str
    f = io.BytesIO()
    im.save(f, 'png')
    #Return image data in memory to client, MIME type is picture png
    return HttpResponse(f.getvalue(), 'image/png')

Writing interface
I used template inheritance. Here's the login interface

{% extends 'Base.html' %}
{% block title %}
Login interface
{% endblock %}

{% block body %}

{% comment %}
<form action="{% url 'polls:login' %}" method="post">
    {% csrf_token %}
    {{lf}}
    <input type="submit" value="Sign in">

</form>

<form action="#" method="post">
    {% csrf_token %}
    {{rf}}
    <input type="submit" value="register">
</form>
{% endcomment %}

<div class="container">

    <!-- Nav tabs -->
    <ul class="nav nav-tabs" role="tablist">
        <li role="presentation" class="active"><a href="#Home "aria-controls=" home "role=" tab "data-toggle=" tab "> login</a>
        </li>
        <li role="presentation"><a href="#Messages "aria-controls=" messages "role=" tab "data-toggle=" tab "> registration</a></li>
    </ul>

    <!-- Tab panes -->
    <div class="tab-content">
        <div role="tabpanel" class="tab-pane active" id="home">
            state:{{ res }}
            <div id="info"></div>
            <br>

            <form action="{% url 'voting:login' %}" method="POST" id="select">
                {% csrf_token %}
                <h4>Landing page</h4>

                <p>
                    <input name="account" id="username" autocomplete="off" type="text" placeholder="Please enter your account/Cell-phone number">
                </p>
                <p>
                    <input name="pwd" type="password" placeholder="Please input a password">
                </p>
                <p>
                    <img id="Img" src="{% url 'voting:verify' %}" alt="Verification Code"  />
                    <a href="#"Onclick=" reImg (); "> can't see clearly, change one.</a>
                </p>
                <p>
                    <input name="verify" type="text" placeholder="Please enter the verification code.">
                </p>
                <p>
                    <button type="submit" class="btn btn-primary" id="vote">Land</button>
                </p>
            </form>

        </div>

        <div role="tabpanel" class="tab-pane" id="messages">
            <p><a href="{% url 'voting:regist' %}" class="btn btn-info">register</a></p>

        </div>

        <div role="tabpanel" class="tab-pane" id="settings">

        </div>
    </div>

</div>

<script>

    <!--Verification code refresh-->
    function reImg(){
        var img = document.getElementById("Img");
        img.src = "{% url 'voting:verify' %}?rnd=" + Math.random();
    }

</script>

{% endblock %}

Here's the regist er interface
{% extends 'Base.html' %}

{% block title %}
Registration interface

{% endblock %}

{% block body %}

    <div class="container">
        //Status: {{res}}
        <br>

        <form action="{% url 'voting:regist' %}" method="POST" id="select">
            {% csrf_token %}
            <h3>Registration page</h3>

                <input type="text" class="form-control" name="username_regi" id="username_regi" placeholder="enter one user name">

                <input type="password" class="form-control" name="password_regi" id="password_regi" placeholder="Please input a password">

                <input type="password" class="form-control" name="password_regi_2" id="password_regi_2" placeholder="Please enter your password again.">

                <button type="submit" class="btn btn-default">register</button>
        </form>

    </div>

{% endblock %}

Here's the Base interface

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>
        {% block title %}
        base class
        {% endblock %}
    </title>

    {% load static %}
    <link rel="stylesheet" href="{% static 'js/lib/bootstrap-3.3.7-dist/css/bootstrap.css' %}">
    <script src="{% static 'js/lib/jQuery/jquery-1.12.4.min.js' %}"></script>
    <script src="{% static 'js/lib/bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
</head>
<body>

{% block body %}

{% endblock %}

</body>
</html>

Because I used the BootStrap plug-in, I wanted to introduce it.

Create folders under the project's peer directory
 The static folder creates the js folder below and then creates the lib folder to put the BootStrap file in and the jQuery file in.

The first parameter is the theme
The second parameter is the text
The third parameter is the sender
The fourth parameter is the recipient list
send_mass_mail for bulk mail
The first parameter is the tuple type
Each item in the tuple is four parameters in send_mail

3. How to Activate User Registration
1. Register the user directly to the database when the user registers, and set is_activity to false.
And send mail to the user's mailbox
2. How to Stitch Mail Contents
The content of the message is to activate the user's routing: Exp
<a href='http://127.0.0.1:8000/polls/active/10/'&gt Click Activate</a>
3. Writing Activation Routing
Extracting parameters in active routing
Set the is_activity of the user corresponding to the parameter to True
Then redirect the login page

4. How to keep secret and set up validity period
1. Install itsdangerous
pip install itsdangerous
2. Serialization
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,SignatureExpired

Serialization of dictionary formal content
# 1 Get the serialization tool
serutil = Serializer(settings.SECRET_KEY)
# 2 Use tools to serialize dictionary objects
result = serutil.dumps({"userid": user.id }).decode("utf-8")
3. Deserialization
Using the same serialization tool
serutil = Serializer(settings.SECRET_KEY)
# info stands for deserialized strings
obj = serutil.loads(info)
print(obj["userid"])

Posted by TheRealPenguin on Sat, 25 May 2019 13:13:15 -0700